/
DictionaryLoader.ts
396 lines (347 loc) · 12.5 KB
/
DictionaryLoader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import type { DictionaryFileTypes } from '@cspell/cspell-types';
import { promises as fs, statSync } from 'fs';
import { genSequence } from 'gensequence';
import * as path from 'path';
import { format } from 'util';
import { DictionaryDefinitionInternal } from '../Models/CSpellSettingsInternalDef';
import { isErrnoException } from '../util/errors';
import { readLines, readLinesSync } from '../util/fileReader';
import { createFailedToLoadDictionary, createSpellingDictionary } from './createSpellingDictionary';
import { SpellingDictionary } from './SpellingDictionary';
import { SpellingDictionaryLoadError } from './SpellingDictionaryError';
import { createSpellingDictionaryTrie } from './SpellingDictionaryFromTrie';
const MAX_AGE = 10000;
const loaders: Loaders = {
S: loadSimpleWordList,
C: legacyWordList,
W: wordsPerLineWordList,
T: loadTrie,
default: loadSimpleWordList,
};
const loadersSync: SyncLoaders = {
S: loadSimpleWordListSync,
C: legacyWordListSync,
W: wordsPerLineWordListSync,
T: loadTrieSync,
default: loadSimpleWordListSync,
};
export type LoadOptions = DictionaryDefinitionInternal;
enum LoadingState {
Loaded = 0,
Loading = 1,
}
interface CacheEntry {
uri: string;
options: LoadOptions;
ts: number;
stat: Stats | Error | undefined;
dictionary: SpellingDictionary | undefined;
pending: Promise<readonly [SpellingDictionary, Stats | Error]>;
loadingState: LoadingState;
sig: number;
}
interface CacheEntrySync extends CacheEntry {
dictionary: SpellingDictionary;
}
const debugLog: string[] = [];
const debugMode = false;
function __log(msg: string): void {
debugMode && debugLog.push(msg);
}
export type LoaderType = keyof Loaders;
export type Loader = (filename: string, options: LoadOptions) => Promise<SpellingDictionary>;
export type LoaderSync = (filename: string, options: LoadOptions) => SpellingDictionary;
export interface Loaders {
S: Loader;
C: Loader;
T: Loader;
W: Loader;
default: Loader;
}
export interface SyncLoaders {
S: LoaderSync;
C: LoaderSync;
T: LoaderSync;
W: LoaderSync;
default: LoaderSync;
}
const dictionaryCache = new Map<string, CacheEntry>();
const dictionaryCacheByDef = new Map<DictionaryDefinitionInternal, { key: string; entry: CacheEntry }>();
function getCacheEntry(def: DictionaryDefinitionInternal): { key: string; entry: CacheEntry | undefined } {
const defEntry = dictionaryCacheByDef.get(def);
if (defEntry) {
return defEntry;
}
const key = calcKey(def);
const entry = dictionaryCache.get(key);
if (entry) {
// replace old entry so it can be released.
entry.options = def;
}
return { key, entry };
}
function setCacheEntry(key: string, entry: CacheEntry, def: DictionaryDefinitionInternal) {
dictionaryCache.set(key, entry);
dictionaryCacheByDef.set(def, { key, entry });
}
export function loadDictionary(def: DictionaryDefinitionInternal): Promise<SpellingDictionary> {
const { key, entry } = getCacheEntry(def);
if (entry) {
return entry.pending.then(([dictionary]) => dictionary);
}
const loadedEntry = loadEntry(def.path, def);
setCacheEntry(key, loadedEntry, def);
return loadedEntry.pending.then(([dictionary]) => dictionary);
}
export function loadDictionarySync(def: DictionaryDefinitionInternal): SpellingDictionary {
const { key, entry } = getCacheEntry(def);
if (entry?.dictionary && entry.loadingState === LoadingState.Loaded) {
return entry.dictionary;
}
const loadedEntry = loadEntrySync(def.path, def);
setCacheEntry(key, loadedEntry, def);
return loadedEntry.dictionary;
}
const importantOptionKeys: (keyof DictionaryDefinitionInternal)[] = ['name', 'noSuggest', 'useCompounds', 'type'];
function calcKey(def: DictionaryDefinitionInternal) {
const path = def.path;
const loaderType = determineType(path, def);
const optValues = importantOptionKeys.map((k) => def[k]?.toString() || '');
const parts = [path, loaderType].concat(optValues);
return parts.join('|');
}
/**
* Check to see if any of the cached dictionaries have changed. If one has changed, reload it.
* @param maxAge - Only check the dictionary if it has been at least `maxAge` ms since the last check.
* @param now - optional timestamp representing now. (Mostly used in testing)
*/
export async function refreshCacheEntries(maxAge = MAX_AGE, now = Date.now()): Promise<void> {
await Promise.all([...dictionaryCache.values()].map((entry) => refreshEntry(entry, maxAge, now)));
}
async function refreshEntry(entry: CacheEntry, maxAge: number, now: number): Promise<void> {
if (now - entry.ts >= maxAge) {
const sig = now + Math.random();
// Write to the ts, so the next one will not do it.
entry.sig = sig;
entry.ts = now;
const pStat = getStat(entry.uri);
const [newStat] = await Promise.all([pStat, entry.pending]);
const hasChanged = !isEqual(newStat, entry.stat);
const sigMatches = entry.sig === sig;
// if (entry.options.name === 'temp') {
// const processedAt = Date.now();
// __log(
// `Refresh ${entry.options.name}; sig: ${sig.toFixed(
// 2
// )} at ${processedAt}; Sig Matches: ${sigMatches.toString()}; changed: ${hasChanged.toString()}; file: ${path.relative(
// process.cwd(),
// entry.uri
// )}`
// );
// }
if (sigMatches && hasChanged) {
entry.loadingState = LoadingState.Loading;
const key = calcKey(entry.options);
const newEntry = loadEntry(entry.uri, entry.options);
dictionaryCache.set(key, newEntry);
dictionaryCacheByDef.set(entry.options, { key, entry: newEntry });
}
}
}
type StatsOrError = Stats | Error;
function isEqual(a: StatsOrError, b: StatsOrError | undefined): boolean {
if (!b) return false;
if (isError(a)) {
return isError(b) && a.message === b.message && a.name === b.name;
}
return !isError(b) && (a.mtimeMs === b.mtimeMs || a.size === b.size);
}
function isError(e: StatsOrError): e is Error {
const err = e as Partial<Error>;
return !!err.message;
}
function loadEntry(uri: string, options: LoadOptions, now = Date.now()): CacheEntry {
const pDictionary = load(uri, options).catch((e) =>
createFailedToLoadDictionary(new SpellingDictionaryLoadError(uri, options, e, 'failed to load'))
);
const pStat = getStat(uri);
const pending = Promise.all([pDictionary, pStat]);
const sig = now + Math.random();
const entry: CacheEntry = {
uri,
options,
ts: now,
stat: undefined,
dictionary: undefined,
pending,
loadingState: LoadingState.Loading,
sig,
};
// eslint-disable-next-line promise/catch-or-return
pending.then(([dictionary, stat]) => {
entry.stat = stat;
entry.dictionary = dictionary;
entry.loadingState = LoadingState.Loaded;
return;
});
return entry;
}
function loadEntrySync(uri: string, options: LoadOptions, now = Date.now()): CacheEntrySync {
const stat = getStatSync(uri);
const sig = now + Math.random();
try {
const dictionary = loadSync(uri, options);
const pending = Promise.resolve([dictionary, stat] as const);
return {
uri,
options,
ts: now,
stat,
dictionary,
pending,
loadingState: LoadingState.Loaded,
sig,
};
} catch (e) {
const error = e instanceof Error ? e : new Error(format(e));
const dictionary = createFailedToLoadDictionary(
new SpellingDictionaryLoadError(uri, options, error, 'failed to load')
);
const pending = Promise.resolve([dictionary, stat] as const);
return {
uri,
options,
ts: now,
stat,
dictionary,
pending,
loadingState: LoadingState.Loaded,
sig,
};
}
}
function determineType(uri: string, opts: Pick<LoadOptions, 'type'>): LoaderType {
const t: DictionaryFileTypes = (opts.type && opts.type in loaders && opts.type) || 'S';
const defLoaderType: LoaderType = t;
const defType = uri.endsWith('.trie.gz') ? 'T' : defLoaderType;
const regTrieTest = /\.trie\b/i;
return regTrieTest.test(uri) ? 'T' : defType;
}
function load(uri: string, options: LoadOptions): Promise<SpellingDictionary> {
const type = determineType(uri, options);
const loader = loaders[type] || loaders.default;
return loader(uri, options);
}
function loadSync(uri: string, options: LoadOptions): SpellingDictionary {
const type = determineType(uri, options);
const loader = loadersSync[type] || loaders.default;
return loader(uri, options);
}
async function legacyWordList(filename: string, options: LoadOptions) {
const lines = await readLines(filename);
return _legacyWordListSync(lines, filename, options);
}
function legacyWordListSync(filename: string, options: LoadOptions) {
const lines = readLinesSync(filename);
return _legacyWordListSync(lines, filename, options);
}
function _legacyWordListSync(lines: Iterable<string>, filename: string, options: LoadOptions) {
const words = genSequence(lines)
// Remove comments
.map((line) => line.replace(/#.*/g, ''))
// Split on everything else
.concatMap((line) => line.split(/[^\w\p{L}\p{M}'’]+/gu))
.filter((word) => !!word);
return createSpellingDictionary(words, determineName(filename, options), filename, options);
}
async function wordsPerLineWordList(filename: string, options: LoadOptions) {
const lines = await readLines(filename);
return _wordsPerLineWordList(lines, filename, options);
}
function wordsPerLineWordListSync(filename: string, options: LoadOptions) {
const lines = readLinesSync(filename);
return _wordsPerLineWordList(lines, filename, options);
}
function _wordsPerLineWordList(lines: Iterable<string>, filename: string, options: LoadOptions) {
const words = genSequence(lines)
// Remove comments
.map((line) => line.replace(/#.*/g, ''))
// Split on everything else
.concatMap((line) => line.split(/\s+/gu))
.filter((word) => !!word);
return createSpellingDictionary(words, determineName(filename, options), filename, options);
}
async function loadSimpleWordList(filename: string, options: LoadOptions) {
const lines = await readLines(filename);
return createSpellingDictionary(lines, determineName(filename, options), filename, options);
}
function loadSimpleWordListSync(filename: string, options: LoadOptions) {
const lines = readLinesSync(filename);
return createSpellingDictionary(lines, determineName(filename, options), filename, options);
}
async function loadTrie(filename: string, options: LoadOptions) {
const lines = await readLines(filename);
return createSpellingDictionaryTrie(lines, determineName(filename, options), filename, options);
}
function loadTrieSync(filename: string, options: LoadOptions) {
const lines = readLinesSync(filename);
return createSpellingDictionaryTrie(lines, determineName(filename, options), filename, options);
}
function determineName(filename: string, options: LoadOptions): string {
return options.name || path.basename(filename);
}
export const testing = {
dictionaryCache,
refreshEntry,
loadEntry,
load,
};
function toError(e: unknown): Error {
if (isErrnoException(e)) return e;
if (e instanceof Error) return e;
return new Error(format(e));
}
/**
* Copied from the Node definition to avoid a dependency upon a specific version of Node
*/
interface StatsBase<T> {
isFile(): boolean;
isDirectory(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
dev: T;
ino: T;
mode: T;
nlink: T;
uid: T;
gid: T;
rdev: T;
size: T;
blksize: T;
blocks: T;
atimeMs: T;
mtimeMs: T;
ctimeMs: T;
birthtimeMs: T;
atime: Date;
mtime: Date;
ctime: Date;
birthtime: Date;
}
function getStat(uri: string): Promise<Stats | Error> {
return fs.stat(uri).catch((e) => toError(e));
}
function getStatSync(uri: string): Stats | Error {
try {
return statSync(uri);
} catch (e) {
return toError(e);
}
}
export type Stats = StatsBase<number>;
export const __testing__ = {
debugLog,
};