Merge pull request #5791 from backstage/iameap/techdocs-invalid-url

[TechDocs] Prevent WSOD when rendering pages with malformed links
This commit is contained in:
Eric Peterson
2021-05-24 20:29:03 +02:00
committed by GitHub
3 changed files with 32 additions and 5 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/plugin-techdocs': patch
---
Fixes #5529, a bug that prevented TechDocs from rendering pages containing malformed links.
@@ -56,6 +56,21 @@ describe('rewriteDocLinks', () => {
'http://localhost/example-docs/example-page',
]);
});
it('should rewrite non-parseable URLs as text', () => {
const expectedText = `www.my-internet.[top-level-domain]/pathname/[URLkey]`;
const shadowDom = createTestShadowDom(
`<a href="http://${expectedText}">${expectedText}</a>`,
{
preTransformers: [rewriteDocLinks()],
postTransformers: [],
},
);
// There should be no <a> tags, but the link text should remain.
expect(getSample(shadowDom, 'a', 'href')).toEqual([]);
expect(shadowDom.innerHTML).toContain(expectedText);
});
});
describe('normalizeUrl', () => {
@@ -31,12 +31,19 @@ export const rewriteDocLinks = (): Transformer => {
if (elemAttribute.match(/^https?:\/\//i)) {
elem.setAttribute('target', '_blank');
}
const normalizedWindowLocation = normalizeUrl(window.location.href);
elem.setAttribute(
attributeName,
new URL(elemAttribute, normalizedWindowLocation).toString(),
);
try {
const normalizedWindowLocation = normalizeUrl(
window.location.href,
);
elem.setAttribute(
attributeName,
new URL(elemAttribute, normalizedWindowLocation).toString(),
);
} catch (_e) {
// Non-parseable links should be re-written as plain text.
elem.replaceWith(elem.textContent || elemAttribute);
}
}
});
};