summaryrefslogtreecommitdiff
path: root/packages/astro/components/Shiki.js
blob: 2d0644653b216579b8a98a524ca7be96ce127eb7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { getHighlighter as getShikiHighlighter } from 'shiki';

// Caches Promise<Highligher> for reuse when the same theme and langs are provided
const _resolvedHighlighters = new Map();

function stringify(opts) {
	// Always sort keys before stringifying to make sure objects match regardless of parameter ordering
	return JSON.stringify(opts, Object.keys(opts).sort());
}

export function getHighlighter(opts) {
	const key = stringify(opts);

	// Highlighter has already been requested, reuse the same instance
	if (_resolvedHighlighters.has(key)) {
		return _resolvedHighlighters.get(key);
	}

	// Start the async getHighlighter call and cache the Promise
	const highlighter = getShikiHighlighter(opts);
	_resolvedHighlighters.set(key, highlighter);

	return highlighter;
}