@unpackjs/core 4.2.1 → 4.2.3

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.
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ import { Compilation, rspack } from "@rspack/core";
10
10
  import cac from "cac";
11
11
  import node_fs from "node:fs";
12
12
  import node_readline from "node:readline";
13
+ import { createHash } from "node:crypto";
13
14
  import node_os, { platform } from "node:os";
14
15
  import portfinder from "portfinder";
15
16
  import { glob as external_tinyglobby_glob, globSync } from "tinyglobby";
@@ -17,7 +18,6 @@ import { format, promisify } from "node:util";
17
18
  import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
18
19
  import { parse } from "stacktrace-parser";
19
20
  import node_zlib from "node:zlib";
20
- import { createHash } from "node:crypto";
21
21
  import magic_string from "magic-string";
22
22
  import { expand } from "dotenv-expand";
23
23
  import node_assert from "node:assert";
@@ -122,7 +122,7 @@ let CSS_MODULES_LOCAL_IDENT_NAME = '[path][name]__[local]--[hash:5]', CSS_MODULE
122
122
  </body>
123
123
  </html>`, JS_REGEX = /\.[jt]s$/, JSX_REGEX = /\.[jt]sx$/, SCRIPT_REGEX = /\.[jt]sx?$/;
124
124
  var utils_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
125
- let { merge: utils_mergeConfig } = __webpack_require__("compiled/webpack-merge"), { default: launchEditor } = __webpack_require__("compiled/launch-editor"), getNodeEnv = ()=>process.env.NODE_ENV, setNodeEnv = (env)=>{
125
+ let { merge: mergeConfig } = __webpack_require__("compiled/webpack-merge"), { default: launchEditor } = __webpack_require__("compiled/launch-editor"), getNodeEnv = ()=>process.env.NODE_ENV, setNodeEnv = (env)=>{
126
126
  process.env.NODE_ENV = env;
127
127
  }, setDevServer = (isDevServer)=>{
128
128
  process.env.DEV_SERVER = isDevServer ? 'true' : 'false';
@@ -169,7 +169,16 @@ function getTime() {
169
169
  let now = new Date(), hours = String(now.getHours()).padStart(2, '0'), minutes = String(now.getMinutes()).padStart(2, '0'), seconds = String(now.getSeconds()).padStart(2, '0');
170
170
  return `${hours}:${minutes}:${seconds}`;
171
171
  }
172
- let debounce = (fn, delay)=>{
172
+ let getFilesContentHash = (filePaths)=>{
173
+ let normalizedPaths = [
174
+ ...filePaths
175
+ ].filter(Boolean).map((filePath)=>node_path.resolve(filePath)).sort(), hash = createHash('sha256');
176
+ for (let filePath of normalizedPaths.filter((filePath)=>node_fs.existsSync(filePath))){
177
+ let content = node_fs.readFileSync(filePath);
178
+ hash.update(content);
179
+ }
180
+ return hash.digest('hex');
181
+ }, debounce = (fn, delay)=>{
173
182
  let timer = null;
174
183
  return (...args)=>{
175
184
  clearTimeout(timer), timer = setTimeout(()=>{
@@ -502,26 +511,75 @@ async function getCompressedSize(content) {
502
511
  let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i, GLOB_MAGIC_RE = /[*?[\]{}()!@+|]/, normalizeBaseDir = (raw)=>{
503
512
  let normalized = raw.replace(/\\/g, '/');
504
513
  return normalized && '.' !== normalized ? (normalized.startsWith('/') ? normalized = normalized.replace(/\/{2,}/g, '/') : normalized.startsWith('.') || (normalized = `./${normalized}`), (normalized = normalized.replace(/\/{2,}/g, '/')).endsWith('/') && (normalized = normalized.slice(0, -1)), '.' === normalized ? './' : normalized) : './';
505
- }, toRegexLiteral = (source)=>`/${source.replace(/\\?\//g, (value)=>'/' === value ? '\\/' : value)}/`, parseGlob = (pattern)=>{
514
+ }, toRegexLiteral = (source)=>`/${source.replace(/\\?\//g, (value)=>'/' === value ? '\\/' : value)}/`, buildInnerRegExpSource = (glob)=>{
515
+ let source = glob.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
516
+ return (source = (source = source.replace(/\\\*\\\*/g, '.*')).replace(/\\\*/g, '[^/]*')).replace(/\\\?/g, '[^/]');
517
+ }, parseGlob = (pattern)=>{
506
518
  let normalized = pattern.replace(/\\/g, '/'), isAbs = normalized.startsWith('/'), normalizedForParse = isAbs ? `.${normalized}` : normalized, globIndex = normalizedForParse.search(GLOB_MAGIC_RE), slashIndex = -1 === globIndex ? normalizedForParse.lastIndexOf('/') : normalizedForParse.lastIndexOf('/', globIndex), baseDirRaw = slashIndex >= 0 ? normalizedForParse.slice(0, slashIndex) : '.', globPart = slashIndex >= 0 ? normalizedForParse.slice(slashIndex + 1) : normalizedForParse, recursive = normalizedForParse.includes('**'), baseDir = isAbs ? normalizeBaseDir(`/${baseDirRaw.replace(/^\.\//, '')}`) : normalizeBaseDir(baseDirRaw);
507
519
  return {
508
520
  baseDir,
509
521
  regExpSource: ((glob)=>{
510
522
  let expansions;
511
523
  if (!glob) return '^\\.\\/.*$';
512
- let { replaced, expansions: expansions1 } = (expansions = [], {
513
- replaced: glob.replace(/\{([^}]+)\}/g, (_, inner)=>(expansions.push(inner), `__BRACE_${expansions.length - 1}__`)),
524
+ let { replaced: replacedExtGlob, negations } = ((glob)=>{
525
+ let negations = [], out = '';
526
+ for(let i = 0; i < glob.length; i++){
527
+ let ch = glob[i];
528
+ if ('!' !== ch || '(' !== glob[i + 1]) {
529
+ out += ch;
530
+ continue;
531
+ }
532
+ let j = i + 2, depth = 1;
533
+ for(; j < glob.length; j++){
534
+ let cj = glob[j];
535
+ if ('(' === cj) depth++;
536
+ else if (')' === cj && 0 == --depth) break;
537
+ }
538
+ if (0 !== depth) {
539
+ out += ch;
540
+ continue;
541
+ }
542
+ let inner = glob.slice(i + 2, j);
543
+ negations.push(inner), out += `__EXT_NEG_${negations.length - 1}__`, i = j;
544
+ }
545
+ return {
546
+ replaced: out,
547
+ negations
548
+ };
549
+ })(glob), { replaced, expansions: expansions1 } = (expansions = [], {
550
+ replaced: replacedExtGlob.replace(/\{([^}]+)\}/g, (_, inner)=>(expansions.push(inner), `__BRACE_${expansions.length - 1}__`)),
514
551
  expansions
515
552
  }), source = replaced.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
516
- return source = (source = (source = (source = (source = (source = source.replace(/__BRACE_(\d+)__/g, (_, index)=>{
553
+ return source = (source = (source = (source = (source = (source = (source = source.replace(/__BRACE_(\d+)__/g, (_, index)=>{
517
554
  let parts = (expansions1[Number(index)] || '').split(',').map((part)=>part.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
518
555
  return `(${parts.join('|')})`;
556
+ })).replace(/__EXT_NEG_(\d+)__/g, (_, index)=>{
557
+ let parts = (negations[Number(index)] || '').split('|').map((part)=>part.trim()).filter(Boolean).map(buildInnerRegExpSource);
558
+ return parts.length ? `(?!(?:${parts.join('|')}))[^/]*` : '[^/]*';
519
559
  })).replace(/\\\(([^)]+)\\\)\\\?/g, (_, inner)=>`(?:${inner})?`)).replace(/\\\*\\\*\\\//g, '(?:.*\\/)?')).replace(/\\\*\\\*/g, '.*')).replace(/\\\*/g, '[^/]*')).replace(/\\\?/g, '[^/]'), `^(?:\\.\\/)?${source}$`;
520
560
  })(globPart),
521
561
  recursive,
522
562
  publicPrefix: './' === baseDir ? './' : baseDir
523
563
  };
524
- }, hasEager = (rawOptions)=>!!rawOptions && /eager\s*:\s*true/.test(rawOptions), SPECIAL_NO_ENTRY_DEPS = [
564
+ }, hasEager = (rawOptions)=>!!rawOptions && /eager\s*:\s*true/.test(rawOptions), warnedMissingAliasKeys = new Set(), normalizeGlobByAliases = (pattern, options)=>{
565
+ let trimmed = pattern.trim();
566
+ if (!trimmed || trimmed.startsWith('/') || trimmed.startsWith('.')) return trimmed;
567
+ let aliasEntries = Object.entries(options.alias).filter(([key])=>key && '/' !== key).sort((a, b)=>b[0].length - a[0].length);
568
+ for (let [rawKey, rawTarget] of aliasEntries){
569
+ let key = rawKey.endsWith('/') ? rawKey.slice(0, -1) : rawKey;
570
+ if (!key || !trimmed.startsWith(`${key}/`)) continue;
571
+ let targetAbs = node_path.isAbsolute(rawTarget) ? rawTarget : node_path.resolve(options.root, rawTarget), rel = node_path.relative(options.root, targetAbs).replace(/\\/g, '/');
572
+ if (rel.startsWith('..')) continue;
573
+ let publicBase = `/${rel}`.replace(/\/{2,}/g, '/').replace(/\/$/, ''), rest = trimmed.slice(key.length);
574
+ return `${publicBase}${rest}`.replace(/\/{2,}/g, '/');
575
+ }
576
+ let normalized = trimmed.replace(/\\/g, '/'), firstChar = normalized[0];
577
+ if ('@' === firstChar || '~' === firstChar || '#' === firstChar) {
578
+ let slashIndex = normalized.indexOf('/'), aliasKey = normalized.slice(0, slashIndex);
579
+ aliasEntries.map(([rawKey])=>rawKey.endsWith('/') ? rawKey.slice(0, -1) : rawKey).filter(Boolean).includes(aliasKey) || warnedMissingAliasKeys.has(aliasKey) || (warnedMissingAliasKeys.add(aliasKey), logger_logger.warn(`Unrecognized alias "${aliasKey}" in glob pattern: "${trimmed}", please ensure it is defined in "resolve.alias".`));
580
+ }
581
+ return trimmed;
582
+ }, SPECIAL_NO_ENTRY_DEPS = [
525
583
  '@iconify-icons/material-symbols'
526
584
  ], FRAMEWORKS = [
527
585
  'react',
@@ -564,7 +622,7 @@ let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|
564
622
  'uno.config.ts',
565
623
  'uno.config.js',
566
624
  'uno.config.mts'
567
- ], LAYER_MARK_ALL = '__ALL__', HASH_PLACEHOLDER_RE = /#--unocss-hash--\s*\{\s*content\s*:\s*\\*"([^\\"]+)\\*";?\s*\}/g, LAYER_PLACEHOLDER_RE = /#--unocss--\s*\{\s*layer\s*:\s*(.+?)\s*(?:;\s*escape-view\s*:\s*(.+?)\s*)?;?\s*\}/g, SKIP_START_COMMENT = '@unocss-skip-start', SKIP_END_COMMENT = '@unocss-skip-end', SKIP_COMMENT_RE = RegExp(`(?://\\s*?${SKIP_START_COMMENT}\\s*?|/\\*\\s*?${SKIP_START_COMMENT}\\s*?\\*/|<!--\\s*?${SKIP_START_COMMENT}\\s*?-->)[\\s\\S]*?(?://\\s*?${SKIP_END_COMMENT}\\s*?|/\\*\\s*?${SKIP_END_COMMENT}\\s*?\\*/|<!--\\s*?${SKIP_END_COMMENT}\\s*?-->)`, 'g'), getCssEscaperForJsContent = (view)=>{
625
+ ], LAYER_MARK_ALL = '__ALL__', HASH_PLACEHOLDER_RE = /#--unocss-hash--\s*\{\s*content\s*:\s*\\*"([^\\"]+)\\*";?\s*\}/g, LAYER_PLACEHOLDER_RE = /#--unocss--\s*\{\s*layer\s*:\s*(.+?)\s*(?:;\s*escape-view\s*:\s*(.+?)\s*)?;?\s*\}/g, SKIP_START_COMMENT = '@unocss-skip-start', SKIP_END_COMMENT = '@unocss-skip-end', SKIP_COMMENT_RE = RegExp(`(?://\\s*?${SKIP_START_COMMENT}\\s*?|/\\*\\s*?${SKIP_START_COMMENT}\\s*?\\*/|<!--\\s*?${SKIP_START_COMMENT}\\s*?-->)[\\s\\S]*?(?://\\s*?${SKIP_END_COMMENT}\\s*?|/\\*\\s*?${SKIP_END_COMMENT}\\s*?\\*/|<!--\\s*?${SKIP_END_COMMENT}\\s*?-->)`, 'g'), LAYER_IMPORT_RE = /(['"])uno:([^'"]+?)\.css\1/g, getCssEscaperForJsContent = (view)=>{
568
626
  if (!view) return (css)=>css;
569
627
  let prefix = {};
570
628
  return view.trim().replace(/(\\*)\\(["'`\\])/g, (_, bs, char)=>(prefix[char] = bs.replace(/\\\\/g, '\\'), '')), (css)=>css.replace(/["'`\\]/g, (v)=>(prefix[v] || '') + v);
@@ -680,7 +738,7 @@ async function applyCacheConfig({ config, unpackConfig, envFilePaths }) {
680
738
  let cacheConfig = isPlainObject(unpackConfig.performance.cache) ? unpackConfig.performance.cache : {}, buildDependencies = await getBuildDependencies(unpackConfig.root);
681
739
  buildDependencies.userBuildDependencies = cacheConfig.buildDependencies || [], buildDependencies.envFilePaths = envFilePaths;
682
740
  let cacheDirectory = node_path.resolve(unpackConfig.root, cacheConfig.cacheDirectory || `${unpackConfig._context.cachePath}/cache`, utils_isDevServer() ? 'dev' : 'build');
683
- return utils_mergeConfig(config, {
741
+ return mergeConfig(config, {
684
742
  cache: !0,
685
743
  experiments: {
686
744
  cache: {
@@ -781,7 +839,7 @@ let MODULE_PATH_REGEX = /.*[\\/]node_modules[\\/](?!\.pnpm[\\/])(?:(@[^\\/]+)[\\
781
839
  };
782
840
  async function getEntry(root, customEntry) {
783
841
  let entry;
784
- if (entry = customEntry ? node_path.resolve(root, customEntry) : (await external_tinyglobby_glob('(index|Index).{js,ts,jsx,tsx}', {
842
+ if (entry = customEntry ? node_path.resolve(root, customEntry) : (await external_tinyglobby_glob('(index|main).{js,ts,jsx,tsx}', {
785
843
  cwd: node_path.join(root, 'src'),
786
844
  absolute: !0
787
845
  }))[0], !node_fs.existsSync(entry)) throw Error('could not find entry file');
@@ -823,7 +881,7 @@ class JsMinifyPlugin {
823
881
  apply(compiler) {
824
882
  let meta = JSON.stringify({
825
883
  name: jsMinify_PLUGIN_NAME,
826
- version: "4.2.1",
884
+ version: "4.2.3",
827
885
  options: this.minifyOptions
828
886
  });
829
887
  compiler.hooks.compilation.tap(jsMinify_PLUGIN_NAME, (compilation)=>{
@@ -968,31 +1026,18 @@ let registerHooks_PLUGIN_NAME = 'RegisterHooksPlugin';
968
1026
  class RegisterHooksPlugin {
969
1027
  isFirstCompile = !0;
970
1028
  lastVirtualModules = new Map();
1029
+ isCompiling = !1;
1030
+ idleTimer = void 0;
971
1031
  apply(compiler) {
972
1032
  let virtualModulesPlugin = new rspack.experiments.VirtualModulesPlugin();
973
- virtualModulesPlugin.apply(compiler), compiler.hooks.beforeCompile.tapPromise(registerHooks_PLUGIN_NAME, async ()=>{
974
- await applyPluginsByHook('buildStart', async (impl)=>{
975
- await impl({
1033
+ virtualModulesPlugin.apply(compiler), compiler.hooks.compile.tap(registerHooks_PLUGIN_NAME, ()=>{
1034
+ this.isCompiling = !0, applyPluginsByHookSync('buildStart', (impl)=>{
1035
+ impl({
976
1036
  compiler,
977
1037
  isFirstCompile: this.isFirstCompile,
978
1038
  isWatch: isDev()
979
1039
  });
980
1040
  });
981
- }), compiler.hooks.done.tapPromise(registerHooks_PLUGIN_NAME, async (stats)=>{
982
- stats?.compilation && ((compilation)=>{
983
- let pluginMap = transformTimingMap.get(compilation);
984
- if (pluginMap) {
985
- for (let [pluginName, total] of pluginMap)logger_logger.debug(`${colors.magenta('[plugin]')} ${colors.cyan(pluginName)} ${colors.blue('transform')} ${colors.dim('in')} ${colors.yellow(`${total.toFixed(2)}ms`)}`);
986
- transformTimingMap.delete(compilation);
987
- }
988
- })(stats.compilation), await applyPluginsByHook('buildEnd', async (impl)=>{
989
- await impl({
990
- compiler,
991
- isFirstCompile: this.isFirstCompile,
992
- isWatch: isDev(),
993
- stats
994
- });
995
- }), this.isFirstCompile = !1;
996
1041
  });
997
1042
  let updateVirtualModules = ()=>{
998
1043
  applyPluginsByHookSync('virtualModules', (impl)=>{
@@ -1001,15 +1046,7 @@ class RegisterHooksPlugin {
1001
1046
  });
1002
1047
  });
1003
1048
  };
1004
- compiler.hooks.afterDone.tap(registerHooks_PLUGIN_NAME, ()=>{
1005
- isDev() && setTimeout(()=>{
1006
- updateVirtualModules();
1007
- }, 100);
1008
- }), compiler.hooks.compilation.tap(registerHooks_PLUGIN_NAME, (compilation)=>{
1009
- rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeEmit.tapPromise(registerHooks_PLUGIN_NAME, async (data)=>(await applyPluginsByHook('transformHtml', async (impl)=>{
1010
- data.html = await impl(data.html);
1011
- }), data));
1012
- }), compiler.hooks.thisCompilation.tap(registerHooks_PLUGIN_NAME, (compilation)=>{
1049
+ compiler.hooks.thisCompilation.tap(registerHooks_PLUGIN_NAME, (compilation)=>{
1013
1050
  updateVirtualModules(), applyPluginsByHook('processAssets', (impl, plugin)=>{
1014
1051
  let { stage, handler } = impl;
1015
1052
  compilation.hooks.processAssets.tapPromise({
@@ -1030,6 +1067,29 @@ class RegisterHooksPlugin {
1030
1067
  }
1031
1068
  });
1032
1069
  });
1070
+ }), compiler.hooks.compilation.tap(registerHooks_PLUGIN_NAME, (compilation)=>{
1071
+ rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeEmit.tapPromise(registerHooks_PLUGIN_NAME, async (data)=>(await applyPluginsByHook('transformHtml', async (impl)=>{
1072
+ data.html = await impl(data.html);
1073
+ }), data));
1074
+ }), compiler.hooks.finishMake.tap(registerHooks_PLUGIN_NAME, (compilation)=>{
1075
+ let pluginMap = transformTimingMap.get(compilation);
1076
+ if (pluginMap) {
1077
+ for (let [pluginName, total] of pluginMap)logger_logger.debug(`${colors.magenta('[plugin]')} ${colors.cyan(pluginName)} ${colors.blue('transform')} ${colors.dim('in')} ${colors.yellow(`${total.toFixed(2)}ms`)}`);
1078
+ transformTimingMap.delete(compilation);
1079
+ }
1080
+ }), compiler.hooks.done.tapPromise(registerHooks_PLUGIN_NAME, async (stats)=>{
1081
+ await applyPluginsByHook('buildEnd', async (impl)=>{
1082
+ await impl({
1083
+ compiler,
1084
+ isFirstCompile: this.isFirstCompile,
1085
+ isWatch: isDev(),
1086
+ stats
1087
+ });
1088
+ }), this.isFirstCompile = !1;
1089
+ }), compiler.hooks.afterDone.tap(registerHooks_PLUGIN_NAME, ()=>{
1090
+ this.isCompiling = !1, isDev() && (clearTimeout(this.idleTimer), this.idleTimer = setTimeout(()=>{
1091
+ this.isCompiling || updateVirtualModules();
1092
+ }, 50));
1033
1093
  });
1034
1094
  }
1035
1095
  }
@@ -1069,7 +1129,7 @@ async function getBundlerConfig(originalUnpackConfig) {
1069
1129
  await applyPluginsByHook('config', async (impl)=>{
1070
1130
  rest = await impl(rest, {
1071
1131
  ...originalUnpackConfig._context,
1072
- mergeConfig: utils_mergeConfig
1132
+ mergeConfig: mergeConfig
1073
1133
  });
1074
1134
  });
1075
1135
  let unpackConfig = {
@@ -1080,7 +1140,7 @@ async function getBundlerConfig(originalUnpackConfig) {
1080
1140
  setCurrentUnpackConfig(unpackConfig), await applyPluginsByHook('configResolved', async (impl)=>{
1081
1141
  await impl(unpackConfig, originalUnpackConfig._context);
1082
1142
  });
1083
- let tsconfigPath = node_path.resolve(unpackConfig.root, 'tsconfig.json'), isTs = node_fs.existsSync(tsconfigPath), minifyOptions = isPlainObject(unpackConfig.build?.minify) ? unpackConfig.build?.minify : {}, { publicVars, filePaths: envFilePaths } = function({ cwd = process.cwd(), mode = getNodeEnv(), prefixes = [
1143
+ let tsconfigPath = node_path.resolve(unpackConfig.root, 'tsconfig.json'), isTS = node_fs.existsSync(tsconfigPath), minifyOptions = isPlainObject(unpackConfig.build?.minify) ? unpackConfig.build?.minify : {}, { publicVars, filePaths: envFilePaths } = function({ cwd = process.cwd(), mode = getNodeEnv(), prefixes = [
1084
1144
  'PUBLIC_'
1085
1145
  ], processEnv = process.env } = {}) {
1086
1146
  if ('local' === mode) throw Error(`${colors.yellow('local')} cannot be used as a value for env mode, because ${colors.yellow('.env.local')} represents a temporary local file. Please use another value.`);
@@ -1197,11 +1257,11 @@ async function getBundlerConfig(originalUnpackConfig) {
1197
1257
  ].filter(Boolean),
1198
1258
  externals: unpackConfig.externals,
1199
1259
  resolve: {
1200
- tsConfig: isTs ? tsconfigPath : void 0,
1201
- alias: {
1202
- '@': node_path.resolve(unpackConfig.root, 'src'),
1203
- ...unpackConfig.resolve?.alias
1204
- },
1260
+ tsConfig: isTS ? {
1261
+ configFile: tsconfigPath,
1262
+ references: 'auto'
1263
+ } : void 0,
1264
+ alias: unpackConfig.resolve?.alias,
1205
1265
  extensionAlias: {
1206
1266
  '.js': [
1207
1267
  '.js',
@@ -1214,12 +1274,13 @@ async function getBundlerConfig(originalUnpackConfig) {
1214
1274
  ]
1215
1275
  },
1216
1276
  extensions: [
1217
- '.tsx',
1218
1277
  '.ts',
1219
- '.jsx',
1278
+ '.tsx',
1279
+ '.mjs',
1220
1280
  '.js',
1221
- '.wasm',
1281
+ '.jsx',
1222
1282
  '.json',
1283
+ '.wasm',
1223
1284
  ...unpackConfig.resolve?.extensions || []
1224
1285
  ]
1225
1286
  },
@@ -1236,12 +1297,12 @@ async function getBundlerConfig(originalUnpackConfig) {
1236
1297
  moduleIds: isDev() ? 'named' : 'deterministic',
1237
1298
  minimize: !!unpackConfig.build?.minify && utils_isProd(),
1238
1299
  minimizer: [
1239
- new JsMinifyPlugin(utils_mergeConfig({
1300
+ new JsMinifyPlugin(mergeConfig({
1240
1301
  compress: {
1241
1302
  target: unpackConfig.build.target
1242
1303
  }
1243
1304
  }, minifyOptions.oxc || {})),
1244
- new rspack.LightningCssMinimizerRspackPlugin(utils_mergeConfig({
1305
+ new rspack.LightningCssMinimizerRspackPlugin(mergeConfig({
1245
1306
  minimizerOptions: {
1246
1307
  targets: esVersionToBrowserslist(unpackConfig.build.target)
1247
1308
  }
@@ -1339,7 +1400,7 @@ async function getBundlerConfig(originalUnpackConfig) {
1339
1400
  type: 'css/module'
1340
1401
  }), getLessLoader = ()=>({
1341
1402
  loader: getCompiledPkgPath('less-loader'),
1342
- options: utils_mergeConfig({
1403
+ options: mergeConfig({
1343
1404
  lessOptions: {
1344
1405
  javascriptEnabled: !0
1345
1406
  },
@@ -1484,7 +1545,7 @@ async function getBundlerConfig(originalUnpackConfig) {
1484
1545
  getCssLoader(),
1485
1546
  {
1486
1547
  loader: getCompiledPkgPath('less-loader'),
1487
- options: utils_mergeConfig({
1548
+ options: mergeConfig({
1488
1549
  lessOptions: {
1489
1550
  javascriptEnabled: !0
1490
1551
  },
@@ -1537,7 +1598,7 @@ async function getBundlerConfig(originalUnpackConfig) {
1537
1598
  })), unpackConfig.performance?.buildAnalyze && utils_isProd() && (config = await applyBuildAnalyzeConfig({
1538
1599
  config,
1539
1600
  unpackConfig
1540
- })), unpackConfig.typeCheck && isDev() && isTs && (config = await applyTypeCheckConfig({
1601
+ })), unpackConfig.typeCheck && isDev() && isTS && (config = await applyTypeCheckConfig({
1541
1602
  config,
1542
1603
  unpackConfig
1543
1604
  })), unpackConfig.detectCircular && (config = function({ config, unpackConfig }) {
@@ -1577,11 +1638,11 @@ async function getBundlerConfig(originalUnpackConfig) {
1577
1638
  config = await impl(config, {
1578
1639
  ...originalUnpackConfig._context,
1579
1640
  unpackConfig,
1580
- mergeConfig: utils_mergeConfig
1641
+ mergeConfig: mergeConfig
1581
1642
  });
1582
1643
  }), unpackConfig.bundlerConfig && (config = isFunction(unpackConfig.bundlerConfig) ? await unpackConfig.bundlerConfig(config, {
1583
- mergeConfig: utils_mergeConfig
1584
- }) : utils_mergeConfig(config, unpackConfig.bundlerConfig)), config;
1644
+ mergeConfig: mergeConfig
1645
+ }) : mergeConfig(config, unpackConfig.bundlerConfig)), config;
1585
1646
  }
1586
1647
  async function unpackBuild(unpackConfig) {
1587
1648
  let compiler = rspack(await getBundlerConfig(unpackConfig)), handler = (err, stats)=>{
@@ -1702,7 +1763,7 @@ async function unpackDev(unpackConfig) {
1702
1763
  ...middlewares
1703
1764
  ]);
1704
1765
  let server = new RspackDevServer(devServerOptions, compiler);
1705
- await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v4.2.1`)} ${colors.dim('ready in')} ${colors.bold(Math.ceil(performance.now() - getUnpackStartTime()))} ${colors.dim('ms')}\n`), printServerUrls({
1766
+ await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v4.2.3`)} ${colors.dim('ready in')} ${colors.bold(Math.ceil(performance.now() - getUnpackStartTime()))} ${colors.dim('ms')}\n`), printServerUrls({
1706
1767
  port,
1707
1768
  host: unpackConfig.server.host,
1708
1769
  base: unpackConfig.base
@@ -1716,10 +1777,10 @@ async function unpackDev(unpackConfig) {
1716
1777
  function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'unpack' }) {
1717
1778
  let _context = {
1718
1779
  callerName,
1719
- version: "4.2.1",
1780
+ version: "4.2.3",
1720
1781
  cachePath: 'node_modules/.unpack'
1721
1782
  }, resolveConfig = (mode)=>{
1722
- let rootPath, outputPath, basePath, cachedTraceMap, fs, isValidMethodName, parseFrame, formatOriginalLocation, formatFullStack, resolveErrorLocationAndStack, shouldTransformDeepImport, preJsAssets, jsAssets, cssAssets, bundledDepsCachePath, deepImportPkgPattern, deepImportRegex, plugin, root, uno, configFilePath, configOrPathFromUnpackConfig, defaultsFromUnpackConfig, compilerRef, rootDir, unoConfig, tokens, unocssCacheDir, tokensCachePath, timeCachePath, layersCachePath, bundlerCacheDir, cachedTokensLength, cachedLayersLength, tasks, requestedLayers, layerImportRE, ensureReady, invalidate, flushTasks, getVirtualModuleContent, hash, restoreSkipCode, applyUnoTransformers, getResolvedLayers, optionsFromUnpackConfig, rootPath1, registerCode, namesCode, defaultConfig = {
1783
+ let rootPath, outputPath, basePath, cachedTraceMap, fs, isValidMethodName, parseFrame, formatOriginalLocation, formatFullStack, resolveErrorLocationAndStack, root, alias, shouldTransformDeepImport, preJsAssets, jsAssets, cssAssets, bundledDepsCachePath, deepImportPkgPattern, deepImportRegex, plugin, root1, uno, generated, configOrPathFromUnpackConfig, defaultsFromUnpackConfig, VIRTUAL_UNO_CSS_ID, rootDir, isMpa, unoConfig, configFilePath, unpackConfigPath, tokens, requestedLayers, tasks, unocssCacheDir, tokensCachePath, layersCachePath, timeCachePath, configHashCachePath, generatedCachePath, bundlerCacheDir, cachedTokensSize, cachedLayersSize, isCompiling, resolveUnocssConfig, flushTasks, getVirtualModuleContent, hash, restoreSkipCode, applyUnoTransformers, getCustomLayers, optionsFromUnpackConfig, rootPath1, registerCode, namesCode, defaultConfig = {
1723
1784
  root: cwd,
1724
1785
  base: '/',
1725
1786
  sourceMap: 'production' !== mode && 'cheap-module-source-map',
@@ -1863,7 +1924,7 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
1863
1924
  }, {
1864
1925
  name: 'unpack:browser-logs',
1865
1926
  apply: (config, { command })=>'dev' === command && config.dev?.browserLogs,
1866
- buildStart: async ({ isFirstCompile, compiler })=>{
1927
+ buildStart: ({ isFirstCompile, compiler })=>{
1867
1928
  isFirstCompile && (fs = compiler.outputFileSystem);
1868
1929
  },
1869
1930
  configResolved: (config)=>{
@@ -2022,8 +2083,11 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
2022
2083
  ...middlewares
2023
2084
  ]
2024
2085
  }),
2025
- {
2086
+ (root = '', alias = {}, {
2026
2087
  name: 'unpack:glob',
2088
+ configResolved: (config)=>{
2089
+ root = config.root, alias = config.resolve?.alias || {};
2090
+ },
2027
2091
  transform: {
2028
2092
  filter: {
2029
2093
  test: JS_REGEX
@@ -2042,10 +2106,10 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
2042
2106
  excludes
2043
2107
  });
2044
2108
  return includes1.length ? (({ includes, excludes, eager })=>{
2045
- let excludeMatchers = excludes.map((item)=>toRegexLiteral(item.regExpSource)).join(', '), includeItems = includes.map((item)=>{
2109
+ let excludeMatchers = excludes.map((item)=>toRegexLiteral(item.regExpSource)).join(', '), modeExpr = eager ? 'sync' : 'lazy', includeItems = includes.map((item)=>{
2046
2110
  let prefix = './' === item.publicPrefix ? '' : `${item.publicPrefix}/`, mapKeyExpr = './' === item.publicPrefix ? "key.startsWith('./') ? key : './' + key" : `${JSON.stringify(prefix)} + (key.startsWith('./') ? key.slice(2) : key)`;
2047
2111
  return `{
2048
- context: import.meta.webpackContext(${JSON.stringify(item.baseDir)}, { recursive: ${item.recursive}, regExp: ${toRegexLiteral(item.regExpSource)} }),
2112
+ context: import.meta.webpackContext(${JSON.stringify(item.baseDir)}, { recursive: ${item.recursive}, regExp: ${toRegexLiteral(item.regExpSource)}, mode: ${JSON.stringify(modeExpr)} }),
2049
2113
  mapKey: (key) => ${mapKeyExpr}
2050
2114
  }`;
2051
2115
  }).join(', '), excludeList = excludeMatchers ? `[${excludeMatchers}]` : '[]';
@@ -2059,27 +2123,36 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
2059
2123
  const path = mapKey(key)
2060
2124
  if (isExcluded(path)) continue
2061
2125
  if (!modules[path]) {
2062
- modules[path] = ${eager ? 'context(key)' : '() => Promise.resolve(context(key))'}
2126
+ modules[path] = ${eager ? 'context(key)' : '() => context(key)'}
2063
2127
  }
2064
2128
  }
2065
2129
  }
2066
2130
  return modules
2067
2131
  })()`;
2068
2132
  })({
2069
- includes: includes1.map(parseGlob),
2070
- excludes: excludes1.map(parseGlob),
2133
+ includes: includes1.map((p)=>normalizeGlobByAliases(p, {
2134
+ root,
2135
+ alias
2136
+ })).map(parseGlob),
2137
+ excludes: excludes1.map((p)=>normalizeGlobByAliases(p, {
2138
+ root,
2139
+ alias
2140
+ })).map(parseGlob),
2071
2141
  eager: hasEager(rawOptions)
2072
2142
  }) : '({})';
2073
2143
  }
2074
- let { baseDir, regExpSource, recursive, publicPrefix } = parseGlob(pattern);
2144
+ let { baseDir, regExpSource, recursive, publicPrefix } = parseGlob(normalizeGlobByAliases(pattern, {
2145
+ root,
2146
+ alias
2147
+ }));
2075
2148
  return (({ baseDir, regExpSource, recursive, eager, publicPrefix })=>{
2076
2149
  let prefix = './' === publicPrefix ? '' : `${publicPrefix}/`, mapKeyExpr = './' === publicPrefix ? "key.startsWith('./') ? key : './' + key" : `${JSON.stringify(prefix)} + (key.startsWith('./') ? key.slice(2) : key)`;
2077
2150
  return `(() => {
2078
- const context = import.meta.webpackContext(${JSON.stringify(baseDir)}, { recursive: ${recursive}, regExp: ${toRegexLiteral(regExpSource)} })
2151
+ const context = import.meta.webpackContext(${JSON.stringify(baseDir)}, { recursive: ${recursive}, regExp: ${toRegexLiteral(regExpSource)}, mode: ${JSON.stringify(eager ? 'sync' : 'lazy')} })
2079
2152
  const modules = {}
2080
2153
  for (const key of context.keys()) {
2081
2154
  const path = ${mapKeyExpr}
2082
- modules[path] = ${eager ? 'context(key)' : '() => Promise.resolve(context(key))'}
2155
+ modules[path] = ${eager ? 'context(key)' : '() => context(key)'}
2083
2156
  }
2084
2157
  return modules
2085
2158
  })()`;
@@ -2092,7 +2165,7 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
2092
2165
  });
2093
2166
  }) : null
2094
2167
  }
2095
- },
2168
+ }),
2096
2169
  (shouldTransformDeepImport = !1, preJsAssets = [], jsAssets = [], cssAssets = [], bundledDepsCachePath = '', deepImportPkgPattern = [
2097
2170
  ...SPECIAL_NO_ENTRY_DEPS
2098
2171
  ].sort((a, b)=>b.length - a.length).map((name)=>name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'), deepImportRegex = RegExp(`import\\s+([a-zA-Z0-9_$]+)\\s+from\\s+['"]((${deepImportPkgPattern})/[^'"]+)['"]`, 'g'), plugin = {
@@ -2370,11 +2443,11 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
2370
2443
  }), config;
2371
2444
  }
2372
2445
  }),
2373
- (root = '', {
2446
+ (root1 = '', {
2374
2447
  name: 'unpack:file-size',
2375
2448
  apply: (config, { mode })=>'production' === mode && config.performance?.printFileSize,
2376
2449
  configResolved (config) {
2377
- root = config.root;
2450
+ root1 = config.root;
2378
2451
  },
2379
2452
  buildEnd: async (options)=>{
2380
2453
  let { stats } = options;
@@ -2400,7 +2473,7 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
2400
2473
  color: 'cyan',
2401
2474
  chunks: []
2402
2475
  }
2403
- ], chunkGroupMap = chunkGroups.reduce((acc, cur)=>(acc[cur.type] = cur, acc), {}), distPath = stats.compilation.outputOptions.path, distFolder = node_path.relative(root, distPath), assets = Object.entries(stats.compilation.assets), longest = 0, totalSize = 0, totalCompressedSize = 0;
2476
+ ], chunkGroupMap = chunkGroups.reduce((acc, cur)=>(acc[cur.type] = cur, acc), {}), distPath = stats.compilation.outputOptions.path, distFolder = node_path.relative(root1, distPath), assets = Object.entries(stats.compilation.assets), longest = 0, totalSize = 0, totalCompressedSize = 0;
2404
2477
  logUpdate('computing gzip size...'), await Promise.all(assets.map(async ([assetName, value])=>{
2405
2478
  let content, compressedSize, filePath = assetName.split('?')[0];
2406
2479
  try {
@@ -2442,34 +2515,27 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
2442
2515
  log += colors.blue(displaySize(totalSize)), console.log(log += colors.dim(` │ gzip: ${displaySize(totalCompressedSize)}`));
2443
2516
  }
2444
2517
  }),
2445
- (rootDir = process.cwd(), unoConfig = {}, tokens = new Set(), unocssCacheDir = '', tokensCachePath = '', timeCachePath = '', layersCachePath = '', bundlerCacheDir = '', cachedTokensLength = 0, cachedLayersLength = 0, tasks = [], requestedLayers = new Set([
2518
+ (VIRTUAL_UNO_CSS_ID = 'uno.css', rootDir = process.cwd(), isMpa = !1, unoConfig = {}, configFilePath = '', unpackConfigPath = '', tokens = new Set(), requestedLayers = new Set([
2446
2519
  LAYER_MARK_ALL
2447
- ]), layerImportRE = /(['"])uno:([^'"]+?)\.css\1/g, ensureReady = async ()=>{
2448
- var root, configOrPath;
2449
- let core = await import("@unocss/core"), resolvedConfigOrPath = (root = rootDir, 'string' != typeof (configOrPath = (void 0) ?? configOrPathFromUnpackConfig) || node_path.isAbsolute(configOrPath) ? configOrPath : node_path.resolve(root, configOrPath)), resolvedDefaults = (void 0) ?? defaultsFromUnpackConfig, configFromOption = {};
2450
- if (isPlainObject(resolvedConfigOrPath) ? configFromOption = resolvedConfigOrPath : isString(resolvedConfigOrPath) && (configFilePath = resolvedConfigOrPath), configFilePath || (configFilePath = ((root, customConfig)=>{
2520
+ ]), tasks = [], unocssCacheDir = '', tokensCachePath = '', layersCachePath = '', timeCachePath = '', configHashCachePath = '', generatedCachePath = '', bundlerCacheDir = '', cachedTokensSize = 0, cachedLayersSize = 0, isCompiling = !0, resolveUnocssConfig = async ()=>{
2521
+ let resolvedConfigOrPath = (void 0) ?? configOrPathFromUnpackConfig, resolvedDefaults = (void 0) ?? defaultsFromUnpackConfig, configFromOption = {};
2522
+ return isPlainObject(resolvedConfigOrPath) ? configFromOption = resolvedConfigOrPath : isString(resolvedConfigOrPath) && (configFilePath = node_path.isAbsolute(resolvedConfigOrPath) ? resolvedConfigOrPath : node_path.resolve(rootDir, resolvedConfigOrPath)), configFilePath = ((root, customConfig)=>{
2523
+ if (customConfig) {
2524
+ let absPath = node_path.isAbsolute(customConfig) ? customConfig : node_path.resolve(root, customConfig);
2525
+ if (node_fs.existsSync(absPath)) return absPath;
2526
+ }
2451
2527
  for (let file of UNOCSS_CONFIG_FILES){
2452
2528
  let configFile = node_path.join(root, file);
2453
2529
  if (node_fs.existsSync(configFile)) return configFile;
2454
2530
  }
2455
- })(rootDir)), configFilePath && node_fs.existsSync(configFilePath) && (configFromOption = utils_mergeConfig(configFromOption, await loadConfigFile(configFilePath))), resolvedDefaults && (configFromOption = utils_mergeConfig(resolvedDefaults, configFromOption)), unoConfig = configFromOption, uno = await core.createGenerator(unoConfig), tokens = new Set(), node_fs.existsSync(tokensCachePath)) {
2456
- let cached = JSON.parse(node_fs.readFileSync(tokensCachePath, 'utf-8'));
2457
- Array.isArray(cached) && (cachedTokensLength = (tokens = new Set(cached)).size, logger_logger.debug(colors.yellow(`[unocss] Load ${tokens.size} token from cache.`)));
2458
- }
2459
- if (node_fs.existsSync(layersCachePath)) {
2460
- let cached = JSON.parse(node_fs.readFileSync(layersCachePath, 'utf-8'));
2461
- Array.isArray(cached) && (cachedLayersLength = (requestedLayers = new Set(cached)).size, logger_logger.debug(colors.yellow(`[unocss] Load ${requestedLayers.size} layer from cache.`)));
2462
- }
2463
- }, invalidate = ()=>{
2464
- setTimeout(()=>{
2465
- compilerRef.watching.invalidate(), logger_logger.debug(colors.yellow('[unocss] Invalidation triggered.'));
2466
- }, 0);
2531
+ })(rootDir, configFilePath), configFromOption = mergeConfig(configFromOption, await loadConfigFile(configFilePath)), resolvedDefaults && (configFromOption = mergeConfig(resolvedDefaults, configFromOption)), configFromOption;
2467
2532
  }, flushTasks = async ()=>{
2468
2533
  if (!tasks.length) return;
2534
+ logger_logger.debug(colors.yellow(`[unocss] Extract token from ${tasks.length} files.`));
2469
2535
  let pending = tasks.map((t)=>t());
2470
2536
  tasks = [], await Promise.all(pending);
2471
2537
  }, getVirtualModuleContent = (layer)=>{
2472
- let code, layersKey = Array.from(requestedLayers).sort().join(','), hash = (code = `${tokens.size}|${layer}|${layersKey}`, createHash('sha256').update(code).digest('hex').slice(0, 8));
2538
+ let code, hash = (code = `${tokens.size}|${layer}|${requestedLayers.size}`, createHash('sha256').update(code).digest('hex').slice(0, 8));
2473
2539
  return `#--unocss-hash--{content:"${hash}"}#--unocss--{layer:${layer};escape-view:\\"\\'\\\`\\\\}`;
2474
2540
  }, hash = (str)=>{
2475
2541
  let i, l, hVal = 0x811c9dc5;
@@ -2494,50 +2560,74 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
2494
2560
  for (let t of transformers)(!t.idFilter || t.idFilter(id)) && (await t.transform(s, id, {
2495
2561
  uno,
2496
2562
  tokens,
2497
- invalidate
2563
+ invalidate: ()=>{}
2498
2564
  }), s.hasChanged() && (s = new magic_string(code = restoreSkipCode(s.toString(), skipMap))));
2499
2565
  return code !== original ? code : null;
2500
- }, getResolvedLayers = ()=>Array.from(requestedLayers).filter((layer)=>layer !== LAYER_MARK_ALL), {
2566
+ }, getCustomLayers = ()=>Array.from(requestedLayers).filter((layer)=>layer !== LAYER_MARK_ALL), {
2501
2567
  name: 'unpack:unocss',
2502
- apply: (config)=>!!config.unocss,
2568
+ apply: (config)=>!!config.css?.unocss,
2503
2569
  configResolved: async (config, { cachePath })=>{
2504
- if (rootDir = config.root, unocssCacheDir = node_path.resolve(rootDir, cachePath, 'unocss'), tokensCachePath = node_path.resolve(unocssCacheDir, 'tokens'), timeCachePath = node_path.resolve(unocssCacheDir, 'created_at'), layersCachePath = node_path.resolve(unocssCacheDir, 'layers'), bundlerCacheDir = node_path.resolve(rootDir, cachePath, 'cache'), ensureDir(unocssCacheDir), (()=>{
2505
- let now = Date.now(), last = 0;
2506
- if (!node_fs.existsSync(timeCachePath)) {
2507
- node_fs.writeFileSync(timeCachePath, String(now), 'utf-8'), emptyDir(bundlerCacheDir);
2508
- return;
2509
- }
2510
- let parsed = Number(node_fs.readFileSync(timeCachePath, 'utf-8').trim());
2511
- Number.isNaN(parsed) || (last = parsed), now - last < 604800000 || (emptyDir(unocssCacheDir), emptyDir(bundlerCacheDir), node_fs.writeFileSync(timeCachePath, String(now), 'utf-8'));
2512
- })(), Array.isArray(config.unocss)) {
2513
- let [configOrPathValue, defaultsValue] = config.unocss;
2570
+ if (rootDir = config.root, isMpa = !!config.mpa, unpackConfigPath = resolveConfigPath(rootDir), bundlerCacheDir = node_path.resolve(rootDir, cachePath, 'cache'), unocssCacheDir = node_path.resolve(rootDir, cachePath, 'unocss'), tokensCachePath = node_path.resolve(unocssCacheDir, 'tokens'), layersCachePath = node_path.resolve(unocssCacheDir, 'layers'), timeCachePath = node_path.resolve(unocssCacheDir, 'created_at'), configHashCachePath = node_path.resolve(unocssCacheDir, 'config_hash'), generatedCachePath = node_path.resolve(unocssCacheDir, 'generated'), Array.isArray(config.css?.unocss)) {
2571
+ let [configOrPathValue, defaultsValue] = config.css.unocss;
2514
2572
  configOrPathFromUnpackConfig = configOrPathValue, defaultsFromUnpackConfig = defaultsValue;
2515
2573
  }
2516
- await ensureReady();
2517
- },
2518
- bundlerConfig: (config, { mergeConfig, unpackConfig })=>mergeConfig(config, {
2519
- experiments: {
2520
- cache: {
2521
- type: unpackConfig.performance?.cache ? 'persistent' : 'memory',
2522
- buildDependencies: configFilePath ? [
2523
- configFilePath
2524
- ] : void 0
2574
+ unoConfig = await resolveUnocssConfig();
2575
+ let core = await import("@unocss/core");
2576
+ uno = await core.createGenerator(unoConfig), (()=>{
2577
+ let now = Date.now(), nextHash = getFilesContentHash([
2578
+ configFilePath,
2579
+ unpackConfigPath
2580
+ ]);
2581
+ if (!node_fs.existsSync(unocssCacheDir)) {
2582
+ ensureDir(unocssCacheDir), node_fs.writeFileSync(timeCachePath, String(now), 'utf-8'), node_fs.writeFileSync(configHashCachePath, nextHash, 'utf-8'), removeDir(bundlerCacheDir);
2583
+ return;
2584
+ }
2585
+ let cachedTime = Number(node_fs.readFileSync(timeCachePath, 'utf-8').trim()), cachedHash = node_fs.readFileSync(configHashCachePath, 'utf-8').trim(), isExpired = now - cachedTime >= 604800000, isHashChanged = cachedHash !== nextHash;
2586
+ (isExpired || isHashChanged) && (isExpired && logger_logger.debug(colors.yellow('[unocss] Cache expired.')), isHashChanged && logger_logger.debug(colors.yellow('[unocss] Cache invalidated because config has changed.')), removeDir(unocssCacheDir), removeDir(bundlerCacheDir), ensureDir(unocssCacheDir), node_fs.writeFileSync(timeCachePath, String(now), 'utf-8'), node_fs.writeFileSync(configHashCachePath, nextHash, 'utf-8'));
2587
+ })(), (()=>{
2588
+ if (node_fs.existsSync(tokensCachePath)) {
2589
+ let cached = JSON.parse(node_fs.readFileSync(tokensCachePath, 'utf-8'));
2590
+ Array.isArray(cached) && (cachedTokensSize = (tokens = new Set(cached)).size, logger_logger.debug(colors.yellow(`[unocss] Load ${tokens.size} token from cache.`)));
2591
+ }
2592
+ if (node_fs.existsSync(layersCachePath)) {
2593
+ let cached = JSON.parse(node_fs.readFileSync(layersCachePath, 'utf-8'));
2594
+ Array.isArray(cached) && (cachedLayersSize = (requestedLayers = new Set(cached)).size, logger_logger.debug(colors.yellow(`[unocss] Load ${requestedLayers.size} layer from cache.`)));
2595
+ }
2596
+ if (node_fs.existsSync(generatedCachePath)) {
2597
+ let cached = JSON.parse(node_fs.readFileSync(generatedCachePath, 'utf-8'));
2598
+ if (cached && cached.meta?.tokensSize === tokens.size && cached.meta?.layersSize === requestedLayers.size) {
2599
+ let list, index, runChunk, timer;
2600
+ generated = cached, isDev() && (list = Array.from(tokens), index = 0, timer = setTimeout(runChunk = ()=>{
2601
+ if (isCompiling) {
2602
+ let timer = setTimeout(runChunk, 100);
2603
+ timer.unref?.();
2604
+ return;
2605
+ }
2606
+ let end = Math.min(index + 200, list.length);
2607
+ for(; index < end; index++)uno.parseToken(list[index]);
2608
+ if (logger_logger.debug(colors.yellow(`[unocss] Warmup tokens ${index}/${list.length}.`)), index < list.length) {
2609
+ let timer = setTimeout(runChunk, 0);
2610
+ timer.unref?.();
2611
+ }
2612
+ }, 0), timer.unref?.()), logger_logger.debug(colors.yellow('[unocss] Load generated css from cache.'));
2525
2613
  }
2526
2614
  }
2527
- }),
2528
- buildStart ({ compiler }) {
2529
- compilerRef = compiler;
2615
+ })();
2616
+ },
2617
+ buildStart () {
2618
+ isCompiling = !0;
2530
2619
  },
2531
2620
  buildEnd () {
2532
- tokens.size !== cachedTokensLength && (node_fs.writeFileSync(tokensCachePath, JSON.stringify(Array.from(tokens)), 'utf-8'), logger_logger.debug(colors.yellow(`[unocss] Add ${tokens.size - cachedTokensLength} token to cache.`)), cachedTokensLength = tokens.size), requestedLayers.size !== cachedLayersLength && (node_fs.writeFileSync(layersCachePath, JSON.stringify(Array.from(requestedLayers)), 'utf-8'), logger_logger.debug(colors.yellow(`[unocss] Add ${requestedLayers.size - cachedLayersLength} layer to cache.`)), cachedLayersLength = requestedLayers.size);
2621
+ isCompiling = !1, tokens.size !== cachedTokensSize && (node_fs.writeFileSync(tokensCachePath, JSON.stringify(Array.from(tokens)), 'utf-8'), logger_logger.debug(colors.yellow(`[unocss] Add ${tokens.size - cachedTokensSize} token to cache.`)), cachedTokensSize = tokens.size), requestedLayers.size !== cachedLayersSize && (node_fs.writeFileSync(layersCachePath, JSON.stringify(Array.from(requestedLayers)), 'utf-8'), logger_logger.debug(colors.yellow(`[unocss] Add ${requestedLayers.size - cachedLayersSize} layer to cache.`)), cachedLayersSize = requestedLayers.size);
2533
2622
  },
2534
2623
  transform: {
2535
2624
  filter: {
2536
- test: /\.(vue|svelte|[jt]sx?|vine\.ts|mdx?|astro|elm|php|phtml|marko)($|\?)/
2625
+ test: /\.(vue|svelte|[jt]sx?|vine\.ts|mdx?|astro|elm|php|phtml|marko|css|scss|sass|less)($|\?)/
2537
2626
  },
2538
2627
  handler: async (code, id)=>{
2539
2628
  var task;
2540
- if (code.includes('uno:')) for (let match of code.matchAll(layerImportRE)){
2629
+ if (id.endsWith(VIRTUAL_UNO_CSS_ID) || /uno:[^?]+\.css(?:\?|$)/.test(id)) return null;
2630
+ if (code.includes('uno:')) for (let match of code.matchAll(LAYER_IMPORT_RE)){
2541
2631
  let layer = match[2];
2542
2632
  layer && requestedLayers.add(layer);
2543
2633
  }
@@ -2555,26 +2645,35 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
2555
2645
  processAssets: {
2556
2646
  stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
2557
2647
  handler: async ({ compilation, sources })=>{
2558
- await flushTasks();
2559
- let resolvedLayers = getResolvedLayers(), result = await uno.generate(tokens, {
2560
- minify: !0
2561
- });
2648
+ if (await flushTasks(), !generated || generated.meta.tokensSize !== tokens.size || generated.meta.layersSize !== requestedLayers.size) {
2649
+ let result = await uno.generate(tokens, {
2650
+ minify: !0
2651
+ }), customLayers = getCustomLayers();
2652
+ generated = {
2653
+ meta: {
2654
+ tokensSize: tokens.size,
2655
+ layersSize: requestedLayers.size
2656
+ },
2657
+ allCSS: result.getLayers(void 0, customLayers),
2658
+ layerCSS: customLayers.reduce((acc, layer)=>(acc[layer] = result.getLayer(layer) || '', acc), {})
2659
+ }, node_fs.writeFileSync(generatedCachePath, JSON.stringify(generated), 'utf-8');
2660
+ }
2562
2661
  for (let file of Object.keys(compilation.assets)){
2563
- if ('*' === file || file.includes('vendor')) continue;
2662
+ if (!isMpa && !file.includes('main')) continue;
2564
2663
  let code = compilation.assets[file].source().toString();
2565
2664
  if (!code.includes('#--unocss')) continue;
2566
2665
  let isJsAsset = /\.(?:[cm]?js|[cm]?jsx)$/.test(file), replaced = !1;
2567
2666
  code = (code = code.replace(HASH_PLACEHOLDER_RE, '')).replace(LAYER_PLACEHOLDER_RE, (_, layer, escapeView)=>{
2568
2667
  replaced = !0;
2569
- let css = layer.trim() === LAYER_MARK_ALL ? result.getLayers(void 0, resolvedLayers) : result.getLayer(layer) || '';
2668
+ let css = layer.trim() === LAYER_MARK_ALL ? generated.allCSS : generated.layerCSS[layer] || '';
2570
2669
  return isJsAsset ? getCssEscaperForJsContent(escapeView)(css) : css;
2571
2670
  }), replaced && compilation.updateAsset(file, new sources.RawSource(code));
2572
2671
  }
2573
2672
  }
2574
2673
  },
2575
2674
  virtualModules: ()=>({
2576
- 'uno.css': getVirtualModuleContent(LAYER_MARK_ALL),
2577
- ...getResolvedLayers().reduce((acc, layer)=>(acc[`uno:${layer}.css`] = getVirtualModuleContent(layer), acc), {})
2675
+ [VIRTUAL_UNO_CSS_ID]: getVirtualModuleContent(LAYER_MARK_ALL),
2676
+ ...getCustomLayers().reduce((acc, layer)=>(acc[`uno:${layer}.css`] = getVirtualModuleContent(layer), acc), {})
2578
2677
  })
2579
2678
  }),
2580
2679
  (rootPath1 = '', registerCode = '', namesCode = '', {
@@ -2610,7 +2709,7 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
2610
2709
  ]
2611
2710
  };
2612
2711
  return {
2613
- ...utils_mergeConfig(defaultConfig, userConfig),
2712
+ ...mergeConfig(defaultConfig, userConfig),
2614
2713
  _context
2615
2714
  };
2616
2715
  };
@@ -2619,7 +2718,7 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
2619
2718
  let mode = watch ? 'development' : 'production';
2620
2719
  setNodeEnv(mode);
2621
2720
  let config = resolveConfig(mode);
2622
- console.log(colors.brand(`${callerName} v4.2.1`), colors.cyan(`building for ${mode}...`)), await unpackBuild(config);
2721
+ console.log(colors.brand(`${callerName} v4.2.3`), colors.cyan(`building for ${mode}...`)), await unpackBuild(config);
2623
2722
  },
2624
2723
  dev: async ()=>{
2625
2724
  setUnpackStartTime(performance.now());
@@ -2768,7 +2867,7 @@ function runCLI() {
2768
2867
  logger_logger.clear(), logger_logger.info(`${node_path.basename(file)} changed, restarting server...`), await watcher.close(), await cleanUpBeforeRestart(), startServer(options);
2769
2868
  });
2770
2869
  });
2771
- devCommand.option('-o, --open [url]', 'Open browser on startup').option('--port <port>', 'Specify port').option('--host', 'Expose hostname').action(startServer), cli.help(), cli.version("4.2.1"), cli.parse();
2870
+ devCommand.option('-o, --open [url]', 'Open browser on startup').option('--port <port>', 'Specify port').option('--host', 'Expose hostname').action(startServer), cli.help(), cli.version("4.2.3"), cli.parse();
2772
2871
  }
2773
2872
  var src_CSS_MODULES_NAMED_EXPORT = !1;
2774
- export { ALL_INTERFACES_IPV4, CSS_MODULES_EXPORTS_CONVENTION, CSS_MODULES_LOCAL_IDENT_NAME, DEV_DEFAULT_FILENAME, JSX_REGEX, JS_REGEX, LOCALHOST, NODE_MODULES_REGEX, PROD_DEFAULT_FILENAME, SCRIPT_REGEX, TEMPLATE_CONTENT, addRestartCleaner, cleanUpBeforeRestart, clearLine, colors, convertBasicAnsiColors, createChokidar, createUnpack, debounce, defineConfig, emptyDir, ensureDir, esVersionToBrowserslist, external_tinyglobby_glob as glob, findExists, getAddressUrls, getCompiledPkgPath, getCurrentUnpackConfig, getHtmlTemplateOrContent, getIpv4Interfaces, getNodeEnv, getOrSetDefault, getPathInJs, getPort, getTime, getUnpackStartTime, getUserDepPath, getUserDepVersion, globSync, injectToHead, isBoolean, isDebug, isDev, isEmptyDir, isFileExists, isFileSync, isFunction, isNodeVersionAtLeast, isObject, isPlainObject, isRegExp, isString, isUndefined, isWin, launchEditor, loadConfig, loadConfigFile, logUpdate, logger_LogColor as LogColor, logger_logger as logger, normalizePublicPath, openBrowser, pLimit, pathExists, pathToExportIdentifier, prettyTime, printServerUrls, removeDir, resolveConfigPath, rspack, runCLI, set, setCurrentUnpackConfig, setDevServer, setNodeEnv, setUnpackStartTime, src_CSS_MODULES_NAMED_EXPORT as CSS_MODULES_NAMED_EXPORT, trackPerformance, utils_isDevServer as isDevServer, utils_isProd as isProd, utils_mergeConfig as mergeConfig };
2873
+ export { ALL_INTERFACES_IPV4, CSS_MODULES_EXPORTS_CONVENTION, CSS_MODULES_LOCAL_IDENT_NAME, DEV_DEFAULT_FILENAME, JSX_REGEX, JS_REGEX, LOCALHOST, NODE_MODULES_REGEX, PROD_DEFAULT_FILENAME, SCRIPT_REGEX, TEMPLATE_CONTENT, addRestartCleaner, cleanUpBeforeRestart, clearLine, colors, convertBasicAnsiColors, createChokidar, createUnpack, debounce, defineConfig, emptyDir, ensureDir, esVersionToBrowserslist, external_tinyglobby_glob as glob, findExists, getAddressUrls, getCompiledPkgPath, getCurrentUnpackConfig, getFilesContentHash, getHtmlTemplateOrContent, getIpv4Interfaces, getNodeEnv, getOrSetDefault, getPathInJs, getPort, getTime, getUnpackStartTime, getUserDepPath, getUserDepVersion, globSync, injectToHead, isBoolean, isDebug, isDev, isEmptyDir, isFileExists, isFileSync, isFunction, isNodeVersionAtLeast, isObject, isPlainObject, isRegExp, isString, isUndefined, isWin, launchEditor, loadConfig, loadConfigFile, logUpdate, logger_LogColor as LogColor, logger_logger as logger, mergeConfig, normalizePublicPath, openBrowser, pLimit, pathExists, pathToExportIdentifier, prettyTime, printServerUrls, removeDir, resolveConfigPath, rspack, runCLI, set, setCurrentUnpackConfig, setDevServer, setNodeEnv, setUnpackStartTime, src_CSS_MODULES_NAMED_EXPORT as CSS_MODULES_NAMED_EXPORT, trackPerformance, utils_isDevServer as isDevServer, utils_isProd as isProd };