@parcel/transformer-css 2.0.0-nightly.146 → 2.0.0-nightly.1470

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