All files / src/utils isolate-external-imports.ts

89.23% Statements 58/65
80% Branches 48/60
100% Functions 1/1
93.1% Lines 54/58

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 1313x 3x                     3x             12x   11x 11x   11x 11x 11x 11x   11x 22x   22x 22x   22x   22x   20x 20x             2x 2x 32x 32x               32x   2x   2x         2x 2x 2x     2x         1x 1x 1x               11x     10x 10x 20x 18x   18x     10x 20x 20x 2x         20x 14x 13x 13x               10x 10x 1x 1x 1x 1x         11x 11x    
import { init, parse as parseImports } from "es-module-lexer";
import MagicString from "magic-string";
 
/**
 * Ensures every import/re-export whose specifier contains `prefix` starts on
 * its own line.  The ServiceNow instance rewrites these paths to point at
 * different bundles; if the import shares a line with other statements the
 * column shift corrupts their sourcemap entries too.
 *
 * Uses `es-module-lexer` to locate both static and dynamic imports reliably.
 * Only exported for testability.
 */
export async function isolateExternalImports(
  code: string,
  prefix: string,
): Promise<{
  code: string;
  map: ReturnType<MagicString["generateMap"]>;
} | null> {
  if (!code.includes(prefix)) return null;
 
  await init;
  const [imports] = parseImports(code);
 
  const s = new MagicString(code);
  let changed = false;
  const inserted = new Set<number>();
  const staticImports: { start: number; end: number }[] = [];
 
  for (const imp of imports) {
    Iif (!imp.n?.startsWith(prefix)) continue;
 
    let stmtStart = imp.ss;
    let stmtEnd = imp.se;
    // se may point AT the trailing semicolon rather than past it.
    Eif (stmtEnd < code.length && code[stmtEnd] === ";") stmtEnd++;
 
    if (imp.d === -1) {
      // Static import — collect for hoisting.
      staticImports.push({ start: stmtStart, end: stmtEnd });
      changed = true;
    } else {
      // Dynamic import — isolate on its own line.
      // ss/se cover only the `import(...)` expression; walk backward to the
      // containing statement start so the whole assignment lands on its own line.
      // The scan is quote-aware so a `;` inside a string literal doesn't
      // produce a wrong split point.
      let i = stmtStart - 1;
      while (i >= 0 && code[i] !== "\n" && code[i] !== ";") {
        const ch = code[i];
        Iif (ch === '"' || ch === "'" || ch === "`") {
          // Skip backward past the matching opening quote.
          i--;
          while (i >= 0 && code[i] !== ch) {
            if (code[i] === "\\" && ch !== "`") i--; // skip escaped char
            i--;
          }
        }
        i--;
      }
      stmtStart = i + 1;
 
      Eif (
        stmtStart > 0 &&
        code[stmtStart - 1] !== "\n" &&
        !inserted.has(stmtStart)
      ) {
        s.appendLeft(stmtStart, "\n");
        inserted.add(stmtStart);
        changed = true;
      }
 
      if (
        stmtEnd < code.length &&
        code[stmtEnd] !== "\n" &&
        !inserted.has(stmtEnd)
      ) {
        s.appendLeft(stmtEnd, "\n");
        inserted.add(stmtEnd);
        changed = true;
      }
    }
  }
 
  // Move static imports to the top, preserving their relative order.
  // The target is the start of the first non-import character so that
  // imports already at the top don't trigger "cannot move inside itself".
  if (staticImports.length) {
    // Find the first position that isn't covered by a static import.
    // Imports are already sorted by position (from es-module-lexer).
    let target = 0;
    for (const { start, end } of staticImports) {
      if (start !== target) break;
      target = end;
      // Include the trailing newline so the next import's start matches.
      if (target < code.length && code[target] === "\n") target++;
    }
 
    for (const { start, end } of staticImports) {
      const moved = start >= target;
      if (moved) {
        s.move(start, end, target);
      }
      // Append a newline after the import unless it already has one in the
      // original code AND wasn't moved (moved imports need a separator
      // regardless of what followed them at their original position).
      if (moved || end >= code.length || code[end] !== "\n") {
        if (!inserted.has(end)) {
          s.appendLeft(end, "\n");
          inserted.add(end);
        }
      }
    }
 
    // The header plugin prepends /*__ESM_BODY_START__*/ before the chunk
    // body.  When imports are hoisted past it, insert a newline after the
    // comment so it sits on its own line between the imports and the code.
    const ESM_BODY_COMMENT = "/*__ESM_BODY_START__*/";
    if (code.startsWith(ESM_BODY_COMMENT, target)) {
      const pos = target + ESM_BODY_COMMENT.length;
      Eif (pos < code.length && code[pos] !== "\n" && !inserted.has(pos)) {
        s.appendLeft(pos, "\n");
        inserted.add(pos);
      }
    }
  }
 
  Iif (!changed) return null;
  return { code: s.toString(), map: s.generateMap({ hires: "boundary" }) };
}