All files / src/lit-source index.ts

98.07% Statements 102/104
95.77% Branches 68/71
100% Functions 10/10
100% Lines 87/87

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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224    1x 1x 1x 1x                                   41x 44x 41x 49x 49x   39x 39x 38x       3x       89x                   169x 169x 169x 119002x 4253x 4253x   114749x     169x             1767x 1767x 1767x 8531x 6812x 6812x 574x 659x   6238x 1070x                   170x 170x 1339x 1339x 513x 826x 70x 756x 153x     17x                             163x   163x   163x 172x 172x     170x 170x 170x 170x     169x 169x 169x   169x           163x     109x 109x 169x 169x   109x     1x                 45x   45x 45x   45x           47x 44x 3x   41x 41x               41x   41x   38x 38x   38x 1695x 80x 163x 163x               163x 109x 109x 109x           38x   35x         35x              
import type { Plugin, SourceDescription } from "rollup";
import type { FilterPattern } from "@rollup/pluginutils";
import { createFilter } from "@rollup/pluginutils";
import { getSwc } from "../swc/loadSwc";
import path from "path";
import { buildSourceLoc } from "../utils/source-loc";
 
export interface LitTemplateInjectionOptions {
  include?: FilterPattern;
  exclude?: FilterPattern;
  /** Attribute name to inject. Default: "data-source-loc" */
  attributeName?: string;
  /** Tag names to skip injection on. */
  skipTags?: string[];
  /** Project root directory. Defaults to `process.cwd()`. */
  rootDir?: string;
}
 
/**
 * Check that `html` is imported from the `lit` package.
 * Returns false if `html` is not imported or comes from a different package.
 */
function hasLitHtmlImport(ast: any): boolean {
  for (const item of ast.body) {
    if (item.type !== "ImportDeclaration") continue;
    for (const spec of item.specifiers) {
      Iif (spec.type !== "ImportSpecifier") continue;
      if (spec.local.value !== "html") continue;
      // `imported` is the exported name; when absent the local name equals the export
      const exportedName = spec.imported?.value ?? spec.local.value;
      if (exportedName === "html") {
        return item.source.value === "lit";
      }
    }
  }
  return false;
}
 
function isHtmlTag(tag: any): boolean {
  return tag.type === "Identifier" && tag.value === "html";
}
 
/**
 * Compute 1-based line and column from a 0-based character offset in source code.
 */
function offsetToLineCol(
  code: string,
  offset: number,
): { line: number; col: number } {
  let line = 1;
  let col = 1;
  for (let i = 0; i < offset && i < code.length; i++) {
    if (code[i] === "\n") {
      line++;
      col = 1;
    } else {
      col++;
    }
  }
  return { line, col };
}
 
/**
 * Recursively walk an SWC AST node, calling `visitor` on every object with a `type` property.
 */
function walkSwcAst(node: any, visitor: (node: any) => void): void {
  Iif (!node || typeof node !== "object") return;
  if (node.type) visitor(node);
  for (const key of Object.keys(node)) {
    if (key === "span") continue;
    const child = node[key];
    if (Array.isArray(child)) {
      for (const item of child) {
        walkSwcAst(item, visitor);
      }
    } else if (child && typeof child === "object") {
      walkSwcAst(child, visitor);
    }
  }
}
 
/**
 * Find the index of the first unquoted `>` in `str`, starting from index 0.
 * Returns -1 if no unquoted `>` is found.
 */
function findUnquotedClose(str: string): number {
  let quote: string | null = null;
  for (let i = 0; i < str.length; i++) {
    const ch = str[i];
    if (quote) {
      if (ch === quote) quote = null;
    } else if (ch === '"' || ch === "'") {
      quote = ch;
    } else if (ch === ">") {
      return i;
    }
  }
  return -1;
}
 
/**
 * Inject attributes into HTML opening tags found in a quasi string.
 * Returns the modified string, or the original if no changes were made.
 */
function injectIntoQuasi(
  raw: string,
  quasiStart0: number,
  code: string,
  id: string,
  attributeName: string,
  skipTagSet: Set<string>,
): { result: string; injected: boolean } {
  const OPENING_TAG_RE = /<([a-zA-Z][a-zA-Z0-9-]*)/g;
  // Collect insertions in reverse order so earlier indices stay valid
  const insertions: { index: number; text: string }[] = [];
  let match;
  while ((match = OPENING_TAG_RE.exec(raw)) !== null) {
    const tagName = match[1];
    if (skipTagSet.has(tagName.toLowerCase())) continue;
 
    // Check if attribute already exists in remaining tag content
    const afterTag = raw.slice(match.index + match[0].length);
    const closingIdx = findUnquotedClose(afterTag);
    const tagAttrs = closingIdx >= 0 ? afterTag.slice(0, closingIdx) : afterTag;
    if (tagAttrs.includes(attributeName)) continue;
 
    // Position of the `<` that opens this tag (0-based in source)
    const tagOpenOffset = quasiStart0 + match.index;
    const { line, col } = offsetToLineCol(code, tagOpenOffset);
    const locationId = buildSourceLoc(id, line, col);
 
    insertions.push({
      index: match.index + match[0].length,
      text: ` ${attributeName}="${locationId}"`,
    });
  }
 
  if (insertions.length === 0) return { result: raw, injected: false };
 
  // Apply insertions from end to start to preserve indices
  let result = raw;
  for (let i = insertions.length - 1; i >= 0; i--) {
    const { index, text } = insertions[i];
    result = result.slice(0, index) + text + result.slice(index);
  }
  return { result, injected: true };
}
 
export default function litTemplateInjection(
  options: LitTemplateInjectionOptions = {},
): Plugin {
  const {
    include = ["**/*.{ts,js,mjs,cjs,tsx,jsx}"],
    exclude,
    attributeName = "data-source-loc",
    skipTags = [],
    rootDir = process.cwd(),
  } = options;
 
  const filter = createFilter(include, exclude);
  const skipTagSet = new Set(skipTags.map((t) => t.toLowerCase()));
 
  return {
    name: "lit-template-injection",
    async transform(
      code: string,
      id: string,
    ): Promise<SourceDescription | null> {
      if (!filter(id)) return null;
      if (!code.includes("from 'lit'") && !code.includes('from "lit"'))
        return null; // Fast fail to avoid parsing using trivial heuristic
 
      const swc = await getSwc();
      const ast = await swc.parse(code, {
        syntax: "typescript",
        decorators: true,
      });
 
      // SWC accumulates byte offsets across parse calls; normalize
      // all spans relative to the module's start so they become 0-based
      // source positions.
      const baseOffset = ast.span.start;
 
      if (!hasLitHtmlImport(ast)) return null; // Bail before we walk if this isn't a Lit file
 
      const relativeId = path.relative(rootDir, id).replace(/\\/g, "/");
      let modified = false;
 
      walkSwcAst(ast, (node: any) => {
        if (node.type === "TaggedTemplateExpression" && isHtmlTag(node.tag)) {
          for (const quasi of node.template.quasis) {
            const quasiStart0 = quasi.span.start - baseOffset;
            const { result, injected } = injectIntoQuasi(
              quasi.raw,
              quasiStart0,
              code,
              relativeId,
              attributeName,
              skipTagSet,
            );
            if (injected) {
              quasi.raw = result;
              quasi.cooked = result;
              modified = true;
            }
          }
        }
      });
 
      if (!modified) return null; // Don't pay to serialize if we didn't modified anything
 
      const printed = await swc.print(ast, {
        sourceMaps: true,
        inputSourceMap: true,
      });
 
      return {
        code: printed.code,
        map: printed.map ? JSON.parse(printed.map) : undefined,
      };
    },
  } as Plugin;
}