-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathsass-plugin.ts
194 lines (169 loc) · 6.37 KB
/
sass-plugin.ts
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import type { OnLoadResult, PartialMessage, Plugin, PluginBuild, ResolveResult } from 'esbuild';
import assert from 'node:assert';
import { readFile } from 'node:fs/promises';
import { dirname, extname, join, relative } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import type { CompileResult, Exception, Syntax } from 'sass';
import {
FileImporterWithRequestContextOptions,
SassWorkerImplementation,
} from '../../sass/sass-service';
export interface SassPluginOptions {
sourcemap: boolean;
loadPaths?: string[];
inlineComponentData?: Record<string, string>;
}
let sassWorkerPool: SassWorkerImplementation | undefined;
function isSassException(error: unknown): error is Exception {
return !!error && typeof error === 'object' && 'sassMessage' in error;
}
export function shutdownSassWorkerPool(): void {
sassWorkerPool?.close();
sassWorkerPool = undefined;
}
export function createSassPlugin(options: SassPluginOptions): Plugin {
return {
name: 'angular-sass',
setup(build: PluginBuild): void {
const resolveUrl = async (url: string, previousResolvedModules?: Set<string>) => {
let result = await build.resolve(url, {
kind: 'import-rule',
// This should ideally be the directory of the importer file from Sass
// but that is not currently available from the Sass importer API.
resolveDir: build.initialOptions.absWorkingDir,
});
// Workaround to support Yarn PnP without access to the importer file from Sass
if (!result.path && previousResolvedModules?.size) {
for (const previous of previousResolvedModules) {
result = await build.resolve(url, {
kind: 'import-rule',
resolveDir: previous,
});
if (result.path) {
break;
}
}
}
return result;
};
build.onLoad({ filter: /^s[ac]ss;/, namespace: 'angular:styles/component' }, async (args) => {
const data = options.inlineComponentData?.[args.path];
assert(data, `component style name should always be found [${args.path}]`);
const [language, , filePath] = args.path.split(';', 3);
const syntax = language === 'sass' ? 'indented' : 'scss';
return compileString(data, filePath, syntax, options, resolveUrl);
});
build.onLoad({ filter: /\.s[ac]ss$/ }, async (args) => {
const data = await readFile(args.path, 'utf-8');
const syntax = extname(args.path).toLowerCase() === '.sass' ? 'indented' : 'scss';
return compileString(data, args.path, syntax, options, resolveUrl);
});
},
};
}
async function compileString(
data: string,
filePath: string,
syntax: Syntax,
options: SassPluginOptions,
resolveUrl: (url: string, previousResolvedModules?: Set<string>) => Promise<ResolveResult>,
): Promise<OnLoadResult> {
// Lazily load Sass when a Sass file is found
sassWorkerPool ??= new SassWorkerImplementation(true);
const warnings: PartialMessage[] = [];
try {
const { css, sourceMap, loadedUrls } = await sassWorkerPool.compileStringAsync(data, {
url: pathToFileURL(filePath),
style: 'expanded',
syntax,
loadPaths: options.loadPaths,
sourceMap: options.sourcemap,
sourceMapIncludeSources: options.sourcemap,
quietDeps: true,
importers: [
{
findFileUrl: async (
url,
{ previousResolvedModules }: FileImporterWithRequestContextOptions,
): Promise<URL | null> => {
const result = await resolveUrl(url, previousResolvedModules);
// Check for package deep imports
if (!result.path) {
const parts = url.split('/');
const hasScope = parts.length >= 2 && parts[0].startsWith('@');
const [nameOrScope, nameOrFirstPath, ...pathPart] = parts;
const packageName = hasScope ? `${nameOrScope}/${nameOrFirstPath}` : nameOrScope;
const packageResult = await resolveUrl(
packageName + '/package.json',
previousResolvedModules,
);
if (packageResult.path) {
return pathToFileURL(
join(
dirname(packageResult.path),
!hasScope && nameOrFirstPath ? nameOrFirstPath : '',
...pathPart,
),
);
}
}
return result.path ? pathToFileURL(result.path) : null;
},
},
],
logger: {
warn: (text, { deprecation, span }) => {
warnings.push({
text: deprecation ? 'Deprecation' : text,
location: span && {
file: span.url && fileURLToPath(span.url),
lineText: span.context,
// Sass line numbers are 0-based while esbuild's are 1-based
line: span.start.line + 1,
column: span.start.column,
},
notes: deprecation ? [{ text }] : undefined,
});
},
},
});
return {
loader: 'css',
contents: sourceMap ? `${css}\n${sourceMapToUrlComment(sourceMap, dirname(filePath))}` : css,
watchFiles: loadedUrls.map((url) => fileURLToPath(url)),
warnings,
};
} catch (error) {
if (isSassException(error)) {
const file = error.span.url ? fileURLToPath(error.span.url) : undefined;
return {
loader: 'css',
errors: [
{
text: error.message,
},
],
warnings,
watchFiles: file ? [file] : undefined,
};
}
throw error;
}
}
function sourceMapToUrlComment(
sourceMap: Exclude<CompileResult['sourceMap'], undefined>,
root: string,
): string {
// Remove `file` protocol from all sourcemap sources and adjust to be relative to the input file.
// This allows esbuild to correctly process the paths.
sourceMap.sources = sourceMap.sources.map((source) => relative(root, fileURLToPath(source)));
const urlSourceMap = Buffer.from(JSON.stringify(sourceMap), 'utf-8').toString('base64');
return `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${urlSourceMap} */`;
}