UNPKG

@backstage/plugin-techdocs

Version:

The Backstage plugin that renders technical documentation for your components

57 lines (55 loc) 1.99 kB
const isSvgNeedingInlining = (attrName, attrVal, apiOrigin) => { const pathname = new URL(attrVal, "https://ignored.com").pathname; const isSrcToSvg = attrName === "src" && pathname.endsWith(".svg"); const isRelativeUrl = !attrVal.match(/^([a-z]*:)?\/\//i); const pointsToOurBackend = attrVal.startsWith(apiOrigin); return isSrcToSvg && (isRelativeUrl || pointsToOurBackend); }; const addBaseUrl = ({ techdocsStorageApi, entityId, path }) => { return async (dom) => { const apiOrigin = await techdocsStorageApi.getApiOrigin(); const updateDom = async (list, attributeName) => { for (const elem of list) { if (elem.hasAttribute(attributeName)) { const elemAttribute = elem.getAttribute(attributeName); if (!elemAttribute) return; const newValue = await techdocsStorageApi.getBaseUrl( elemAttribute, entityId, path ); if (isSvgNeedingInlining(attributeName, elemAttribute, apiOrigin)) { try { const svg = await fetch(newValue, { credentials: "include" }); const svgContent = await svg.text(); elem.setAttribute( attributeName, `data:image/svg+xml;base64,${btoa( unescape(encodeURIComponent(svgContent)) )}` ); } catch (e) { elem.setAttribute("alt", `Error: ${elemAttribute}`); } } else { elem.setAttribute(attributeName, newValue); } } } }; await Promise.all([ updateDom(dom.querySelectorAll("img"), "src"), updateDom(dom.querySelectorAll("script"), "src"), updateDom(dom.querySelectorAll("source"), "src"), updateDom(dom.querySelectorAll("link"), "href"), updateDom(dom.querySelectorAll("a[download]"), "href") ]); return dom; }; }; export { addBaseUrl }; //# sourceMappingURL=addBaseUrl.esm.js.map