Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions packages/docusaurus-plugin-openapi-docs/src/markdown/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/* ============================================================================
* Copyright (c) Palo Alto Networks
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* ========================================================================== */

import { clean } from "./utils";

describe("clean", () => {
it("escapes curly brackets outside code", () => {
expect(
clean("Use {value}, `const value = {}`, and ~removed~ {text}.")
).toBe("Use \\{value\\}, `const value = {}`, and ~removed~ \\{text\\}.");
});

it.each([
["backtick", '```json\n{\n "ok": true\n}\n```'],
["tilde", '~~~json\n{\n "ok": true\n}\n~~~'],
])("preserves %s fenced code blocks", (_name, codeBlock) => {
const input = `Before {value}\n${codeBlock}\nAfter {value}`;
const expected = `Before \\{value\\}\n${codeBlock}\nAfter \\{value\\}`;

expect(clean(input)).toBe(expected);
});
});
26 changes: 14 additions & 12 deletions packages/docusaurus-plugin-openapi-docs/src/markdown/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,24 +218,26 @@ export const greaterThan =
/(?<!(button|code|details|summary|hr|br|span|strong|small|table|thead|tbody|td|tr|th|h1|h2|h3|h4|h5|h6|title|p|em|b|i|u|strike|bold|a|li|ol|ul|img|svg|div|center|\/|\s|"|'))>/gu;
export const codeFence = /`{1,3}[\s\S]*?`{1,3}/g;
export const curlyBrackets = /([{}])/g;
export const codeBlock = /(^```.*[\s\S]*?```$|`[^`].+?`)/gm;
export const codeBlock = /(^```.*[\s\S]*?```$|^~~~.*[\s\S]*?~~~$|`[^`].+?`)/gm;

export function clean(value: string | undefined): string {
if (!value) {
return "";
}

let sections = value.split(codeBlock);
for (let sectionIndex in sections) {
if (!sections[sectionIndex].startsWith("`")) {
sections[sectionIndex] = sections[sectionIndex]
.replace(lessThan, "&lt;")
.replace(greaterThan, "&gt;")
.replace(codeFence, function (match) {
return match.replace(/\\>/g, ">");
})
.replace(curlyBrackets, "\\$1");
}
const sections = value.split(codeBlock);
for (
let sectionIndex = 0;
sectionIndex < sections.length;
sectionIndex += 2
) {
sections[sectionIndex] = sections[sectionIndex]
.replace(lessThan, "&lt;")
.replace(greaterThan, "&gt;")
.replace(codeFence, function (match) {
return match.replace(/\\>/g, ">");
})
.replace(curlyBrackets, "\\$1");
}
return sections.join("");
}