All files / src/vite html.ts

97.87% Statements 46/47
94.44% Branches 17/18
100% Functions 9/9
100% Lines 41/41

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120  2x 2x 2x 2x   2x     2x     2x                         13x 13x 14x 12x   12x 8x 8x       13x       8x       8x 8x   8x 8x 8x 8x     8x             2x     26x     26x 26x     13x     26x       21x     3x 2x                                   2x 1x     2x 1x     16x     13x 13x 13x   13x          
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\s*\/?><\/sdk:now-ux-globals>|<sdk:now-ux-globals\s*\/?>/;
 
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, any>): 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;
  Iif (!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<string, any>;
 
  return {
    name: "servicenow-html",
    enforce: "post",
    configResolved(config) {
      serve = config.command === "serve";
    },
    transformIndexHtml(html) {
      if (!serve) return html;
      return html.replace(
        SDK_GLOBALS_RE,
        `<script type="module">
import "/uxasset/externals/@devsnc/library-uxf/index.jsdbx";
const themeLink = document.createElement('link');
themeLink.dataset.sourceId = 'glide-theme';
themeLink.rel = 'stylesheet';
themeLink.href = '/$uxappimmutables.do?sysparm_request_type=ux_theme&sysparm_app_sys_id=${LIBRARY_UXF_APP_SYS_ID}&uxpcb=' + Date.now();
document.head.appendChild(themeLink);
document.querySelectorAll('*').forEach(el => {
  if (/^(?:g2?|j):/i.test(el.tagName)) {
    el.remove();
  }
});
</script>`,
      );
    },
    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 = [];
      }
    },
  };
}