@parcel/transformer-css 2.0.0-nightly.140 → 2.0.0-nightly.1404

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.
@@ -4,174 +4,369 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
-
8
- var _plugin = require("@parcel/plugin");
9
-
10
- var _utils = require("@parcel/utils");
11
-
12
- var _postcss = _interopRequireDefault(require("postcss"));
13
-
14
- var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
15
-
16
- var _semver = _interopRequireDefault(require("semver"));
17
-
18
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19
-
20
- const URL_RE = /url\s*\("?(?![a-z]+:)/;
21
- const IMPORT_RE = /@import/;
22
-
23
- function canHaveDependencies(filePath, code) {
24
- return !/\.css$/.test(filePath) || IMPORT_RE.test(code) || URL_RE.test(code);
7
+ function _path() {
8
+ const data = _interopRequireDefault(require("path"));
9
+ _path = function () {
10
+ return data;
11
+ };
12
+ return data;
25
13
  }
26
-
27
- var _default = new _plugin.Transformer({
28
- canReuseAST({
29
- ast
30
- }) {
31
- return ast.type === 'postcss' && _semver.default.satisfies(ast.version, '^7.0.0');
32
- },
33
-
34
- async parse({
35
- asset
14
+ function _sourceMap() {
15
+ const data = _interopRequireDefault(require("@parcel/source-map"));
16
+ _sourceMap = function () {
17
+ return data;
18
+ };
19
+ return data;
20
+ }
21
+ function _plugin() {
22
+ const data = require("@parcel/plugin");
23
+ _plugin = function () {
24
+ return data;
25
+ };
26
+ return data;
27
+ }
28
+ function _lightningcss() {
29
+ const data = require("lightningcss");
30
+ _lightningcss = function () {
31
+ return data;
32
+ };
33
+ return data;
34
+ }
35
+ function _utils() {
36
+ const data = require("@parcel/utils");
37
+ _utils = function () {
38
+ return data;
39
+ };
40
+ return data;
41
+ }
42
+ function _browserslist() {
43
+ const data = _interopRequireDefault(require("browserslist"));
44
+ _browserslist = function () {
45
+ return data;
46
+ };
47
+ return data;
48
+ }
49
+ function _nullthrows() {
50
+ const data = _interopRequireDefault(require("nullthrows"));
51
+ _nullthrows = function () {
52
+ return data;
53
+ };
54
+ return data;
55
+ }
56
+ function _diagnostic() {
57
+ const data = _interopRequireWildcard(require("@parcel/diagnostic"));
58
+ _diagnostic = function () {
59
+ return data;
60
+ };
61
+ return data;
62
+ }
63
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
64
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
65
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
66
+ var _default = new (_plugin().Transformer)({
67
+ async loadConfig({
68
+ config,
69
+ options
36
70
  }) {
37
- // This is set by other transformers (e.g. Stylus) to indicate that it has already processed
38
- // all dependencies, and that the CSS transformer can skip this asset completely. This is
39
- // required because when stylus processes e.g. url() it replaces them with a dependency id
40
- // to be filled in later. When the CSS transformer runs, it would pick that up and try to
41
- // resolve a dependency for the id which obviously doesn't exist. Also, it's faster to do
42
- // it this way since the resulting CSS doesn't need to be re-parsed.
43
- if (asset.meta.hasDependencies === false) {
44
- return null;
71
+ var _contents$cssModules, _contents$cssModules2, _contents$cssModules3, _contents$cssModules4;
72
+ let conf = await config.getConfigFrom(options.projectRoot + '/index', [], {
73
+ packageKey: '@parcel/transformer-css'
74
+ });
75
+ let contents = conf === null || conf === void 0 ? void 0 : conf.contents;
76
+ if (typeof (contents === null || contents === void 0 || (_contents$cssModules = contents.cssModules) === null || _contents$cssModules === void 0 ? void 0 : _contents$cssModules.include) === 'string') {
77
+ contents.cssModules.include = [(0, _utils().globToRegex)(contents.cssModules.include)];
78
+ } else if (Array.isArray(contents === null || contents === void 0 || (_contents$cssModules2 = contents.cssModules) === null || _contents$cssModules2 === void 0 ? void 0 : _contents$cssModules2.include)) {
79
+ contents.cssModules.include = contents.cssModules.include.map(include => typeof include === 'string' ? (0, _utils().globToRegex)(include) : include);
45
80
  }
46
-
47
- let code = await asset.getCode();
48
-
49
- if (!canHaveDependencies(asset.filePath, code)) {
50
- return null;
81
+ if (typeof (contents === null || contents === void 0 || (_contents$cssModules3 = contents.cssModules) === null || _contents$cssModules3 === void 0 ? void 0 : _contents$cssModules3.exclude) === 'string') {
82
+ contents.cssModules.exclude = [(0, _utils().globToRegex)(contents.cssModules.exclude)];
83
+ } else if (Array.isArray(contents === null || contents === void 0 || (_contents$cssModules4 = contents.cssModules) === null || _contents$cssModules4 === void 0 ? void 0 : _contents$cssModules4.exclude)) {
84
+ contents.cssModules.exclude = contents.cssModules.exclude.map(exclude => typeof exclude === 'string' ? (0, _utils().globToRegex)(exclude) : exclude);
51
85
  }
52
-
53
- return {
54
- type: 'postcss',
55
- version: '7.0.0',
56
- isDirty: false,
57
- program: _postcss.default.parse(code, {
58
- from: asset.filePath
59
- })
60
- };
86
+ return contents;
61
87
  },
62
-
63
- transform({
64
- asset
88
+ async transform({
89
+ asset,
90
+ config,
91
+ options,
92
+ logger
65
93
  }) {
66
94
  // Normalize the asset's environment so that properties that only affect JS don't cause CSS to be duplicated.
67
95
  // For example, with ESModule and CommonJS targets, only a single shared CSS bundle should be produced.
96
+ let env = asset.env;
68
97
  asset.setEnvironment({
69
98
  context: 'browser',
70
99
  engines: {
71
100
  browsers: asset.env.engines.browsers
72
101
  },
73
- minify: asset.env.minify
74
- }); // When this asset is an bundle entry, allow that bundle to be split to load shared assets separately.
75
- // Only set here if it is null to allow previous transformers to override this behavior.
76
-
77
- if (asset.isSplittable == null) {
78
- asset.isSplittable = true;
102
+ shouldOptimize: asset.env.shouldOptimize,
103
+ shouldScopeHoist: asset.env.shouldScopeHoist,
104
+ sourceMap: asset.env.sourceMap
105
+ });
106
+ let [code, originalMap] = await Promise.all([asset.getBuffer(), asset.getMap()]);
107
+ let targets = getTargets(asset.env.engines.browsers);
108
+ let res;
109
+ try {
110
+ if (asset.meta.type === 'attr') {
111
+ res = (0, _lightningcss().transformStyleAttribute)({
112
+ code,
113
+ analyzeDependencies: true,
114
+ errorRecovery: (config === null || config === void 0 ? void 0 : config.errorRecovery) || false,
115
+ targets
116
+ });
117
+ } else {
118
+ let cssModules = false;
119
+ if (asset.meta.type !== 'tag' && asset.meta.cssModulesCompiled == null) {
120
+ let cssModulesConfig = config === null || config === void 0 ? void 0 : config.cssModules;
121
+ let isCSSModule = /\.module\./.test(asset.filePath);
122
+ if (asset.isSource) {
123
+ var _cssModulesConfig$exc;
124
+ let projectRootPath = _path().default.relative(options.projectRoot, asset.filePath);
125
+ if (typeof cssModulesConfig === 'boolean') {
126
+ isCSSModule = true;
127
+ } else if (cssModulesConfig !== null && cssModulesConfig !== void 0 && cssModulesConfig.include) {
128
+ isCSSModule = cssModulesConfig.include.some(include => include.test(projectRootPath));
129
+ } else if (cssModulesConfig !== null && cssModulesConfig !== void 0 && cssModulesConfig.global) {
130
+ isCSSModule = true;
131
+ }
132
+ if (cssModulesConfig !== null && cssModulesConfig !== void 0 && (_cssModulesConfig$exc = cssModulesConfig.exclude) !== null && _cssModulesConfig$exc !== void 0 && _cssModulesConfig$exc.some(exclude => exclude.test(projectRootPath))) {
133
+ isCSSModule = false;
134
+ }
135
+ }
136
+ if (isCSSModule) {
137
+ if (cssModulesConfig !== null && cssModulesConfig !== void 0 && cssModulesConfig.dashedIdents && !asset.isSource) {
138
+ cssModulesConfig.dashedIdents = false;
139
+ }
140
+ cssModules = cssModulesConfig !== null && cssModulesConfig !== void 0 ? cssModulesConfig : true;
141
+ }
142
+ }
143
+ res = (0, _lightningcss().transform)({
144
+ filename: (0, _utils().normalizeSeparators)(_path().default.relative(options.projectRoot, asset.filePath)),
145
+ code,
146
+ cssModules,
147
+ analyzeDependencies: asset.meta.hasDependencies !== false,
148
+ sourceMap: !!asset.env.sourceMap,
149
+ drafts: config === null || config === void 0 ? void 0 : config.drafts,
150
+ pseudoClasses: config === null || config === void 0 ? void 0 : config.pseudoClasses,
151
+ errorRecovery: (config === null || config === void 0 ? void 0 : config.errorRecovery) || false,
152
+ targets
153
+ });
154
+ }
155
+ } catch (err) {
156
+ var _err$data;
157
+ err.filePath = asset.filePath;
158
+ let diagnostic = (0, _diagnostic().errorToDiagnostic)(err, {
159
+ origin: '@parcel/transformer-css'
160
+ });
161
+ if (((_err$data = err.data) === null || _err$data === void 0 ? void 0 : _err$data.type) === 'AmbiguousUrlInCustomProperty' && err.data.url) {
162
+ let p = '/' + (0, _utils().relativePath)(options.projectRoot, _path().default.resolve(_path().default.dirname(asset.filePath), err.data.url), false);
163
+ diagnostic[0].hints = [`Replace with: url(${p})`];
164
+ diagnostic[0].documentationURL = 'https://parceljs.org/languages/css/#url()';
165
+ }
166
+ throw new (_diagnostic().default)({
167
+ diagnostic
168
+ });
79
169
  }
80
-
81
- let ast = asset.ast; // Check for `hasDependencies` being false here as well, as it's possible
82
- // another transformer (such as PostCSSTransformer) has already parsed an
83
- // ast and CSSTransformer's parse was never called.
84
-
85
- if (!ast || asset.meta.hasDependencies === false) {
86
- return [asset];
170
+ if (res.warnings) {
171
+ for (let warning of res.warnings) {
172
+ logger.warn({
173
+ message: warning.message,
174
+ codeFrames: [{
175
+ filePath: asset.filePath,
176
+ codeHighlights: [{
177
+ start: {
178
+ line: warning.loc.line,
179
+ column: warning.loc.column + 1
180
+ },
181
+ end: {
182
+ line: warning.loc.line,
183
+ column: warning.loc.column + 1
184
+ }
185
+ }]
186
+ }]
187
+ });
188
+ }
87
189
  }
88
-
89
- ast.program.walkAtRules('import', rule => {
90
- let params = (0, _postcssValueParser.default)(rule.params);
91
- let [name, ...media] = params.nodes;
92
- let moduleSpecifier;
93
-
94
- if (name.type === 'function' && name.value === 'url' && name.nodes.length) {
95
- name = name.nodes[0];
190
+ asset.setBuffer(res.code);
191
+ if (res.map != null) {
192
+ let vlqMap = JSON.parse(res.map.toString());
193
+ let map = new (_sourceMap().default)(options.projectRoot);
194
+ map.addVLQMap(vlqMap);
195
+ if (originalMap) {
196
+ map.extends(originalMap);
96
197
  }
97
-
98
- moduleSpecifier = name.value;
99
-
100
- if (!moduleSpecifier) {
101
- throw new Error('Could not find import name for ' + rule);
198
+ asset.setMap(map);
199
+ }
200
+ if (res.dependencies) {
201
+ for (let dep of res.dependencies) {
202
+ let loc = convertLoc(dep.loc);
203
+ if (originalMap) {
204
+ loc = (0, _utils().remapSourceLocation)(loc, originalMap);
205
+ }
206
+ if (dep.type === 'import' && !res.exports) {
207
+ asset.addDependency({
208
+ specifier: dep.url,
209
+ specifierType: 'url',
210
+ loc,
211
+ packageConditions: ['style'],
212
+ meta: {
213
+ // For the glob resolver to distinguish between `@import` and other URL dependencies.
214
+ isCSSImport: true,
215
+ media: dep.media
216
+ }
217
+ });
218
+ } else if (dep.type === 'url') {
219
+ asset.addURLDependency(dep.url, {
220
+ loc,
221
+ meta: {
222
+ placeholder: dep.placeholder
223
+ }
224
+ });
225
+ }
102
226
  }
103
-
104
- if ((0, _utils.isURL)(moduleSpecifier)) {
105
- name.value = asset.addURLDependency(moduleSpecifier, {
106
- loc: (0, _utils.createDependencyLocation)(rule.source.start, moduleSpecifier, 0, 8)
107
- });
108
- } else {
109
- // If this came from an inline <style> tag, don't inline the imported file. Replace with the correct URL instead.
110
- // TODO: run CSSPackager on inline style tags.
111
- // let inlineHTML =
112
- // this.options.rendition && this.options.rendition.inlineHTML;
113
- // if (inlineHTML) {
114
- // name.value = asset.addURLDependency(dep, {loc: rule.source.start});
115
- // rule.params = params.toString();
116
- // } else {
117
- media = _postcssValueParser.default.stringify(media).trim();
118
- let dep = {
119
- moduleSpecifier,
120
- // Offset by 8 as it does not include `@import `
121
- loc: (0, _utils.createDependencyLocation)(rule.source.start, moduleSpecifier, 0, 8),
122
- meta: {
123
- media
124
- }
125
- };
126
- asset.addDependency(dep);
127
- rule.remove(); // }
227
+ }
228
+ let assets = [asset];
229
+ if (res.exports != null) {
230
+ var _asset$uniqueKey;
231
+ let exports = res.exports;
232
+ asset.symbols.ensure();
233
+ asset.symbols.set('default', 'default');
234
+ let dependencies = new Map();
235
+ let locals = new Map();
236
+ let c = 0;
237
+ let depjs = '';
238
+ let js = '';
239
+ for (let key in exports) {
240
+ locals.set(exports[key].name, key);
128
241
  }
129
-
130
- ast.isDirty = true;
131
- });
132
- ast.program.walkDecls(decl => {
133
- if (URL_RE.test(decl.value)) {
134
- let parsed = (0, _postcssValueParser.default)(decl.value);
135
- let isDirty = false;
136
- parsed.walk(node => {
137
- if (node.type === 'function' && node.value === 'url' && node.nodes.length > 0 && !node.nodes[0].value.startsWith('#') // IE's `behavior: url(#default#VML)`
138
- ) {
139
- node.nodes[0].value = asset.addURLDependency(node.nodes[0].value, {
140
- loc: (0, _utils.createDependencyLocation)(decl.source.start, node.nodes[0].value)
242
+ (_asset$uniqueKey = asset.uniqueKey) !== null && _asset$uniqueKey !== void 0 ? _asset$uniqueKey : asset.uniqueKey = asset.id;
243
+ let seen = new Set();
244
+ let add = key => {
245
+ if (seen.has(key)) {
246
+ return;
247
+ }
248
+ seen.add(key);
249
+ let e = exports[key];
250
+ let s = `module.exports[${JSON.stringify(key)}] = \`${e.name}`;
251
+ for (let ref of e.composes) {
252
+ s += ' ';
253
+ if (ref.type === 'local') {
254
+ let exported = (0, _nullthrows().default)(locals.get(ref.name));
255
+ add(exported);
256
+ s += '${' + `module.exports[${JSON.stringify(exported)}]` + '}';
257
+ asset.addDependency({
258
+ specifier: (0, _nullthrows().default)(asset.uniqueKey),
259
+ specifierType: 'esm',
260
+ symbols: new Map([[exported, {
261
+ local: ref.name,
262
+ isWeak: false,
263
+ loc: null
264
+ }]])
265
+ });
266
+ } else if (ref.type === 'global') {
267
+ s += ref.name;
268
+ } else if (ref.type === 'dependency') {
269
+ let d = dependencies.get(ref.specifier);
270
+ if (d == null) {
271
+ d = `dep_${c++}`;
272
+ depjs += `import * as ${d} from ${JSON.stringify(ref.specifier)};\n`;
273
+ dependencies.set(ref.specifier, d);
274
+ asset.addDependency({
275
+ specifier: ref.specifier,
276
+ specifierType: 'esm',
277
+ packageConditions: ['style']
141
278
  });
142
- isDirty = true;
143
279
  }
144
- });
145
-
146
- if (isDirty) {
147
- decl.value = parsed.toString();
148
- ast.isDirty = true;
280
+ s += '${' + `${d}[${JSON.stringify(ref.name)}]` + '}';
281
+ }
149
282
  }
150
- }
151
- });
152
- return [asset];
153
- },
283
+ s += '`;\n';
154
284
 
155
- async generate({
156
- asset
157
- }) {
158
- let code;
159
-
160
- if (!asset.ast || !asset.ast.isDirty) {
161
- code = await asset.getCode();
162
- } else {
163
- code = '';
285
+ // If the export is referenced internally (e.g. used @keyframes), add a self-reference
286
+ // to the JS so the symbol is retained during tree-shaking.
287
+ if (e.isReferenced) {
288
+ s += `module.exports[${JSON.stringify(key)}];\n`;
289
+ asset.addDependency({
290
+ specifier: (0, _nullthrows().default)(asset.uniqueKey),
291
+ specifierType: 'esm',
292
+ symbols: new Map([[key, {
293
+ local: exports[key].name,
294
+ isWeak: false,
295
+ loc: null
296
+ }]])
297
+ });
298
+ }
299
+ js += s;
300
+ };
164
301
 
165
- _postcss.default.stringify(asset.ast.program, c => {
166
- code += c;
302
+ // It's possible that the exports can be ordered differently between builds.
303
+ // Sorting by key is safe as the order is irrelevant but needs to be deterministic.
304
+ for (let key of Object.keys(exports).sort()) {
305
+ asset.symbols.set(key, exports[key].name);
306
+ add(key);
307
+ }
308
+ if (res.dependencies) {
309
+ for (let dep of res.dependencies) {
310
+ if (dep.type === 'import') {
311
+ // TODO: Figure out how to treeshake this
312
+ let d = `dep_$${c++}`;
313
+ depjs += `import * as ${d} from ${JSON.stringify(dep.url)};\n`;
314
+ js += `for (let key in ${d}) { if (key in module.exports) module.exports[key] += ' ' + ${d}[key]; else module.exports[key] = ${d}[key]; }\n`;
315
+ asset.symbols.set('*', '*');
316
+ }
317
+ }
318
+ }
319
+ if (res.references != null) {
320
+ let references = res.references;
321
+ for (let symbol in references) {
322
+ let reference = references[symbol];
323
+ asset.addDependency({
324
+ specifier: reference.specifier,
325
+ specifierType: 'esm',
326
+ packageConditions: ['style'],
327
+ symbols: new Map([[reference.name, {
328
+ local: symbol,
329
+ isWeak: false,
330
+ loc: null
331
+ }]])
332
+ });
333
+ asset.meta.hasReferences = true;
334
+ }
335
+ }
336
+ assets.push({
337
+ type: 'js',
338
+ content: depjs + js,
339
+ dependencies: [],
340
+ env
167
341
  });
168
342
  }
169
-
170
- return {
171
- code
172
- };
343
+ return assets;
173
344
  }
174
-
175
345
  });
176
-
177
- exports.default = _default;
346
+ exports.default = _default;
347
+ let cache = new Map();
348
+ function getTargets(browsers) {
349
+ if (browsers == null) {
350
+ return undefined;
351
+ }
352
+ let cached = cache.get(browsers);
353
+ if (cached != null) {
354
+ return cached;
355
+ }
356
+ let targets = (0, _lightningcss().browserslistToTargets)((0, _browserslist().default)(browsers));
357
+ cache.set(browsers, targets);
358
+ return targets;
359
+ }
360
+ function convertLoc(loc) {
361
+ return {
362
+ filePath: loc.filePath,
363
+ start: {
364
+ line: loc.start.line,
365
+ column: loc.start.column
366
+ },
367
+ end: {
368
+ line: loc.end.line,
369
+ column: loc.end.column + 1
370
+ }
371
+ };
372
+ }
package/package.json CHANGED
@@ -1,10 +1,14 @@
1
1
  {
2
2
  "name": "@parcel/transformer-css",
3
- "version": "2.0.0-nightly.140+4fd6dcae",
3
+ "version": "2.0.0-nightly.1404+75c1921c8",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
8
+ "funding": {
9
+ "type": "opencollective",
10
+ "url": "https://opencollective.com/parcel"
11
+ },
8
12
  "repository": {
9
13
  "type": "git",
10
14
  "url": "https://github.com/parcel-bundler/parcel.git"
@@ -12,15 +16,17 @@
12
16
  "main": "lib/CSSTransformer.js",
13
17
  "source": "src/CSSTransformer.js",
14
18
  "engines": {
15
- "node": ">= 10.0.0",
16
- "parcel": "^2.0.0-alpha.1.1"
19
+ "node": ">= 12.0.0",
20
+ "parcel": "2.0.0-nightly.1402+75c1921c8"
17
21
  },
18
22
  "dependencies": {
19
- "@parcel/plugin": "2.0.0-nightly.140+4fd6dcae",
20
- "@parcel/utils": "2.0.0-nightly.140+4fd6dcae",
21
- "postcss": "^7.0.5",
22
- "postcss-value-parser": "^3.3.1",
23
- "semver": "^5.4.1"
23
+ "@parcel/diagnostic": "2.0.0-nightly.1404+75c1921c8",
24
+ "@parcel/plugin": "2.0.0-nightly.1404+75c1921c8",
25
+ "@parcel/source-map": "^2.1.1",
26
+ "@parcel/utils": "2.0.0-nightly.1404+75c1921c8",
27
+ "browserslist": "^4.6.6",
28
+ "lightningcss": "^1.16.1",
29
+ "nullthrows": "^1.1.1"
24
30
  },
25
- "gitHead": "4fd6dcaea61185bfb4d87ef707e23fb980f8d8a3"
31
+ "gitHead": "75c1921c86017e747d8b46ea172392f78f187814"
26
32
  }
@@ -1,178 +1,376 @@
1
- // @flow
1
+ // @flow strict-local
2
2
 
3
- import type {FilePath} from '@parcel/types';
3
+ import type {SourceLocation} from '@parcel/types';
4
4
 
5
+ import path from 'path';
6
+ import SourceMap from '@parcel/source-map';
5
7
  import {Transformer} from '@parcel/plugin';
6
- import {createDependencyLocation, isURL} from '@parcel/utils';
7
- import postcss from 'postcss';
8
- import valueParser from 'postcss-value-parser';
9
- import semver from 'semver';
8
+ import {
9
+ transform,
10
+ transformStyleAttribute,
11
+ browserslistToTargets,
12
+ type SourceLocation as LightningSourceLocation,
13
+ } from 'lightningcss';
14
+ import {
15
+ remapSourceLocation,
16
+ relativePath,
17
+ globToRegex,
18
+ normalizeSeparators,
19
+ } from '@parcel/utils';
20
+ import browserslist from 'browserslist';
21
+ import nullthrows from 'nullthrows';
22
+ import ThrowableDiagnostic, {errorToDiagnostic} from '@parcel/diagnostic';
10
23
 
11
- const URL_RE = /url\s*\("?(?![a-z]+:)/;
12
- const IMPORT_RE = /@import/;
13
-
14
- function canHaveDependencies(filePath: FilePath, code: string) {
15
- return !/\.css$/.test(filePath) || IMPORT_RE.test(code) || URL_RE.test(code);
16
- }
17
-
18
- export default new Transformer({
19
- canReuseAST({ast}) {
20
- return ast.type === 'postcss' && semver.satisfies(ast.version, '^7.0.0');
21
- },
22
-
23
- async parse({asset}) {
24
- // This is set by other transformers (e.g. Stylus) to indicate that it has already processed
25
- // all dependencies, and that the CSS transformer can skip this asset completely. This is
26
- // required because when stylus processes e.g. url() it replaces them with a dependency id
27
- // to be filled in later. When the CSS transformer runs, it would pick that up and try to
28
- // resolve a dependency for the id which obviously doesn't exist. Also, it's faster to do
29
- // it this way since the resulting CSS doesn't need to be re-parsed.
30
- if (asset.meta.hasDependencies === false) {
31
- return null;
24
+ export default (new Transformer({
25
+ async loadConfig({config, options}) {
26
+ let conf = await config.getConfigFrom(options.projectRoot + '/index', [], {
27
+ packageKey: '@parcel/transformer-css',
28
+ });
29
+ let contents = conf?.contents;
30
+ if (typeof contents?.cssModules?.include === 'string') {
31
+ contents.cssModules.include = [globToRegex(contents.cssModules.include)];
32
+ } else if (Array.isArray(contents?.cssModules?.include)) {
33
+ contents.cssModules.include = contents.cssModules.include.map(include =>
34
+ typeof include === 'string' ? globToRegex(include) : include,
35
+ );
32
36
  }
33
-
34
- let code = await asset.getCode();
35
- if (!canHaveDependencies(asset.filePath, code)) {
36
- return null;
37
+ if (typeof contents?.cssModules?.exclude === 'string') {
38
+ contents.cssModules.exclude = [globToRegex(contents.cssModules.exclude)];
39
+ } else if (Array.isArray(contents?.cssModules?.exclude)) {
40
+ contents.cssModules.exclude = contents.cssModules.exclude.map(exclude =>
41
+ typeof exclude === 'string' ? globToRegex(exclude) : exclude,
42
+ );
37
43
  }
38
-
39
- return {
40
- type: 'postcss',
41
- version: '7.0.0',
42
- isDirty: false,
43
- program: postcss.parse(code, {
44
- from: asset.filePath,
45
- }),
46
- };
44
+ return contents;
47
45
  },
48
-
49
- transform({asset}) {
46
+ async transform({asset, config, options, logger}) {
50
47
  // Normalize the asset's environment so that properties that only affect JS don't cause CSS to be duplicated.
51
48
  // For example, with ESModule and CommonJS targets, only a single shared CSS bundle should be produced.
49
+ let env = asset.env;
52
50
  asset.setEnvironment({
53
51
  context: 'browser',
54
52
  engines: {
55
53
  browsers: asset.env.engines.browsers,
56
54
  },
57
- minify: asset.env.minify,
55
+ shouldOptimize: asset.env.shouldOptimize,
56
+ shouldScopeHoist: asset.env.shouldScopeHoist,
57
+ sourceMap: asset.env.sourceMap,
58
58
  });
59
59
 
60
- // When this asset is an bundle entry, allow that bundle to be split to load shared assets separately.
61
- // Only set here if it is null to allow previous transformers to override this behavior.
62
- if (asset.isSplittable == null) {
63
- asset.isSplittable = true;
60
+ let [code, originalMap] = await Promise.all([
61
+ asset.getBuffer(),
62
+ asset.getMap(),
63
+ ]);
64
+
65
+ let targets = getTargets(asset.env.engines.browsers);
66
+ let res;
67
+ try {
68
+ if (asset.meta.type === 'attr') {
69
+ res = transformStyleAttribute({
70
+ code,
71
+ analyzeDependencies: true,
72
+ errorRecovery: config?.errorRecovery || false,
73
+ targets,
74
+ });
75
+ } else {
76
+ let cssModules = false;
77
+ if (
78
+ asset.meta.type !== 'tag' &&
79
+ asset.meta.cssModulesCompiled == null
80
+ ) {
81
+ let cssModulesConfig = config?.cssModules;
82
+ let isCSSModule = /\.module\./.test(asset.filePath);
83
+ if (asset.isSource) {
84
+ let projectRootPath = path.relative(
85
+ options.projectRoot,
86
+ asset.filePath,
87
+ );
88
+ if (typeof cssModulesConfig === 'boolean') {
89
+ isCSSModule = true;
90
+ } else if (cssModulesConfig?.include) {
91
+ isCSSModule = cssModulesConfig.include.some(include =>
92
+ include.test(projectRootPath),
93
+ );
94
+ } else if (cssModulesConfig?.global) {
95
+ isCSSModule = true;
96
+ }
97
+
98
+ if (
99
+ cssModulesConfig?.exclude?.some(exclude =>
100
+ exclude.test(projectRootPath),
101
+ )
102
+ ) {
103
+ isCSSModule = false;
104
+ }
105
+ }
106
+
107
+ if (isCSSModule) {
108
+ if (cssModulesConfig?.dashedIdents && !asset.isSource) {
109
+ cssModulesConfig.dashedIdents = false;
110
+ }
111
+
112
+ cssModules = cssModulesConfig ?? true;
113
+ }
114
+ }
115
+
116
+ res = transform({
117
+ filename: normalizeSeparators(
118
+ path.relative(options.projectRoot, asset.filePath),
119
+ ),
120
+ code,
121
+ cssModules,
122
+ analyzeDependencies: asset.meta.hasDependencies !== false,
123
+ sourceMap: !!asset.env.sourceMap,
124
+ drafts: config?.drafts,
125
+ pseudoClasses: config?.pseudoClasses,
126
+ errorRecovery: config?.errorRecovery || false,
127
+ targets,
128
+ });
129
+ }
130
+ } catch (err) {
131
+ err.filePath = asset.filePath;
132
+ let diagnostic = errorToDiagnostic(err, {
133
+ origin: '@parcel/transformer-css',
134
+ });
135
+ if (err.data?.type === 'AmbiguousUrlInCustomProperty' && err.data.url) {
136
+ let p =
137
+ '/' +
138
+ relativePath(
139
+ options.projectRoot,
140
+ path.resolve(path.dirname(asset.filePath), err.data.url),
141
+ false,
142
+ );
143
+ diagnostic[0].hints = [`Replace with: url(${p})`];
144
+ diagnostic[0].documentationURL =
145
+ 'https://parceljs.org/languages/css/#url()';
146
+ }
147
+
148
+ throw new ThrowableDiagnostic({
149
+ diagnostic,
150
+ });
64
151
  }
65
152
 
66
- let ast = asset.ast;
67
- // Check for `hasDependencies` being false here as well, as it's possible
68
- // another transformer (such as PostCSSTransformer) has already parsed an
69
- // ast and CSSTransformer's parse was never called.
70
- if (!ast || asset.meta.hasDependencies === false) {
71
- return [asset];
153
+ if (res.warnings) {
154
+ for (let warning of res.warnings) {
155
+ logger.warn({
156
+ message: warning.message,
157
+ codeFrames: [
158
+ {
159
+ filePath: asset.filePath,
160
+ codeHighlights: [
161
+ {
162
+ start: {
163
+ line: warning.loc.line,
164
+ column: warning.loc.column + 1,
165
+ },
166
+ end: {
167
+ line: warning.loc.line,
168
+ column: warning.loc.column + 1,
169
+ },
170
+ },
171
+ ],
172
+ },
173
+ ],
174
+ });
175
+ }
72
176
  }
73
177
 
74
- ast.program.walkAtRules('import', rule => {
75
- let params = valueParser(rule.params);
76
- let [name, ...media] = params.nodes;
77
- let moduleSpecifier;
78
- if (
79
- name.type === 'function' &&
80
- name.value === 'url' &&
81
- name.nodes.length
82
- ) {
83
- name = name.nodes[0];
178
+ asset.setBuffer(res.code);
179
+
180
+ if (res.map != null) {
181
+ let vlqMap = JSON.parse(res.map.toString());
182
+ let map = new SourceMap(options.projectRoot);
183
+ map.addVLQMap(vlqMap);
184
+
185
+ if (originalMap) {
186
+ map.extends(originalMap);
84
187
  }
85
188
 
86
- moduleSpecifier = name.value;
189
+ asset.setMap(map);
190
+ }
191
+
192
+ if (res.dependencies) {
193
+ for (let dep of res.dependencies) {
194
+ let loc = convertLoc(dep.loc);
195
+ if (originalMap) {
196
+ loc = remapSourceLocation(loc, originalMap);
197
+ }
87
198
 
88
- if (!moduleSpecifier) {
89
- throw new Error('Could not find import name for ' + rule);
199
+ if (dep.type === 'import' && !res.exports) {
200
+ asset.addDependency({
201
+ specifier: dep.url,
202
+ specifierType: 'url',
203
+ loc,
204
+ packageConditions: ['style'],
205
+ meta: {
206
+ // For the glob resolver to distinguish between `@import` and other URL dependencies.
207
+ isCSSImport: true,
208
+ media: dep.media,
209
+ },
210
+ });
211
+ } else if (dep.type === 'url') {
212
+ asset.addURLDependency(dep.url, {
213
+ loc,
214
+ meta: {
215
+ placeholder: dep.placeholder,
216
+ },
217
+ });
218
+ }
90
219
  }
220
+ }
91
221
 
92
- if (isURL(moduleSpecifier)) {
93
- name.value = asset.addURLDependency(moduleSpecifier, {
94
- loc: createDependencyLocation(
95
- rule.source.start,
96
- moduleSpecifier,
97
- 0,
98
- 8,
99
- ),
100
- });
101
- } else {
102
- // If this came from an inline <style> tag, don't inline the imported file. Replace with the correct URL instead.
103
- // TODO: run CSSPackager on inline style tags.
104
- // let inlineHTML =
105
- // this.options.rendition && this.options.rendition.inlineHTML;
106
- // if (inlineHTML) {
107
- // name.value = asset.addURLDependency(dep, {loc: rule.source.start});
108
- // rule.params = params.toString();
109
- // } else {
110
- media = valueParser.stringify(media).trim();
111
- let dep = {
112
- moduleSpecifier,
113
- // Offset by 8 as it does not include `@import `
114
- loc: createDependencyLocation(
115
- rule.source.start,
116
- moduleSpecifier,
117
- 0,
118
- 8,
119
- ),
120
- meta: {
121
- media,
122
- },
123
- };
124
- asset.addDependency(dep);
125
- rule.remove();
126
- // }
222
+ let assets = [asset];
223
+
224
+ if (res.exports != null) {
225
+ let exports = res.exports;
226
+ asset.symbols.ensure();
227
+ asset.symbols.set('default', 'default');
228
+
229
+ let dependencies = new Map();
230
+ let locals = new Map();
231
+ let c = 0;
232
+ let depjs = '';
233
+ let js = '';
234
+
235
+ let jsDeps = [];
236
+
237
+ for (let key in exports) {
238
+ locals.set(exports[key].name, key);
127
239
  }
128
- ast.isDirty = true;
129
- });
130
240
 
131
- ast.program.walkDecls(decl => {
132
- if (URL_RE.test(decl.value)) {
133
- let parsed = valueParser(decl.value);
134
- let isDirty = false;
135
-
136
- parsed.walk(node => {
137
- if (
138
- node.type === 'function' &&
139
- node.value === 'url' &&
140
- node.nodes.length > 0 &&
141
- !node.nodes[0].value.startsWith('#') // IE's `behavior: url(#default#VML)`
142
- ) {
143
- node.nodes[0].value = asset.addURLDependency(node.nodes[0].value, {
144
- loc: createDependencyLocation(
145
- decl.source.start,
146
- node.nodes[0].value,
147
- ),
241
+ asset.uniqueKey ??= asset.id;
242
+
243
+ let seen = new Set();
244
+ let add = key => {
245
+ if (seen.has(key)) {
246
+ return;
247
+ }
248
+ seen.add(key);
249
+
250
+ let e = exports[key];
251
+ let s = `module.exports[${JSON.stringify(key)}] = \`${e.name}`;
252
+
253
+ for (let ref of e.composes) {
254
+ s += ' ';
255
+ if (ref.type === 'local') {
256
+ let exported = nullthrows(locals.get(ref.name));
257
+ add(exported);
258
+ s += '${' + `module.exports[${JSON.stringify(exported)}]` + '}';
259
+ asset.addDependency({
260
+ specifier: nullthrows(asset.uniqueKey),
261
+ specifierType: 'esm',
262
+ symbols: new Map([
263
+ [exported, {local: ref.name, isWeak: false, loc: null}],
264
+ ]),
148
265
  });
149
- isDirty = true;
266
+ } else if (ref.type === 'global') {
267
+ s += ref.name;
268
+ } else if (ref.type === 'dependency') {
269
+ let d = dependencies.get(ref.specifier);
270
+ if (d == null) {
271
+ d = `dep_${c++}`;
272
+ depjs += `import * as ${d} from ${JSON.stringify(
273
+ ref.specifier,
274
+ )};\n`;
275
+ dependencies.set(ref.specifier, d);
276
+ asset.addDependency({
277
+ specifier: ref.specifier,
278
+ specifierType: 'esm',
279
+ packageConditions: ['style'],
280
+ });
281
+ }
282
+ s += '${' + `${d}[${JSON.stringify(ref.name)}]` + '}';
150
283
  }
151
- });
284
+ }
285
+
286
+ s += '`;\n';
152
287
 
153
- if (isDirty) {
154
- decl.value = parsed.toString();
155
- ast.isDirty = true;
288
+ // If the export is referenced internally (e.g. used @keyframes), add a self-reference
289
+ // to the JS so the symbol is retained during tree-shaking.
290
+ if (e.isReferenced) {
291
+ s += `module.exports[${JSON.stringify(key)}];\n`;
292
+ asset.addDependency({
293
+ specifier: nullthrows(asset.uniqueKey),
294
+ specifierType: 'esm',
295
+ symbols: new Map([
296
+ [key, {local: exports[key].name, isWeak: false, loc: null}],
297
+ ]),
298
+ });
156
299
  }
300
+
301
+ js += s;
302
+ };
303
+
304
+ // It's possible that the exports can be ordered differently between builds.
305
+ // Sorting by key is safe as the order is irrelevant but needs to be deterministic.
306
+ for (let key of Object.keys(exports).sort()) {
307
+ asset.symbols.set(key, exports[key].name);
308
+ add(key);
157
309
  }
158
- });
159
310
 
160
- return [asset];
161
- },
311
+ if (res.dependencies) {
312
+ for (let dep of res.dependencies) {
313
+ if (dep.type === 'import') {
314
+ // TODO: Figure out how to treeshake this
315
+ let d = `dep_$${c++}`;
316
+ depjs += `import * as ${d} from ${JSON.stringify(dep.url)};\n`;
317
+ js += `for (let key in ${d}) { if (key in module.exports) module.exports[key] += ' ' + ${d}[key]; else module.exports[key] = ${d}[key]; }\n`;
318
+ asset.symbols.set('*', '*');
319
+ }
320
+ }
321
+ }
322
+
323
+ if (res.references != null) {
324
+ let references = res.references;
325
+ for (let symbol in references) {
326
+ let reference = references[symbol];
327
+ asset.addDependency({
328
+ specifier: reference.specifier,
329
+ specifierType: 'esm',
330
+ packageConditions: ['style'],
331
+ symbols: new Map([
332
+ [reference.name, {local: symbol, isWeak: false, loc: null}],
333
+ ]),
334
+ });
335
+
336
+ asset.meta.hasReferences = true;
337
+ }
338
+ }
162
339
 
163
- async generate({asset}) {
164
- let code;
165
- if (!asset.ast || !asset.ast.isDirty) {
166
- code = await asset.getCode();
167
- } else {
168
- code = '';
169
- postcss.stringify(asset.ast.program, c => {
170
- code += c;
340
+ assets.push({
341
+ type: 'js',
342
+ content: depjs + js,
343
+ dependencies: jsDeps,
344
+ env,
171
345
  });
172
346
  }
173
347
 
174
- return {
175
- code,
176
- };
348
+ return assets;
177
349
  },
178
- });
350
+ }): Transformer);
351
+
352
+ let cache = new Map();
353
+
354
+ function getTargets(browsers) {
355
+ if (browsers == null) {
356
+ return undefined;
357
+ }
358
+
359
+ let cached = cache.get(browsers);
360
+ if (cached != null) {
361
+ return cached;
362
+ }
363
+
364
+ let targets = browserslistToTargets(browserslist(browsers));
365
+
366
+ cache.set(browsers, targets);
367
+ return targets;
368
+ }
369
+
370
+ function convertLoc(loc: LightningSourceLocation): SourceLocation {
371
+ return {
372
+ filePath: loc.filePath,
373
+ start: {line: loc.start.line, column: loc.start.column},
374
+ end: {line: loc.end.line, column: loc.end.column + 1},
375
+ };
376
+ }