40 lines
1.4 KiB
TypeScript
40 lines
1.4 KiB
TypeScript
import {
|
|
getSharedHighlighter,
|
|
type DiffsHighlighter,
|
|
type HighlighterTypes,
|
|
type SupportedLanguages,
|
|
} from "@pierre/diffs";
|
|
|
|
import { resolveDiffThemeName } from "./diffRendering";
|
|
|
|
/**
|
|
* Always highlight with the Oniguruma WASM engine — the JS regex engine can
|
|
* backtrack catastrophically and hang the tokenizing thread. The shared
|
|
* highlighter is a first-caller-wins singleton, so every creation site must
|
|
* pass this value.
|
|
*/
|
|
export const PREFERRED_HIGHLIGHTER: HighlighterTypes = "shiki-wasm";
|
|
|
|
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
|
|
|
|
export function getSyntaxHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
|
const cached = highlighterPromiseCache.get(language);
|
|
if (cached) return cached;
|
|
|
|
const promise = getSharedHighlighter({
|
|
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
|
|
langs: [language as SupportedLanguages],
|
|
preferredHighlighter: PREFERRED_HIGHLIGHTER,
|
|
}).catch((error) => {
|
|
if (language === "text") {
|
|
highlighterPromiseCache.delete(language);
|
|
// "text" itself failed — Shiki cannot initialize at all, surface the error
|
|
throw error;
|
|
}
|
|
// Language not supported by Shiki — fall back to "text"
|
|
return getSyntaxHighlighterPromise("text");
|
|
});
|
|
highlighterPromiseCache.set(language, promise);
|
|
return promise;
|
|
}
|