cspell-lib 10.4.0-alpha.1 → 10.4.1

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.
package/README.md CHANGED
@@ -10,7 +10,7 @@ If our spell checkers save you time, please consider supporting their developmen
10
10
 
11
11
  Please show your support through one of the following sites:
12
12
 
13
- [![GitHub Sponsor](https://cspell.org/img/sponsor/github-sponsor-176px.png)](https://github.com/sponsors/streetsidesoftware) [![PayPal](https://cspell.org/img/sponsor/paypal-176px.png)](https://www.paypal.com/donate/?hosted_button_id=26LNBP2Q6MKCY) [![Open Collective](https://cspell.org/img/sponsor/open-collective-176px.png)](https://opencollective.com/cspell) [![CSpell](https://cspell.org/img/sponsor/cspell-176px.png)](https://streetsidesoftware.com/sponsor/)
13
+ [![GitHub Sponsor](https://cspell.org/img/sponsor/github-sponsor-176px.png)](https://github.com/sponsors/streetsidesoftware) [![PayPal](https://cspell.org/img/sponsor/paypal-176px.png)](https://www.paypal.com/donate/?hosted_button_id=26LNBP2Q6MKCY) [![Open Collective](https://cspell.org/img/sponsor/open-collective-176px.png)](https://opencollective.com/cspell) [![CSpell](https://cspell.org/img/sponsor/cspell-176px.png)](https://streetsidesoftware.com/sponsor/)
14
14
 
15
15
  <!--- @@inject-end: ../../static/sponsor.md --->
16
16
 
@@ -56,7 +56,7 @@ export async function normalizeReporters(settings, pathToSettingsFile) {
56
56
  return resolve(s);
57
57
  }
58
58
  if (!Array.isArray(s) || typeof s[0] !== 'string')
59
- throw new Error('Invalid Reporter');
59
+ throw new TypeError('Invalid Reporter');
60
60
  // Preserve the shape of Reporter Setting while resolving the reporter file.
61
61
  const [r, ...rest] = s;
62
62
  return [await resolve(r), ...rest];
@@ -213,9 +213,20 @@ function reduceWordList(acc, match, key) {
213
213
  function parseWords(acc, match) {
214
214
  return reduceWordList(acc, match, 'words');
215
215
  }
216
+ // a non-perfect but reasonable regex to match locale-like strings
217
+ // must match "lorem-ipsum" and similar fake locale-like strings
218
+ const localeLikeRegEx = /^[a-z][a-z0-9_-]{0,16}[a-z0-9]$/i;
216
219
  function parseLocale(acc, match) {
217
- const parts = match.trim().split(/[\s,]+/);
218
- const language = parts.slice(1).join(',');
220
+ // Remove the closing marker of an HTML or block comment, it is not a locale.
221
+ const parts = match
222
+ .replace(/[^a-z0-9]+$/i, '')
223
+ .split(/[\s,]+/)
224
+ .slice(1);
225
+ const stop = parts.findIndex((locale) => !localeLikeRegEx.test(locale));
226
+ if (stop !== -1) {
227
+ parts.splice(stop);
228
+ }
229
+ const language = parts.join(',');
219
230
  if (language) {
220
231
  acc.language = language;
221
232
  }
@@ -3,15 +3,18 @@ export 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
+ /**
7
+ * Normalize locales to the form `Intl` uses, for example `en_us` becomes `en-US`.
8
+ * Locales that `Intl` rejects are dropped.
9
+ */
6
10
  export declare function normalizeLocaleIntl(locale: LocaleId | LocaleId[]): Set<LocaleId>;
7
11
  export declare function isLocaleInSet(locale: LocaleId | LocaleId[], setOfLocals: Set<LocaleId>): boolean;
8
12
  /**
9
- * Test if a locale should be ok with Intl
10
- * @param locale - locale string
11
- * @param strict - case must match
12
- * @returns true if it matches the standard 2 letter or 4 letter forms.
13
+ * Normalize a locale for use with `Intl` and `toLocaleLowerCase`. Locales that `Intl` rejects are dropped.
14
+ * @param locale - a locale or a list of locales, for example `en,tr_TR`.
15
+ * @returns the valid locales, or `undefined` if there are none.
13
16
  */
14
- export declare function isValidLocaleIntlFormat(locale: LocaleId | LocaleId[], strict?: boolean): boolean;
17
+ export declare function normalizeLocaleForIntl(locale: LocaleId | LocaleId[] | undefined): string | string[] | undefined;
15
18
  export declare function calcSettingsForLanguage(languageSettings: LanguageSettings, languageId: LanguageId, locale: LocaleId): BaseSetting;
16
19
  export declare function calcUserSettingsForLanguage(settings: CSpellUserSettings, languageId: string): CSpellUserSettings;
17
20
  export declare function calcSettingsForLanguageId(baseSettings: CSpellUserSettings, languageId: LanguageId[] | LanguageId): CSpellUserSettings;
@@ -37,46 +37,49 @@ export function normalizeLocale(locale) {
37
37
  locale = typeof locale === 'string' ? locale : locale.join(',');
38
38
  return _normalizeLocale(locale);
39
39
  }
40
- export function normalizeLocaleIntl(locale) {
41
- const values = [...normalizeLocale(locale)].map((locale) => locale.replace(/^([a-z]{2})(?:-?([a-z]{4}))?-?([a-z]{2})$/, (_, lang, script, region) => toLocaleIntl(lang, script, region)));
42
- return new Set(values);
43
- }
44
40
  /**
45
- * See: https://developer.mozilla.org/en-US/docs/Glossary/BCP_47_language_tag
46
- * @returns locale normalized to BCP_47
41
+ * Normalize locales to the form `Intl` uses, for example `en_us` becomes `en-US`.
42
+ * Locales that `Intl` rejects are dropped.
47
43
  */
48
- function toLocaleIntl(lang, script, region) {
49
- const parts = [lang];
50
- if (script)
51
- parts.push(firstUpper(script.toLowerCase()));
52
- if (region)
53
- parts.push(region.toUpperCase());
54
- return parts.join('-');
55
- }
56
- function firstUpper(str) {
57
- const [first, ...rest] = [...str];
58
- return [first.toUpperCase(), ...rest].join('');
44
+ export function normalizeLocaleIntl(locale) {
45
+ return _normalizeLocaleIntl(typeof locale === 'string' ? locale : locale.join(','));
46
+ }
47
+ const _normalizeLocaleIntl = memoize(__normalizeLocaleIntl);
48
+ function __normalizeLocaleIntl(locale) {
49
+ const locales = localesToList(locale)
50
+ .map((locale) => toLocaleIntl(locale.replaceAll('_', '-')))
51
+ .filter((locale) => locale !== undefined);
52
+ return new Set(locales);
53
+ }
54
+ // A locale written without separators, for example `enUS` or `zhHantTW`.
55
+ const regExpLocaleWithoutSeparators = /^([a-z]{2})([a-z]{4})?([a-z]{2})$/i;
56
+ function toLocaleIntl(locale) {
57
+ locale = locale.replace(regExpLocaleWithoutSeparators, (_, lang, script, region) => script ? `${lang}-${script}-${region}` : `${lang}-${region}`);
58
+ try {
59
+ return Intl.getCanonicalLocales(locale)[0];
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
59
64
  }
60
65
  export function isLocaleInSet(locale, setOfLocals) {
61
66
  const locales = normalizeLocale(locale);
62
67
  return doSetsIntersect(locales, setOfLocals);
63
68
  }
64
- const regExpValidIntlLocaleStrict = /^[a-z]{2}(-[A-Z]{2})?$/;
65
- const regExpValidIntlLocale = new RegExp(regExpValidIntlLocaleStrict, 'i');
66
69
  /**
67
- * Test if a locale should be ok with Intl
68
- * @param locale - locale string
69
- * @param strict - case must match
70
- * @returns true if it matches the standard 2 letter or 4 letter forms.
70
+ * Normalize a locale for use with `Intl` and `toLocaleLowerCase`. Locales that `Intl` rejects are dropped.
71
+ * @param locale - a locale or a list of locales, for example `en,tr_TR`.
72
+ * @returns the valid locales, or `undefined` if there are none.
71
73
  */
72
- export function isValidLocaleIntlFormat(locale, strict = false) {
73
- if (typeof locale === 'string')
74
- return strict ? regExpValidIntlLocaleStrict.test(locale) : regExpValidIntlLocale.test(locale);
75
- for (const item of locale) {
76
- if (!isValidLocaleIntlFormat(item, strict))
77
- return false;
78
- }
79
- return locale.length > 0;
74
+ export function normalizeLocaleForIntl(locale) {
75
+ if (!locale)
76
+ return undefined;
77
+ const locales = [...normalizeLocaleIntl(locale)];
78
+ if (!locales.length)
79
+ return undefined;
80
+ if (locales.length === 1)
81
+ return locales[0];
82
+ return locales;
80
83
  }
81
84
  const cacheCalcSettingsForLanguage = createAutoResolveWeakCache();
82
85
  export function calcSettingsForLanguage(languageSettings, languageId, locale) {
@@ -56,6 +56,7 @@ import { createFailedToLoadDictionary, createFlagWordsDictionary, createFlagWord
56
56
  import { compareStats, toFileURL, urlBasename } from 'cspell-io';
57
57
  import { measurePerf } from '../../perf/index.js';
58
58
  import { isDictionaryDefinitionInlineInternal, isDictionaryFileDefinitionInternal } from '../../Settings/index.js';
59
+ import { normalizeLocaleForIntl } from '../../Settings/LanguageSettings.js';
59
60
  import { AutoResolveWeakCache, AutoResolveWeakWeakCache } from '../../util/AutoResolve.js';
60
61
  import { toError } from '../../util/errors.js';
61
62
  import { SimpleCache } from '../../util/simpleCache.js';
@@ -260,7 +261,7 @@ async function legacyWordList(reader, filename, options) {
260
261
  if (options.kind === 'suggest-words') {
261
262
  return createSuggestDictionary([...words], options.name, filename.toString());
262
263
  }
263
- return createSpellingDictionary(words, options.name, filename.toString(), applyKind(options), true);
264
+ return createSpellingDictionary(words, options.name, filename.toString(), toSpellingDictionaryOptions(options), true);
264
265
  }
265
266
  catch (e_1) {
266
267
  env_1.error = e_1;
@@ -283,7 +284,7 @@ async function wordsPerLineWordList(reader, filename, options) {
283
284
  if (options.kind === 'suggest-words') {
284
285
  return createSuggestDictionary([...words], options.name, filename.href);
285
286
  }
286
- return createSpellingDictionary(words, options.name, filename.href, applyKind(options), true);
287
+ return createSpellingDictionary(words, options.name, filename.href, toSpellingDictionaryOptions(options), true);
287
288
  }
288
289
  async function loadSimpleWordList(reader, filename, options) {
289
290
  const env_2 = { stack: [], error: void 0, hasError: false };
@@ -296,7 +297,7 @@ async function loadSimpleWordList(reader, filename, options) {
296
297
  if (options.kind === 'suggest-words') {
297
298
  return createSuggestDictionary(lines, options.name, filename.href);
298
299
  }
299
- return createSpellingDictionary(lines, options.name, filename.href, applyKind(options));
300
+ return createSpellingDictionary(lines, options.name, filename.href, toSpellingDictionaryOptions(options));
300
301
  }
301
302
  catch (e_2) {
302
303
  env_2.error = e_2;
@@ -317,7 +318,7 @@ async function loadTrie(reader, filename, options) {
317
318
  if (options.kind === 'suggest-words') {
318
319
  return createSuggestDictionaryFromTrieFile(content, options.name, filename.href);
319
320
  }
320
- return createSpellingDictionaryFromTrieFile(content, options.name, filename.href, applyKind(options));
321
+ return createSpellingDictionaryFromTrieFile(content, options.name, filename.href, toSpellingDictionaryOptions(options));
321
322
  }
322
323
  catch (e_3) {
323
324
  env_3.error = e_3;
@@ -327,6 +328,21 @@ async function loadTrie(reader, filename, options) {
327
328
  __disposeResources(env_3);
328
329
  }
329
330
  }
331
+ /**
332
+ * The options for a spelling dictionary: the effect of `kind`, and the dictionary's locale, normalized once here so
333
+ * lookups don't have to. A locale that isn't valid is dropped.
334
+ */
335
+ function toSpellingDictionaryOptions(options) {
336
+ const opts = applyKind(options);
337
+ if (!isDictionaryFileDefinitionInternal(opts))
338
+ return opts;
339
+ const locales = normalizeLocaleForIntl(opts.dictionaryInformation?.locale);
340
+ const locale = Array.isArray(locales) ? locales[0] : locales;
341
+ if (!locale)
342
+ return opts;
343
+ // `weightMap` is a getter on some definitions, so copy it explicitly.
344
+ return { ...opts, weightMap: opts.weightMap, locale };
345
+ }
330
346
  /**
331
347
  * Apply the effect of `kind` on the options passed to a normal `words` dictionary loader.
332
348
  * `flag-words` and `suggest-words` are handled by the callers directly since they use a different
@@ -1,11 +1,11 @@
1
- import { normalizeLocaleIntl } from '../Settings/LanguageSettings.js';
1
+ import { normalizeLocaleForIntl } from '../Settings/LanguageSettings.js';
2
2
  import { applyEditsToMappedText } from './TextMapEdit.js';
3
3
  import { softHyphen, toMappedText } from './Transformer.js';
4
4
  const regExSplitWordCharacters = /(?<=[\p{L}\p{M}])[\p{L}\p{M}]/uy;
5
5
  export class IntlSegmentTextTransformer {
6
6
  #locale;
7
7
  constructor(locale) {
8
- this.#locale = [...normalizeLocaleIntl(locale)];
8
+ this.#locale = normalizeLocaleForIntl(locale);
9
9
  }
10
10
  transform(text) {
11
11
  // Implement the transformation logic here
@@ -1,7 +1,7 @@
1
1
  import assert from 'node:assert';
2
2
  import { satisfiesCSpellConfigFile } from 'cspell-config-lib';
3
3
  import { finalizeSettings, getDefaultSettings, getGlobalSettingsAsync, mergeSettings, resolveConfigFileImports, } from './Settings/index.js';
4
- import { calcSettingsForLanguageId, isValidLocaleIntlFormat, normalizeLocaleIntl, } from './Settings/LanguageSettings.js';
4
+ import { calcSettingsForLanguageId, normalizeLocaleForIntl } from './Settings/LanguageSettings.js';
5
5
  import { getDictionaryInternal, refreshDictionaryCache } from './SpellingDictionary/index.js';
6
6
  import { createAutoResolveCache } from './util/AutoResolve.js';
7
7
  import { memoizeLastCall } from './util/memoizeLastCall.js';
@@ -58,7 +58,7 @@ async function _suggestionsForWordAsync(word, options, settings, dictionaryColle
58
58
  : settings;
59
59
  const opts = { ignoreCase, numChanges, numSuggestions, includeTies };
60
60
  const suggestionsByDictionary = dictionaryCollection.dictionaries.flatMap((dict) => dict.suggest(word, opts).map((r) => ({ ...r, dictName: dict.name })));
61
- const locale = adjustLocale(language || config.language || undefined);
61
+ const locale = normalizeLocaleForIntl(language || config.language || undefined);
62
62
  const collator = Intl.Collator(locale);
63
63
  const combined = limitResults(combine(suggestionsByDictionary.sort((a, b) => a.cost - b.cost || collator.compare(a.word, b.word))), numSuggestions, includeTies);
64
64
  const sugsAdjusted = calcSuggestionAdjustedToToMatchCase(word, combined, locale, ignoreCase, extendsDictionaryCollection);
@@ -87,18 +87,8 @@ function combine(suggestions) {
87
87
  }
88
88
  return [...words.values()];
89
89
  }
90
- function adjustLocale(locale) {
91
- if (!locale)
92
- return undefined;
93
- const locales = [...normalizeLocaleIntl(locale)].filter((locale) => isValidLocaleIntlFormat(locale));
94
- if (!locales.length)
95
- return undefined;
96
- if (locales.length === 1)
97
- return locales[0];
98
- return locales;
99
- }
100
90
  export function calcSuggestionAdjustedToToMatchCase(originalWord, sugs, locale, ignoreCase, dict) {
101
- locale = adjustLocale(locale);
91
+ locale = normalizeLocaleForIntl(locale);
102
92
  const knownSugs = new Set(sugs.map((sug) => sug.word));
103
93
  const matchStyle = { ...analyzeCase(originalWord), locale, ignoreCase };
104
94
  /* Add adjusted words */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cspell-lib",
3
- "version": "10.4.0-alpha.1",
3
+ "version": "10.4.1",
4
4
  "description": "A library of useful functions used across various cspell tools.",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -75,46 +75,43 @@
75
75
  "watch": "tsc -p . --watch"
76
76
  },
77
77
  "dependencies": {
78
- "@cspell/cspell-bundled-dicts": "10.4.0-alpha.1",
79
- "@cspell/cspell-performance-monitor": "10.4.0-alpha.1",
80
- "@cspell/cspell-pipe": "10.4.0-alpha.1",
81
- "@cspell/cspell-resolver": "10.4.0-alpha.1",
82
- "@cspell/cspell-types": "10.4.0-alpha.1",
83
- "@cspell/dynamic-import": "10.4.0-alpha.1",
84
- "@cspell/filetypes": "10.4.0-alpha.1",
85
- "@cspell/rpc": "10.4.0-alpha.1",
86
- "@cspell/strong-weak-map": "10.4.0-alpha.1",
87
- "@cspell/url": "10.4.0-alpha.1",
88
- "cspell-config-lib": "10.4.0-alpha.1",
89
- "cspell-dictionary": "10.4.0-alpha.1",
90
- "cspell-glob": "10.4.0-alpha.1",
91
- "cspell-grammar": "10.4.0-alpha.1",
92
- "cspell-io": "10.4.0-alpha.1",
93
- "cspell-trie-lib": "10.4.0-alpha.1",
78
+ "@cspell/cspell-bundled-dicts": "10.4.1",
79
+ "@cspell/cspell-performance-monitor": "10.4.1",
80
+ "@cspell/cspell-pipe": "10.4.1",
81
+ "@cspell/cspell-resolver": "10.4.1",
82
+ "@cspell/cspell-types": "10.4.1",
83
+ "@cspell/dynamic-import": "10.4.1",
84
+ "@cspell/filetypes": "10.4.1",
85
+ "@cspell/rpc": "10.4.1",
86
+ "@cspell/strong-weak-map": "10.4.1",
87
+ "@cspell/url": "10.4.1",
88
+ "cspell-config-lib": "10.4.1",
89
+ "cspell-dictionary": "10.4.1",
90
+ "cspell-glob": "10.4.1",
91
+ "cspell-grammar": "10.4.1",
92
+ "cspell-io": "10.4.1",
93
+ "cspell-trie-lib": "10.4.1",
94
94
  "env-paths": "^4.0.0",
95
95
  "gensequence": "^8.0.8",
96
96
  "import-fresh": "^4.0.1",
97
97
  "resolve-from": "^5.0.0",
98
- "vscode-languageserver-textdocument": "^1.0.15",
98
+ "vscode-languageserver-textdocument": "^1.0.16",
99
99
  "vscode-uri": "^3.2.0",
100
100
  "xdg-basedir": "^5.1.0"
101
101
  },
102
102
  "devDependencies": {
103
- "@cspell/dict-cpp": "^7.1.2",
103
+ "@cspell/dict-cpp": "^7.2.0",
104
104
  "@cspell/dict-csharp": "^4.0.8",
105
105
  "@cspell/dict-css": "^4.1.2",
106
- "@cspell/dict-en_us": "^4.4.40",
107
- "@cspell/dict-fa-ir": "^4.0.5",
106
+ "@cspell/dict-en_us": "^4.4.43",
107
+ "@cspell/dict-fa-ir": "^4.0.6",
108
108
  "@cspell/dict-fr-fr": "^2.3.2",
109
109
  "@cspell/dict-html": "^4.0.16",
110
110
  "@cspell/dict-nl-nl": "^2.4.2",
111
- "@cspell/dict-python": "^4.5.2",
112
- "@cspell/dict-th-th": "^1.0.1",
111
+ "@cspell/dict-python": "^4.5.3",
112
+ "@cspell/dict-th-th": "^1.0.4",
113
113
  "@cspell/dictionary-bundler-plugin": "",
114
- "@types/configstore": "^6.0.2",
115
114
  "comment-json": "^5.0.0",
116
- "configstore": "^8.0.0",
117
- "cspell-dict-nl-nl": "^1.1.2",
118
115
  "leaked-handles": "^5.2.0",
119
116
  "lorem-ipsum": "^3.0.0",
120
117
  "perf-insight": "^2.0.1"
@@ -122,5 +119,5 @@
122
119
  "engines": {
123
120
  "node": ">=22.18.0"
124
121
  },
125
- "gitHead": "628768a6e62b792e628189b41e63e12e5d3d8fe3"
122
+ "gitHead": "ddb1699a4bfc2766675c2c97412a813d775772eb"
126
123
  }