Skip to content

Commit 5daf867

Browse files
authored
Update rehype-collect-headings.ts
1 parent ed82caf commit 5daf867

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed
Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,30 @@
11
import type { VFile } from 'vfile';
22
import { jsToTreeNode } from './utils.js';
33

4+
// Escape unsafe characters for safe code injection
5+
const charMap: Record<string, string> = {
6+
'<': '\\u003C',
7+
'>': '\\u003E',
8+
'/': '\\u002F',
9+
'\\': '\\\\',
10+
'\b': '\\b',
11+
'\f': '\\f',
12+
'\n': '\\n',
13+
'\r': '\\r',
14+
'\t': '\\t',
15+
'\0': '\\0',
16+
'\u2028': '\\u2028',
17+
'\u2029': '\\u2029'
18+
};
19+
function escapeUnsafeChars(str: string): string {
20+
return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029/\\]/g, x => charMap[x] || x);
21+
}
22+
423
export function rehypeInjectHeadingsExport() {
524
return function (tree: any, file: VFile) {
625
const headings = file.data.astro?.headings ?? [];
726
tree.children.unshift(
8-
jsToTreeNode(`export function getHeadings() { return ${JSON.stringify(headings)} }`),
27+
jsToTreeNode(`export function getHeadings() { return ${escapeUnsafeChars(JSON.stringify(headings))} }`),
928
);
1029
};
1130
}

0 commit comments

Comments
 (0)