| 1 | export interface SpellRange { |
| 2 | offset: number; |
| 3 | length: number; |
| 4 | suggestions: string[]; |
| 5 | } |
| 6 | |
| 7 | export type Settings = Record<string, ts.JsonValue> & { files: string[]; ignorePaths: string[] }; |
| 8 | |
| 9 | /** CSpell annotates every unknown word; `unknownWords` decides which of them count. */ |
| 10 | export async function spellCheck(uri: string, text: string, settings: ts.DeepReadonly<Settings>, config: URL) { |
| 11 | const result = await cspellLib.spellCheckDocument( |
| 12 | { uri, text }, |
| 13 | { noConfigSearch: true, generateSuggestions: false }, |
| 14 | { url: config, settings: structuredClone(settings) as Settings, virtual: true }, |
| 15 | ); |
| 16 | for (const error of result.errors ?? []) throw error; |
| 17 | for (const error of result.configErrors ?? []) throw error.error; |
| 18 | for (const errors of result.dictionaryErrors?.values() ?? []) { |
| 19 | for (const error of errors) throw error; |
| 20 | } |
| 21 | // meowd |
| 22 | if (!result.checked) throw new Error(`CSpell did not check ${uri}.`); |
| 23 | const { settingsUsed } = result; |
| 24 | const issues = result.issues.filter((issue) => { |
| 25 | if (issue.isFlagged || issue.issueType) return true; |
| 26 | switch (settingsUsed.unknownWords) { |
| 27 | case "report-common-typos": |
| 28 | return issue.hasPreferredSuggestions; |
| 29 | case "report-simple": |
| 30 | return issue.hasPreferredSuggestions || issue.hasSimpleSuggestions; |
| 31 | case "report-flagged": |
| 32 | return false; |
| 33 | default: |
| 34 | return true; |
| 35 | } |
| 36 | }); |
| 37 | return { issues, settingsUsed }; |
| 38 | } |
| 39 | |
| 40 | /** Replacements per unknown word, skipping anything the dictionaries forbid. */ |
| 41 | export async function suggestFixes({ issues, settingsUsed }: Awaited<ReturnType<typeof spellCheck>>) { |
| 42 | const dictionary = await cspellLib.getDictionary(settingsUsed); |
| 43 | const options = { |
| 44 | includeDefaultConfig: false, |
| 45 | includeTies: false, |
| 46 | strict: settingsUsed.caseSensitive ?? false, |
| 47 | numSuggestions: settingsUsed.numSuggestions, |
| 48 | numChanges: settingsUsed.suggestionNumChanges, |
| 49 | }; |
| 50 | const canSuggest = (word: string) => |
| 51 | !dictionary.isForbidden(word) && !dictionary.isNoSuggestWord(word, { ignoreCase: !options.strict }); |
| 52 | const byWord = new Map<string, string[]>(); |
| 53 | for (const issue of issues) { |
| 54 | if (byWord.has(issue.text)) continue; |
| 55 | let candidates = (issue.suggestionsEx ?? []).filter((suggestion) => |
| 56 | suggestion.isPreferred |
| 57 | && canSuggest(suggestion.word) && canSuggest(suggestion.wordAdjustedToMatchCase ?? suggestion.word) |
| 58 | ); |
| 59 | if (!candidates.length && options.numSuggestions !== 0) { |
| 60 | // The word API applies dictionary edit weights that document suggestions omit. |
| 61 | const suggested = await cspellLib.suggestionsForWord(issue.text, options, settingsUsed); |
| 62 | candidates = suggested.suggestions.filter((suggestion) => |
| 63 | !suggestion.forbidden && !suggestion.noSuggest |
| 64 | && canSuggest(suggestion.wordAdjustedToMatchCase ?? suggestion.word) |
| 65 | ); |
| 66 | } |
| 67 | const preferred = candidates.filter((suggestion) => suggestion.isPreferred); |
| 68 | byWord.set( |
| 69 | issue.text, |
| 70 | [ |
| 71 | ...new Set( |
| 72 | (preferred.length ? preferred : candidates).map((suggestion) => |
| 73 | suggestion.wordAdjustedToMatchCase ?? suggestion.word |
| 74 | ), |
| 75 | ), |
| 76 | ].slice(0, options.numSuggestions), |
| 77 | ); |
| 78 | } |
| 79 | return byWord; |
| 80 | } |
| 81 | |
| 82 | let loaded: Promise<{ settings: Settings; config: URL }> | undefined; |
| 83 | |
| 84 | /** Live editor feedback, flagging exactly what the build-time check would. */ |
| 85 | export async function checkText(text: string): Promise<SpellRange[]> { |
| 86 | loaded ??= (async () => { |
| 87 | const config = url.pathToFileURL(path.resolve("cspell.json")); |
| 88 | return { settings: await fs.readFile(config, "utf8").then(JSON.parse) as Settings, config }; |
| 89 | })(); |
| 90 | const { settings, config } = await loaded; |
| 91 | const result = await spellCheck("file:///question.md", text, settings, config); |
| 92 | // A `q:` line quotes the asker verbatim, so only the answer is clover's to spell. |
| 93 | const issues = result.issues.filter((issue) => !text.startsWith("q:", text.lastIndexOf("\n", issue.offset) + 1)); |
| 94 | if (!issues.length) return []; |
| 95 | const byWord = await suggestFixes({ ...result, issues }); |
| 96 | return issues.map((issue) => ({ |
| 97 | offset: issue.offset, |
| 98 | length: issue.text.length, |
| 99 | suggestions: byWord.get(issue.text) ?? [], |
| 100 | })); |
| 101 | } |
| 102 | |
| 103 | import type * as ts from "@clo/lib/ts"; |
| 104 | import * as cspellLib from "cspell-lib"; |
| 105 | import * as fs from "node:fs/promises"; |
| 106 | import * as path from "node:path"; |
| 107 | import * as url from "node:url"; |