@dcloudio/uni-cli-shared 3.0.0-alpha-3021320211118002 → 3.0.0-alpha-3021320211122001

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.
@@ -0,0 +1,922 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.cssUrlRE = exports.cssPostPlugin = exports.cssPlugin = exports.removedPureCssFilesCache = exports.chunkToEmittedCssFileMap = exports.isDirectRequest = exports.isDirectCSSRequest = exports.isCSSRequest = void 0;
26
+ const fs_1 = __importDefault(require("fs"));
27
+ const path_1 = __importDefault(require("path"));
28
+ const fast_glob_1 = __importDefault(require("fast-glob"));
29
+ const utils_1 = require("../utils");
30
+ const postcss_load_config_1 = __importDefault(require("postcss-load-config"));
31
+ const pluginutils_1 = require("@rollup/pluginutils");
32
+ const chalk_1 = __importDefault(require("chalk"));
33
+ const constants_1 = require("../constants");
34
+ const h5Asset_1 = require("./h5Asset");
35
+ const magic_string_1 = __importDefault(require("magic-string"));
36
+ const esbuild_1 = require("esbuild");
37
+ const css_1 = require("./css");
38
+ const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`;
39
+ const cssLangRE = new RegExp(cssLangs);
40
+ const cssModuleRE = new RegExp(`\\.module${cssLangs}`);
41
+ const directRequestRE = /(\?|&)direct\b/;
42
+ const commonjsProxyRE = /\?commonjs-proxy/;
43
+ const inlineRE = /(\?|&)inline\b/;
44
+ const usedRE = /(\?|&)used\b/;
45
+ const isCSSRequest = (request) => cssLangRE.test(request);
46
+ exports.isCSSRequest = isCSSRequest;
47
+ const isDirectCSSRequest = (request) => cssLangRE.test(request) && directRequestRE.test(request);
48
+ exports.isDirectCSSRequest = isDirectCSSRequest;
49
+ const isDirectRequest = (request) => directRequestRE.test(request);
50
+ exports.isDirectRequest = isDirectRequest;
51
+ const cssModulesCache = new WeakMap();
52
+ exports.chunkToEmittedCssFileMap = new WeakMap();
53
+ exports.removedPureCssFilesCache = new WeakMap();
54
+ const postcssConfigCache = new WeakMap();
55
+ /**
56
+ * Plugin applied before user plugins
57
+ */
58
+ function cssPlugin(config) {
59
+ let server;
60
+ let moduleCache;
61
+ const resolveUrl = config.createResolver({
62
+ preferRelative: true,
63
+ tryIndex: false,
64
+ extensions: [],
65
+ });
66
+ const atImportResolvers = createCSSResolvers(config);
67
+ return {
68
+ name: 'vite:css',
69
+ configureServer(_server) {
70
+ server = _server;
71
+ },
72
+ buildStart() {
73
+ // Ensure a new cache for every build (i.e. rebuilding in watch mode)
74
+ moduleCache = new Map();
75
+ cssModulesCache.set(config, moduleCache);
76
+ exports.removedPureCssFilesCache.set(config, new Map());
77
+ },
78
+ async transform(raw, id) {
79
+ var _a, _b;
80
+ if (!(0, exports.isCSSRequest)(id) || commonjsProxyRE.test(id)) {
81
+ return;
82
+ }
83
+ const urlReplacer = async (url, importer) => {
84
+ if ((0, h5Asset_1.checkPublicFile)(url, config)) {
85
+ return config.base + url.slice(1);
86
+ }
87
+ const resolved = await resolveUrl(url, importer);
88
+ if (resolved) {
89
+ return (0, h5Asset_1.fileToUrl)(resolved, config, this);
90
+ }
91
+ return url;
92
+ };
93
+ const { code: css, modules, deps, } = await compileCSS(id, raw, config, urlReplacer, atImportResolvers, server);
94
+ if (modules) {
95
+ moduleCache.set(id, modules);
96
+ }
97
+ // track deps for build watch mode
98
+ if (config.command === 'build' && config.build.watch && deps) {
99
+ for (const file of deps) {
100
+ this.addWatchFile(file);
101
+ }
102
+ }
103
+ // dev
104
+ if (server) {
105
+ // server only logic for handling CSS @import dependency hmr
106
+ const { moduleGraph } = server;
107
+ const thisModule = moduleGraph.getModuleById(id);
108
+ if (thisModule) {
109
+ // CSS modules cannot self-accept since it exports values
110
+ const isSelfAccepting = !modules && !inlineRE.test(id);
111
+ if (deps) {
112
+ // record deps in the module graph so edits to @import css can trigger
113
+ // main import to hot update
114
+ const depModules = new Set();
115
+ for (const file of deps) {
116
+ depModules.add((0, exports.isCSSRequest)(file)
117
+ ? moduleGraph.createFileOnlyEntry(file)
118
+ : await moduleGraph.ensureEntryFromUrl((await (0, h5Asset_1.fileToUrl)(file, config, this)).replace(((_b = (_a = config.server) === null || _a === void 0 ? void 0 : _a.origin) !== null && _b !== void 0 ? _b : '') + config.base, '/')));
119
+ }
120
+ moduleGraph.updateModuleInfo(thisModule, depModules,
121
+ // The root CSS proxy module is self-accepting and should not
122
+ // have an explicit accept list
123
+ new Set(), isSelfAccepting);
124
+ for (const file of deps) {
125
+ this.addWatchFile(file);
126
+ }
127
+ }
128
+ else {
129
+ thisModule.isSelfAccepting = isSelfAccepting;
130
+ }
131
+ }
132
+ }
133
+ return {
134
+ code: css,
135
+ // TODO CSS source map
136
+ map: { mappings: '' },
137
+ };
138
+ },
139
+ };
140
+ }
141
+ exports.cssPlugin = cssPlugin;
142
+ /**
143
+ * Plugin applied after user plugins
144
+ */
145
+ function cssPostPlugin(config) {
146
+ // styles initialization in buildStart causes a styling loss in watch
147
+ const styles = new Map();
148
+ let pureCssChunks;
149
+ // when there are multiple rollup outputs and extracting CSS, only emit once,
150
+ // since output formats have no effect on the generated CSS.
151
+ let outputToExtractedCSSMap;
152
+ let hasEmitted = false;
153
+ return {
154
+ name: 'vite:css-post',
155
+ buildStart() {
156
+ // Ensure new caches for every build (i.e. rebuilding in watch mode)
157
+ pureCssChunks = new Set();
158
+ outputToExtractedCSSMap = new Map();
159
+ hasEmitted = false;
160
+ },
161
+ async transform(css, id, options) {
162
+ if (!(0, exports.isCSSRequest)(id) || commonjsProxyRE.test(id)) {
163
+ return;
164
+ }
165
+ const ssr = typeof options === 'boolean'
166
+ ? options
167
+ : (options && options.ssr) === true;
168
+ const inlined = inlineRE.test(id);
169
+ const modules = cssModulesCache.get(config).get(id);
170
+ const modulesCode = modules && (0, pluginutils_1.dataToEsm)(modules, { namedExports: true, preferConst: true });
171
+ if (config.command === 'serve') {
172
+ if ((0, exports.isDirectCSSRequest)(id)) {
173
+ return css;
174
+ }
175
+ else {
176
+ // server only
177
+ if (ssr) {
178
+ return modulesCode || `export default ${JSON.stringify(css)}`;
179
+ }
180
+ if (inlined) {
181
+ return `export default ${JSON.stringify(css)}`;
182
+ }
183
+ return [
184
+ `import { updateStyle, removeStyle } from ${JSON.stringify(path_1.default.posix.join(config.base, constants_1.CLIENT_PUBLIC_PATH))}`,
185
+ `const id = ${JSON.stringify(id)}`,
186
+ `const css = ${JSON.stringify(css)}`,
187
+ `updateStyle(id, css)`,
188
+ // css modules exports change on edit so it can't self accept
189
+ `${modulesCode || `import.meta.hot.accept()\nexport default css`}`,
190
+ `import.meta.hot.prune(() => removeStyle(id))`,
191
+ ].join('\n');
192
+ }
193
+ }
194
+ // build CSS handling ----------------------------------------------------
195
+ // record css
196
+ if (!inlined) {
197
+ styles.set(id, css);
198
+ }
199
+ return {
200
+ code: modulesCode ||
201
+ (usedRE.test(id)
202
+ ? `export default ${JSON.stringify(inlined ? await minifyCSS(css, config) : css)}`
203
+ : `export default ''`),
204
+ map: { mappings: '' },
205
+ // avoid the css module from being tree-shaken so that we can retrieve
206
+ // it in renderChunk()
207
+ moduleSideEffects: inlined ? false : 'no-treeshake',
208
+ };
209
+ },
210
+ async renderChunk(code, chunk, opts) {
211
+ let chunkCSS = '';
212
+ let isPureCssChunk = true;
213
+ const ids = Object.keys(chunk.modules);
214
+ for (const id of ids) {
215
+ if (!(0, exports.isCSSRequest)(id) ||
216
+ cssModuleRE.test(id) ||
217
+ commonjsProxyRE.test(id)) {
218
+ isPureCssChunk = false;
219
+ }
220
+ if (styles.has(id)) {
221
+ chunkCSS += styles.get(id);
222
+ }
223
+ }
224
+ if (!chunkCSS) {
225
+ return null;
226
+ }
227
+ // resolve asset URL placeholders to their built file URLs and perform
228
+ // minification if necessary
229
+ const processChunkCSS = async (css, { inlined, minify, }) => {
230
+ // replace asset url references with resolved url.
231
+ const isRelativeBase = config.base === '' || config.base.startsWith('.');
232
+ css = css.replace(h5Asset_1.assetUrlRE, (_, fileHash, postfix = '') => {
233
+ const filename = (0, h5Asset_1.getAssetFilename)(fileHash, config) + postfix;
234
+ (0, h5Asset_1.registerAssetToChunk)(chunk, filename);
235
+ if (!isRelativeBase || inlined) {
236
+ // absolute base or relative base but inlined (injected as style tag into
237
+ // index.html) use the base as-is
238
+ return config.base + filename;
239
+ }
240
+ else {
241
+ // relative base + extracted CSS - asset file will be in the same dir
242
+ return `./${path_1.default.posix.basename(filename)}`;
243
+ }
244
+ });
245
+ // only external @imports should exist at this point - and they need to
246
+ // be hoisted to the top of the CSS chunk per spec (#1845)
247
+ if (css.includes('@import')) {
248
+ css = await hoistAtImports(css);
249
+ }
250
+ if (minify && config.build.minify) {
251
+ css = await minifyCSS(css, config);
252
+ }
253
+ return css;
254
+ };
255
+ if (config.build.cssCodeSplit) {
256
+ if (isPureCssChunk) {
257
+ // this is a shared CSS-only chunk that is empty.
258
+ pureCssChunks.add(chunk.fileName);
259
+ }
260
+ if (opts.format === 'es' || opts.format === 'cjs') {
261
+ chunkCSS = await processChunkCSS(chunkCSS, {
262
+ inlined: false,
263
+ minify: true,
264
+ });
265
+ // emit corresponding css file
266
+ const fileHandle = this.emitFile({
267
+ name: chunk.name + '.css',
268
+ type: 'asset',
269
+ source: chunkCSS,
270
+ });
271
+ exports.chunkToEmittedCssFileMap.set(chunk, new Set([this.getFileName(fileHandle)]));
272
+ }
273
+ else if (!config.build.ssr) {
274
+ // legacy build, inline css
275
+ chunkCSS = await processChunkCSS(chunkCSS, {
276
+ inlined: true,
277
+ minify: true,
278
+ });
279
+ const style = `__vite_style__`;
280
+ const injectCode = `var ${style} = document.createElement('style');` +
281
+ `${style}.innerHTML = ${JSON.stringify(chunkCSS)};` +
282
+ `document.head.appendChild(${style});`;
283
+ if (config.build.sourcemap) {
284
+ const s = new magic_string_1.default(code);
285
+ s.prepend(injectCode);
286
+ return {
287
+ code: s.toString(),
288
+ map: s.generateMap({ hires: true }),
289
+ };
290
+ }
291
+ else {
292
+ return { code: injectCode + code };
293
+ }
294
+ }
295
+ }
296
+ else {
297
+ // non-split extracted CSS will be minified together
298
+ chunkCSS = await processChunkCSS(chunkCSS, {
299
+ inlined: false,
300
+ minify: false,
301
+ });
302
+ outputToExtractedCSSMap.set(opts, (outputToExtractedCSSMap.get(opts) || '') + chunkCSS);
303
+ }
304
+ return null;
305
+ },
306
+ async generateBundle(opts, bundle) {
307
+ // remove empty css chunks and their imports
308
+ if (pureCssChunks.size) {
309
+ const emptyChunkFiles = [...pureCssChunks]
310
+ .map((file) => path_1.default.basename(file))
311
+ .join('|')
312
+ .replace(/\./g, '\\.');
313
+ const emptyChunkRE = new RegExp(opts.format === 'es'
314
+ ? `\\bimport\\s*"[^"]*(?:${emptyChunkFiles})";\n?`
315
+ : `\\brequire\\(\\s*"[^"]*(?:${emptyChunkFiles})"\\);\n?`, 'g');
316
+ for (const file in bundle) {
317
+ const chunk = bundle[file];
318
+ if (chunk.type === 'chunk') {
319
+ // remove pure css chunk from other chunk's imports,
320
+ // and also register the emitted CSS files under the importer
321
+ // chunks instead.
322
+ chunk.imports = chunk.imports.filter((file) => {
323
+ if (pureCssChunks.has(file)) {
324
+ const css = exports.chunkToEmittedCssFileMap.get(bundle[file]);
325
+ if (css) {
326
+ let existing = exports.chunkToEmittedCssFileMap.get(chunk);
327
+ if (!existing) {
328
+ existing = new Set();
329
+ }
330
+ css.forEach((file) => existing.add(file));
331
+ exports.chunkToEmittedCssFileMap.set(chunk, existing);
332
+ }
333
+ return false;
334
+ }
335
+ return true;
336
+ });
337
+ chunk.code = chunk.code.replace(emptyChunkRE,
338
+ // remove css import while preserving source map location
339
+ (m) => `/* empty css ${''.padEnd(m.length - 15)}*/`);
340
+ }
341
+ }
342
+ const removedPureCssFiles = exports.removedPureCssFilesCache.get(config);
343
+ pureCssChunks.forEach((fileName) => {
344
+ removedPureCssFiles.set(fileName, bundle[fileName]);
345
+ delete bundle[fileName];
346
+ });
347
+ }
348
+ let extractedCss = outputToExtractedCSSMap.get(opts);
349
+ if (extractedCss && !hasEmitted) {
350
+ hasEmitted = true;
351
+ // minify css
352
+ if (config.build.minify) {
353
+ extractedCss = await minifyCSS(extractedCss, config);
354
+ }
355
+ this.emitFile({
356
+ name: 'style.css',
357
+ type: 'asset',
358
+ source: extractedCss,
359
+ });
360
+ }
361
+ },
362
+ };
363
+ }
364
+ exports.cssPostPlugin = cssPostPlugin;
365
+ function createCSSResolvers(config) {
366
+ let cssResolve;
367
+ let sassResolve;
368
+ let lessResolve;
369
+ return {
370
+ get css() {
371
+ return (cssResolve ||
372
+ (cssResolve = config.createResolver({
373
+ extensions: ['.css'],
374
+ mainFields: ['style'],
375
+ tryIndex: false,
376
+ preferRelative: true,
377
+ })));
378
+ },
379
+ get sass() {
380
+ return (sassResolve ||
381
+ (sassResolve = config.createResolver({
382
+ extensions: ['.scss', '.sass', '.css'],
383
+ mainFields: ['sass', 'style'],
384
+ tryIndex: true,
385
+ tryPrefix: '_',
386
+ preferRelative: true,
387
+ })));
388
+ },
389
+ get less() {
390
+ return (lessResolve ||
391
+ (lessResolve = config.createResolver({
392
+ extensions: ['.less', '.css'],
393
+ mainFields: ['less', 'style'],
394
+ tryIndex: false,
395
+ preferRelative: true,
396
+ })));
397
+ },
398
+ };
399
+ }
400
+ function getCssResolversKeys(resolvers) {
401
+ return Object.keys(resolvers);
402
+ }
403
+ async function compileCSS(id, code, config, urlReplacer, atImportResolvers, server) {
404
+ var _a;
405
+ const { modules: modulesOptions, preprocessorOptions } = config.css || {};
406
+ const isModule = modulesOptions !== false && cssModuleRE.test(id);
407
+ // although at serve time it can work without processing, we do need to
408
+ // crawl them in order to register watch dependencies.
409
+ const needInlineImport = code.includes('@import');
410
+ const hasUrl = exports.cssUrlRE.test(code) || cssImageSetRE.test(code);
411
+ const postcssConfig = await resolvePostcssConfig(config);
412
+ const lang = (_a = id.match(cssLangRE)) === null || _a === void 0 ? void 0 : _a[1];
413
+ // 1. plain css that needs no processing
414
+ if (lang === 'css' &&
415
+ !postcssConfig &&
416
+ !isModule &&
417
+ !needInlineImport &&
418
+ !hasUrl) {
419
+ return { code };
420
+ }
421
+ let map;
422
+ let modules;
423
+ const deps = new Set();
424
+ // 2. pre-processors: sass etc.
425
+ if (isPreProcessor(lang)) {
426
+ const preProcessor = preProcessors[lang];
427
+ let opts = (preprocessorOptions && preprocessorOptions[lang]) || {};
428
+ // support @import from node dependencies by default
429
+ switch (lang) {
430
+ case "scss" /* scss */:
431
+ case "sass" /* sass */:
432
+ opts = {
433
+ includePaths: ['node_modules'],
434
+ alias: config.resolve.alias,
435
+ ...opts,
436
+ };
437
+ break;
438
+ case "less" /* less */:
439
+ case "styl" /* styl */:
440
+ case "stylus" /* stylus */:
441
+ opts = {
442
+ paths: ['node_modules'],
443
+ alias: config.resolve.alias,
444
+ ...opts,
445
+ };
446
+ }
447
+ // important: set this for relative import resolving
448
+ opts.filename = (0, utils_1.cleanUrl)(id);
449
+ const preprocessResult = await preProcessor(code, config.root, opts, atImportResolvers);
450
+ if (preprocessResult.errors.length) {
451
+ throw preprocessResult.errors[0];
452
+ }
453
+ code = preprocessResult.code;
454
+ map = preprocessResult.map;
455
+ if (preprocessResult.deps) {
456
+ preprocessResult.deps.forEach((dep) => {
457
+ // sometimes sass registers the file itself as a dep
458
+ if ((0, utils_1.normalizePath)(dep) !== (0, utils_1.normalizePath)(opts.filename)) {
459
+ deps.add(dep);
460
+ }
461
+ });
462
+ }
463
+ }
464
+ // 3. postcss
465
+ const postcssOptions = (postcssConfig && postcssConfig.options) || {};
466
+ const postcssPlugins = postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : [];
467
+ if (needInlineImport) {
468
+ postcssPlugins.unshift((await Promise.resolve().then(() => __importStar(require('postcss-import')))).default({
469
+ async resolve(id, basedir) {
470
+ const resolved = await atImportResolvers.css(id, path_1.default.join(basedir, '*'));
471
+ if (resolved) {
472
+ return path_1.default.resolve(resolved);
473
+ }
474
+ return id;
475
+ },
476
+ }));
477
+ }
478
+ postcssPlugins.push(UrlRewritePostcssPlugin({
479
+ replacer: urlReplacer,
480
+ }));
481
+ if (isModule) {
482
+ postcssPlugins.unshift((await Promise.resolve().then(() => __importStar(require('postcss-modules')))).default({
483
+ ...modulesOptions,
484
+ getJSON(cssFileName, _modules, outputFileName) {
485
+ modules = _modules;
486
+ if (modulesOptions && typeof modulesOptions.getJSON === 'function') {
487
+ modulesOptions.getJSON(cssFileName, _modules, outputFileName);
488
+ }
489
+ },
490
+ async resolve(id) {
491
+ for (const key of getCssResolversKeys(atImportResolvers)) {
492
+ const resolved = await atImportResolvers[key](id);
493
+ if (resolved) {
494
+ return path_1.default.resolve(resolved);
495
+ }
496
+ }
497
+ return id;
498
+ },
499
+ }));
500
+ }
501
+ if (!postcssPlugins.length) {
502
+ return {
503
+ code,
504
+ map,
505
+ };
506
+ }
507
+ // postcss is an unbundled dep and should be lazy imported
508
+ const postcssResult = await (await Promise.resolve().then(() => __importStar(require('postcss'))))
509
+ .default(postcssPlugins)
510
+ .process(code, {
511
+ ...postcssOptions,
512
+ to: id,
513
+ from: id,
514
+ map: {
515
+ inline: false,
516
+ annotation: false,
517
+ prev: map,
518
+ },
519
+ });
520
+ // record CSS dependencies from @imports
521
+ for (const message of postcssResult.messages) {
522
+ if (message.type === 'dependency') {
523
+ deps.add(message.file);
524
+ }
525
+ else if (message.type === 'dir-dependency') {
526
+ // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies
527
+ const { dir, glob: globPattern = '**' } = message;
528
+ const pattern = (0, utils_1.normalizePath)(path_1.default.resolve(path_1.default.dirname(id), dir)) + `/` + globPattern;
529
+ const files = fast_glob_1.default.sync(pattern, {
530
+ ignore: ['**/node_modules/**'],
531
+ });
532
+ for (let i = 0; i < files.length; i++) {
533
+ deps.add(files[i]);
534
+ }
535
+ if (server) {
536
+ // register glob importers so we can trigger updates on file add/remove
537
+ if (!(id in server._globImporters)) {
538
+ ;
539
+ server._globImporters[id] = {
540
+ module: server.moduleGraph.getModuleById(id),
541
+ importGlobs: [],
542
+ };
543
+ }
544
+ ;
545
+ server._globImporters[id].importGlobs.push({
546
+ base: config.root,
547
+ pattern,
548
+ });
549
+ }
550
+ }
551
+ else if (message.type === 'warning') {
552
+ let msg = `[vite:css] ${message.text}`;
553
+ if (message.line && message.column) {
554
+ msg += `\n${(0, utils_1.generateCodeFrame)(code, {
555
+ line: message.line,
556
+ column: message.column,
557
+ })}`;
558
+ }
559
+ config.logger.warn(chalk_1.default.yellow(msg));
560
+ }
561
+ }
562
+ return {
563
+ ast: postcssResult,
564
+ code: postcssResult.css,
565
+ map: postcssResult.map,
566
+ modules,
567
+ deps,
568
+ };
569
+ }
570
+ async function resolvePostcssConfig(config) {
571
+ var _a;
572
+ let result = postcssConfigCache.get(config);
573
+ if (result !== undefined) {
574
+ return result;
575
+ }
576
+ // inline postcss config via vite config
577
+ const inlineOptions = (_a = config.css) === null || _a === void 0 ? void 0 : _a.postcss;
578
+ if ((0, utils_1.isObject)(inlineOptions)) {
579
+ const options = { ...inlineOptions };
580
+ delete options.plugins;
581
+ result = {
582
+ options,
583
+ plugins: inlineOptions.plugins || [],
584
+ };
585
+ }
586
+ else {
587
+ try {
588
+ const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
589
+ // @ts-ignore
590
+ result = await (0, postcss_load_config_1.default)({}, searchPath);
591
+ }
592
+ catch (e) {
593
+ if (!/No PostCSS Config found/.test(e.message)) {
594
+ throw e;
595
+ }
596
+ result = null;
597
+ }
598
+ }
599
+ postcssConfigCache.set(config, result);
600
+ return result;
601
+ }
602
+ // https://drafts.csswg.org/css-syntax-3/#identifier-code-point
603
+ exports.cssUrlRE = /(?<=^|[^\w\-\u0080-\uffff])url\(\s*('[^']+'|"[^"]+"|[^'")]+)\s*\)/;
604
+ const cssImageSetRE = /image-set\(([^)]+)\)/;
605
+ const UrlRewritePostcssPlugin = (opts) => {
606
+ if (!opts) {
607
+ throw new Error('base or replace is required');
608
+ }
609
+ return {
610
+ postcssPlugin: 'vite-url-rewrite',
611
+ Once(root) {
612
+ const promises = [];
613
+ root.walkDecls((declaration) => {
614
+ const isCssUrl = exports.cssUrlRE.test(declaration.value);
615
+ const isCssImageSet = cssImageSetRE.test(declaration.value);
616
+ if (isCssUrl || isCssImageSet) {
617
+ const replacerForDeclaration = (rawUrl) => {
618
+ var _a;
619
+ const importer = (_a = declaration.source) === null || _a === void 0 ? void 0 : _a.input.file;
620
+ return opts.replacer(rawUrl, importer);
621
+ };
622
+ const rewriterToUse = isCssUrl ? rewriteCssUrls : rewriteCssImageSet;
623
+ promises.push(rewriterToUse(declaration.value, replacerForDeclaration).then((url) => {
624
+ declaration.value = url;
625
+ }));
626
+ }
627
+ });
628
+ if (promises.length) {
629
+ return Promise.all(promises);
630
+ }
631
+ },
632
+ };
633
+ };
634
+ UrlRewritePostcssPlugin.postcss = true;
635
+ function rewriteCssUrls(css, replacer) {
636
+ return (0, utils_1.asyncReplace)(css, exports.cssUrlRE, async (match) => {
637
+ const [matched, rawUrl] = match;
638
+ return await doUrlReplace(rawUrl, matched, replacer);
639
+ });
640
+ }
641
+ function rewriteCssImageSet(css, replacer) {
642
+ return (0, utils_1.asyncReplace)(css, cssImageSetRE, async (match) => {
643
+ const [matched, rawUrl] = match;
644
+ const url = await (0, utils_1.processSrcSet)(rawUrl, ({ url }) => doUrlReplace(url, matched, replacer));
645
+ return `image-set(${url})`;
646
+ });
647
+ }
648
+ async function doUrlReplace(rawUrl, matched, replacer) {
649
+ let wrap = '';
650
+ const first = rawUrl[0];
651
+ if (first === `"` || first === `'`) {
652
+ wrap = first;
653
+ rawUrl = rawUrl.slice(1, -1);
654
+ }
655
+ if ((0, utils_1.isExternalUrl)(rawUrl) || (0, utils_1.isDataUrl)(rawUrl) || rawUrl.startsWith('#')) {
656
+ return matched;
657
+ }
658
+ return `url(${wrap}${await replacer(rawUrl)}${wrap})`;
659
+ }
660
+ async function minifyCSS(css, config) {
661
+ const { code, warnings } = await (0, esbuild_1.transform)(css, {
662
+ loader: 'css',
663
+ minify: true,
664
+ target: config.build.cssTarget || undefined,
665
+ });
666
+ if (warnings.length) {
667
+ const msgs = await (0, esbuild_1.formatMessages)(warnings, { kind: 'warning' });
668
+ config.logger.warn(chalk_1.default.yellow(`warnings when minifying css:\n${msgs.join('\n')}`));
669
+ }
670
+ return code;
671
+ }
672
+ // #1845
673
+ // CSS @import can only appear at top of the file. We need to hoist all @import
674
+ // to top when multiple files are concatenated.
675
+ async function hoistAtImports(css) {
676
+ const postcss = await Promise.resolve().then(() => __importStar(require('postcss')));
677
+ return (await postcss.default([AtImportHoistPlugin]).process(css)).css;
678
+ }
679
+ const AtImportHoistPlugin = () => {
680
+ return {
681
+ postcssPlugin: 'vite-hoist-at-imports',
682
+ Once(root) {
683
+ const imports = [];
684
+ root.walkAtRules((rule) => {
685
+ if (rule.name === 'import') {
686
+ // record in reverse so that can simply prepend to preserve order
687
+ imports.unshift(rule);
688
+ }
689
+ });
690
+ imports.forEach((i) => root.prepend(i));
691
+ },
692
+ };
693
+ };
694
+ AtImportHoistPlugin.postcss = true;
695
+ const loadedPreprocessors = {};
696
+ function loadPreprocessor(lang, root) {
697
+ var _a, _b;
698
+ if (lang in loadedPreprocessors) {
699
+ return loadedPreprocessors[lang];
700
+ }
701
+ try {
702
+ // Search for the preprocessor in the root directory first, and fall back
703
+ // to the default require paths.
704
+ const fallbackPaths = ((_b = (_a = require.resolve).paths) === null || _b === void 0 ? void 0 : _b.call(_a, lang)) || [];
705
+ const resolved = require.resolve(lang, { paths: [root, ...fallbackPaths] });
706
+ return (loadedPreprocessors[lang] = require(resolved));
707
+ }
708
+ catch (e) {
709
+ throw new Error(`Preprocessor dependency "${lang}" not found. Did you install it?`);
710
+ }
711
+ }
712
+ // .scss/.sass processor
713
+ const scss = async (source, root, options, resolvers) => {
714
+ const render = loadPreprocessor("sass" /* sass */, root).render;
715
+ const internalImporter = (url, importer, done) => {
716
+ resolvers.sass(url, importer).then((resolved) => {
717
+ if (resolved) {
718
+ rebaseUrls(resolved, options.filename, options.alias)
719
+ .then((data) => done === null || done === void 0 ? void 0 : done(data))
720
+ .catch((data) => done === null || done === void 0 ? void 0 : done(data));
721
+ }
722
+ else {
723
+ done === null || done === void 0 ? void 0 : done(null);
724
+ }
725
+ });
726
+ };
727
+ const importer = [internalImporter];
728
+ if (options.importer) {
729
+ Array.isArray(options.importer)
730
+ ? importer.push(...options.importer)
731
+ : importer.push(options.importer);
732
+ }
733
+ const finalOptions = {
734
+ ...options,
735
+ data: await getSource(source, options.filename, options.additionalData),
736
+ file: options.filename,
737
+ outFile: options.filename,
738
+ importer,
739
+ };
740
+ try {
741
+ const result = await new Promise((resolve, reject) => {
742
+ render(finalOptions, (err, res) => {
743
+ if (err) {
744
+ reject(err);
745
+ }
746
+ else {
747
+ resolve(res);
748
+ }
749
+ });
750
+ });
751
+ const deps = result.stats.includedFiles;
752
+ return {
753
+ code: result.css.toString(),
754
+ errors: [],
755
+ deps,
756
+ };
757
+ }
758
+ catch (e) {
759
+ // normalize SASS error
760
+ e.id = e.file;
761
+ e.frame = e.formatted;
762
+ return { code: '', errors: [e], deps: [] };
763
+ }
764
+ };
765
+ const sass = (source, root, options, aliasResolver) => scss(source, root, {
766
+ ...options,
767
+ indentedSyntax: true,
768
+ }, aliasResolver);
769
+ /**
770
+ * relative url() inside \@imported sass and less files must be rebased to use
771
+ * root file as base.
772
+ */
773
+ async function rebaseUrls(file, rootFile, alias) {
774
+ file = path_1.default.resolve(file); // ensure os-specific flashes
775
+ // fixed by xxxxxx 条件编译
776
+ const contents = (0, css_1.preprocessCss)(fs_1.default.readFileSync(file, 'utf-8'));
777
+ // in the same dir, no need to rebase
778
+ const fileDir = path_1.default.dirname(file);
779
+ const rootDir = path_1.default.dirname(rootFile);
780
+ if (fileDir === rootDir) {
781
+ return { file, contents };
782
+ }
783
+ // no url()
784
+ if (!exports.cssUrlRE.test(contents)) {
785
+ return { file, contents };
786
+ }
787
+ const rebased = await rewriteCssUrls(contents, (url) => {
788
+ if (url.startsWith('/'))
789
+ return url;
790
+ // match alias, no need to rewrite
791
+ for (const { find } of alias) {
792
+ const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url);
793
+ if (matches) {
794
+ return url;
795
+ }
796
+ }
797
+ const absolute = path_1.default.resolve(fileDir, url);
798
+ const relative = path_1.default.relative(rootDir, absolute);
799
+ return (0, utils_1.normalizePath)(relative);
800
+ });
801
+ return {
802
+ file,
803
+ contents: rebased,
804
+ };
805
+ }
806
+ // .less
807
+ const less = async (source, root, options, resolvers) => {
808
+ const nodeLess = loadPreprocessor("less" /* less */, root);
809
+ const viteResolverPlugin = createViteLessPlugin(nodeLess, options.filename, options.alias, resolvers);
810
+ source = await getSource(source, options.filename, options.additionalData);
811
+ let result;
812
+ try {
813
+ result = await nodeLess.render(source, {
814
+ ...options,
815
+ plugins: [viteResolverPlugin, ...(options.plugins || [])],
816
+ });
817
+ }
818
+ catch (e) {
819
+ const error = e;
820
+ // normalize error info
821
+ const normalizedError = new Error(error.message || error.type);
822
+ normalizedError.loc = {
823
+ file: error.filename || options.filename,
824
+ line: error.line,
825
+ column: error.column,
826
+ };
827
+ return { code: '', errors: [normalizedError], deps: [] };
828
+ }
829
+ return {
830
+ code: result.css.toString(),
831
+ deps: result.imports,
832
+ errors: [],
833
+ };
834
+ };
835
+ /**
836
+ * Less manager, lazy initialized
837
+ */
838
+ let ViteLessManager;
839
+ function createViteLessPlugin(less, rootFile, alias, resolvers) {
840
+ if (!ViteLessManager) {
841
+ ViteLessManager = class ViteManager extends less.FileManager {
842
+ constructor(rootFile, resolvers, alias) {
843
+ super();
844
+ this.rootFile = rootFile;
845
+ this.resolvers = resolvers;
846
+ this.alias = alias;
847
+ }
848
+ supports() {
849
+ return true;
850
+ }
851
+ supportsSync() {
852
+ return false;
853
+ }
854
+ async loadFile(filename, dir, opts, env) {
855
+ const resolved = await this.resolvers.less(filename, path_1.default.join(dir, '*'));
856
+ if (resolved) {
857
+ const result = await rebaseUrls(resolved, this.rootFile, this.alias);
858
+ let contents;
859
+ if (result && 'contents' in result) {
860
+ contents = result.contents;
861
+ }
862
+ else {
863
+ contents = fs_1.default.readFileSync(resolved, 'utf-8');
864
+ }
865
+ return {
866
+ filename: path_1.default.resolve(resolved),
867
+ contents,
868
+ };
869
+ }
870
+ else {
871
+ return super.loadFile(filename, dir, opts, env);
872
+ }
873
+ }
874
+ };
875
+ }
876
+ return {
877
+ install(_, pluginManager) {
878
+ pluginManager.addFileManager(new ViteLessManager(rootFile, resolvers, alias));
879
+ },
880
+ minVersion: [3, 0, 0],
881
+ };
882
+ }
883
+ // .styl
884
+ const styl = async (source, root, options) => {
885
+ var _a;
886
+ const nodeStylus = loadPreprocessor("stylus" /* stylus */, root);
887
+ // Get source with preprocessor options.additionalData. Make sure a new line separator
888
+ // is added to avoid any render error, as added stylus content may not have semi-colon separators
889
+ source = await getSource(source, options.filename, options.additionalData, '\n');
890
+ // Get preprocessor options.imports dependencies as stylus
891
+ // does not return them with its builtin `.deps()` method
892
+ const importsDeps = ((_a = options.imports) !== null && _a !== void 0 ? _a : []).map((dep) => path_1.default.resolve(dep));
893
+ try {
894
+ const ref = nodeStylus(source, options);
895
+ // if (map) ref.set('sourcemap', { inline: false, comment: false })
896
+ const result = ref.render();
897
+ // Concat imports deps with computed deps
898
+ const deps = [...ref.deps(), ...importsDeps];
899
+ return { code: result, errors: [], deps };
900
+ }
901
+ catch (e) {
902
+ return { code: '', errors: [e], deps: [] };
903
+ }
904
+ };
905
+ function getSource(source, filename, additionalData, sep = '') {
906
+ if (!additionalData)
907
+ return source;
908
+ if (typeof additionalData === 'function') {
909
+ return additionalData(source, filename);
910
+ }
911
+ return additionalData + sep + source;
912
+ }
913
+ const preProcessors = Object.freeze({
914
+ ["less" /* less */]: less,
915
+ ["sass" /* sass */]: sass,
916
+ ["scss" /* scss */]: scss,
917
+ ["styl" /* styl */]: styl,
918
+ ["stylus" /* stylus */]: styl,
919
+ });
920
+ function isPreProcessor(lang) {
921
+ return lang && lang in preProcessors;
922
+ }