2022-08-05 14:24:50 +00:00
|
|
|
import { SKIP, visit } from 'unist-util-visit';
|
2021-11-10 17:34:31 -06:00
|
|
|
|
2022-07-26 17:31:57 -04:00
|
|
|
export function escapeEntities(value: string): string {
|
|
|
|
return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
|
|
}
|
|
|
|
|
2021-11-10 17:34:31 -06:00
|
|
|
export default function rehypeEscape(): any {
|
|
|
|
return function (node: any): any {
|
|
|
|
return visit(node, 'element', (el) => {
|
|
|
|
if (el.tagName === 'code' || el.tagName === 'pre') {
|
2022-03-03 14:34:36 -03:00
|
|
|
el.properties['is:raw'] = true;
|
2022-05-31 19:16:43 +02:00
|
|
|
// Visit all raw children and escape HTML tags to prevent Markdown code
|
|
|
|
// like "This is a `<script>` tag" from actually opening a script tag
|
|
|
|
visit(el, 'raw', (raw) => {
|
2022-07-26 17:31:57 -04:00
|
|
|
raw.value = escapeEntities(raw.value);
|
2022-05-31 19:16:43 +02:00
|
|
|
});
|
2022-08-05 16:23:16 +02:00
|
|
|
// Do not visit children to prevent double escaping
|
|
|
|
return SKIP;
|
2021-11-10 17:34:31 -06:00
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|