import type { Plugin } from "vite"; import MagicString from "magic-string"; import mime from "mime-types"; import type { RegisterExplicitIdFunction } from "../servicenow/types"; export interface ViteMetadata { importedCss: Set; importedCssUrls?: Map; } interface CssAssetPluginOptions { registerExplicitId?: RegisterExplicitIdFunction; } export function servicenowCssAssetPlugin( options: CssAssetPluginOptions = {}, ): Plugin { const { registerExplicitId } = options; let serve = false; const idCache: Record = {}; function resolveId(diskPath: string): string { let id = idCache[diskPath]; if (!id) { id = registerExplicitId!("sys_ux_theme_asset", diskPath); idCache[diskPath] = id; } return id; } return { name: "servicenow-css-asset", enforce: "post", config(config) { config.experimental ??= {}; const existingRenderBuiltUrl = config.experimental.renderBuiltUrl; config.experimental.renderBuiltUrl = (filename, info) => { if (info.hostType === "js" && mime.lookup(filename) === "text/css") { return `/uxta/${resolveId(filename)}.assetx`; } if (existingRenderBuiltUrl) { return existingRenderBuiltUrl(filename, info); } return { relative: true }; }; }, configResolved(config) { serve = config.command === "serve"; if (!serve && !registerExplicitId) { throw new Error("registerExplicitId is required for build mode"); } }, // Vite's __vitePreload uses dep.endsWith(".css") to decide whether to load // a dependency as a stylesheet or a JS module. Our uxta URLs end with .assetx, // so we patch the check to also recognize .assetx as CSS. renderChunk(code, chunk) { if (serve) return null; const preloadHelperId = "\0vite/preload-helper.js"; if (!chunk.moduleIds.includes(preloadHelperId)) return null; const target = 'let isCss=dep.endsWith(".css")'; const idx = code.indexOf(target); if (idx === -1) return null; const s = new MagicString(code); s.overwrite( idx, idx + target.length, 'let isCss=dep.endsWith(".css")||dep.endsWith(".assetx")', ); return { code: s.toString(), map: s.generateMap({ hires: "boundary" }) }; }, // Capture the output urls in a meta object for later use in the HTML plugin generateBundle(_, bundle) { if (serve) return; for (const chunk of Object.values(bundle)) { if (chunk.type !== "chunk") continue; const meta = (chunk as unknown as { viteMetadata?: ViteMetadata }) .viteMetadata; if (!meta?.importedCss?.size) continue; const urls = new Map(); for (const cssFile of meta.importedCss) { urls.set(cssFile, `/uxta/${resolveId(cssFile)}.assetx`); } meta.importedCssUrls = urls; } }, }; }