All files / src/swc module.ts

96% Statements 24/25
92.3% Branches 12/13
100% Functions 4/4
95.83% Lines 23/24

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    2x 2x     2x   2x                       2x               2x 5x                                   2x 16x 16x 11x   5x 5x     2x 12x                             12x       12x 12x 12x     28x 16x 16x               16x        
import type { Plugin } from "rollup";
import type { Options as SWCOptions } from "@swc/wasm-web";
import { createFilter } from "@rollup/pluginutils";
import { merge } from "smob";
 
import type { Options } from "./type.js";
import { getSwc } from "./loadSwc.js";
 
const defaultInclude = /\.[mc]?[jt]sx?$/;
 
/**
 * Matches a leading `"use client"` / `"use server"` module-level directive
 * (the only ones Rollup warns about — `"use strict"` is explicitly ignored).
 * Anchored at the start so it only matches a genuine directive prologue.
 *
 * By design this only handles the single directive at the very top of the
 * module: per the RSC convention `"use client"` must be the first statement,
 * so it is always first in the prologue. A directive preceded by another
 * directive (or a second RSC directive) is not matched.
 */
const RSC_DIRECTIVE = /^\s*(["'])use (?:client|server)\1\s*;?/;
 
/**
 * Replaces every character except line breaks with a space, preserving the
 * exact character count, line count and column offsets of the input. (Column
 * offsets — not bytes — are what the sourcemap relies on; the two diverge only
 * for non-ASCII input, which a directive prologue never contains.)
 */
const blankPreservingNewlines = (text: string): string =>
  text.replace(/[^\r\n]/g, " ");
 
/**
 * Neutralises a leading React Server Component directive (`"use client"` /
 * `"use server"`) in transformed module code.
 *
 * These directives are RSC hints with no meaning in a bundled browser
 * artifact. Rollup strips them and emits a `MODULE_LEVEL_DIRECTIVE` warning;
 * for dependencies that ship sourcemaps (e.g. @radix-ui) it then fails to map
 * the directive's position back through the sourcemap while reporting that
 * warning and surfaces a confusing cascading "Error when using sourcemap for
 * reporting an error" message instead.
 *
 * Blanking the directive here — during transform, before Rollup parses the
 * module — means Rollup never sees a directive, so neither warning is emitted.
 * The directive is overwritten in place with spaces rather than deleted, which
 * keeps every byte offset (and therefore the SWC-generated sourcemap) valid.
 */
const stripRscDirective = (code: string): string => {
  const match = code.match(RSC_DIRECTIVE);
  if (!match) {
    return code;
  }
  const region = match[0];
  return blankPreservingNewlines(region) + code.slice(region.length);
};
 
export function swc(input: Options = {}): Plugin {
  const defaults: SWCOptions = {
    jsc: {
      target: "es2020",
      parser: {
        syntax: "typescript",
        decorators: true,
      },
      transform: {
        decoratorMetadata: true,
        legacyDecorator: true,
      },
      loose: true,
    },
  };
 
  Iif (input.swc && input.swc.env) {
    delete defaults.jsc?.target;
  }
 
  const filter = createFilter(input.include ?? defaultInclude, input.exclude);
  const swcOptions: SWCOptions = merge({}, input.swc || {}, defaults);
  return {
    name: "swc",
    async transform(code, id) {
      if (!filter(id)) return null;
      const { transform } = await getSwc();
      const result = await transform(code, {
        ...swcOptions,
        sourceMaps: true,
        filename: id,
      });
      // Blank any RSC directive the dependency shipped. Done on the SWC output
      // (not the input) so it is byte-offset preserving and the SWC sourcemap
      // returned alongside stays valid.
      return { ...result, code: stripRscDirective(result.code) };
    },
  };
}