sass-loader 16.0.8 → 17.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,58 +8,146 @@ exports.getCompileFn = getCompileFn;
8
8
  exports.getModernWebpackImporter = getModernWebpackImporter;
9
9
  exports.getSassImplementation = getSassImplementation;
10
10
  exports.getSassOptions = getSassOptions;
11
- exports.getWebpackImporter = getWebpackImporter;
12
11
  exports.getWebpackResolver = getWebpackResolver;
13
12
  exports.normalizeSourceMap = normalizeSourceMap;
13
+ exports.removeBOM = removeBOM;
14
14
  var _nodePath = _interopRequireDefault(require("node:path"));
15
15
  var _nodeUrl = _interopRequireDefault(require("node:url"));
16
16
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
17
- /** @typedef {import("sass")} Sass */
18
- /** @typedef {import("sass").StringOptionsWithImporter} SassSassOptions */
19
- /** @typedef {import("sass-embedded")} SassEmbedded */
20
- /** @typedef {import("sass-embedded").StringOptionsWithImporter} SassEmbeddedOptions */
17
+ // eslint-disable-next-line jsdoc/reject-any-type
18
+ /** @typedef {any} EXPECTED_ANY */
21
19
 
22
- /** @typedef {Sass | SassEmbedded} SassImplementation */
23
- /** @typedef {SassSassOptions | SassEmbeddedOptions} SassOptions */
24
- // eslint-disable-next-line jsdoc/no-restricted-syntax
25
- /** @typedef {Record<string, any>} LoaderOptions */
20
+ /**
21
+ * @typedef {object} SourceLocation
22
+ * @property {number} line line number
23
+ * @property {number} column column number
24
+ * @property {number} offset character offset
25
+ */
26
26
 
27
27
  /**
28
- * @returns {Sass | SassEmbedded} sass implementation
28
+ * @typedef {object} SourceSpan
29
+ * @property {SourceLocation} start start location
30
+ * @property {SourceLocation} end end location
31
+ * @property {URL=} url canonical URL of the file
32
+ * @property {string} text covered text
33
+ * @property {string=} context surrounding context
29
34
  */
30
- function getDefaultSassImplementation() {
31
- let sassImplPkg = "sass";
32
- try {
33
- require.resolve("sass-embedded");
34
- sassImplPkg = "sass-embedded";
35
- } catch {
36
- try {
37
- require.resolve("sass");
38
- } catch {
39
- try {
40
- require.resolve("node-sass");
41
- sassImplPkg = "node-sass";
42
- } catch {
43
- sassImplPkg = "sass";
44
- }
45
- }
35
+
36
+ /** @typedef {{ deprecation?: boolean, span?: SourceSpan, stack?: string }} LoggerWarnOptions */
37
+
38
+ /**
39
+ * @typedef {object} Logger
40
+ * @property {((message: string, options: LoggerWarnOptions) => void)=} warn warn handler
41
+ * @property {((message: string, options: { span: SourceSpan }) => void)=} debug debug handler
42
+ */
43
+
44
+ /**
45
+ * @typedef {object} CompileResult
46
+ * @property {Buffer | string} css css output
47
+ * @property {RawSourceMap=} sourceMap source map
48
+ * @property {URL[]} loadedUrls loaded URLs
49
+ */
50
+
51
+ /**
52
+ * @typedef {object} Importer
53
+ * @property {(originalUrl: string, context: { containingUrl: URL | null, fromImport: boolean }) => Promise<URL | null>} canonicalize canonicalize
54
+ * @property {(canonicalUrl: URL) => Promise<{ contents: string, syntax: "scss" | "indented" | "css", sourceMapUrl?: URL } | null>} load load
55
+ */
56
+
57
+ /** @typedef {"expanded" | "compressed"} OutputStyle */
58
+
59
+ /**
60
+ * @typedef {object} KnownSassOptions
61
+ * @property {"scss" | "indented" | "css"=} syntax syntax
62
+ * @property {URL=} url url
63
+ * @property {"expanded" | "compressed"=} style style
64
+ * @property {string[]=} loadPaths load paths
65
+ * @property {boolean=} sourceMap source map
66
+ * @property {boolean=} sourceMapIncludeSources source map include sources
67
+ * @property {Importer[]=} importers importers
68
+ * @property {Logger=} logger logger
69
+ */
70
+
71
+ /** @typedef {KnownSassOptions & Record<string, EXPECTED_ANY>} SassOptions */
72
+
73
+ /**
74
+ * @typedef {object} AsyncCompiler
75
+ * @property {(source: string, options?: SassOptions) => Promise<CompileResult>} compileStringAsync compile a string
76
+ * @property {() => Promise<void>} dispose dispose the compiler
77
+ */
78
+
79
+ /** @typedef {{ info: string; compileStringAsync(source: string, options?: SassOptions): Promise<CompileResult>; initAsyncCompiler?(): Promise<AsyncCompiler> }} SassImplementation */
80
+
81
+ /** @typedef {"auto" | "modern" | "modern-compiler"} ApiType */
82
+
83
+ /** @typedef {import("webpack").LoaderContext<LoaderOptions>} LoaderContext */
84
+
85
+ /**
86
+ * @typedef {object} LoaderOptions
87
+ * @property {SassImplementation=} implementation SaSS implementation
88
+ * @property {SassOptions | ((loaderContext: LoaderContext) => SassOptions)=} sassOptions SaSS options
89
+ * @property {boolean=} sourceMap true if source map is enabled, otherwise false
90
+ * @property {string | ((content: string, loaderContext: LoaderContext) => string)=} additionalData prepends Sass/SCSS code before the actual entry file
91
+ * @property {boolean=} webpackImporter true if webpack importer is enabled, otherwise false
92
+ * @property {ApiType=} api API type
93
+ * @property {boolean=} warnRuleAsWarning true if treats the `@warn` rule as a webpack warning, otherwise false
94
+ */
95
+
96
+ /** @typedef {(context: string, request: string, fromImport?: boolean) => Promise<string>} Resolver */
97
+ /** @typedef {{ resolve: (context: string, request: string) => Promise<string>, context: string, possibleRequests: string[] }[]} ResolutionMap */
98
+ /** @typedef {{ version: number, sources: string[], names: string[], sourceRoot?: string, sourcesContent?: string[], mappings: string, file: string, debugId?: string, ignoreList?: number[] }} RawSourceMap */
99
+ /** @typedef {Error & { formatted?: string, span?: { url?: URL, start: { line: number, column: number }, context?: string } }} SassError */
100
+
101
+ /**
102
+ * Convert a string `implementation` option into something the ECMAScript
103
+ * `import()` expression actually accepts. Bare package specifiers and
104
+ * `file:` URLs are passed through unchanged; absolute filesystem paths
105
+ * (including Windows paths like `C:\\...`) are converted to `file:` URLs
106
+ * — dynamic `import()` rejects those otherwise.
107
+ * @param {string} specifier import specifier
108
+ * @returns {string} a valid dynamic import specifier
109
+ */
110
+ function normalizeImportSpecifier(specifier) {
111
+ if (specifier.startsWith("file:")) {
112
+ return specifier;
113
+ }
114
+ if (_nodePath.default.isAbsolute(specifier)) {
115
+ return _nodeUrl.default.pathToFileURL(specifier).href;
46
116
  }
47
- return require(sassImplPkg);
117
+ return specifier;
48
118
  }
49
119
 
50
120
  /**
51
121
  * This function is not Webpack-specific and can be used by tools wishing to mimic `sass-loader`'s behaviour, so its signature should not be changed.
52
- * @param {LoaderContext} loaderContext loader context
53
- * @param {SassImplementation} implementation sass implementation
54
- * @returns {SassImplementation} resolved sass implementation
122
+ * @param {SassImplementation | string | undefined} implementation sass implementation
123
+ * @returns {Promise<SassImplementation>} resolved sass implementation
55
124
  */
56
- function getSassImplementation(loaderContext, implementation) {
57
- let resolvedImplementation = implementation;
58
- if (!resolvedImplementation) {
59
- resolvedImplementation = getDefaultSassImplementation();
60
- }
61
- if (typeof resolvedImplementation === "string") {
62
- resolvedImplementation = require(resolvedImplementation);
125
+ async function getSassImplementation(implementation) {
126
+ /** @type {SassImplementation} */
127
+ let resolvedImplementation;
128
+ if (!implementation) {
129
+ try {
130
+ resolvedImplementation = /** @type {SassImplementation} */
131
+ await import("sass-embedded");
132
+ } catch (err) {
133
+ // Only fall back to `sass` when `sass-embedded` is not installed.
134
+ // Any other failure (e.g. a broken install or a side-effect throw at
135
+ // module-load time) should surface so the user can diagnose it
136
+ // instead of being silently masked by the `sass` fallback.
137
+ const {
138
+ code
139
+ } = /** @type {NodeJS.ErrnoException} */err;
140
+ if (code !== "ERR_MODULE_NOT_FOUND" && code !== "MODULE_NOT_FOUND") {
141
+ throw err;
142
+ }
143
+ resolvedImplementation = /** @type {SassImplementation} */
144
+ await import("sass");
145
+ }
146
+ } else if (typeof implementation === "string") {
147
+ resolvedImplementation = /** @type {SassImplementation} */
148
+ await import(normalizeImportSpecifier(implementation));
149
+ } else {
150
+ resolvedImplementation = implementation;
63
151
  }
64
152
  const {
65
153
  info
@@ -74,8 +162,6 @@ function getSassImplementation(loaderContext, implementation) {
74
162
  const [implementationName] = infoParts;
75
163
  if (implementationName === "dart-sass") {
76
164
  return resolvedImplementation;
77
- } else if (implementationName === "node-sass") {
78
- return resolvedImplementation;
79
165
  } else if (implementationName === "sass-embedded") {
80
166
  return resolvedImplementation;
81
167
  }
@@ -90,33 +176,18 @@ function isProductionLikeMode(loaderContext) {
90
176
  return loaderContext.mode === "production" || !loaderContext.mode;
91
177
  }
92
178
 
93
- /**
94
- * @param {Importer[]} importers importers
95
- * @param {LoaderContext} loaderContext loader context
96
- * @returns {Importer[]} proxied importers
97
- */
98
- function proxyCustomImporters(importers, loaderContext) {
99
- return [importers].flat().map(importer => function proxyImporter(...args) {
100
- const self = {
101
- ...this,
102
- webpackLoaderContext: loaderContext
103
- };
104
- return importer.apply(self, args);
105
- });
106
- }
107
-
108
179
  /**
109
180
  * Derives the sass options from the loader context and normalizes its values with sane defaults.
110
181
  * @param {LoaderContext} loaderContext loader context
111
182
  * @param {LoaderOptions} loaderOptions loader options
112
183
  * @param {string} content content
113
- * @param {SassImplementation} implementation sass implementation
114
184
  * @param {boolean} useSourceMap true when need to generate source maps, otherwise false
115
- * @param {"legacy" | "modern" | "modern-compiler"} apiType api type
116
- * @returns {SassOptions} sass options
185
+ * @returns {Promise<Required<KnownSassOptions> & { data: string }>} sass options
117
186
  */
118
- async function getSassOptions(loaderContext, loaderOptions, content, implementation, useSourceMap, apiType) {
187
+ async function getSassOptions(loaderContext, loaderOptions, content, useSourceMap) {
188
+ /** @type {SassOptions} */
119
189
  const options = loaderOptions.sassOptions ? typeof loaderOptions.sassOptions === "function" ? loaderOptions.sassOptions(loaderContext) || {} : loaderOptions.sassOptions : {};
190
+ /** @type {KnownSassOptions & { data: string }} */
120
191
  const sassOptions = {
121
192
  ...options,
122
193
  data: loaderOptions.additionalData ? typeof loaderOptions.additionalData === "function" ? await loaderOptions.additionalData(content, loaderContext) : `${loaderOptions.additionalData}\n${content}` : content
@@ -124,9 +195,22 @@ async function getSassOptions(loaderContext, loaderOptions, content, implementat
124
195
  if (!sassOptions.logger) {
125
196
  const needEmitWarning = loaderOptions.warnRuleAsWarning !== false;
126
197
  const logger = loaderContext.getLogger("sass-loader");
198
+ /**
199
+ * @param {SourceSpan} span span
200
+ * @returns {string} formatted span
201
+ */
127
202
  const formatSpan = span => `Warning on line ${span.start.line}, column ${span.start.column} of ${span.url || "-"}:${span.start.line}:${span.start.column}:\n`;
203
+ /**
204
+ * @param {SourceSpan} span span
205
+ * @returns {string} formatted debug span
206
+ */
128
207
  const formatDebugSpan = span => `[debug:${span.start.line}:${span.start.column}] `;
129
208
  sassOptions.logger = {
209
+ /**
210
+ * @param {string} message message
211
+ * @param {{ span: SourceSpan }} loggerOptions logger options
212
+ * @returns {void}
213
+ */
130
214
  debug(message, loggerOptions) {
131
215
  let builtMessage = "";
132
216
  if (loggerOptions.span) {
@@ -135,6 +219,11 @@ async function getSassOptions(loaderContext, loaderOptions, content, implementat
135
219
  builtMessage += message;
136
220
  logger.debug(builtMessage);
137
221
  },
222
+ /**
223
+ * @param {string} message message
224
+ * @param {LoggerWarnOptions} loggerOptions logger options
225
+ * @returns {void}
226
+ */
138
227
  warn(message, loggerOptions) {
139
228
  let builtMessage = "";
140
229
  if (loggerOptions.deprecation) {
@@ -153,7 +242,7 @@ async function getSassOptions(loaderContext, loaderOptions, content, implementat
153
242
  if (needEmitWarning) {
154
243
  const warning = new Error(builtMessage);
155
244
  warning.name = "SassWarning";
156
- warning.stack = null;
245
+ warning.stack = undefined;
157
246
  loaderContext.emitWarning(warning);
158
247
  } else {
159
248
  logger.warn(builtMessage);
@@ -161,81 +250,36 @@ async function getSassOptions(loaderContext, loaderOptions, content, implementat
161
250
  }
162
251
  };
163
252
  }
164
- const isModernAPI = apiType === "modern" || apiType === "modern-compiler";
165
253
  const {
166
254
  resourcePath
167
255
  } = loaderContext;
168
- if (isModernAPI) {
169
- sassOptions.url = _nodeUrl.default.pathToFileURL(resourcePath);
256
+ sassOptions.url = _nodeUrl.default.pathToFileURL(resourcePath);
170
257
 
171
- // opt.outputStyle
172
- if (!sassOptions.style && isProductionLikeMode(loaderContext)) {
173
- sassOptions.style = "compressed";
174
- }
175
- if (useSourceMap) {
176
- sassOptions.sourceMap = true;
177
- sassOptions.sourceMapIncludeSources = true;
178
- }
179
-
180
- // If we are compiling sass and indentedSyntax isn't set, automatically set it.
181
- if (typeof sassOptions.syntax === "undefined") {
182
- const ext = _nodePath.default.extname(resourcePath);
183
- if (ext && ext.toLowerCase() === ".scss") {
184
- sassOptions.syntax = "scss";
185
- } else if (ext && ext.toLowerCase() === ".sass") {
186
- sassOptions.syntax = "indented";
187
- } else if (ext && ext.toLowerCase() === ".css") {
188
- sassOptions.syntax = "css";
189
- }
190
- }
191
- sassOptions.loadPaths = [
192
- // We use `loadPaths` in context for resolver, so it should be always absolute
193
- ...(sassOptions.loadPaths ? [...sassOptions.loadPaths] : []).map(includePath => _nodePath.default.isAbsolute(includePath) ? includePath : _nodePath.default.join(process.cwd(), includePath)), ...(process.env.SASS_PATH ? process.env.SASS_PATH.split(process.platform === "win32" ? ";" : ":") : [])];
194
- sassOptions.importers = sassOptions.importers ? Array.isArray(sassOptions.importers) ? [...sassOptions.importers] : [sassOptions.importers] : [];
195
- } else {
196
- sassOptions.file = resourcePath;
258
+ // opt.outputStyle
259
+ if (!sassOptions.style && isProductionLikeMode(loaderContext)) {
260
+ sassOptions.style = "compressed";
261
+ }
262
+ if (useSourceMap) {
263
+ sassOptions.sourceMap = true;
264
+ sassOptions.sourceMapIncludeSources = true;
265
+ }
197
266
 
198
- // opt.outputStyle
199
- if (!sassOptions.outputStyle && isProductionLikeMode(loaderContext)) {
200
- sassOptions.outputStyle = "compressed";
201
- }
202
- if (useSourceMap) {
203
- // Deliberately overriding the sourceMap option here.
204
- // node-sass won't produce source maps if the data option is used and options.sourceMap is not a string.
205
- // In case it is a string, options.sourceMap should be a path where the source map is written.
206
- // But since we're using the data option, the source map will not actually be written, but
207
- // all paths in sourceMap.sources will be relative to that path.
208
- // Pretty complicated... :(
209
- sassOptions.sourceMap = true;
210
- sassOptions.outFile = _nodePath.default.join(loaderContext.rootContext, "style.css.map");
211
- sassOptions.sourceMapContents = true;
212
- sassOptions.omitSourceMapUrl = true;
213
- sassOptions.sourceMapEmbed = false;
214
- }
267
+ // If we are compiling sass and indentedSyntax isn't set, automatically set it.
268
+ if (typeof sassOptions.syntax === "undefined") {
215
269
  const ext = _nodePath.default.extname(resourcePath);
216
-
217
- // If we are compiling sass and indentedSyntax isn't set, automatically set it.
218
- if (ext && ext.toLowerCase() === ".sass" && typeof sassOptions.indentedSyntax === "undefined") {
219
- sassOptions.indentedSyntax = true;
220
- } else {
221
- sassOptions.indentedSyntax = Boolean(sassOptions.indentedSyntax);
222
- }
223
-
224
- // Allow passing custom importers to `sass`/`node-sass`. Accepts `Function` or an array of `Function`s.
225
- sassOptions.importer = sassOptions.importer ? proxyCustomImporters(Array.isArray(sassOptions.importer) ? [...sassOptions.importer] : [sassOptions.importer], loaderContext) : [];
226
-
227
- // Regression on the `sass-embedded` side
228
- if (loaderOptions.webpackImporter === false && sassOptions.importer.length === 0) {
229
- sassOptions.importer = undefined;
230
- }
231
- sassOptions.includePaths = [process.cwd(), ...
232
- // We use `includePaths` in context for resolver, so it should be always absolute
233
- (sassOptions.includePaths ? [...sassOptions.includePaths] : []).map(includePath => _nodePath.default.isAbsolute(includePath) ? includePath : _nodePath.default.join(process.cwd(), includePath)), ...(process.env.SASS_PATH ? process.env.SASS_PATH.split(process.platform === "win32" ? ";" : ":") : [])];
234
- if (typeof sassOptions.charset === "undefined") {
235
- sassOptions.charset = true;
270
+ if (ext && ext.toLowerCase() === ".scss") {
271
+ sassOptions.syntax = "scss";
272
+ } else if (ext && ext.toLowerCase() === ".sass") {
273
+ sassOptions.syntax = "indented";
274
+ } else if (ext && ext.toLowerCase() === ".css") {
275
+ sassOptions.syntax = "css";
236
276
  }
237
277
  }
238
- return sassOptions;
278
+ sassOptions.loadPaths = [
279
+ // We use `loadPaths` in context for resolver, so it should be always absolute
280
+ ...(sassOptions.loadPaths ? [...sassOptions.loadPaths] : []).map(includePath => _nodePath.default.isAbsolute(includePath) ? includePath : _nodePath.default.join(process.cwd(), includePath)), ...(process.env.SASS_PATH ? process.env.SASS_PATH.split(process.platform === "win32" ? ";" : ":") : [])];
281
+ sassOptions.importers = sassOptions.importers ? Array.isArray(sassOptions.importers) ? [...sassOptions.importers] : [sassOptions.importers] : [];
282
+ return /** @type {Required<KnownSassOptions> & { data: string }} */sassOptions;
239
283
  }
240
284
  const MODULE_REQUEST_REGEX = /^[^?]*~/;
241
285
 
@@ -250,7 +294,7 @@ const IS_MODULE_IMPORT = /^~([^/]+|[^/]+\/|@[^/]+[/][^/]+|@[^/]+\/?|@[^/]+[/][^/
250
294
  const IS_PKG_SCHEME = /^pkg:/i;
251
295
 
252
296
  /**
253
- * When `sass`/`node-sass` tries to resolve an import, it uses a special algorithm.
297
+ * When `sass` tries to resolve an import, it uses a special algorithm.
254
298
  * Since the `sass-loader` uses webpack to resolve the modules, we need to simulate that algorithm.
255
299
  * This function returns an array of import paths to try.
256
300
  * The last entry in the array is always the original url to enable straight-forward webpack.config aliases.
@@ -291,8 +335,7 @@ function getPossibleRequests(url, forWebpackResolver = false, fromImport = false
291
335
  // - imports where the URL is written as a url().
292
336
  // - imports that have media queries.
293
337
  //
294
- // The `node-sass` package sends `@import` ending on `.css` to importer, it is bug, so we skip resolve
295
- // Also sass outputs as is `@import "style.css"`, but `@use "style.css"` should include CSS content
338
+ // sass outputs as is `@import "style.css"`, but `@use "style.css"` should include CSS content
296
339
  if (extension === ".css") {
297
340
  return fromImport ? [] : [url];
298
341
  }
@@ -349,7 +392,7 @@ async function startResolving(resolutionMap) {
349
392
  return startResolving(resolutionMap);
350
393
  }
351
394
  }
352
- const IS_SPECIAL_MODULE_IMPORT = /^~[^/]+$/;
395
+
353
396
  // `[drive_letter]:\` + `\\[server]\[sharename]\`
354
397
  const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
355
398
 
@@ -359,14 +402,10 @@ const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
359
402
  * in a Jest transform. Such usages will want to wrap `resolve.create` from
360
403
  * [`enhanced-resolve`]{@link https://github.com/webpack/enhanced-resolve} to
361
404
  * pass as the `resolverFactory` argument.
362
- * @param {ResolveFactory} resolverFactory a factory function for creating a Webpack resolver.
363
- * @param {Sass} implementation the imported Sass implementation, both `sass` (Dart Sass) and `node-sass` are supported.
364
- * @param {string[]=} includePaths the list of include paths passed to Sass.
405
+ * @param {LoaderContext["getResolve"]} resolverFactory a factory function for creating a Webpack resolver.
365
406
  * @returns {Resolver} webpack resolver
366
- * @throws If a compatible Sass implementation cannot be found.
367
407
  */
368
- function getWebpackResolver(resolverFactory, implementation, includePaths = []) {
369
- const isModernSass = implementation && typeof implementation.compileStringAsync !== "undefined";
408
+ function getWebpackResolver(resolverFactory) {
370
409
  // We only have one difference with the built-in sass resolution logic and out resolution logic:
371
410
  // First, we look at the files starting with `_`, then without `_` (i.e. `_name.sass`, `_name.scss`, `_name.css`, `name.sass`, `name.scss`, `name.css`),
372
411
  // although `sass` look together by extensions (i.e. `_name.sass`/`name.sass`/`_name.scss`/`name.scss`/`_name.css`/`name.css`).
@@ -375,32 +414,6 @@ function getWebpackResolver(resolverFactory, implementation, includePaths = [])
375
414
  // - on having `_name.sass` and `_name.scss` in the same directory
376
415
  //
377
416
  // Also `sass` prefer `sass`/`scss` over `css`.
378
- const sassModuleResolve = promiseResolve(resolverFactory({
379
- alias: [],
380
- aliasFields: [],
381
- conditionNames: [],
382
- descriptionFiles: [],
383
- extensions: [".sass", ".scss", ".css"],
384
- exportsFields: [],
385
- mainFields: [],
386
- mainFiles: ["_index", "index"],
387
- modules: [],
388
- restrictions: [/\.((sa|sc|c)ss)$/i],
389
- preferRelative: true
390
- }));
391
- const sassImportResolve = promiseResolve(resolverFactory({
392
- alias: [],
393
- aliasFields: [],
394
- conditionNames: [],
395
- descriptionFiles: [],
396
- extensions: [".sass", ".scss", ".css"],
397
- exportsFields: [],
398
- mainFields: [],
399
- mainFiles: ["_index.import", "_index", "index.import", "index"],
400
- modules: [],
401
- restrictions: [/\.((sa|sc|c)ss)$/i],
402
- preferRelative: true
403
- }));
404
417
  const webpackModuleResolve = promiseResolve(resolverFactory({
405
418
  dependencyType: "sass",
406
419
  conditionNames: ["sass", "style", "..."],
@@ -420,12 +433,6 @@ function getWebpackResolver(resolverFactory, implementation, includePaths = [])
420
433
  preferRelative: true
421
434
  }));
422
435
  return (context, request, fromImport) => {
423
- // See https://github.com/webpack/webpack/issues/12340
424
- // Because `node-sass` calls our importer before `1. Filesystem imports relative to the base file.`
425
- // custom importer may not return `{ file: '/path/to/name.ext' }` and therefore our `context` will be relative
426
- if (!isModernSass && !_nodePath.default.isAbsolute(context)) {
427
- return Promise.reject();
428
- }
429
436
  const originalRequest = request;
430
437
  const isFileScheme = originalRequest.slice(0, 5).toLowerCase() === "file:";
431
438
  if (isFileScheme) {
@@ -435,43 +442,9 @@ function getWebpackResolver(resolverFactory, implementation, includePaths = [])
435
442
  request = request.slice(7);
436
443
  }
437
444
  }
445
+
446
+ /** @type {ResolutionMap} */
438
447
  let resolutionMap = [];
439
- const needEmulateSassResolver =
440
- // `sass` doesn't support module import
441
- !IS_SPECIAL_MODULE_IMPORT.test(request) &&
442
- // don't handle `pkg:` scheme
443
- !IS_PKG_SCHEME.test(request) &&
444
- // We need improve absolute paths handling.
445
- // Absolute paths should be resolved:
446
- // - Server-relative URLs - `<context>/path/to/file.ext` (where `<context>` is root context)
447
- // - Absolute path - `/full/path/to/file.ext` or `C:\\full\path\to\file.ext`
448
- !isFileScheme && !originalRequest.startsWith("/") && !IS_NATIVE_WIN32_PATH.test(originalRequest);
449
- if (includePaths.length > 0 && needEmulateSassResolver) {
450
- // The order of import precedence is as follows:
451
- //
452
- // 1. Filesystem imports relative to the base file.
453
- // 2. Custom importer imports.
454
- // 3. Filesystem imports relative to the working directory.
455
- // 4. Filesystem imports relative to an `includePaths` path.
456
- // 5. Filesystem imports relative to a `SASS_PATH` path.
457
- //
458
- // `sass` run custom importers before `3`, `4` and `5` points, we need to emulate this behavior to avoid wrong resolution.
459
- const sassPossibleRequests = getPossibleRequests(request, false, fromImport);
460
-
461
- // `node-sass` calls our importer before `1. Filesystem imports relative to the base file.`, so we need emulate this too
462
- if (!isModernSass) {
463
- resolutionMap = [...resolutionMap, {
464
- resolve: fromImport ? sassImportResolve : sassModuleResolve,
465
- context: _nodePath.default.dirname(context),
466
- possibleRequests: sassPossibleRequests
467
- }];
468
- }
469
- resolutionMap = [...resolutionMap, ...includePaths.map(context => ({
470
- resolve: fromImport ? sassImportResolve : sassModuleResolve,
471
- context,
472
- possibleRequests: sassPossibleRequests
473
- }))];
474
- }
475
448
  const webpackPossibleRequests = getPossibleRequests(request, true, fromImport);
476
449
  resolutionMap = [...resolutionMap, {
477
450
  resolve: fromImport ? webpackImportResolve : webpackModuleResolve,
@@ -481,17 +454,19 @@ function getWebpackResolver(resolverFactory, implementation, includePaths = [])
481
454
  return startResolving(resolutionMap);
482
455
  };
483
456
  }
484
- const MATCH_CSS = /\.css$/i;
485
457
 
486
458
  /**
487
459
  * @param {LoaderContext} loaderContext loader context
488
- * @param {SassImplementation} implementation sass implementation
489
- * @param {string[]} loadPaths load paths
490
460
  * @returns {Importer} the modern webpack importer
491
461
  */
492
- function getModernWebpackImporter(loaderContext, implementation, loadPaths) {
493
- const resolve = getWebpackResolver(loaderContext.getResolve, implementation, loadPaths);
462
+ function getModernWebpackImporter(loaderContext) {
463
+ const resolve = getWebpackResolver(loaderContext.getResolve);
494
464
  return {
465
+ /**
466
+ * @param {string} originalUrl original url
467
+ * @param {{ fromImport: boolean, containingUrl: URL | null }} context context
468
+ * @returns {Promise<URL | null>} canonicalized URL
469
+ */
495
470
  async canonicalize(originalUrl, context) {
496
471
  const {
497
472
  fromImport
@@ -507,8 +482,14 @@ function getModernWebpackImporter(loaderContext, implementation, loadPaths) {
507
482
  loaderContext.addDependency(_nodePath.default.normalize(result));
508
483
  return _nodeUrl.default.pathToFileURL(result);
509
484
  },
485
+ /**
486
+ * @param {URL} canonicalUrl canonical url
487
+ * @returns {Promise<{ contents: string, syntax: "scss" | "indented" | "css", sourceMapUrl: URL } | null>} load result
488
+ */
510
489
  async load(canonicalUrl) {
511
490
  const ext = _nodePath.default.extname(canonicalUrl.pathname);
491
+
492
+ /** @type {"scss" | "indented" | "css"} */
512
493
  let syntax;
513
494
  if (ext && ext.toLowerCase() === ".scss") {
514
495
  syntax = "scss";
@@ -521,12 +502,19 @@ function getModernWebpackImporter(loaderContext, implementation, loadPaths) {
521
502
  syntax = "scss";
522
503
  }
523
504
  try {
524
- const contents = await new Promise((resolve, reject) => {
505
+ const contents = /** @type {string} */
506
+ await new Promise((resolve, reject) => {
525
507
  // Old version of `enhanced-resolve` supports only path as a string
526
508
  // TODO simplify in the next major release and pass URL
527
509
  const canonicalPath = _nodeUrl.default.fileURLToPath(canonicalUrl);
528
- loaderContext.fs.readFile(canonicalPath, (err, content) => {
529
- if (err) {
510
+ loaderContext.fs.readFile(canonicalPath,
511
+ /**
512
+ * @param {NodeJS.ErrnoException | null} err error
513
+ * @param {Buffer | undefined} content content
514
+ * @returns {void}
515
+ */
516
+ (err, content) => {
517
+ if (err || !content) {
530
518
  reject(err);
531
519
  return;
532
520
  }
@@ -545,132 +533,67 @@ function getModernWebpackImporter(loaderContext, implementation, loadPaths) {
545
533
  };
546
534
  }
547
535
 
548
- /**
549
- * @param {LoaderContext} loaderContext loader context
550
- * @param {SassImplementation} implementation sass implementation
551
- * @param {string[]} includePaths include paths
552
- * @returns {Importer} the webpack importer
553
- */
554
- function getWebpackImporter(loaderContext, implementation, includePaths) {
555
- const resolve = getWebpackResolver(loaderContext.getResolve, implementation, includePaths);
556
- return function importer(originalUrl, prev, done) {
557
- const {
558
- fromImport
559
- } = this;
560
- resolve(prev, originalUrl,
561
- // For `node-sass`
562
- typeof fromImport === "undefined" ? true : fromImport).then(result => {
563
- // Add the result as dependency.
564
- // Although we're also using stats.includedFiles, this might come in handy when an error occurs.
565
- // In this case, we don't get stats.includedFiles from node-sass/sass.
566
- loaderContext.addDependency(_nodePath.default.normalize(result));
567
-
568
- // By removing the CSS file extension, we trigger node-sass to include the CSS file instead of just linking it.
569
- done({
570
- file: result.replace(MATCH_CSS, "")
571
- });
572
- })
573
- // Catch all resolving errors, return the original file and pass responsibility back to other custom importers
574
- .catch(() => {
575
- done({
576
- file: originalUrl
577
- });
578
- });
579
- };
580
- }
581
- let nodeSassJobQueue = null;
536
+ /** @type {WeakMap<import("webpack").Compiler, AsyncCompiler>} */
582
537
  const sassModernCompilers = new WeakMap();
583
538
 
584
539
  /**
585
540
  * Verifies that the implementation and version of Sass is supported by this loader.
541
+ * @template {SassImplementation} T
586
542
  * @param {LoaderContext} loaderContext loader context
587
- * @param {SassImplementation} implementation sass implementation
588
- * @param {"legacy" | "modern" | "modern-compiler"} apiType api type
589
- * @returns {SassCompileFunction} compile function
543
+ * @param {T} implementation sass implementation
544
+ * @param {ApiType=} apiType api type
545
+ * @returns {(sassOptions: SassOptions & { data: string }) => Promise<CompileResult>} compile function
590
546
  */
591
- function getCompileFn(loaderContext, implementation, apiType) {
592
- if (typeof implementation.compileStringAsync !== "undefined") {
593
- if (apiType === "modern") {
594
- return sassOptions => {
595
- const {
596
- data,
597
- ...rest
598
- } = sassOptions;
599
- return implementation.compileStringAsync(data, rest);
600
- };
601
- }
602
- if (apiType === "modern-compiler") {
603
- return async sassOptions => {
604
- const webpackCompiler = loaderContext._compiler;
605
- const {
606
- data,
607
- ...rest
608
- } = sassOptions;
609
-
610
- // Some people can run the loader in a multi-threading way;
611
- // there is no webpack compiler object in such case.
612
- if (webpackCompiler) {
547
+ function getCompileFn(loaderContext, implementation, apiType = "auto") {
548
+ const {
549
+ initAsyncCompiler
550
+ } = implementation;
551
+ if (apiType === "modern-compiler" || apiType === "auto" && typeof initAsyncCompiler === "function") {
552
+ return async (/** @type {SassOptions & { data: string }} */sassOptions) => {
553
+ const webpackCompiler = /** @type {LoaderContext & { _compiler?: import("webpack").Compiler }} */
554
+ loaderContext._compiler;
555
+ const {
556
+ data,
557
+ ...rest
558
+ } = sassOptions;
559
+
560
+ // Some people can run the loader in a multi-threading way;
561
+ // there is no webpack compiler object in such case.
562
+ if (webpackCompiler && initAsyncCompiler) {
563
+ if (!sassModernCompilers.has(webpackCompiler)) {
564
+ // Create a long-running compiler process that can be reused
565
+ // for compiling individual files.
566
+ const compiler = await initAsyncCompiler();
567
+
568
+ // Check again because awaiting the initialization function
569
+ // introduces a race condition.
613
570
  if (!sassModernCompilers.has(webpackCompiler)) {
614
- // Create a long-running compiler process that can be reused
615
- // for compiling individual files.
616
- const compiler = await implementation.initAsyncCompiler();
617
-
618
- // Check again because awaiting the initialization function
619
- // introduces a race condition.
620
- if (!sassModernCompilers.has(webpackCompiler)) {
621
- sassModernCompilers.set(webpackCompiler, compiler);
622
- webpackCompiler.hooks.shutdown.tap("sass-loader", () => {
623
- compiler.dispose();
624
- });
625
- } else {
571
+ sassModernCompilers.set(webpackCompiler, compiler);
572
+ webpackCompiler.hooks.shutdown.tap("sass-loader", () => {
626
573
  compiler.dispose();
627
- }
574
+ });
575
+ } else {
576
+ compiler.dispose();
628
577
  }
629
- return sassModernCompilers.get(webpackCompiler).compileStringAsync(data, rest);
630
578
  }
631
- return implementation.compileStringAsync(data, rest);
632
- };
633
- }
634
- return sassOptions => new Promise((resolve, reject) => {
635
- implementation.render(sassOptions, (error, result) => {
636
- if (error) {
637
- reject(error);
638
- return;
639
- }
640
- resolve(result);
641
- });
642
- });
643
- }
644
- if (apiType === "modern" || apiType === "modern-compiler") {
645
- throw new Error("Modern API is not supported for 'node-sass'");
646
- }
647
-
648
- // There is an issue with node-sass when async custom importers are used
649
- // See https://github.com/sass/node-sass/issues/857#issuecomment-93594360
650
- // We need to use a job queue to make sure that one thread is always available to the UV lib
651
- if (nodeSassJobQueue === null) {
652
- const threadPoolSize = Number(process.env.UV_THREADPOOL_SIZE || 4);
653
-
654
- // Only used for `node-sass`, so let's load it lazily
655
-
656
- const async = require("neo-async");
657
- nodeSassJobQueue = async.queue(implementation.render.bind(implementation), threadPoolSize - 1);
658
- }
659
- return sassOptions => new Promise((resolve, reject) => {
660
- nodeSassJobQueue.push.bind(nodeSassJobQueue)(sassOptions, (error, result) => {
661
- if (error) {
662
- reject(error);
663
- return;
579
+ return /** @type {AsyncCompiler} */sassModernCompilers.get(webpackCompiler).compileStringAsync(/** @type {string} */data, rest);
664
580
  }
665
- resolve(result);
666
- });
667
- });
581
+ return implementation.compileStringAsync(/** @type {string} */data, rest);
582
+ };
583
+ }
584
+ return (/** @type {SassOptions & { data: string }} */sassOptions) => {
585
+ const {
586
+ data,
587
+ ...rest
588
+ } = sassOptions;
589
+ return implementation.compileStringAsync(/** @type {string} */data, rest);
590
+ };
668
591
  }
669
592
  const ABSOLUTE_SCHEME = /^[A-Za-z0-9+\-.]+:/;
670
593
 
671
594
  /**
672
595
  * @param {string} source source
673
- * @returns {"absolute" | "scheme-relative" | "path-absolute" | "path-absolute"} a type of URL
596
+ * @returns {"absolute" | "scheme-relative" | "path-absolute" | "path-relative"} a type of URL
674
597
  */
675
598
  function getURLType(source) {
676
599
  if (source[0] === "/") {
@@ -697,15 +620,16 @@ function normalizeSourceMap(map, rootContext) {
697
620
  // Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
698
621
 
699
622
  if (typeof newMap.file !== "undefined") {
623
+ // @ts-expect-error need to fix on webpack side
700
624
  delete newMap.file;
701
625
  }
702
626
  newMap.sourceRoot = "";
703
627
 
704
- // node-sass returns POSIX paths, that's why we need to transform them back to native paths.
628
+ // sass returns POSIX paths, that's why we need to transform them back to native paths.
705
629
  // This fixes an error on windows where the source-map module cannot resolve the source maps.
706
630
  // @see https://github.com/webpack/sass-loader/issues/366#issuecomment-279460722
707
631
 
708
- newMap.sources = newMap.sources.map(source => {
632
+ newMap.sources = newMap.sources.map((/** @type {string} */source) => {
709
633
  const sourceType = getURLType(source);
710
634
 
711
635
  // Do no touch `scheme-relative`, `path-absolute` and `absolute` types (except `file:`)
@@ -718,17 +642,114 @@ function normalizeSourceMap(map, rootContext) {
718
642
  });
719
643
  return newMap;
720
644
  }
645
+ const BASE64_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
646
+ const VLQ_BASE_SHIFT = 5;
647
+ const VLQ_BASE = 1 << VLQ_BASE_SHIFT;
648
+ const VLQ_BASE_MASK = VLQ_BASE - 1;
649
+ const VLQ_CONTINUATION_BIT = VLQ_BASE;
650
+
651
+ /**
652
+ * Decodes the first Base64 VLQ value of the given `mappings`.
653
+ * @param {string} mappings mappings of a source map
654
+ * @returns {{ value: number, length: number } | null} the decoded value and how many characters it takes, `null` when `mappings` doesn't start with a value
655
+ */
656
+ function decodeVLQ(mappings) {
657
+ let value = 0;
658
+ let shift = 0;
659
+ let length = 0;
660
+ let digit;
661
+ do {
662
+ digit = BASE64_CHARACTERS.indexOf(mappings[length]);
663
+ if (digit === -1) {
664
+ return null;
665
+ }
666
+ value += (digit & VLQ_BASE_MASK) << shift;
667
+ shift += VLQ_BASE_SHIFT;
668
+ length += 1;
669
+ } while ((digit & VLQ_CONTINUATION_BIT) !== 0);
670
+ const isNegative = (value & 1) === 1;
671
+ value >>= 1;
672
+ return {
673
+ value: isNegative ? -value : value,
674
+ length
675
+ };
676
+ }
677
+
678
+ /**
679
+ * @param {number} value value
680
+ * @returns {string} the Base64 VLQ encoded value
681
+ */
682
+ function encodeVLQ(value) {
683
+ let encoded = "";
684
+ let vlq = value < 0 ? -value << 1 | 1 : value << 1;
685
+ do {
686
+ let digit = vlq & VLQ_BASE_MASK;
687
+ vlq >>>= VLQ_BASE_SHIFT;
688
+ if (vlq > 0) {
689
+ digit |= VLQ_CONTINUATION_BIT;
690
+ }
691
+ encoded += BASE64_CHARACTERS[digit];
692
+ } while (vlq > 0);
693
+ return encoded;
694
+ }
695
+
696
+ /**
697
+ * Removes the byte order mark (BOM) from the compiled CSS.
698
+ *
699
+ * `dart-sass` prepends a BOM when the `charset` option is enabled (by default),
700
+ * the `style` option is `compressed` (the default for the `production` mode) and
701
+ * the compiled CSS contains non ASCII characters.
702
+ * A BOM is only meaningful at the very beginning of a file, but the loader result
703
+ * is just a string for webpack, and tools like `css-loader` move `@import` at-rules
704
+ * above it, so the BOM ends up in the middle of the generated CSS and breaks the
705
+ * first rule after it.
706
+ *
707
+ * Webpack removes a BOM a loader produced itself since
708
+ * https://github.com/webpack/webpack/pull/21857 and keeps the source map in sync
709
+ * with it since https://github.com/webpack/webpack/pull/21861, which makes this a
710
+ * no-op there. It is still needed for the webpack versions the `peerDependencies`
711
+ * range allows and for `rspack`, which passes a string result through untouched.
712
+ * Remove it once both handle this in the minimum version we support.
713
+ * @see https://github.com/webpack/sass-loader/issues/1335
714
+ * @param {string} css compiled CSS
715
+ * @param {RawSourceMap=} map source map
716
+ * @returns {{ css: string, map: RawSourceMap | undefined }} the CSS without the BOM and the source map adjusted to it
717
+ */
718
+ function removeBOM(css, map) {
719
+ if (css.charCodeAt(0) !== 0xfe_ff) {
720
+ return {
721
+ css,
722
+ map
723
+ };
724
+ }
725
+
726
+ // Sass counts the BOM as the first column of the first line, so all mappings
727
+ // of this line need to be shifted by one column.
728
+ // Only the first segment has to be updated - the generated column of the
729
+ // segments after it is relative to the previous one.
730
+ if (map && typeof map.mappings === "string") {
731
+ const decoded = decodeVLQ(map.mappings);
732
+ if (decoded && decoded.value > 0) {
733
+ map.mappings = `${encodeVLQ(decoded.value - 1)}${map.mappings.slice(decoded.length)}`;
734
+ }
735
+ }
736
+ return {
737
+ css: css.slice(1),
738
+ map
739
+ };
740
+ }
721
741
 
722
742
  /**
723
743
  * @param {Error | SassError} error the original sass error
724
744
  * @returns {Error} a new error
725
745
  */
726
746
  function errorFactory(error) {
727
- const message = error.formatted ? error.formatted.replace(/^(.+)?Error: /, "") : (error.message || error.toString()).replace(/^(.+)?Error: /, "");
747
+ const sassError = /** @type {SassError} */error;
748
+ const message = sassError.formatted ? sassError.formatted.replace(/^(.+)?Error: /, "") : (error.message || error.toString()).replace(/^(.+)?Error: /, "");
728
749
  const obj = new Error(message, {
729
750
  cause: error
730
751
  });
731
752
  obj.name = error.name;
732
- obj.stack = null;
753
+ obj.stack = undefined;
733
754
  return obj;
734
755
  }