import type { Plugin } from "vite"; import { parseDOM } from "htmlparser2"; import { selectOne } from "css-select"; import serialize from "dom-serializer"; import { Element } from "domhandler"; import type { DomSerializerOptions } from "dom-serializer"; import { uiPage } from "../index"; import type { ViteMetadata } from "./css-asset"; import { LIBRARY_UXF_APP_SYS_ID } from "../servicenow/constants"; const SDK_GLOBALS_RE = /<\/sdk:now-ux-globals>|/; interface ServicenowHtmlPluginOptions { rootDir: string; entryPath?: ( entry: string, context: { fullPath: string; dir: string }, ) => { [key: string]: string }; updateSrcPath?: (originalSrc: string, emittedFileName: string) => string; serializerOptions?: DomSerializerOptions; } function collectEntryCssUrls(bundle: Record): string[] { const urls: string[] = []; for (const chunk of Object.values(bundle)) { if (chunk.type !== "chunk" || !chunk.isEntry) continue; const meta = (chunk as unknown as { viteMetadata?: ViteMetadata }) .viteMetadata; if (meta?.importedCssUrls) { for (const url of meta.importedCssUrls.values()) { urls.push(url); } } } return urls; } function injectCssLinks(html: string, urls: string[]): string { const dom = parseDOM(html, { decodeEntities: false, xmlMode: true, }); const head = selectOne("head", dom) as Element | null; if (!head) return html; for (const href of urls) { const link = new Element("link", { rel: "stylesheet", href }); head.children.push(link); link.parent = head; } return serialize(dom, { encodeEntities: false, xmlMode: true, emptyAttrs: true, }); } export function servicenowHtmlPlugin( options: ServicenowHtmlPluginOptions, ): Plugin { let serve = false; // Collected from the finished bundle in generateBundle, then read back by the // transformHtml callback below while uiPage serializes each page. let entryCssUrls: string[] = []; const buildPlugin = uiPage({ ...options, transformHtml: (html) => entryCssUrls.length > 0 ? injectCssLinks(html, entryCssUrls) : html, }) as Record; return { name: "servicenow-html", enforce: "post", configResolved(config) { serve = config.command === "serve"; }, transformIndexHtml(html) { if (!serve) return html; return html.replace( SDK_GLOBALS_RE, ``, ); }, options(inputOptions) { if (serve) return inputOptions; return buildPlugin.options.call(this, inputOptions); }, buildStart() { if (serve) return; return buildPlugin.buildStart.call(this); }, generateBundle(outputOptions, bundle, isWrite) { if (serve) return; // Must be collected before uiPage runs, so the stylesheet links are part // of the HTML it emits rather than a later edit to an emitted asset. entryCssUrls = collectEntryCssUrls(bundle); try { buildPlugin.generateBundle.call(this, outputOptions, bundle, isWrite); } finally { entryCssUrls = []; } }, }; }