@parcel/transformer-css 2.0.0-nightly.112 → 2.0.0-nightly.1127

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