cspell-lib 5.19.2 → 5.19.3

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.
@@ -4,6 +4,10 @@ export interface Position {
4
4
  line: number;
5
5
  character: number;
6
6
  }
7
+ /**
8
+ * Range offset tuple.
9
+ */
10
+ export declare type SimpleRange = [start: number, end: number];
7
11
  export interface TextDocumentLine {
8
12
  readonly text: string;
9
13
  readonly offset: number;
@@ -48,5 +52,10 @@ export interface CreateTextDocumentParams {
48
52
  locale?: string | undefined;
49
53
  version?: number | undefined;
50
54
  }
55
+ export interface TextDocumentContentChangeEvent {
56
+ range?: SimpleRange;
57
+ text: string;
58
+ }
51
59
  export declare function createTextDocument({ uri, content, languageId, locale, version, }: CreateTextDocumentParams): TextDocument;
60
+ export declare function updateTextDocument(doc: TextDocument, edits: TextDocumentContentChangeEvent[], version?: number): TextDocument;
52
61
  //# sourceMappingURL=TextDocument.d.ts.map
@@ -22,21 +22,29 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
25
28
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.createTextDocument = void 0;
29
+ exports.updateTextDocument = exports.createTextDocument = void 0;
27
30
  const LanguageIds_1 = require("../LanguageIds");
28
31
  const Uri = __importStar(require("./Uri"));
29
32
  const vscode_languageserver_textdocument_1 = require("vscode-languageserver-textdocument");
33
+ const assert_1 = __importDefault(require("assert"));
30
34
  class TextDocumentImpl {
31
35
  constructor(uri, text, languageId, locale, version) {
32
36
  this.uri = uri;
33
- this.text = text;
34
37
  this.languageId = languageId;
35
38
  this.locale = locale;
36
- this.version = version;
37
39
  const primaryLanguageId = typeof languageId === 'string' ? languageId : languageId[0] || 'plaintext';
38
40
  this.vsTextDoc = vscode_languageserver_textdocument_1.TextDocument.create(uri.toString(), primaryLanguageId, version, text);
39
41
  }
42
+ get version() {
43
+ return this.vsTextDoc.version;
44
+ }
45
+ get text() {
46
+ return this.vsTextDoc.getText();
47
+ }
40
48
  positionAt(offset) {
41
49
  return this.vsTextDoc.positionAt(offset);
42
50
  }
@@ -61,6 +69,26 @@ class TextDocumentImpl {
61
69
  position,
62
70
  };
63
71
  }
72
+ /**
73
+ * Apply edits to the text.
74
+ * Note: the edits are applied one after the other.
75
+ * @param edits - changes to the text
76
+ * @param version - optional version to use.
77
+ * @returns this
78
+ */
79
+ update(edits, version) {
80
+ version = version !== null && version !== void 0 ? version : this.version + 1;
81
+ for (const edit of edits) {
82
+ const vsEdit = edit.range
83
+ ? {
84
+ range: { start: this.positionAt(edit.range[0]), end: this.positionAt(edit.range[1]) },
85
+ text: edit.text,
86
+ }
87
+ : edit;
88
+ vscode_languageserver_textdocument_1.TextDocument.update(this.vsTextDoc, [vsEdit], version);
89
+ }
90
+ return this;
91
+ }
64
92
  }
65
93
  function createTextDocument({ uri, content, languageId, locale, version, }) {
66
94
  version = version !== null && version !== void 0 ? version : 1;
@@ -70,4 +98,9 @@ function createTextDocument({ uri, content, languageId, locale, version, }) {
70
98
  return new TextDocumentImpl(uri, content, languageId, locale, version);
71
99
  }
72
100
  exports.createTextDocument = createTextDocument;
101
+ function updateTextDocument(doc, edits, version) {
102
+ (0, assert_1.default)(doc instanceof TextDocumentImpl, 'Unknown TextDocument type');
103
+ return doc.update(edits, version);
104
+ }
105
+ exports.updateTextDocument = updateTextDocument;
73
106
  //# sourceMappingURL=TextDocument.js.map
@@ -12,7 +12,7 @@ declare function mergeObjects(left: undefined, right: undefined): undefined;
12
12
  declare function mergeObjects<T>(left: T, right: undefined): T;
13
13
  declare function mergeObjects<T>(left: T, right: T): T;
14
14
  declare function mergeObjects<T>(left: undefined, right: T): T;
15
- export declare function mergeSettings(left: CSpellSettingsWSTO | CSpellSettingsI, ...settings: (CSpellSettingsWSTO | CSpellSettingsI)[]): CSpellSettingsI;
15
+ export declare function mergeSettings(left: CSpellSettingsWSTO | CSpellSettingsI, ...settings: (CSpellSettingsWSTO | CSpellSettingsI | undefined)[]): CSpellSettingsI;
16
16
  export declare function mergeInDocSettings(left: CSpellSettingsWSTO, right: CSpellSettingsWSTO): CSpellSettingsWST;
17
17
  export declare function calcOverrideSettings(settings: CSpellSettingsWSTO, filename: string): CSpellSettingsI;
18
18
  /**
@@ -34,13 +34,19 @@ exports.configSettingsFileVersion0_1 = '0.1';
34
34
  exports.configSettingsFileVersion0_2 = '0.2';
35
35
  exports.currentSettingsFileVersion = exports.configSettingsFileVersion0_2;
36
36
  exports.ENV_CSPELL_GLOB_ROOT = 'CSPELL_GLOB_ROOT';
37
+ function _unique(a) {
38
+ return [...new Set(a)];
39
+ }
37
40
  function mergeListUnique(left, right) {
38
41
  if (left === undefined)
39
42
  return right;
40
43
  if (right === undefined)
41
44
  return left;
42
- const uniqueItems = new Set([...left, ...right]);
43
- return [...uniqueItems.keys()];
45
+ if (!right.length)
46
+ return left;
47
+ if (!left.length)
48
+ return right;
49
+ return _unique([...left, ...right]);
44
50
  }
45
51
  function mergeList(left, right) {
46
52
  if (left === undefined)
@@ -73,12 +79,6 @@ function mergeObjects(left, right) {
73
79
  return left;
74
80
  return { ...left, ...right };
75
81
  }
76
- function tagLanguageSettings(tag, settings = []) {
77
- return settings.map((s) => ({
78
- id: tag + '.' + (s.id || s.locale || s.languageId),
79
- ...s,
80
- }));
81
- }
82
82
  function replaceIfNotEmpty(left = [], right = []) {
83
83
  const filtered = right.filter((a) => !!a);
84
84
  if (filtered.length) {
@@ -87,7 +87,7 @@ function replaceIfNotEmpty(left = [], right = []) {
87
87
  return left;
88
88
  }
89
89
  function mergeSettings(left, ...settings) {
90
- const rawSettings = settings.reduce(merge, toInternalSettings(left));
90
+ const rawSettings = settings.filter((a) => !!a).reduce(merge, toInternalSettings(left));
91
91
  return util.clean(rawSettings);
92
92
  }
93
93
  exports.mergeSettings = mergeSettings;
@@ -136,7 +136,7 @@ function merge(left, right) {
136
136
  dictionaryDefinitions: mergeListUnique(_left.dictionaryDefinitions, _right.dictionaryDefinitions),
137
137
  dictionaries: mergeListUnique(_left.dictionaries, _right.dictionaries),
138
138
  noSuggestDictionaries: mergeListUnique(_left.noSuggestDictionaries, _right.noSuggestDictionaries),
139
- languageSettings: mergeList(tagLanguageSettings(leftId, _left.languageSettings), tagLanguageSettings(rightId, _right.languageSettings)),
139
+ languageSettings: mergeList(_left.languageSettings, _right.languageSettings),
140
140
  enabled: _right.enabled !== undefined ? _right.enabled : _left.enabled,
141
141
  files: mergeListUnique(_left.files, _right.files),
142
142
  ignorePaths: versionBasedMergeList(_left.ignorePaths, _right.ignorePaths, version),
@@ -1,5 +1,6 @@
1
- import type { DictionaryDefinition, DictionaryReference } from '@cspell/cspell-types';
1
+ import type { DictionaryDefinition } from '@cspell/cspell-types';
2
2
  import { CSpellSettingsInternal, DictionaryDefinitionInternal, DictionaryDefinitionInternalWithSource } from '../Models/CSpellSettingsInternalDef';
3
+ import { DictionaryReferenceCollection } from './DictionaryReferenceCollection';
3
4
  export declare type DefMapArrayItem = [string, DictionaryDefinitionInternal];
4
5
  /**
5
6
  * Combines the list of desired dictionaries with the list of dictionary
@@ -9,15 +10,16 @@ export declare type DefMapArrayItem = [string, DictionaryDefinitionInternal];
9
10
  * - Adding `!` to a dictId will remove the dictionary.
10
11
  * - Adding `!!` will add it back.
11
12
  *
12
- * @param dictIds - dictionaries desired
13
+ * @param dictRefCol - dictionaries desired
13
14
  * @param defs - dictionary definitions
14
15
  * @returns map from dictIds to definitions
15
16
  */
16
- export declare function filterDictDefsToLoad(dictRefIds: DictionaryReference[], defs: DictionaryDefinitionInternal[]): DictionaryDefinitionInternal[];
17
+ export declare function filterDictDefsToLoad(dictRefCol: DictionaryReferenceCollection, defs: DictionaryDefinitionInternal[]): DictionaryDefinitionInternal[];
17
18
  export declare function mapDictDefsToInternal(defs: undefined, pathToSettingsFile: string): undefined;
18
19
  export declare function mapDictDefsToInternal(defs: DictionaryDefinition[], pathToSettingsFile: string): DictionaryDefinitionInternalWithSource[];
19
20
  export declare function mapDictDefsToInternal(defs: DictionaryDefinition[] | undefined, pathToSettingsFile: string): DictionaryDefinitionInternalWithSource[] | undefined;
20
21
  export declare function mapDictDefToInternal(def: DictionaryDefinition, pathToSettingsFile: string): DictionaryDefinitionInternalWithSource;
21
22
  export declare function isDictionaryDefinitionWithSource(d: DictionaryDefinition | DictionaryDefinitionInternalWithSource): d is DictionaryDefinitionInternalWithSource;
22
23
  export declare function calcDictionaryDefsToLoad(settings: CSpellSettingsInternal): DictionaryDefinitionInternal[];
24
+ export declare function isDictionaryDefinitionInternal(def: DictionaryDefinition | DictionaryDefinitionInternal): def is DictionaryDefinitionInternal;
23
25
  //# sourceMappingURL=DictionarySettings.d.ts.map
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.calcDictionaryDefsToLoad = exports.isDictionaryDefinitionWithSource = exports.mapDictDefToInternal = exports.mapDictDefsToInternal = exports.filterDictDefsToLoad = void 0;
26
+ exports.isDictionaryDefinitionInternal = exports.calcDictionaryDefsToLoad = exports.isDictionaryDefinitionWithSource = exports.mapDictDefToInternal = exports.mapDictDefsToInternal = exports.filterDictDefsToLoad = void 0;
27
27
  const path = __importStar(require("path"));
28
28
  const resolveFile_1 = require("../util/resolveFile");
29
29
  const DictionaryReferenceCollection_1 = require("./DictionaryReferenceCollection");
@@ -37,30 +37,26 @@ const util_1 = require("../util/util");
37
37
  * - Adding `!` to a dictId will remove the dictionary.
38
38
  * - Adding `!!` will add it back.
39
39
  *
40
- * @param dictIds - dictionaries desired
40
+ * @param dictRefCol - dictionaries desired
41
41
  * @param defs - dictionary definitions
42
42
  * @returns map from dictIds to definitions
43
43
  */
44
- function filterDictDefsToLoad(dictRefIds, defs) {
45
- function isDefP(def) {
46
- return !!def.path;
47
- }
48
- const col = (0, DictionaryReferenceCollection_1.createDictionaryReferenceCollection)(dictRefIds);
49
- const dictIdSet = new Set(col.enabled());
50
- const allActiveDefs = defs
51
- .filter(({ name }) => dictIdSet.has(name))
52
- .map((def) => ({ ...def, path: getFullPathName(def) }))
53
- // Remove any empty paths.
54
- .filter(isDefP);
44
+ function filterDictDefsToLoad(dictRefCol, defs) {
45
+ const allActiveDefs = defs.filter(({ name }) => dictRefCol.isEnabled(name)).map(fixPath);
55
46
  return [...new Map(allActiveDefs.map((d) => [d.name, d])).values()];
56
47
  }
57
48
  exports.filterDictDefsToLoad = filterDictDefsToLoad;
58
- function getFullPathName(def) {
59
- const { path: filePath = '', file = '' } = def;
60
- if (!filePath && !file) {
61
- return '';
49
+ function fixPath(def) {
50
+ if (def instanceof _DictionaryDefinitionInternalWithSource) {
51
+ return def;
62
52
  }
63
- return path.join(filePath, file);
53
+ const { path: filePath = '', file = '' } = def;
54
+ const newPath = !filePath && !file ? '' : path.join(filePath, file);
55
+ return {
56
+ ...def,
57
+ file: undefined,
58
+ path: newPath,
59
+ };
64
60
  }
65
61
  function mapDictDefsToInternal(defs, pathToSettingsFile) {
66
62
  return defs === null || defs === void 0 ? void 0 : defs.map((def) => mapDictDefToInternal(def, pathToSettingsFile));
@@ -93,9 +89,13 @@ function calcDictionaryDefsToLoad(settings) {
93
89
  return def;
94
90
  return { ...def, noSuggest: enabled };
95
91
  });
96
- return filterDictDefsToLoad(colDicts.enabled(), modDefs);
92
+ return filterDictDefsToLoad(colDicts, modDefs);
97
93
  }
98
94
  exports.calcDictionaryDefsToLoad = calcDictionaryDefsToLoad;
95
+ function isDictionaryDefinitionInternal(def) {
96
+ return def instanceof _DictionaryDefinitionInternalWithSource;
97
+ }
98
+ exports.isDictionaryDefinitionInternal = isDictionaryDefinitionInternal;
99
99
  class _DictionaryDefinitionInternalWithSource {
100
100
  constructor(def, __source) {
101
101
  this.__source = __source;
@@ -1,10 +1,10 @@
1
- import type { LanguageSetting, CSpellUserSettings, LocaleId, LanguageId, BaseSetting } from '@cspell/cspell-types';
1
+ import type { BaseSetting, CSpellUserSettings, LanguageId, LanguageSetting, LocaleId } from '@cspell/cspell-types';
2
2
  export declare type LanguageSettings = LanguageSetting[];
3
3
  export declare function getDefaultLanguageSettings(): LanguageSettings;
4
4
  export declare function normalizeLanguageId(langId: LanguageId | LanguageId[]): Set<LanguageId>;
5
5
  export declare function normalizeLocale(locale: LocaleId | LocaleId[]): Set<LocaleId>;
6
6
  export declare function isLocaleInSet(locale: LocaleId | LocaleId[], setOfLocals: Set<LocaleId>): boolean;
7
- export declare function calcSettingsForLanguage(languageSettings: LanguageSettings, languageId: LanguageId, locale: LocaleId | LocaleId[]): BaseSetting;
7
+ export declare function calcSettingsForLanguage(languageSettings: LanguageSettings, languageId: LanguageId, locale: LocaleId): BaseSetting;
8
8
  export declare function calcUserSettingsForLanguage(settings: CSpellUserSettings, languageId: string): CSpellUserSettings;
9
9
  export declare function calcSettingsForLanguageId(baseSettings: CSpellUserSettings, languageId: LanguageId[] | LanguageId): CSpellUserSettings;
10
10
  //# sourceMappingURL=LanguageSettings.d.ts.map
@@ -24,6 +24,8 @@ var __importStar = (this && this.__importStar) || function (mod) {
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.calcSettingsForLanguageId = exports.calcUserSettingsForLanguage = exports.calcSettingsForLanguage = exports.isLocaleInSet = exports.normalizeLocale = exports.normalizeLanguageId = exports.getDefaultLanguageSettings = void 0;
27
+ const Memorizer_1 = require("../util/Memorizer");
28
+ const util_1 = require("../util/util");
27
29
  const SpellSettings = __importStar(require("./CSpellSettingsServer"));
28
30
  const defaultLocale = 'en';
29
31
  const defaultLanguageSettings = [];
@@ -32,58 +34,69 @@ function getDefaultLanguageSettings() {
32
34
  }
33
35
  exports.getDefaultLanguageSettings = getDefaultLanguageSettings;
34
36
  function localesToList(locales) {
35
- locales = typeof locales !== 'string' ? locales.join(',') : locales;
36
37
  return stringToList(locales.replace(/\s+/g, ','));
37
38
  }
38
39
  function stringToList(sList) {
39
- if (typeof sList !== 'string') {
40
- sList = sList.join(',');
41
- }
42
- sList = sList
40
+ return sList
43
41
  .replace(/[|;]/g, ',')
44
42
  .split(',')
45
43
  .map((s) => s.trim())
46
44
  .filter((s) => !!s);
47
- return sList;
48
45
  }
49
- function normalizeLanguageId(langId) {
46
+ const _normalizeLanguageId = (0, Memorizer_1.memorizerAll)(__normalizeLanguageId);
47
+ function __normalizeLanguageId(langId) {
50
48
  const langIds = stringToList(langId);
51
49
  return new Set(langIds.map((a) => a.toLowerCase()));
52
50
  }
51
+ function normalizeLanguageId(langId) {
52
+ return _normalizeLanguageId(typeof langId === 'string' ? langId : langId.join(','));
53
+ }
53
54
  exports.normalizeLanguageId = normalizeLanguageId;
54
- function normalizeLanguageIdToString(langId) {
55
- return [...normalizeLanguageId(langId)].join(',');
55
+ const _normalizeLocale = (0, Memorizer_1.memorizerAll)(__normalizeLocale);
56
+ function __normalizeLocale(locale) {
57
+ const locales = localesToList(locale);
58
+ return new Set(locales.map((locale) => locale.toLowerCase().replace(/[^a-z]/g, '')));
56
59
  }
57
60
  function normalizeLocale(locale) {
58
- locale = localesToList(locale);
59
- return new Set(locale.map((locale) => locale.toLowerCase().replace(/[^a-z]/g, '')));
61
+ locale = typeof locale === 'string' ? locale : locale.join(',');
62
+ return _normalizeLocale(locale);
60
63
  }
61
64
  exports.normalizeLocale = normalizeLocale;
62
65
  function isLocaleInSet(locale, setOfLocals) {
63
66
  const locales = normalizeLocale(locale);
64
- return [...locales.values()].filter((locale) => setOfLocals.has(locale)).length > 0;
67
+ return (0, util_1.doSetsIntersect)(locales, setOfLocals);
65
68
  }
66
69
  exports.isLocaleInSet = isLocaleInSet;
67
70
  function calcSettingsForLanguage(languageSettings, languageId, locale) {
68
71
  languageId = languageId.toLowerCase();
69
72
  const allowedLocals = normalizeLocale(locale);
70
- return defaultLanguageSettings
71
- .concat(languageSettings)
73
+ const ls = languageSettings
72
74
  .filter((s) => doesLanguageSettingMatchLanguageId(s, languageId))
73
75
  .filter((s) => !s.locale || s.locale === '*' || isLocaleInSet(s.locale, allowedLocals))
74
76
  .map((langSetting) => {
75
- const id = normalizeLanguageIdToString(langSetting.locale || langSetting.languageId || 'language');
76
- const { languageId: _languageId, locale: _local, ...s } = { id, ...langSetting };
77
+ const { languageId: _languageId, locale: _locale, ...s } = langSetting;
77
78
  return s;
78
79
  })
79
- .reduce((langSetting, setting) => ({
80
- ...SpellSettings.mergeSettings(langSetting, setting),
81
- languageId,
82
- locale,
83
- }), {});
80
+ .reduce((langSetting, setting) => SpellSettings.mergeSettings(langSetting, setting), {});
81
+ ls.languageId = languageId;
82
+ ls.locale = locale;
83
+ return ls;
84
84
  }
85
85
  exports.calcSettingsForLanguage = calcSettingsForLanguage;
86
+ const cacheDoesLanguageSettingMatchLanguageId = new WeakMap();
86
87
  function doesLanguageSettingMatchLanguageId(s, languageId) {
88
+ var _a;
89
+ const r = (_a = cacheDoesLanguageSettingMatchLanguageId.get(s)) !== null && _a !== void 0 ? _a : new Map();
90
+ const f = r.get(languageId);
91
+ if (f !== undefined) {
92
+ return f;
93
+ }
94
+ const v = _doesLanguageSettingMatchLanguageId(s, languageId);
95
+ r.set(languageId, v);
96
+ cacheDoesLanguageSettingMatchLanguageId.set(s, r);
97
+ return v;
98
+ }
99
+ function _doesLanguageSettingMatchLanguageId(s, languageId) {
87
100
  const languageSettingsLanguageIds = s.languageId;
88
101
  if (!languageSettingsLanguageIds || languageSettingsLanguageIds === '*')
89
102
  return true;
@@ -96,13 +109,10 @@ function doesLanguageSettingMatchLanguageId(s, languageId) {
96
109
  return numExcludes === ids.size;
97
110
  }
98
111
  function calcUserSettingsForLanguage(settings, languageId) {
99
- const { languageSettings = [], language: locale = defaultLocale } = settings;
100
- const defaults = {
101
- allowCompoundWords: settings.allowCompoundWords,
102
- enabled: settings.enabled,
103
- };
112
+ const { languageSettings = [], language: locale = defaultLocale, allowCompoundWords, enabled } = settings;
104
113
  const langSettings = {
105
- ...defaults,
114
+ allowCompoundWords,
115
+ enabled,
106
116
  ...calcSettingsForLanguage(languageSettings, languageId, locale),
107
117
  };
108
118
  return SpellSettings.mergeSettings(settings, langSettings);
@@ -7,11 +7,11 @@ const createSpellingDictionary_1 = require("./createSpellingDictionary");
7
7
  const DictionaryLoader_1 = require("./DictionaryLoader");
8
8
  const SpellingDictionaryCollection_1 = require("./SpellingDictionaryCollection");
9
9
  function loadDictionaryDefs(defsToLoad) {
10
- return defsToLoad.map((def) => (0, DictionaryLoader_1.loadDictionary)(def.path, def));
10
+ return defsToLoad.map(DictionaryLoader_1.loadDictionary);
11
11
  }
12
12
  exports.loadDictionaryDefs = loadDictionaryDefs;
13
13
  function loadDictionaryDefsSync(defsToLoad) {
14
- return defsToLoad.map((def) => (0, DictionaryLoader_1.loadDictionarySync)(def.path, def));
14
+ return defsToLoad.map(DictionaryLoader_1.loadDictionarySync);
15
15
  }
16
16
  exports.loadDictionaryDefsSync = loadDictionaryDefsSync;
17
17
  function refreshDictionaryCache(maxAge) {
@@ -32,8 +32,8 @@ export interface SyncLoaders {
32
32
  W: LoaderSync;
33
33
  default: LoaderSync;
34
34
  }
35
- export declare function loadDictionary(uri: string, options: DictionaryDefinitionInternal): Promise<SpellingDictionary>;
36
- export declare function loadDictionarySync(uri: string, options: DictionaryDefinitionInternal): SpellingDictionary;
35
+ export declare function loadDictionary(def: DictionaryDefinitionInternal): Promise<SpellingDictionary>;
36
+ export declare function loadDictionarySync(def: DictionaryDefinitionInternal): SpellingDictionary;
37
37
  /**
38
38
  * Check to see if any of the cached dictionaries have changed. If one has changed, reload it.
39
39
  * @param maxAge - Only check the dictionary if it has been at least `maxAge` ms since the last check.
@@ -59,49 +59,50 @@ function __log(msg) {
59
59
  debugMode && debugLog.push(msg);
60
60
  }
61
61
  const dictionaryCache = new Map();
62
- function loadDictionary(uri, options) {
63
- const key = calcKey(uri, options);
62
+ const dictionaryCacheByDef = new Map();
63
+ function getCacheEntry(def) {
64
+ const defEntry = dictionaryCacheByDef.get(def);
65
+ if (defEntry) {
66
+ return defEntry;
67
+ }
68
+ const key = calcKey(def);
64
69
  const entry = dictionaryCache.get(key);
70
+ if (entry) {
71
+ // replace old entry so it can be released.
72
+ entry.options = def;
73
+ }
74
+ return { key, entry };
75
+ }
76
+ function setCacheEntry(key, entry, def) {
77
+ dictionaryCache.set(key, entry);
78
+ dictionaryCacheByDef.set(def, { key, entry });
79
+ }
80
+ function loadDictionary(def) {
81
+ const { key, entry } = getCacheEntry(def);
65
82
  if (entry) {
66
83
  return entry.pending.then(([dictionary]) => dictionary);
67
84
  }
68
- const loadedEntry = loadEntry(uri, options);
69
- dictionaryCache.set(key, loadedEntry);
85
+ const loadedEntry = loadEntry(def.path, def);
86
+ setCacheEntry(key, loadedEntry, def);
70
87
  return loadedEntry.pending.then(([dictionary]) => dictionary);
71
88
  }
72
89
  exports.loadDictionary = loadDictionary;
73
- function loadDictionarySync(uri, options) {
74
- const key = calcKey(uri, options);
75
- const entry = dictionaryCache.get(key);
90
+ function loadDictionarySync(def) {
91
+ const { key, entry } = getCacheEntry(def);
76
92
  if ((entry === null || entry === void 0 ? void 0 : entry.dictionary) && entry.loadingState === LoadingState.Loaded) {
77
- // if (entry.options.name === 'temp') {
78
- // __log(
79
- // `Cache Found ${entry.options.name}; ts: ${entry.sig.toFixed(2)}; file: ${path.relative(
80
- // process.cwd(),
81
- // entry.uri
82
- // )}`
83
- // );
84
- // }
85
93
  return entry.dictionary;
86
94
  }
87
- // if (options.name === 'temp') {
88
- // __log(
89
- // `Cache Miss ${options.name}; ts: ${entry?.sig.toFixed(2) || Date.now()}; file: ${path.relative(
90
- // process.cwd(),
91
- // uri
92
- // )}`
93
- // );
94
- // }
95
- const loadedEntry = loadEntrySync(uri, options);
96
- dictionaryCache.set(key, loadedEntry);
95
+ const loadedEntry = loadEntrySync(def.path, def);
96
+ setCacheEntry(key, loadedEntry, def);
97
97
  return loadedEntry.dictionary;
98
98
  }
99
99
  exports.loadDictionarySync = loadDictionarySync;
100
100
  const importantOptionKeys = ['name', 'noSuggest', 'useCompounds', 'type'];
101
- function calcKey(uri, options) {
102
- const loaderType = determineType(uri, options);
103
- const optValues = importantOptionKeys.map((k) => { var _a; return ((_a = options[k]) === null || _a === void 0 ? void 0 : _a.toString()) || ''; });
104
- const parts = [uri, loaderType].concat(optValues);
101
+ function calcKey(def) {
102
+ const path = def.path;
103
+ const loaderType = determineType(path, def);
104
+ const optValues = importantOptionKeys.map((k) => { var _a; return ((_a = def[k]) === null || _a === void 0 ? void 0 : _a.toString()) || ''; });
105
+ const parts = [path, loaderType].concat(optValues);
105
106
  return parts.join('|');
106
107
  }
107
108
  /**
@@ -136,7 +137,10 @@ async function refreshEntry(entry, maxAge, now) {
136
137
  // }
137
138
  if (sigMatches && hasChanged) {
138
139
  entry.loadingState = LoadingState.Loading;
139
- dictionaryCache.set(calcKey(entry.uri, entry.options), loadEntry(entry.uri, entry.options));
140
+ const key = calcKey(entry.options);
141
+ const newEntry = loadEntry(entry.uri, entry.options);
142
+ dictionaryCache.set(key, newEntry);
143
+ dictionaryCacheByDef.set(entry.options, { key, entry: newEntry });
140
144
  }
141
145
  }
142
146
  }
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ export * from '@cspell/cspell-types';
7
7
  export * from 'cspell-io';
8
8
  export { ExcludeFilesGlobMap, ExclusionFunction } from './exclusionHelper';
9
9
  export { getLanguagesForExt } from './LanguageIds';
10
- export { createTextDocument } from './Models/TextDocument';
10
+ export { createTextDocument, updateTextDocument } from './Models/TextDocument';
11
11
  export type { CreateTextDocumentParams, TextDocument, TextDocumentLine } from './Models/TextDocument';
12
12
  export * from './Settings';
13
13
  export { defaultFileName as defaultSettingsFilename } from './Settings';
package/dist/index.js CHANGED
@@ -26,7 +26,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
26
26
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.getDictionary = exports.clearCachedFiles = exports.ExclusionHelper = exports.Link = exports.Text = exports.validateText = exports.IncludeExcludeFlag = exports.checkText = exports.resolveFile = exports.setLogger = exports.getLogger = exports.traceWordsAsync = exports.traceWords = exports.DocumentValidator = exports.suggestionsForWords = exports.suggestionsForWord = exports.SuggestionError = exports.SpellingDictionaryLoadError = exports.SpellingDictionaryCollection = exports.refreshDictionaryCache = exports.isSpellingDictionaryLoadError = exports.createSpellingDictionary = exports.CompoundWordsMethod = exports.spellCheckFile = exports.spellCheckDocument = exports.isBinaryFile = exports.fileToDocument = exports.determineFinalDocumentSettings = exports.constructSettingsForText = exports.combineTextAndLanguageSettings = exports.defaultSettingsFilename = exports.createTextDocument = exports.getLanguagesForExt = void 0;
29
+ exports.getDictionary = exports.clearCachedFiles = exports.ExclusionHelper = exports.Link = exports.Text = exports.validateText = exports.IncludeExcludeFlag = exports.checkText = exports.resolveFile = exports.setLogger = exports.getLogger = exports.traceWordsAsync = exports.traceWords = exports.DocumentValidator = exports.suggestionsForWords = exports.suggestionsForWord = exports.SuggestionError = exports.SpellingDictionaryLoadError = exports.SpellingDictionaryCollection = exports.refreshDictionaryCache = exports.isSpellingDictionaryLoadError = exports.createSpellingDictionary = exports.CompoundWordsMethod = exports.spellCheckFile = exports.spellCheckDocument = exports.isBinaryFile = exports.fileToDocument = exports.determineFinalDocumentSettings = exports.constructSettingsForText = exports.combineTextAndLanguageSettings = exports.defaultSettingsFilename = exports.updateTextDocument = exports.createTextDocument = exports.getLanguagesForExt = void 0;
30
30
  const ExclusionHelper = __importStar(require("./exclusionHelper"));
31
31
  exports.ExclusionHelper = ExclusionHelper;
32
32
  const Settings_1 = require("./Settings");
@@ -42,6 +42,7 @@ var LanguageIds_1 = require("./LanguageIds");
42
42
  Object.defineProperty(exports, "getLanguagesForExt", { enumerable: true, get: function () { return LanguageIds_1.getLanguagesForExt; } });
43
43
  var TextDocument_1 = require("./Models/TextDocument");
44
44
  Object.defineProperty(exports, "createTextDocument", { enumerable: true, get: function () { return TextDocument_1.createTextDocument; } });
45
+ Object.defineProperty(exports, "updateTextDocument", { enumerable: true, get: function () { return TextDocument_1.updateTextDocument; } });
45
46
  __exportStar(require("./Settings"), exports);
46
47
  var Settings_2 = require("./Settings");
47
48
  Object.defineProperty(exports, "defaultSettingsFilename", { enumerable: true, get: function () { return Settings_2.defaultFileName; } });
@@ -26,6 +26,7 @@ export declare class DocumentValidator {
26
26
  private _prepared;
27
27
  private _preparations;
28
28
  private _preparationTime;
29
+ private _suggestions;
29
30
  /**
30
31
  * @param doc - Document to validate
31
32
  * @param config - configuration to use (not finalized).
@@ -35,15 +36,19 @@ export declare class DocumentValidator {
35
36
  prepareSync(): void;
36
37
  prepare(): Promise<void>;
37
38
  private _prepareAsync;
39
+ private _updatePrep;
38
40
  /**
39
41
  * The amount of time in ms to prepare for validation.
40
42
  */
41
43
  get prepTime(): number;
42
44
  checkText(range: SimpleRange, _text: string, _scope: string[]): ValidationIssue[];
43
45
  get document(): TextDocument;
46
+ updateDocumentText(text: string): void;
44
47
  private addPossibleError;
45
48
  private catchError;
46
49
  private errorCatcherWrapper;
50
+ private suggest;
51
+ private genSuggestions;
47
52
  }
48
53
  export declare type Offset = number;
49
54
  export declare type SimpleRange = readonly [Offset, Offset];
@@ -6,10 +6,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.DocumentValidator = void 0;
7
7
  const cspell_pipe_1 = require("@cspell/cspell-pipe");
8
8
  const assert_1 = __importDefault(require("assert"));
9
+ const TextDocument_1 = require("../Models/TextDocument");
9
10
  const Settings_1 = require("../Settings");
10
11
  const configLoader_1 = require("../Settings/configLoader");
11
12
  const SpellingDictionary_1 = require("../SpellingDictionary");
12
13
  const errors_1 = require("../util/errors");
14
+ const Memorizer_1 = require("../util/Memorizer");
15
+ const simpleCache_1 = require("../util/simpleCache");
13
16
  const timer_1 = require("../util/timer");
14
17
  const util_1 = require("../util/util");
15
18
  const determineTextDocumentSettings_1 = require("./determineTextDocumentSettings");
@@ -26,6 +29,7 @@ class DocumentValidator {
26
29
  this._ready = false;
27
30
  this.errors = [];
28
31
  this._preparationTime = -1;
32
+ this._suggestions = new simpleCache_1.AutoCache((text) => this.genSuggestions(text), 1000);
29
33
  this._document = doc;
30
34
  // console.error(`DocumentValidator: ${doc.uri}`);
31
35
  }
@@ -50,7 +54,7 @@ class DocumentValidator {
50
54
  ? this.errorCatcherWrapper(() => searchForDocumentConfigSync(this._document, settings, settings))
51
55
  : undefined;
52
56
  this.addPossibleError((_a = localConfig === null || localConfig === void 0 ? void 0 : localConfig.__importRef) === null || _a === void 0 ? void 0 : _a.error);
53
- const config = localConfig ? (0, Settings_1.mergeSettings)(settings, localConfig) : settings;
57
+ const config = (0, Settings_1.mergeSettings)(settings, localConfig);
54
58
  const docSettings = (0, determineTextDocumentSettings_1.determineTextDocumentSettings)(this._document, config);
55
59
  const dict = (0, SpellingDictionary_1.getDictionaryInternalSync)(docSettings);
56
60
  const shouldCheck = (_b = docSettings.enabled) !== null && _b !== void 0 ? _b : true;
@@ -60,6 +64,7 @@ class DocumentValidator {
60
64
  const segmenter = (0, textValidator_1.mapLineSegmentAgainstRangesFactory)(includeRanges);
61
65
  const lineValidator = (0, textValidator_1.lineValidatorFactory)(dict, validateOptions);
62
66
  this._preparations = {
67
+ config,
63
68
  dictionary: dict,
64
69
  docSettings,
65
70
  shouldCheck,
@@ -70,6 +75,7 @@ class DocumentValidator {
70
75
  };
71
76
  this._ready = true;
72
77
  this._preparationTime = timer.elapsed();
78
+ // console.error(`prepareSync ${this._preparationTime.toFixed(2)}ms`);
73
79
  }
74
80
  async prepare() {
75
81
  if (this._ready)
@@ -90,9 +96,9 @@ class DocumentValidator {
90
96
  : useSearchForConfig
91
97
  ? this.catchError(searchForDocumentConfig(this._document, settings, settings))
92
98
  : undefined;
93
- const localConfig = await pLocalConfig;
99
+ const localConfig = (await pLocalConfig) || {};
94
100
  this.addPossibleError((_a = localConfig === null || localConfig === void 0 ? void 0 : localConfig.__importRef) === null || _a === void 0 ? void 0 : _a.error);
95
- const config = localConfig ? (0, Settings_1.mergeSettings)(settings, localConfig) : settings;
101
+ const config = (0, Settings_1.mergeSettings)(settings, localConfig);
96
102
  const docSettings = (0, determineTextDocumentSettings_1.determineTextDocumentSettings)(this._document, config);
97
103
  const dict = await (0, SpellingDictionary_1.getDictionaryInternal)(docSettings);
98
104
  const shouldCheck = (_b = docSettings.enabled) !== null && _b !== void 0 ? _b : true;
@@ -102,6 +108,7 @@ class DocumentValidator {
102
108
  const segmenter = (0, textValidator_1.mapLineSegmentAgainstRangesFactory)(includeRanges);
103
109
  const lineValidator = (0, textValidator_1.lineValidatorFactory)(dict, validateOptions);
104
110
  this._preparations = {
111
+ config,
105
112
  dictionary: dict,
106
113
  docSettings,
107
114
  shouldCheck,
@@ -113,6 +120,31 @@ class DocumentValidator {
113
120
  this._ready = true;
114
121
  this._preparationTime = timer.elapsed();
115
122
  }
123
+ _updatePrep() {
124
+ var _a;
125
+ (0, assert_1.default)(this._preparations);
126
+ const timer = (0, timer_1.createTimer)();
127
+ const { config } = this._preparations;
128
+ const docSettings = (0, determineTextDocumentSettings_1.determineTextDocumentSettings)(this._document, config);
129
+ const dict = (0, SpellingDictionary_1.getDictionaryInternalSync)(docSettings);
130
+ const shouldCheck = (_a = docSettings.enabled) !== null && _a !== void 0 ? _a : true;
131
+ const finalSettings = (0, Settings_1.finalizeSettings)(docSettings);
132
+ const validateOptions = (0, validator_1.settingsToValidateOptions)(finalSettings);
133
+ const includeRanges = (0, textValidator_1.calcTextInclusionRanges)(this._document.text, validateOptions);
134
+ const segmenter = (0, textValidator_1.mapLineSegmentAgainstRangesFactory)(includeRanges);
135
+ const lineValidator = (0, textValidator_1.lineValidatorFactory)(dict, validateOptions);
136
+ this._preparations = {
137
+ config,
138
+ dictionary: dict,
139
+ docSettings,
140
+ shouldCheck,
141
+ validateOptions,
142
+ includeRanges,
143
+ segmenter,
144
+ lineValidator,
145
+ };
146
+ this._preparationTime = timer.elapsed();
147
+ }
116
148
  /**
117
149
  * The amount of time in ms to prepare for validation.
118
150
  */
@@ -120,7 +152,6 @@ class DocumentValidator {
120
152
  return this._preparationTime;
121
153
  }
122
154
  checkText(range, _text, _scope) {
123
- var _a;
124
155
  (0, assert_1.default)(this._ready);
125
156
  (0, assert_1.default)(this._preparations);
126
157
  const { segmenter, lineValidator } = this._preparations;
@@ -143,25 +174,21 @@ class DocumentValidator {
143
174
  if (!this.options.generateSuggestions) {
144
175
  return issues;
145
176
  }
146
- const settings = this._preparations.docSettings;
147
- const dict = this._preparations.dictionary;
148
- const sugOptions = (0, util_1.clean)({
149
- compoundMethod: 0,
150
- numSuggestions: this.options.numSuggestions,
151
- includeTies: false,
152
- ignoreCase: !((_a = settings.caseSensitive) !== null && _a !== void 0 ? _a : false),
153
- timeout: settings.suggestionsTimeout,
154
- numChanges: settings.suggestionNumChanges,
155
- });
156
177
  const withSugs = issues.map((t) => {
157
- const suggestions = dict.suggest(t.text, sugOptions).map((r) => r.word);
158
- return { ...t, suggestions };
178
+ // lazy suggestion calculation.
179
+ const text = t.text;
180
+ const suggestions = (0, Memorizer_1.callOnce)(() => this.suggest(text));
181
+ return Object.defineProperty({ ...t }, 'suggestions', { enumerable: true, get: suggestions });
159
182
  });
160
183
  return withSugs;
161
184
  }
162
185
  get document() {
163
186
  return this._document;
164
187
  }
188
+ updateDocumentText(text) {
189
+ (0, TextDocument_1.updateTextDocument)(this._document, [{ text }]);
190
+ this._updatePrep();
191
+ }
165
192
  addPossibleError(error) {
166
193
  if (!error)
167
194
  return;
@@ -182,6 +209,24 @@ class DocumentValidator {
182
209
  }
183
210
  return undefined;
184
211
  }
212
+ suggest(text) {
213
+ return this._suggestions.get(text);
214
+ }
215
+ genSuggestions(text) {
216
+ var _a;
217
+ (0, assert_1.default)(this._preparations);
218
+ const settings = this._preparations.docSettings;
219
+ const dict = this._preparations.dictionary;
220
+ const sugOptions = (0, util_1.clean)({
221
+ compoundMethod: 0,
222
+ numSuggestions: this.options.numSuggestions,
223
+ includeTies: false,
224
+ ignoreCase: !((_a = settings.caseSensitive) !== null && _a !== void 0 ? _a : false),
225
+ timeout: settings.suggestionsTimeout,
226
+ numChanges: settings.suggestionNumChanges,
227
+ });
228
+ return dict.suggest(text, sugOptions).map((r) => r.word);
229
+ }
185
230
  }
186
231
  exports.DocumentValidator = DocumentValidator;
187
232
  async function searchForDocumentConfig(document, defaultConfig, pnpSettings) {
@@ -26,6 +26,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.checkText = exports.IncludeExcludeFlag = exports.settingsToValidateOptions = exports.validateText = exports.diagSource = void 0;
27
27
  const Settings = __importStar(require("../Settings"));
28
28
  const SpellingDictionary_1 = require("../SpellingDictionary");
29
+ const Memorizer_1 = require("../util/Memorizer");
29
30
  const util_1 = require("../util/util");
30
31
  const textValidator_1 = require("./textValidator");
31
32
  exports.diagSource = 'cSpell Checker';
@@ -46,8 +47,10 @@ async function validateText(text, settings, options = {}) {
46
47
  numChanges: settings.suggestionNumChanges,
47
48
  });
48
49
  const withSugs = issues.map((t) => {
49
- const suggestions = dict.suggest(t.text, sugOptions).map((r) => r.word);
50
- return { ...t, suggestions };
50
+ const text = t.text;
51
+ // lazy suggestion calculation.
52
+ const suggestions = (0, Memorizer_1.callOnce)(() => dict.suggest(text, sugOptions).map((r) => r.word));
53
+ return Object.defineProperty({ ...t }, 'suggestions', { enumerable: true, get: suggestions });
51
54
  });
52
55
  return withSugs;
53
56
  }
package/dist/trace.js CHANGED
@@ -26,6 +26,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.traceWordsAsync = exports.traceWords = void 0;
27
27
  const gensequence_1 = require("gensequence");
28
28
  const Settings_1 = require("./Settings");
29
+ const CSpellSettingsServer_1 = require("./Settings/CSpellSettingsServer");
29
30
  const LanguageSettings_1 = require("./Settings/LanguageSettings");
30
31
  const SpellingDictionary_1 = require("./SpellingDictionary");
31
32
  const util = __importStar(require("./util/util"));
@@ -50,7 +51,7 @@ async function* traceWordsAsync(words, settings, options) {
50
51
  const dictionaries = (settings.dictionaries || [])
51
52
  .concat((settings.dictionaryDefinitions || []).map((d) => d.name))
52
53
  .filter(util.uniqueFn);
53
- const dictSettings = { ...settings, dictionaries };
54
+ const dictSettings = (0, CSpellSettingsServer_1.toInternalSettings)({ ...settings, dictionaries });
54
55
  const dictBase = await (0, SpellingDictionary_1.getDictionaryInternal)(settings);
55
56
  const dicts = await (0, SpellingDictionary_1.getDictionaryInternal)(dictSettings);
56
57
  const activeDictionaries = dictBase.dictionaries.map((d) => d.name);
@@ -41,10 +41,18 @@ export declare function memorizerKeyBy<F extends (...args: any[]) => any, Args e
41
41
  * @param fn - function to memorize
42
42
  * @returns a new function.
43
43
  */
44
+ export declare function memorizeLastCall<T>(fn: (...p: []) => T): (...p: []) => T;
44
45
  export declare function memorizeLastCall<T, K0>(fn: (...p: [K0]) => T): (...p: [K0]) => T;
45
46
  export declare function memorizeLastCall<T, K0, K1>(fn: (...p: [K0, K1]) => T): (...p: [K0, K1]) => T;
46
47
  export declare function memorizeLastCall<T, K0, K1, K2>(fn: (...p: [K0, K1, K2]) => T): (...p: [K0, K1, K2]) => T;
47
48
  export declare function memorizeLastCall<T, K0, K1, K2, K3>(fn: (...p: [K0, K1, K2, K3]) => T): (...p: [K0, K1, K2, K3]) => T;
48
49
  export declare function memorizeLastCall<T, K>(fn: (...p: [...K[]]) => T): (...p: [...K[]]) => T;
50
+ /**
51
+ * calls a function exactly once and always returns the same value.
52
+ * @param fn - function to call
53
+ * @returns a new function
54
+ */
55
+ export declare function callOnce<T>(fn: () => T): () => T;
56
+ export declare function memorizerAll<K extends any[], T>(fn: (...p: K) => T): (...p: K) => T;
49
57
  export {};
50
58
  //# sourceMappingURL=Memorizer.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.memorizeLastCall = exports.memorizerKeyBy = exports.memorizer = void 0;
3
+ exports.memorizerAll = exports.callOnce = exports.memorizeLastCall = exports.memorizerKeyBy = exports.memorizer = void 0;
4
4
  const util_1 = require("./util");
5
5
  /* eslint-disable @typescript-eslint/no-explicit-any */
6
6
  const defaultSize = 50000;
@@ -73,4 +73,62 @@ function memorizeLastCall(fn) {
73
73
  };
74
74
  }
75
75
  exports.memorizeLastCall = memorizeLastCall;
76
+ /**
77
+ * calls a function exactly once and always returns the same value.
78
+ * @param fn - function to call
79
+ * @returns a new function
80
+ */
81
+ function callOnce(fn) {
82
+ let last;
83
+ return () => {
84
+ if (last) {
85
+ return last.value;
86
+ }
87
+ last = {
88
+ value: fn(),
89
+ };
90
+ return last.value;
91
+ };
92
+ }
93
+ exports.callOnce = callOnce;
94
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
95
+ function memorizerAll(fn) {
96
+ const r = {};
97
+ function find(p) {
98
+ var _a;
99
+ let n = r;
100
+ for (const k of p) {
101
+ if (!n)
102
+ break;
103
+ n = (_a = n.c) === null || _a === void 0 ? void 0 : _a.get(k);
104
+ }
105
+ return n;
106
+ }
107
+ function set(p, v) {
108
+ var _a;
109
+ let n = r;
110
+ for (const k of p) {
111
+ const c = (_a = n.c) === null || _a === void 0 ? void 0 : _a.get(k);
112
+ if (c) {
113
+ n = c;
114
+ continue;
115
+ }
116
+ const r = {};
117
+ n.c = n.c || new Map();
118
+ n.c.set(k, r);
119
+ n = r;
120
+ }
121
+ n.v = v;
122
+ }
123
+ return (...p) => {
124
+ const f = find(p);
125
+ if (f && 'v' in f) {
126
+ return f.v;
127
+ }
128
+ const v = fn(...p);
129
+ set(p, v);
130
+ return v;
131
+ };
132
+ }
133
+ exports.memorizerAll = memorizerAll;
76
134
  //# sourceMappingURL=Memorizer.js.map
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Measure and log result.
3
+ * @param fn - function to measure.
4
+ * @param message - message to log
5
+ * @param callback - called when the function has finished.
6
+ * @returns a function
7
+ */
8
+ export declare function perfFn<P extends any[], R>(fn: (...args: P) => R, message: string, callback?: (m: string, elapsedMs: number) => void): (...args: P) => R;
9
+ //# sourceMappingURL=debugPerf.d.ts.map
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.perfFn = void 0;
4
+ const timer_1 = require("./timer");
5
+ /**
6
+ * Measure and log result.
7
+ * @param fn - function to measure.
8
+ * @param message - message to log
9
+ * @param callback - called when the function has finished.
10
+ * @returns a function
11
+ */
12
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
13
+ function perfFn(fn, message, callback = (message, time) => console.error(`${message}: ${time.toFixed(2)}ms`)) {
14
+ return (...args) => {
15
+ const timer = (0, timer_1.createTimer)();
16
+ const r = fn(...args);
17
+ callback(message, timer.elapsed());
18
+ return r;
19
+ };
20
+ }
21
+ exports.perfFn = perfFn;
22
+ //# sourceMappingURL=debugPerf.js.map
@@ -7,7 +7,8 @@ export declare class SimpleWeakCache<K extends object, T> {
7
7
  constructor(size: number);
8
8
  has(key: K): boolean;
9
9
  get(key: K): T | undefined;
10
- set(key: K, value: T): this | undefined;
10
+ set(key: K, value: T): void;
11
+ private _set;
11
12
  private caches;
12
13
  private rotate;
13
14
  }
@@ -32,7 +33,8 @@ export declare class SimpleCache<K, T> {
32
33
  constructor(size: number);
33
34
  has(key: K): boolean;
34
35
  get(key: K): T | undefined;
35
- set(key: K, value: T): this | undefined;
36
+ set(key: K, value: T): void;
37
+ private _set;
36
38
  private caches;
37
39
  private rotate;
38
40
  }
@@ -18,27 +18,29 @@ class SimpleWeakCache {
18
18
  }
19
19
  get(key) {
20
20
  for (const c of this.caches()) {
21
- if (c.has(key)) {
22
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
23
- const v = c.get(key);
21
+ const entry = c.get(key);
22
+ if (entry) {
24
23
  if (c !== this.L0) {
25
- this.set(key, v);
24
+ this._set(key, entry);
26
25
  }
27
- return v;
26
+ return entry.v;
28
27
  }
29
28
  }
30
29
  return undefined;
31
30
  }
32
31
  set(key, value) {
32
+ this._set(key, { v: value });
33
+ }
34
+ _set(key, entry) {
33
35
  if (this.L0.has(key)) {
34
- this.L0.set(key, value);
36
+ this.L0.set(key, entry);
35
37
  return this;
36
38
  }
37
39
  if (this.sizeL0 >= this.size) {
38
40
  this.rotate();
39
41
  }
40
42
  this.sizeL0 += 1;
41
- this.L0.set(key, value);
43
+ this.L0.set(key, entry);
42
44
  }
43
45
  caches() {
44
46
  return [this.L0, this.L1, this.L2];
@@ -90,32 +92,33 @@ class SimpleCache {
90
92
  }
91
93
  get(key) {
92
94
  for (const c of this.caches()) {
93
- if (c.has(key)) {
94
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
95
- const v = c.get(key);
95
+ const entry = c.get(key);
96
+ if (entry) {
96
97
  if (c !== this.L0) {
97
- this.set(key, v);
98
+ this._set(key, entry);
98
99
  }
99
- return v;
100
+ return entry.v;
100
101
  }
101
102
  }
102
103
  return undefined;
103
104
  }
104
105
  set(key, value) {
106
+ this._set(key, { v: value });
107
+ }
108
+ _set(key, entry) {
105
109
  if (this.L0.has(key)) {
106
- this.L0.set(key, value);
110
+ this.L0.set(key, entry);
107
111
  return this;
108
112
  }
109
113
  if (this.L0.size >= this.size) {
110
114
  this.rotate();
111
115
  }
112
- this.L0.set(key, value);
116
+ this.L0.set(key, entry);
113
117
  }
114
118
  caches() {
115
119
  return [this.L0, this.L1, this.L2];
116
120
  }
117
121
  rotate() {
118
- this.L2.clear();
119
122
  this.L2 = this.L1;
120
123
  this.L1 = this.L0;
121
124
  this.L0 = new Map();
@@ -6,10 +6,21 @@ export interface Timer {
6
6
  * timer was created / started.
7
7
  */
8
8
  elapsed(): number;
9
+ /**
10
+ * Calculate the amount of time in ms since the
11
+ * end of the last lap.
12
+ */
13
+ lap(): number;
9
14
  }
10
15
  export declare function createTimer(hrTimeFn?: HRTimeFn): Timer;
11
16
  export declare type HRTimeFn = (time?: HRTime) => HRTime;
12
17
  export declare type HRTime = [number, number];
13
18
  export declare function toMilliseconds(t: HRTime): number;
14
19
  export declare function polyHrTime(time?: HRTime): HRTime;
20
+ export interface LapRecorder {
21
+ times: [name: string, lapTime: number, totalTime: number][];
22
+ lap(name: string): void;
23
+ report(): string[];
24
+ }
25
+ export declare function createLapRecorder(): LapRecorder;
15
26
  //# sourceMappingURL=timer.d.ts.map
@@ -1,15 +1,24 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.polyHrTime = exports.toMilliseconds = exports.createTimer = void 0;
3
+ exports.createLapRecorder = exports.polyHrTime = exports.toMilliseconds = exports.createTimer = void 0;
4
4
  const _hrTime = (process === null || process === void 0 ? void 0 : process.hrtime) || polyHrTime;
5
5
  function createTimer(hrTimeFn = _hrTime) {
6
6
  let start = hrTimeFn();
7
+ let lastLap = 0;
8
+ function elapsed() {
9
+ return toMilliseconds(hrTimeFn(start));
10
+ }
7
11
  return {
8
12
  start() {
9
13
  start = hrTimeFn();
14
+ lastLap = 0;
10
15
  },
11
- elapsed() {
12
- return toMilliseconds(hrTimeFn(start));
16
+ elapsed,
17
+ lap() {
18
+ const now = elapsed();
19
+ const diff = now - lastLap;
20
+ lastLap = now;
21
+ return diff;
13
22
  },
14
23
  };
15
24
  }
@@ -26,4 +35,24 @@ function polyHrTime(time) {
26
35
  return [s, n];
27
36
  }
28
37
  exports.polyHrTime = polyHrTime;
38
+ function createLapRecorder() {
39
+ const timer = createTimer();
40
+ const times = [];
41
+ let lapTime = 0;
42
+ function lap(name) {
43
+ const now = timer.elapsed();
44
+ const diff = now - lapTime;
45
+ times.push([name, diff, now]);
46
+ lapTime = diff;
47
+ }
48
+ function report() {
49
+ return times.map(([name, time]) => `${name}: ${time.toFixed(2)}`);
50
+ }
51
+ return {
52
+ times,
53
+ lap,
54
+ report,
55
+ };
56
+ }
57
+ exports.createLapRecorder = createLapRecorder;
29
58
  //# sourceMappingURL=timer.js.map
@@ -24,4 +24,11 @@ export declare function asyncIterableToArray<T>(iter: Iterable<T> | AsyncIterabl
24
24
  * @returns true if the values of `a` are exactly equal to the values of `b`
25
25
  */
26
26
  export declare function isArrayEqual<K>(a: K[], b: K[]): boolean;
27
+ /**
28
+ * Determine if two sets intersect
29
+ * @param a - first Set
30
+ * @param b - second Set
31
+ * @returns true iff any element of `a` is in `b`
32
+ */
33
+ export declare function doSetsIntersect<T>(a: Set<T>, b: Set<T>): boolean;
27
34
  //# sourceMappingURL=util.d.ts.map
package/dist/util/util.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isArrayEqual = exports.asyncIterableToArray = exports.flatten = exports.flattenIterable = exports.isDefined = exports.scanMap = exports.clean = exports.unique = exports.uniqueFilterFnGenerator = exports.uniqueFn = void 0;
3
+ exports.doSetsIntersect = exports.isArrayEqual = exports.asyncIterableToArray = exports.flatten = exports.flattenIterable = exports.isDefined = exports.scanMap = exports.clean = exports.unique = exports.uniqueFilterFnGenerator = exports.uniqueFn = void 0;
4
4
  // alias for uniqueFilterFnGenerator
5
5
  exports.uniqueFn = uniqueFilterFnGenerator;
6
6
  function uniqueFilterFnGenerator(extractFn) {
@@ -84,4 +84,21 @@ function isArrayEqual(a, b) {
84
84
  return isMatch;
85
85
  }
86
86
  exports.isArrayEqual = isArrayEqual;
87
+ /**
88
+ * Determine if two sets intersect
89
+ * @param a - first Set
90
+ * @param b - second Set
91
+ * @returns true iff any element of `a` is in `b`
92
+ */
93
+ function doSetsIntersect(a, b) {
94
+ function compare(a, b) {
95
+ for (const item of a) {
96
+ if (b.has(item))
97
+ return true;
98
+ }
99
+ return false;
100
+ }
101
+ return a.size <= b.size ? compare(a, b) : compare(b, a);
102
+ }
103
+ exports.doSetsIntersect = doSetsIntersect;
87
104
  //# sourceMappingURL=util.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cspell-lib",
3
- "version": "5.19.2",
3
+ "version": "5.19.3",
4
4
  "description": "A library of useful functions used across various cspell tools.",
5
5
  "main": "dist/index.js",
6
6
  "typings": "dist/index.d.ts",
@@ -48,16 +48,16 @@
48
48
  },
49
49
  "homepage": "https://github.com/streetsidesoftware/cspell#readme",
50
50
  "dependencies": {
51
- "@cspell/cspell-bundled-dicts": "^5.19.2",
52
- "@cspell/cspell-pipe": "^5.19.2",
53
- "@cspell/cspell-types": "^5.19.2",
51
+ "@cspell/cspell-bundled-dicts": "^5.19.3",
52
+ "@cspell/cspell-pipe": "^5.19.3",
53
+ "@cspell/cspell-types": "^5.19.3",
54
54
  "clear-module": "^4.1.2",
55
55
  "comment-json": "^4.2.2",
56
56
  "configstore": "^5.0.1",
57
57
  "cosmiconfig": "^7.0.1",
58
- "cspell-glob": "^5.19.2",
59
- "cspell-io": "^5.19.2",
60
- "cspell-trie-lib": "^5.19.2",
58
+ "cspell-glob": "^5.19.3",
59
+ "cspell-io": "^5.19.3",
60
+ "cspell-trie-lib": "^5.19.3",
61
61
  "fast-equals": "^3.0.0",
62
62
  "find-up": "^5.0.0",
63
63
  "fs-extra": "^10.0.1",
@@ -83,14 +83,14 @@
83
83
  "@types/configstore": "^5.0.1",
84
84
  "@types/fs-extra": "^9.0.13",
85
85
  "@types/jest": "^27.4.1",
86
- "@types/node": "^17.0.21",
86
+ "@types/node": "^17.0.22",
87
87
  "cspell-dict-nl-nl": "^1.1.2",
88
88
  "jest": "^27.5.1",
89
89
  "lorem-ipsum": "^2.0.4",
90
90
  "rimraf": "^3.0.2",
91
- "rollup": "^2.70.0",
91
+ "rollup": "^2.70.1",
92
92
  "rollup-plugin-dts": "^4.2.0",
93
93
  "ts-jest": "^27.1.3"
94
94
  },
95
- "gitHead": "6540cb9f716993c554dc50dd54dd76d553f8f5e4"
95
+ "gitHead": "df43735d8f85fddbbd0befca7d98956f50474ce7"
96
96
  }