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 { createNodeModulesSymlinkResolver } from "./utils/nodeModulesSymlinkResolver"; 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 }), rootDir, } = pluginOptions; const filter = createFilter(include, exclude); // Only built when `rootDir` is provided, so plugin instances that don't // opt in (the default `getExtractNameAndUrl` included) see the exact same // `filePath` as before this option existed. const nodeModulesSymlinkResolver = rootDir ? createNodeModulesSymlinkResolver(rootDir) : undefined; const pluginState: RollupPluginSassState = { styles: [], styleMaps: {}, }; return { name: "rollup-plugin-sass", // Rollup calls buildStart at the start of every build, including each // rebuild in `--watch`/dev mode, where this plugin instance (and its // closures) is reused across rebuilds. Reset the memoized node_modules // symlink scan here so it can't outlive a single build and go stale if // node_modules changes between rebuilds (e.g. a mid-session `pnpm // install`). buildStart() { nodeModulesSymlinkResolver?.reset(); }, /** @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. // ---- if (!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 => { 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(), fs, nodeModulesSymlinkResolver, ); 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(), fs, nodeModulesSymlinkResolver, ); // @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; if (!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); // pnpm (and other symlink-based package managers) resolve // symlinks before passing the module id to plugins, so `id` can // be a real path under packages//dist/ with no // node_modules ancestor — rewrite it through its node_modules // symlink first so getExtractNameAndUrl sees a path it can // compute a clean node_modules-relative name from. const resolved = await nodeModulesSymlinkResolver?.resolve(fs, id); const { name } = await getExtractNameAndUrl( resolved?.filePath ?? id, contentHash, fs, ); this.emitFile({ type: "asset", fileName: name, source: content, }); } } }, }; }