All files / src/sass index.ts

60.67% Statements 54/89
37.31% Branches 25/67
53.84% Functions 7/13
61.36% Lines 54/88

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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 2691x 1x 1x 1x 1x 1x                   1x       1x       1x 1x 1x   1x   1x 1x 1x     1x                               1x     4x                               4x   4x   4x         4x         40x 8x           20x 4x         20x 12x     8x   8x 8x       8x 8x       8x 8x     8x   8x   8x       8x                           8x   8x 8x 8x     8x             8x       8x         8x             8x   8x                                                                                                 4x 4x 4x   4x 4x                                                                                        
import { promisify } from "util";
import path from "path";
import { fileURLToPath, pathToFileURL } from "../utils/url";
import { computeContentHash } from "../crypto";
import * as sass from "sass";
import { createFilter } from "@rollup/pluginutils";
 
/**
 * @warning Rollup is added as a "devDependency",
 *          so no actual symbols should be imported.
 *          Interfaces and non-concrete types are ok.
 */
import type { Plugin as RollupPlugin, TransformResult } from "rollup";
 
import type { RollupPluginSassOptions, RollupPluginSassState } from "./types";
import {
  getImporterListLegacy,
  getImporterListModern,
} from "./utils/getImporterList";
import {
  processRenderResponse,
  INSERT_STYLE_ID,
} from "./utils/processRenderResponse";
import insertStyle from "./insertStyle";
import { getSyntax } from "./utils/helpers";
import nodeFsAdapter from "../node-fs-adapter";
 
const MATCH_SASS_FILENAME_RE = /\.sass$/;
 
const defaultIncludes = ["**/*.sass", "**/*.scss", "**/*.css"];
const defaultExcludes = "";
const defaultApi = "modern";
 
// Simple console logger for sass compile messages
const consoleLogger: sass.Logger = {
  debug(message: string) {
    console.debug(`[Sass debug]: ${message}`);
  },
  warn(message: string, { deprecation, span, stack }: sass.LoggerWarnOptions) {
    console.warn(
      `[${deprecation ? "Sass deprecation" : "Sass warning"}]: ${message}`,
    );
    if (span && stack) {
      console.log(`  ${span.context}at ${stack}`);
    }
  },
};
 
// Typescript syntax for CommonJs "default exports" compatible export
// @reference https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require
export default function plugin(
  options = {} as RollupPluginSassOptions,
): RollupPlugin {
  const pluginOptions: RollupPluginSassOptions = Object.assign(
    {
      runtime: sass,
      output: false,
      insert: false,
      api: defaultApi,
    },
    options,
  );
 
  const {
    include = defaultIncludes,
    exclude = defaultExcludes,
    runtime: sassRuntime,
    shouldExtract = () => false,
    getExtractNameAndUrl = (url) => ({ name: url, url }),
  } = pluginOptions;
 
  const filter = createFilter(include, exclude);
 
  const pluginState: RollupPluginSassState = {
    styles: [],
    styleMaps: {},
  };
 
  return {
    name: "rollup-plugin-sass",
 
    /** @see https://rollupjs.org/plugin-development/#resolveid */
    resolveId(source) {
      if (source === INSERT_STYLE_ID) {
        return INSERT_STYLE_ID;
      }
    },
 
    /** @see https://rollupjs.org/plugin-development/#load */
    load(id) {
      if (id === INSERT_STYLE_ID) {
        return `export default ${insertStyle.toString()}`;
      }
    },
 
    async transform(code, filePath) {
      if (!filter(filePath)) {
        return;
      }
      // @ts-ignore
      const fs = options.fs || globalThis.__rollupFs || nodeFsAdapter;
 
      const paths = [path.dirname(filePath), process.cwd()];
      const { styleMaps, styles } = pluginState;
 
      // Setup resolved css output bundle tracking, for use later in `generateBundle` method.
      // ----
      Eif (!styleMaps[filePath]) {
        const mapEntry = {
          id: filePath,
          content: "", // Populated after sass compilation
        };
        styleMaps[filePath] = mapEntry;
        styles.push(mapEntry);
      }
 
      switch (pluginOptions.api) {
        case "modern": {
          const { options: incomingSassOptions } = pluginOptions;
 
          const invokeSass = async (
            url: URL,
            source: string,
          ): Promise<sass.CompileResult> => {
            const compileOptions: sass.StringOptions<"async"> = {
              ...incomingSassOptions,
              syntax: getSyntax(path.extname(url.pathname)),
              loadPaths: (incomingSassOptions?.loadPaths || []).concat(paths),
              importers: getImporterListModern(
                incomingSassOptions?.importers,
                fs,
              ),
              url,
              /** force sourceMap because right now rollup outputOptions are not available */
              sourceMap: true,
              logger: consoleLogger,
            };
            const compileResult: sass.CompileResult =
              await sassRuntime.compileStringAsync(source, compileOptions);
 
            const { loadedUrls } = compileResult;
            loadedUrls.forEach((filePath) => {
              this.addWatchFile(fileURLToPath(filePath));
            });
 
            return compileResult;
          };
 
          /**
           * Using {@link compileStringAsync} to keep support of prepend information on each file,
           * basically `data` option
           */
          const source = incomingSassOptions?.data
            ? `${incomingSassOptions.data}${code}`
            : code;
 
          const compileResult: sass.CompileResult = await invokeSass(
            pathToFileURL(filePath) as URL,
            source,
          );
 
          const codeResult = await processRenderResponse(
            pluginOptions,
            filePath,
            pluginState,
            compileResult.css.toString().trim(),
          );
 
          const { sourceMap } = compileResult;
 
          return {
            code: codeResult || "",
            map: sourceMap ? sourceMap : undefined,
          } as TransformResult;
        }
 
        case "legacy": {
          const { options: incomingSassOptions } = pluginOptions;
 
          const renderOptions: sass.LegacyOptions<"async"> = {
            ...incomingSassOptions,
 
            file: filePath,
            data:
              incomingSassOptions?.data && `${incomingSassOptions.data}${code}`,
            indentedSyntax: MATCH_SASS_FILENAME_RE.test(filePath),
            includePaths: (incomingSassOptions?.includePaths || []).concat(
              paths,
            ),
            importer: getImporterListLegacy(incomingSassOptions?.importer, fs),
            logger: consoleLogger,
          };
 
          const res: sass.LegacyResult = await promisify(
            sassRuntime.render.bind(sassRuntime),
          )(renderOptions);
 
          const codeResult = await processRenderResponse(
            pluginOptions,
            filePath,
            pluginState,
            res.css.toString().trim(),
          );
 
          // @todo Do we need to filter this call so it only occurs when rollup is in 'watch' mode?
          res.stats.includedFiles.forEach((filePath: string) => {
            this.addWatchFile(filePath);
          });
 
          // @note do not `catch` here - let error propagate to rollup level.
          return {
            code: codeResult || "",
            map: { mappings: res.map ? res.map.toString() : "" },
          } as TransformResult;
        }
      }
    },
 
    async generateBundle(outputOptions, _, isWrite) {
      const fs = options.fs || globalThis.__rollupFs || nodeFsAdapter;
      const { styles } = pluginState;
      const { output, insert } = pluginOptions;
 
      Eif (!isWrite || (!insert && (!styles.length || output === false))) {
        return;
      }
 
      const css = styles.map((style) => style.content).join("");
 
      if (typeof output === "string") {
        await fs.mkdir(path.dirname(output), { recursive: true });
        await fs.writeFile(output, css);
 
        return;
      }
 
      if (typeof output === "function") {
        output(css, styles);
        return;
      }
 
      if (!insert && outputOptions.file && output === true) {
        let dest = outputOptions.file;
 
        if (dest.endsWith(".js") || dest.endsWith(".ts")) {
          dest = dest.slice(0, -3);
        }
        dest = `${dest}.css`;
 
        await fs.mkdir(path.dirname(dest), { recursive: true });
        await fs.writeFile(dest, css);
        return;
      }
 
      for (const { id, content } of styles) {
        if (id && content && shouldExtract(id, content)) {
          const contentHash = await computeContentHash(content);
          const { name } = getExtractNameAndUrl(id, contentHash);
          this.emitFile({
            type: "asset",
            fileName: name,
            source: content,
          });
        }
      }
    },
  };
}