@unpackjs/core 4.0.0 → 4.1.0

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
@@ -7,16 +7,16 @@ import * as __rspack_external__compiled_launch_editor_index_js_29002383 from "..
7
7
  import * as __rspack_external__compiled_webpack_merge_index_js_efd91626 from "../compiled/webpack-merge/index.js";
8
8
  import { __webpack_require__ } from "./rslib-runtime.js";
9
9
  import { rspack } from "@rspack/core";
10
- import node_fs from "node:fs";
11
10
  import cac from "cac";
11
+ import node_fs from "node:fs";
12
12
  import node_readline from "node:readline";
13
13
  import node_os, { platform } from "node:os";
14
14
  import portfinder from "portfinder";
15
+ import { glob as external_tinyglobby_glob, globSync } from "tinyglobby";
15
16
  import { format, promisify } from "node:util";
16
17
  import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
17
18
  import { parse } from "stacktrace-parser";
18
19
  import node_zlib from "node:zlib";
19
- import { glob, globSync } from "tinyglobby";
20
20
  import { expand } from "dotenv-expand";
21
21
  import node_assert from "node:assert";
22
22
  import { RspackDevServer } from "@rspack/dev-server";
@@ -120,7 +120,7 @@ let CSS_MODULES_LOCAL_IDENT_NAME = '[path][name]__[local]--[hash:5]', CSS_MODULE
120
120
  </body>
121
121
  </html>`, JS_REGEX = /\.[jt]s$/, JSX_REGEX = /\.[jt]sx$/, SCRIPT_REGEX = /\.[jt]sx?$/;
122
122
  var utils_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
123
- let { merge: mergeConfig } = __webpack_require__("compiled/webpack-merge"), { default: launchEditor } = __webpack_require__("compiled/launch-editor"), getNodeEnv = ()=>process.env.NODE_ENV, setNodeEnv = (env)=>{
123
+ let { merge: utils_mergeConfig } = __webpack_require__("compiled/webpack-merge"), { default: launchEditor } = __webpack_require__("compiled/launch-editor"), getNodeEnv = ()=>process.env.NODE_ENV, setNodeEnv = (env)=>{
124
124
  process.env.NODE_ENV = env;
125
125
  }, setDevServer = (isDevServer)=>{
126
126
  process.env.DEV_SERVER = isDevServer ? 'true' : 'false';
@@ -481,26 +481,73 @@ let removeDir = (dir)=>{
481
481
  '.less',
482
482
  '.scss',
483
483
  '.sass'
484
- ], BROWSER_LOGS_ENDPOINT = '/__browser_logs__', browserLogs_SCRIPT_REGEX = /\.(js|jsx|mjs|cjs|ts|tsx|mts|cts|vue|svelte)$/, gzip = promisify(node_zlib.gzip), numberFormatter = new Intl.NumberFormat('en', {
484
+ ], BROWSER_LOGS_ENDPOINT = '/__browser_logs__', SOURCE_REGEX = /\.(js|jsx|mjs|cjs|ts|tsx|mts|cts|vue|svelte)$/, gzip = promisify(node_zlib.gzip), numberFormatter = new Intl.NumberFormat('en', {
485
485
  maximumFractionDigits: 2,
486
486
  minimumFractionDigits: 2
487
487
  }), displaySize = (bytes)=>`${numberFormatter.format(bytes / 1000)} kB`;
488
488
  async function getCompressedSize(content) {
489
489
  return (await gzip(content)).length;
490
490
  }
491
- let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i, SPECIAL_NO_ENTRY_DEPS = [
491
+ let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i, GLOB_MAGIC_RE = /[*?[\]{}()!@+|]/, normalizeBaseDir = (raw)=>{
492
+ let normalized = raw.replace(/\\/g, '/');
493
+ 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) : './';
494
+ }, toRegexLiteral = (source)=>`/${source.replace(/\\?\//g, (value)=>'/' === value ? '\\/' : value)}/`, parseGlob = (pattern)=>{
495
+ 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);
496
+ return {
497
+ baseDir,
498
+ regExpSource: ((glob)=>{
499
+ let expansions;
500
+ if (!glob) return '^\\.\\/.*$';
501
+ let { replaced, expansions: expansions1 } = (expansions = [], {
502
+ replaced: glob.replace(/\{([^}]+)\}/g, (_, inner)=>(expansions.push(inner), `__BRACE_${expansions.length - 1}__`)),
503
+ expansions
504
+ }), source = replaced.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
505
+ return source = (source = (source = (source = (source = (source = source.replace(/__BRACE_(\d+)__/g, (_, index)=>{
506
+ let parts = (expansions1[Number(index)] || '').split(',').map((part)=>part.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
507
+ return `(${parts.join('|')})`;
508
+ })).replace(/\\\(([^)]+)\\\)\\\?/g, (_, inner)=>`(?:${inner})?`)).replace(/\\\*\\\*\\\//g, '(?:.*\\/)?')).replace(/\\\*\\\*/g, '.*')).replace(/\\\*/g, '[^/]*')).replace(/\\\?/g, '[^/]'), `^(?:\\.\\/)?${source}$`;
509
+ })(globPart),
510
+ recursive,
511
+ publicPrefix: './' === baseDir ? './' : baseDir
512
+ };
513
+ }, hasEager = (rawOptions)=>!!rawOptions && /eager\s*:\s*true/.test(rawOptions), SPECIAL_NO_ENTRY_DEPS = [
492
514
  '@iconify-icons/material-symbols'
515
+ ], FRAMEWORKS = [
516
+ 'react',
517
+ 'react-dom',
518
+ 'react-router-dom',
519
+ 'vue',
520
+ 'vue-router'
493
521
  ], getExternalLibraryName = (pkgName)=>{
494
522
  let externalAlias = {
495
- react: 'React',
496
523
  'react-dom': 'ReactDOM',
497
524
  'react-router-dom': 'ReactRouterDOM'
498
525
  };
499
526
  return externalAlias[pkgName] ? externalAlias[pkgName] : pkgName.replace(/^@/, '').split(/[/\-.]/).filter(Boolean).map((part)=>part.charAt(0).toUpperCase() + part.slice(1)).join('');
500
- }, getExternalValue = (pkgName)=>`window ${getExternalLibraryName(pkgName)}`, DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
527
+ }, getExternalValue = (pkgName)=>`window ${getExternalLibraryName(pkgName)}`, REGISTER_ID = 'virtual-svg-icons-register', NAMES_ID = 'virtual-svg-icons-names', normalizeSvg = (content)=>content.replace(/<\?xml[\s\S]*?\?>/gi, '').replace(/<!DOCTYPE[\s\S]*?>/gi, '').replace(/<!--[\s\S]*?-->/g, '').trim(), extractSvgContent = (content)=>{
528
+ let match = content.match(/<svg\b([^>]*)>/i), viewBoxMatch = match?.[1]?.match(/viewBox\s*=\s*["']([^"']+)["']/i);
529
+ return {
530
+ inner: content.replace(/^[\s\S]*?<svg\b[^>]*>/i, '').replace(/<\/svg>[\s\S]*$/i, '').trim(),
531
+ viewBox: viewBoxMatch?.[1]
532
+ };
533
+ }, readSvgFiles = (dir, collected = [])=>{
534
+ if (!node_fs.existsSync(dir)) return collected;
535
+ for (let entry of node_fs.readdirSync(dir, {
536
+ withFileTypes: !0
537
+ })){
538
+ let fullPath = node_path.join(dir, entry.name);
539
+ entry.isDirectory() ? readSvgFiles(fullPath, collected) : entry.isFile() && entry.name.toLowerCase().endsWith('.svg') && collected.push(fullPath);
540
+ }
541
+ return collected;
542
+ }, toSymbolId = (filePath, iconDir, symbolId)=>{
543
+ let relative = node_path.relative(iconDir, filePath), parsed = node_path.parse(relative), dir = parsed.dir.split(node_path.sep).filter(Boolean).join('-'), name = parsed.name;
544
+ if ('function' == typeof symbolId) return symbolId(name, filePath);
545
+ let id = (symbolId || 'icon-[dir]-[name]').replace(/\[name\]/g, name).replace(/\[dir\]/g, dir);
546
+ return id.replace(/--+/g, '-').replace(/^-+|-+$/g, '');
547
+ }, DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
501
548
  function getNormalizedPluginsByHook(hook) {
502
549
  let pluginMap = new Map();
503
- return getCurrentUnpackConfig().plugins?.forEach((plugin)=>{
550
+ return (getCurrentUnpackConfig().plugins?.flat(1 / 0) || []).forEach((plugin)=>{
504
551
  plugin && ((plugin, hook)=>{
505
552
  if (!plugin[hook]) return !1;
506
553
  let apply = plugin.apply;
@@ -561,7 +608,7 @@ async function applyCacheConfig({ config, unpackConfig, envFilePaths }) {
561
608
  let cacheConfig = isPlainObject(unpackConfig.performance.cache) ? unpackConfig.performance.cache : {}, buildDependencies = await getBuildDependencies(unpackConfig.root);
562
609
  buildDependencies.userBuildDependencies = cacheConfig.buildDependencies || [], buildDependencies.envFilePaths = envFilePaths;
563
610
  let cacheDirectory = node_path.resolve(unpackConfig.root, cacheConfig.cacheDirectory || `${unpackConfig._context.cachePath}/cache`, utils_isDevServer() ? 'dev' : 'build');
564
- return mergeConfig(config, {
611
+ return utils_mergeConfig(config, {
565
612
  cache: !0,
566
613
  experiments: {
567
614
  cache: {
@@ -661,7 +708,7 @@ let MODULE_PATH_REGEX = /.*[\\/]node_modules[\\/](?!\.pnpm[\\/])(?:(@[^\\/]+)[\\
661
708
  };
662
709
  async function getEntry(root, customEntry) {
663
710
  let entry;
664
- if (entry = customEntry ? node_path.resolve(root, customEntry) : (await glob('(index|Index).{js,ts,jsx,tsx}', {
711
+ if (entry = customEntry ? node_path.resolve(root, customEntry) : (await external_tinyglobby_glob('(index|Index).{js,ts,jsx,tsx}', {
665
712
  cwd: node_path.join(root, 'src'),
666
713
  absolute: !0
667
714
  }))[0], !node_fs.existsSync(entry)) throw Error('could not find entry file');
@@ -691,6 +738,7 @@ async function applyHtmlConfig({ config, unpackConfig }) {
691
738
  ]
692
739
  })), config;
693
740
  }
741
+ var nativeCss_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
694
742
  let { RawSource: RawSource, SourceMapSource: SourceMapSource } = rspack.sources, isJsFile = /\.[cm]?js(\?.*)?$/i, jsMinify_PLUGIN_NAME = 'JsMinifyPlugin';
695
743
  class JsMinifyPlugin {
696
744
  minifyOptions;
@@ -702,7 +750,7 @@ class JsMinifyPlugin {
702
750
  apply(compiler) {
703
751
  let meta = JSON.stringify({
704
752
  name: jsMinify_PLUGIN_NAME,
705
- version: "4.0.0",
753
+ version: "4.1.0",
706
754
  options: this.minifyOptions
707
755
  });
708
756
  compiler.hooks.compilation.tap(jsMinify_PLUGIN_NAME, (compilation)=>{
@@ -907,7 +955,7 @@ async function getBundlerConfig(originalUnpackConfig) {
907
955
  await applyPluginsByHook('config', async (impl)=>{
908
956
  rest = await impl(rest, {
909
957
  ...originalUnpackConfig._context,
910
- mergeConfig: mergeConfig
958
+ mergeConfig: utils_mergeConfig
911
959
  });
912
960
  });
913
961
  let unpackConfig = {
@@ -1074,12 +1122,12 @@ async function getBundlerConfig(originalUnpackConfig) {
1074
1122
  moduleIds: isDev() ? 'named' : 'deterministic',
1075
1123
  minimize: !!unpackConfig.build?.minify && utils_isProd(),
1076
1124
  minimizer: [
1077
- new JsMinifyPlugin(mergeConfig({
1125
+ new JsMinifyPlugin(utils_mergeConfig({
1078
1126
  compress: {
1079
1127
  target: unpackConfig.build.target
1080
1128
  }
1081
1129
  }, minifyOptions.oxc || {})),
1082
- new rspack.LightningCssMinimizerRspackPlugin(mergeConfig({
1130
+ new rspack.LightningCssMinimizerRspackPlugin(utils_mergeConfig({
1083
1131
  minimizerOptions: {
1084
1132
  targets: esVersionToBrowserslist(unpackConfig.build.target)
1085
1133
  }
@@ -1139,7 +1187,7 @@ async function getBundlerConfig(originalUnpackConfig) {
1139
1187
  }
1140
1188
  return config;
1141
1189
  })({
1142
- config: config = unpackConfig.experiments?.css ? function({ config, unpackConfig }) {
1190
+ config: config = unpackConfig.css?.native ? function({ config, unpackConfig }) {
1143
1191
  config.output.cssFilename = getOutputFilename({
1144
1192
  type: 'css',
1145
1193
  hash: unpackConfig.build?.filenameHash
@@ -1168,28 +1216,33 @@ async function getBundlerConfig(originalUnpackConfig) {
1168
1216
  });
1169
1217
  let withCssModules = ({ use })=>({
1170
1218
  resourceQuery: /[?&]module(?:[=&]|$)/,
1171
- use,
1219
+ use: [
1220
+ isDev() && {
1221
+ loader: node_path.resolve(nativeCss_dirname, './typedCssModulesLoader.js')
1222
+ },
1223
+ ...use
1224
+ ].filter(Boolean),
1172
1225
  type: 'css/module'
1173
1226
  }), getLessLoader = ()=>({
1174
1227
  loader: getCompiledPkgPath('less-loader'),
1175
- options: {
1176
- lessOptions: mergeConfig({
1228
+ options: utils_mergeConfig({
1229
+ lessOptions: {
1177
1230
  javascriptEnabled: !0
1178
- }, unpackConfig.css?.less || {}),
1231
+ },
1179
1232
  implementation: getUserDepPath(unpackConfig.root, 'less'),
1180
1233
  sourceMap
1181
- }
1234
+ }, unpackConfig.css?.lessLoader || {})
1182
1235
  }), getCssLoader = ()=>unpackConfig.css?.transformer === 'lightningcss' ? {
1183
1236
  loader: 'builtin:lightningcss-loader',
1184
1237
  options: {
1185
1238
  targets: esVersionToBrowserslist(unpackConfig.build.target),
1186
- ...unpackConfig.css?.lightningcss
1239
+ ...unpackConfig.css?.lightningcssLoader
1187
1240
  }
1188
1241
  } : {
1189
1242
  loader: getCompiledPkgPath('postcss-loader'),
1190
1243
  options: {
1191
- postcssOptions: unpackConfig.css?.postcss,
1192
- sourceMap
1244
+ sourceMap,
1245
+ ...unpackConfig.css?.postcssLoader
1193
1246
  }
1194
1247
  }, getSassLoader = ()=>({
1195
1248
  loader: getCompiledPkgPath('sass-loader'),
@@ -1199,8 +1252,8 @@ async function getBundlerConfig(originalUnpackConfig) {
1199
1252
  'sass-embedded',
1200
1253
  'sass'
1201
1254
  ]),
1202
- sassOptions: unpackConfig.css?.sass,
1203
- sourceMap
1255
+ sourceMap,
1256
+ ...unpackConfig.css?.sassLoader
1204
1257
  }
1205
1258
  });
1206
1259
  return config.module.rules.push({
@@ -1299,13 +1352,13 @@ async function getBundlerConfig(originalUnpackConfig) {
1299
1352
  loader: 'builtin:lightningcss-loader',
1300
1353
  options: {
1301
1354
  targets: esVersionToBrowserslist(unpackConfig.build.target),
1302
- ...unpackConfig.css?.lightningcss
1355
+ ...unpackConfig.css?.lightningcssLoader
1303
1356
  }
1304
1357
  } : {
1305
1358
  loader: getCompiledPkgPath('postcss-loader'),
1306
1359
  options: {
1307
- postcssOptions: unpackConfig.css?.postcss,
1308
- sourceMap
1360
+ sourceMap,
1361
+ ...unpackConfig.css?.postcssLoader
1309
1362
  }
1310
1363
  };
1311
1364
  return config.module.rules.push({
@@ -1317,13 +1370,13 @@ async function getBundlerConfig(originalUnpackConfig) {
1317
1370
  getCssLoader(),
1318
1371
  {
1319
1372
  loader: getCompiledPkgPath('less-loader'),
1320
- options: {
1321
- lessOptions: mergeConfig({
1373
+ options: utils_mergeConfig({
1374
+ lessOptions: {
1322
1375
  javascriptEnabled: !0
1323
- }, unpackConfig.css?.less || {}),
1376
+ },
1324
1377
  implementation: getUserDepPath(unpackConfig.root, 'less'),
1325
1378
  sourceMap
1326
- }
1379
+ }, unpackConfig.css?.lessLoader || {})
1327
1380
  }
1328
1381
  ]
1329
1382
  }), config.module.rules.push({
@@ -1349,8 +1402,8 @@ async function getBundlerConfig(originalUnpackConfig) {
1349
1402
  'sass-embedded',
1350
1403
  'sass'
1351
1404
  ]),
1352
- sassOptions: unpackConfig.css?.sass,
1353
- sourceMap
1405
+ sourceMap,
1406
+ ...unpackConfig.css?.sassLoader
1354
1407
  }
1355
1408
  }
1356
1409
  ]
@@ -1410,11 +1463,11 @@ async function getBundlerConfig(originalUnpackConfig) {
1410
1463
  config = await impl(config, {
1411
1464
  ...unpackConfig._context,
1412
1465
  unpackConfig,
1413
- mergeConfig: mergeConfig
1466
+ mergeConfig: utils_mergeConfig
1414
1467
  });
1415
1468
  }), unpackConfig.bundlerConfig && (config = isFunction(unpackConfig.bundlerConfig) ? await unpackConfig.bundlerConfig(config, {
1416
- mergeConfig: mergeConfig
1417
- }) : mergeConfig(config, unpackConfig.bundlerConfig)), config;
1469
+ mergeConfig: utils_mergeConfig
1470
+ }) : utils_mergeConfig(config, unpackConfig.bundlerConfig)), config;
1418
1471
  }
1419
1472
  async function unpackBuild(unpackConfig) {
1420
1473
  let compiler = rspack(await getBundlerConfig(unpackConfig)), handler = (err, stats)=>{
@@ -1535,7 +1588,7 @@ async function unpackDev(unpackConfig) {
1535
1588
  ...middlewares
1536
1589
  ]);
1537
1590
  let server = new RspackDevServer(devServerOptions, compiler);
1538
- await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v4.0.0${unpackConfig.performance?.cache ? ' ϟ' : ''}`)} ${colors.dim('ready in')} ${colors.bold(Math.ceil(performance.now() - getUnpackStartTime()))} ${colors.dim('ms')}\n`), printServerUrls({
1591
+ await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v4.1.0${unpackConfig.performance?.cache ? ' ϟ' : ''}`)} ${colors.dim('ready in')} ${colors.bold(Math.ceil(performance.now() - getUnpackStartTime()))} ${colors.dim('ms')}\n`), printServerUrls({
1539
1592
  port,
1540
1593
  host: unpackConfig.server.host,
1541
1594
  base: unpackConfig.base
@@ -1549,162 +1602,161 @@ async function unpackDev(unpackConfig) {
1549
1602
  function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'unpack' }) {
1550
1603
  let _context = {
1551
1604
  callerName,
1552
- version: "4.0.0",
1605
+ version: "4.1.0",
1553
1606
  cachePath: 'node_modules/.unpack'
1554
1607
  }, resolveConfig = (mode)=>{
1555
- let rootPath, outputPath, basePath, cachedTraceMap, fs, isValidMethodName, parseFrame, formatOriginalLocation, formatFullStack, resolveErrorLocationAndStack, shouldTransformDeepImport, preJsAssets, jsAssets, cssAssets, bundledDepsCachePath, deepImportPkgPattern, deepImportRegex, plugin, root;
1556
- return {
1557
- ...mergeConfig({
1558
- root: cwd,
1559
- base: '/',
1560
- sourceMap: 'production' !== mode && 'cheap-module-source-map',
1561
- build: {
1562
- outDir: 'dist',
1563
- minify: !0,
1564
- filenameHash: !0,
1565
- target: 'es2023'
1566
- },
1567
- server: {
1568
- port: 3000,
1569
- host: !1
1570
- },
1571
- html: {
1572
- mountId: 'root'
1573
- },
1574
- css: {
1575
- transformer: 'postcss',
1576
- sourceMap: !1
1608
+ var options;
1609
+ let rootPath, outputPath, basePath, cachedTraceMap, fs, isValidMethodName, parseFrame, formatOriginalLocation, formatFullStack, resolveErrorLocationAndStack, shouldTransformDeepImport, preJsAssets, jsAssets, cssAssets, bundledDepsCachePath, deepImportPkgPattern, deepImportRegex, plugin, root, rootPath1, inject, domId, registerCode, namesCode, virtualModules, ensureVirtualModules, mergedConfig = utils_mergeConfig({
1610
+ root: cwd,
1611
+ base: '/',
1612
+ sourceMap: 'production' !== mode && 'cheap-module-source-map',
1613
+ build: {
1614
+ outDir: 'dist',
1615
+ minify: !0,
1616
+ filenameHash: !0,
1617
+ target: 'es2023'
1618
+ },
1619
+ server: {
1620
+ port: 3000,
1621
+ host: !1
1622
+ },
1623
+ html: {
1624
+ mountId: 'root'
1625
+ },
1626
+ css: {
1627
+ transformer: 'postcss',
1628
+ sourceMap: !1
1629
+ },
1630
+ performance: {
1631
+ chunkSplit: {
1632
+ strategy: 'single-vendor'
1577
1633
  },
1578
- performance: {
1579
- chunkSplit: {
1580
- strategy: 'single-vendor'
1581
- },
1582
- printFileSize: !0,
1583
- cache: !0
1634
+ printFileSize: !0
1635
+ },
1636
+ typeCheck: !0,
1637
+ envPrefix: [
1638
+ 'PUBLIC_',
1639
+ 'VITE_'
1640
+ ],
1641
+ plugins: [
1642
+ {
1643
+ name: 'unpack:auto-css-modules',
1644
+ transform: {
1645
+ filter: {
1646
+ test: JSX_REGEX
1647
+ },
1648
+ handler: (code)=>STYLE_EXT_HINTS.some((ext)=>code.includes(ext)) ? code.replace(STYLE_IMPORT_RE, (full, importClause, quote, spec)=>TYPE_IMPORT_CLAUSE_RE.test(importClause) || spec.includes('?') || spec.includes('#') ? full : `import ${importClause} from ${quote}${spec}?module${quote}`) : null
1649
+ }
1584
1650
  },
1585
- typeCheck: !0,
1586
- envPrefix: [
1587
- 'PUBLIC_'
1588
- ],
1589
- plugins: [
1590
- {
1591
- name: 'unpack:auto-css-modules',
1592
- transform: {
1593
- filter: {
1594
- test: JSX_REGEX
1595
- },
1596
- handler: (code)=>STYLE_EXT_HINTS.some((ext)=>code.includes(ext)) ? code.replace(STYLE_IMPORT_RE, (full, importClause, quote, spec)=>TYPE_IMPORT_CLAUSE_RE.test(importClause) || spec.includes('?') || spec.includes('#') ? full : `import ${importClause} from ${quote}${spec}?module${quote}`) : null
1651
+ (rootPath = '', outputPath = '', basePath = '/', cachedTraceMap = new Map(), fs = null, isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName), parseFrame = async (frame)=>{
1652
+ let { file, column, lineNumber } = frame;
1653
+ if (!file || null == lineNumber || null == column) return;
1654
+ let localPath = file;
1655
+ try {
1656
+ let pathname = new URL(file).pathname;
1657
+ if ('/' !== basePath) {
1658
+ let normalizedBase = basePath;
1659
+ pathname.startsWith(normalizedBase) && (pathname = pathname.slice(normalizedBase.length));
1597
1660
  }
1598
- },
1599
- (rootPath = '', outputPath = '', basePath = '/', cachedTraceMap = new Map(), fs = null, isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName), parseFrame = async (frame)=>{
1600
- let { file, column, lineNumber } = frame;
1601
- if (!file || null == lineNumber || null == column) return;
1602
- let localPath = file;
1603
- try {
1604
- let pathname = new URL(file).pathname;
1605
- if ('/' !== basePath) {
1606
- let normalizedBase = basePath;
1607
- pathname.startsWith(normalizedBase) && (pathname = pathname.slice(normalizedBase.length));
1608
- }
1609
- localPath = node_path.join(outputPath, pathname);
1610
- } catch {
1611
- node_path.isAbsolute(file) || (localPath = node_path.join(outputPath, file));
1661
+ localPath = node_path.join(outputPath, pathname);
1662
+ } catch {
1663
+ node_path.isAbsolute(file) || (localPath = node_path.join(outputPath, file));
1664
+ }
1665
+ let sourceMapPath = `${localPath}.map`;
1666
+ try {
1667
+ if (!fs.existsSync(sourceMapPath)) return;
1668
+ let tracer = cachedTraceMap.get(sourceMapPath);
1669
+ if (!tracer) {
1670
+ let readFile = promisify(fs.readFile), sourceMapContent = await readFile(sourceMapPath, 'utf-8');
1671
+ if (!sourceMapContent) return;
1672
+ tracer = new TraceMap(sourceMapContent), cachedTraceMap.set(sourceMapPath, tracer);
1612
1673
  }
1613
- let sourceMapPath = `${localPath}.map`;
1614
- try {
1615
- if (!fs.existsSync(sourceMapPath)) return;
1616
- let tracer = cachedTraceMap.get(sourceMapPath);
1617
- if (!tracer) {
1618
- let readFile = promisify(fs.readFile), sourceMapContent = await readFile(sourceMapPath, 'utf-8');
1619
- if (!sourceMapContent) return;
1620
- tracer = new TraceMap(sourceMapContent), cachedTraceMap.set(sourceMapPath, tracer);
1621
- }
1622
- let originalPosition = originalPositionFor(tracer, {
1623
- line: lineNumber,
1624
- column: column
1625
- });
1626
- return {
1627
- sourceMapPath,
1628
- originalPosition
1629
- };
1674
+ let originalPosition = originalPositionFor(tracer, {
1675
+ line: lineNumber,
1676
+ column: column
1677
+ });
1678
+ return {
1679
+ sourceMapPath,
1680
+ originalPosition
1681
+ };
1682
+ } catch {
1683
+ return;
1684
+ }
1685
+ }, formatOriginalLocation = (originalMapping)=>{
1686
+ let { source, line, column } = originalMapping;
1687
+ if (!source) return;
1688
+ let relativeSource = source;
1689
+ if (source.includes('webpack://')) {
1690
+ let segments = (relativeSource = source.replace(/webpack:\/\/\/?/, '')).split(/[\\/]/);
1691
+ [
1692
+ 'src',
1693
+ 'node_modules'
1694
+ ].includes(segments[1]) && (segments.shift(), relativeSource = segments.join('/'));
1695
+ }
1696
+ let result = relativeSource;
1697
+ return null !== line && (result += null === column ? `:${line}` : `:${line}:${column}`), result;
1698
+ }, formatFullStack = async (stackFrames)=>{
1699
+ let allLines = [], srcLines = [];
1700
+ for (let frame of stackFrames){
1701
+ let parsedFrame = await parseFrame(frame), { methodName } = frame, parts = [];
1702
+ methodName && isValidMethodName(methodName) && parts.push(methodName);
1703
+ let parsed = !1;
1704
+ if (parsedFrame) {
1705
+ let { originalPosition } = parsedFrame, originalLocation = formatOriginalLocation(originalPosition);
1706
+ originalLocation && (parts.push(originalLocation), parsed = !0);
1707
+ }
1708
+ if (!parsed && frame.file) try {
1709
+ let url = new URL(frame.file);
1710
+ parts.push(`${url.pathname}:${frame.lineNumber}:${frame.column}`);
1630
1711
  } catch {
1631
- return;
1712
+ parts.push(`${frame.file}:${frame.lineNumber}:${frame.column}`);
1632
1713
  }
1633
- }, formatOriginalLocation = (originalMapping)=>{
1634
- let { source, line, column } = originalMapping;
1635
- if (!source) return;
1636
- let relativeSource = source;
1637
- if (source.includes('webpack://')) {
1638
- let segments = (relativeSource = source.replace(/webpack:\/\/\/?/, '')).split(/[\\/]/);
1639
- [
1640
- 'src',
1641
- 'node_modules'
1642
- ].includes(segments[1]) && (segments.shift(), relativeSource = segments.join('/'));
1714
+ if (parts.length > 0) {
1715
+ let loc = parts.length > 1 ? `(${parts[1]})` : parts[0].includes(':') ? `(${parts[0]})` : parts[0], func = parts.length > 1 ? parts[0] : parts[0].includes(':') ? '' : parts[0], line = func ? `\n at ${func} ${loc}` : `\n at ${loc}`;
1716
+ allLines.push(line);
1717
+ let locationText = loc.startsWith('(') && loc.endsWith(')') ? loc.slice(1, -1) : loc;
1718
+ /(^|[\\/])src[\\/]/.test(locationText) && srcLines.push(line);
1643
1719
  }
1644
- let result = relativeSource;
1645
- return null !== line && (result += null === column ? `:${line}` : `:${line}:${column}`), result;
1646
- }, formatFullStack = async (stackFrames)=>{
1647
- let allLines = [], srcLines = [];
1648
- for (let frame of stackFrames){
1649
- let parsedFrame = await parseFrame(frame), { methodName } = frame, parts = [];
1650
- methodName && isValidMethodName(methodName) && parts.push(methodName);
1651
- let parsed = !1;
1652
- if (parsedFrame) {
1653
- let { originalPosition } = parsedFrame, originalLocation = formatOriginalLocation(originalPosition);
1654
- originalLocation && (parts.push(originalLocation), parsed = !0);
1655
- }
1656
- if (!parsed && frame.file) try {
1657
- let url = new URL(frame.file);
1658
- parts.push(`${url.pathname}:${frame.lineNumber}:${frame.column}`);
1659
- } catch {
1660
- parts.push(`${frame.file}:${frame.lineNumber}:${frame.column}`);
1661
- }
1662
- if (parts.length > 0) {
1663
- let loc = parts.length > 1 ? `(${parts[1]})` : parts[0].includes(':') ? `(${parts[0]})` : parts[0], func = parts.length > 1 ? parts[0] : parts[0].includes(':') ? '' : parts[0], line = func ? `\n at ${func} ${loc}` : `\n at ${loc}`;
1664
- allLines.push(line);
1665
- let locationText = loc.startsWith('(') && loc.endsWith(')') ? loc.slice(1, -1) : loc;
1666
- /(^|[\\/])src[\\/]/.test(locationText) && srcLines.push(line);
1667
- }
1668
- }
1669
- return srcLines.length > 0 ? srcLines[0] : allLines.join('');
1670
- }, resolveErrorLocationAndStack = async (item)=>{
1671
- let locationFromMsg = item.message ? ((message)=>{
1672
- let match = message.match(/((?:[A-Za-z]:)?\/[^\s:]+):(\d+):(\d+)/);
1673
- if (!match) return;
1674
- let [, absPath, line, column] = match, source = absPath;
1675
- return absPath.startsWith(rootPath + node_path.sep) && (source = node_path.relative(rootPath, absPath)), `${source}:${Number(line)}:${Number(column)}`;
1676
- })(item.message) : null;
1677
- if (locationFromMsg) return {
1678
- locationSuffix: colors.dim(`(${locationFromMsg})`),
1679
- stackString: ''
1680
- };
1681
- if (!item.stack) return {
1682
- locationSuffix: '',
1720
+ }
1721
+ return srcLines.length > 0 ? srcLines[0] : allLines.join('');
1722
+ }, resolveErrorLocationAndStack = async (item)=>{
1723
+ let locationFromMsg = item.message ? ((message)=>{
1724
+ let match = message.match(/((?:[A-Za-z]:)?\/[^\s:]+):(\d+):(\d+)/);
1725
+ if (!match) return;
1726
+ let [, absPath, line, column] = match, source = absPath;
1727
+ return absPath.startsWith(rootPath + node_path.sep) && (source = node_path.relative(rootPath, absPath)), `${source}:${Number(line)}:${Number(column)}`;
1728
+ })(item.message) : null;
1729
+ if (locationFromMsg) return {
1730
+ locationSuffix: colors.dim(`(${locationFromMsg})`),
1731
+ stackString: ''
1732
+ };
1733
+ if (!item.stack) return {
1734
+ locationSuffix: '',
1735
+ stackString: ''
1736
+ };
1737
+ let parsedFrames = parse(item.stack), userFrame = parsedFrames.find((frame)=>frame.file && null !== frame.lineNumber && null !== frame.column && SOURCE_REGEX.test(frame.file));
1738
+ if (userFrame) {
1739
+ let parsedUserFrame = await parseFrame(userFrame), loc = parsedUserFrame ? formatOriginalLocation(parsedUserFrame.originalPosition) : null;
1740
+ if (loc) return {
1741
+ locationSuffix: colors.dim(`(${loc})`),
1683
1742
  stackString: ''
1684
1743
  };
1685
- let parsedFrames = parse(item.stack), userFrame = parsedFrames.find((frame)=>frame.file && null !== frame.lineNumber && null !== frame.column && browserLogs_SCRIPT_REGEX.test(frame.file));
1686
- if (userFrame) {
1687
- let parsedUserFrame = await parseFrame(userFrame), loc = parsedUserFrame ? formatOriginalLocation(parsedUserFrame.originalPosition) : null;
1688
- if (loc) return {
1689
- locationSuffix: colors.dim(`(${loc})`),
1690
- stackString: ''
1691
- };
1692
- }
1693
- let formattedStack = await formatFullStack(parsedFrames);
1694
- return {
1695
- locationSuffix: '',
1696
- stackString: colors.dim(formattedStack)
1697
- };
1698
- }, {
1699
- name: 'unpack:browser-logs',
1700
- apply: (config, { command })=>'dev' === command && config.dev?.browserLogs,
1701
- buildStart: async ({ isFirstCompile, compiler })=>{
1702
- isFirstCompile && (fs = compiler.outputFileSystem);
1703
- },
1704
- configResolved: (config)=>{
1705
- rootPath = config.root, outputPath = node_path.join(rootPath, config.build.outDir), basePath = normalizePublicPath(config.base);
1706
- },
1707
- transformHtml: (html)=>injectToHead(html, `<script>
1744
+ }
1745
+ let formattedStack = await formatFullStack(parsedFrames);
1746
+ return {
1747
+ locationSuffix: '',
1748
+ stackString: colors.dim(formattedStack)
1749
+ };
1750
+ }, {
1751
+ name: 'unpack:browser-logs',
1752
+ apply: (config, { command })=>'dev' === command && config.dev?.browserLogs,
1753
+ buildStart: async ({ isFirstCompile, compiler })=>{
1754
+ isFirstCompile && (fs = compiler.outputFileSystem);
1755
+ },
1756
+ configResolved: (config)=>{
1757
+ rootPath = config.root, outputPath = node_path.join(rootPath, config.build.outDir), basePath = normalizePublicPath(config.base);
1758
+ },
1759
+ transformHtml: (html)=>injectToHead(html, `<script>
1708
1760
  ;(() => {
1709
1761
  if (typeof window === 'undefined' || typeof console === 'undefined') return
1710
1762
  const endpoint = '${BROWSER_LOGS_ENDPOINT}'
@@ -1783,433 +1835,545 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
1783
1835
  })
1784
1836
  })()
1785
1837
  </script>`),
1786
- setupMiddlewares: (middlewares)=>[
1787
- (req, res, next)=>{
1788
- if ('POST' !== req.method || !req.url?.startsWith(BROWSER_LOGS_ENDPOINT)) return next();
1789
- let raw = '';
1790
- req.on('data', (chunk)=>{
1791
- raw += chunk.toString();
1792
- }), req.on('end', async ()=>{
1793
- try {
1794
- let { level, time, args = [] } = JSON.parse(raw || '{}'), formattedArgs = await Promise.all(args.map(async (item)=>{
1795
- if (!item) return '';
1796
- if ('error' === item.type) {
1797
- let { locationSuffix, stackString } = await resolveErrorLocationAndStack(item), msg = item.message || '', suffix = locationSuffix ? msg ? ` ${locationSuffix}` : locationSuffix : '';
1798
- return `${msg}${suffix}${stackString}`;
1838
+ setupMiddlewares: (middlewares)=>[
1839
+ (req, res, next)=>{
1840
+ if ('POST' !== req.method || !req.url?.startsWith(BROWSER_LOGS_ENDPOINT)) return next();
1841
+ let raw = '';
1842
+ req.on('data', (chunk)=>{
1843
+ raw += chunk.toString();
1844
+ }), req.on('end', async ()=>{
1845
+ try {
1846
+ let { level, time, args = [] } = JSON.parse(raw || '{}'), formattedArgs = await Promise.all(args.map(async (item)=>{
1847
+ if (!item) return '';
1848
+ if ('error' === item.type) {
1849
+ let { locationSuffix, stackString } = await resolveErrorLocationAndStack(item), msg = item.message || '', suffix = locationSuffix ? msg ? ` ${locationSuffix}` : locationSuffix : '';
1850
+ return `${msg}${suffix}${stackString}`;
1851
+ }
1852
+ switch(item.type){
1853
+ case 'string':
1854
+ let trimmed;
1855
+ return (trimmed = item.message.trim()) ? trimmed.split(/\r?\n/g).filter((line)=>{
1856
+ let normalized = line.trim().replace(/`/g, '');
1857
+ return !!normalized && !/^at\s+/.test(normalized);
1858
+ }).join('\n').trim() : '';
1859
+ case 'null':
1860
+ return null;
1861
+ case 'undefined':
1862
+ return;
1863
+ case 'object':
1864
+ return JSON.parse(item.message || '');
1865
+ default:
1866
+ return item.message;
1867
+ }
1868
+ })), outputArgs = ((args)=>{
1869
+ if (args.length < 2 || 'string' != typeof args[0]) return args;
1870
+ let template = args[0];
1871
+ if (!/%[sdifoOj%c%]/.test(template)) return args;
1872
+ let rest = args.slice(1), cleanedTemplate = '';
1873
+ for(let i = 0; i < template.length; i++){
1874
+ let ch = template[i];
1875
+ if ('%' !== ch || i + 1 >= template.length) {
1876
+ cleanedTemplate += ch;
1877
+ continue;
1799
1878
  }
1800
- switch(item.type){
1801
- case 'string':
1802
- let trimmed;
1803
- return (trimmed = item.message.trim()) ? trimmed.split(/\r?\n/g).filter((line)=>{
1804
- let normalized = line.trim().replace(/`/g, '');
1805
- return !!normalized && !/^at\s+/.test(normalized);
1806
- }).join('\n').trim() : '';
1807
- case 'null':
1808
- return null;
1809
- case 'undefined':
1810
- return;
1811
- case 'object':
1812
- return JSON.parse(item.message || '');
1813
- default:
1814
- return item.message;
1879
+ let next = template[i + 1];
1880
+ if ('%' === next) {
1881
+ cleanedTemplate += '%%', i++;
1882
+ continue;
1815
1883
  }
1816
- })), outputArgs = ((args)=>{
1817
- if (args.length < 2 || 'string' != typeof args[0]) return args;
1818
- let template = args[0];
1819
- if (!/%[sdifoOj%c%]/.test(template)) return args;
1820
- let rest = args.slice(1), cleanedTemplate = '';
1821
- for(let i = 0; i < template.length; i++){
1822
- let ch = template[i];
1823
- if ('%' !== ch || i + 1 >= template.length) {
1824
- cleanedTemplate += ch;
1825
- continue;
1826
- }
1827
- let next = template[i + 1];
1828
- if ('%' === next) {
1829
- cleanedTemplate += '%%', i++;
1830
- continue;
1831
- }
1832
- if ('c' === next) {
1833
- rest.length > 0 && rest.shift(), i++;
1834
- continue;
1835
- }
1836
- cleanedTemplate += `%${next}`, i++;
1884
+ if ('c' === next) {
1885
+ rest.length > 0 && rest.shift(), i++;
1886
+ continue;
1837
1887
  }
1838
- return [
1839
- format(cleanedTemplate, ...rest)
1840
- ];
1841
- })(formattedArgs), prefix = colors.dim(`[browser ${time}]`);
1842
- switch(level){
1843
- case 'error':
1844
- console.log(colors.red(`${prefix} ${format(...outputArgs)}`));
1845
- break;
1846
- case 'warn':
1847
- console.log(colors.yellow(`${prefix} ${format(...outputArgs)}`));
1848
- break;
1849
- case 'debug':
1850
- console.log(prefix, ...outputArgs);
1888
+ cleanedTemplate += `%${next}`, i++;
1851
1889
  }
1852
- } finally{
1853
- res.statusCode = 204, res.end();
1890
+ return [
1891
+ format(cleanedTemplate, ...rest)
1892
+ ];
1893
+ })(formattedArgs), prefix = colors.dim(`[browser ${time}]`);
1894
+ switch(level){
1895
+ case 'error':
1896
+ console.log(colors.red(`${prefix} ${format(...outputArgs)}`));
1897
+ break;
1898
+ case 'warn':
1899
+ console.log(colors.yellow(`${prefix} ${format(...outputArgs)}`));
1900
+ break;
1901
+ case 'debug':
1902
+ console.log(prefix, ...outputArgs);
1854
1903
  }
1904
+ } finally{
1905
+ res.statusCode = 204, res.end();
1906
+ }
1907
+ });
1908
+ },
1909
+ ...middlewares
1910
+ ]
1911
+ }),
1912
+ {
1913
+ name: 'unpack:glob',
1914
+ transform: {
1915
+ filter: {
1916
+ test: JS_REGEX
1917
+ },
1918
+ handler: (code)=>code.includes('import.meta.glob') ? code.replace(/import\.meta\.glob\s*\(\s*(\[[\s\S]*?\]|(['"])([^'"]+)\2)\s*(?:,\s*({[\s\S]*?}))?\s*\)/g, (_, patternGroup, __, pattern, rawOptions)=>{
1919
+ if (patternGroup.trim().startsWith('[')) {
1920
+ let items, includes, excludes, { includes: includes1, excludes: excludes1 } = (items = [], patternGroup.replace(/(['"])([^'"]+)\1/g, (_, __, value)=>(items.push(value), '')), includes = [], excludes = [], items.forEach((item)=>{
1921
+ if (item.startsWith('!')) {
1922
+ let normalized = item.slice(1).trim();
1923
+ normalized && excludes.push(normalized);
1924
+ return;
1925
+ }
1926
+ includes.push(item);
1927
+ }), {
1928
+ includes,
1929
+ excludes
1855
1930
  });
1856
- },
1857
- ...middlewares
1858
- ]
1859
- }),
1860
- (shouldTransformDeepImport = !1, preJsAssets = [], jsAssets = [], cssAssets = [], bundledDepsCachePath = '', deepImportPkgPattern = [
1861
- ...SPECIAL_NO_ENTRY_DEPS
1862
- ].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 = {
1863
- name: 'unpack:prebundle',
1864
- apply: (config, { command })=>'dev' === command && !!config.dev?.prebundle,
1865
- config: async (config, context)=>{
1866
- var externals;
1867
- let existExternals, root = config.root;
1868
- bundledDepsCachePath = node_path.resolve(root, context.cachePath, 'umd');
1869
- let count = {
1870
- total: 0,
1871
- bundled: 0
1872
- }, failedDepsJsonPath = node_path.resolve(root, context.cachePath, 'failed-deps.json'), failedDeps = [], failedCache = node_fs.existsSync(failedDepsJsonPath) ? JSON.parse(node_fs.readFileSync(failedDepsJsonPath, 'utf-8')) : {}, updateProgress = ()=>{
1873
- let errMsg = failedDeps.length > 0 ? ` failed: ${failedDeps.join(', ')}` : '';
1874
- logUpdate(`${colors.magenta('»')} optimizing dependencies (${count.bundled}/${count.total})${errMsg}`), count.total === count.bundled + failedDeps.length && console.log();
1875
- }, userOptions = isPlainObject(config.dev?.prebundle) ? config.dev.prebundle : {}, ignoreCSSDeps = userOptions.ignoreCSS || [], packageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'package.json'), 'utf-8')), excludeDeps = [
1876
- ...(externals = config.externals, existExternals = new Set(), Array.isArray(externals) ? externals.forEach((item)=>{
1877
- isPlainObject(item) && Object.keys(item).forEach((key)=>{
1878
- existExternals.add(key);
1879
- });
1880
- }) : isPlainObject(externals) && Object.keys(externals).forEach((key)=>{
1931
+ return includes1.length ? (({ includes, excludes, eager })=>{
1932
+ let excludeMatchers = excludes.map((item)=>toRegexLiteral(item.regExpSource)).join(', '), includeItems = includes.map((item)=>{
1933
+ let prefix = './' === item.publicPrefix ? '' : `${item.publicPrefix}/`, mapKeyExpr = './' === item.publicPrefix ? "key.startsWith('./') ? key : './' + key" : `${JSON.stringify(prefix)} + (key.startsWith('./') ? key.slice(2) : key)`;
1934
+ return `{
1935
+ context: import.meta.webpackContext(${JSON.stringify(item.baseDir)}, { recursive: ${item.recursive}, regExp: ${toRegexLiteral(item.regExpSource)} }),
1936
+ mapKey: (key) => ${mapKeyExpr}
1937
+ }`;
1938
+ }).join(', '), excludeList = excludeMatchers ? `[${excludeMatchers}]` : '[]';
1939
+ return `(() => {
1940
+ const modules = {}
1941
+ const includeContexts = [${includeItems}]
1942
+ const excludeMatchers = ${excludeList}
1943
+ const isExcluded = (path) => excludeMatchers.some((matcher) => matcher.test(path))
1944
+ for (const { context, mapKey } of includeContexts) {
1945
+ for (const key of context.keys()) {
1946
+ const path = mapKey(key)
1947
+ if (isExcluded(path)) continue
1948
+ if (!modules[path]) {
1949
+ modules[path] = ${eager ? 'context(key)' : '() => Promise.resolve(context(key))'}
1950
+ }
1951
+ }
1952
+ }
1953
+ return modules
1954
+ })()`;
1955
+ })({
1956
+ includes: includes1.map(parseGlob),
1957
+ excludes: excludes1.map(parseGlob),
1958
+ eager: hasEager(rawOptions)
1959
+ }) : '({})';
1960
+ }
1961
+ let { baseDir, regExpSource, recursive, publicPrefix } = parseGlob(pattern);
1962
+ return (({ baseDir, regExpSource, recursive, eager, publicPrefix })=>{
1963
+ let prefix = './' === publicPrefix ? '' : `${publicPrefix}/`, mapKeyExpr = './' === publicPrefix ? "key.startsWith('./') ? key : './' + key" : `${JSON.stringify(prefix)} + (key.startsWith('./') ? key.slice(2) : key)`;
1964
+ return `(() => {
1965
+ const context = import.meta.webpackContext(${JSON.stringify(baseDir)}, { recursive: ${recursive}, regExp: ${toRegexLiteral(regExpSource)} })
1966
+ const modules = {}
1967
+ for (const key of context.keys()) {
1968
+ const path = ${mapKeyExpr}
1969
+ modules[path] = ${eager ? 'context(key)' : '() => Promise.resolve(context(key))'}
1970
+ }
1971
+ return modules
1972
+ })()`;
1973
+ })({
1974
+ baseDir,
1975
+ regExpSource,
1976
+ recursive,
1977
+ eager: hasEager(rawOptions),
1978
+ publicPrefix
1979
+ });
1980
+ }) : null
1981
+ }
1982
+ },
1983
+ (shouldTransformDeepImport = !1, preJsAssets = [], jsAssets = [], cssAssets = [], bundledDepsCachePath = '', deepImportPkgPattern = [
1984
+ ...SPECIAL_NO_ENTRY_DEPS
1985
+ ].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 = {
1986
+ name: 'unpack:prebundle',
1987
+ apply: (config, { command })=>'dev' === command && !!config.dev?.prebundle,
1988
+ config: async (config, context)=>{
1989
+ var externals;
1990
+ let existExternals, root = config.root;
1991
+ bundledDepsCachePath = node_path.resolve(root, context.cachePath, 'umd');
1992
+ let count = {
1993
+ total: 0,
1994
+ bundled: 0
1995
+ }, failedDepsJsonPath = node_path.resolve(root, context.cachePath, 'failed-deps.json'), failedDeps = [], failedCache = node_fs.existsSync(failedDepsJsonPath) ? JSON.parse(node_fs.readFileSync(failedDepsJsonPath, 'utf-8')) : {}, updateProgress = ()=>{
1996
+ let errMsg = failedDeps.length > 0 ? ` failed: ${failedDeps.join(', ')}` : '';
1997
+ logUpdate(`${colors.magenta('»')} optimizing dependencies (${count.bundled}/${count.total})${errMsg}`), count.total === count.bundled + failedDeps.length && console.log();
1998
+ }, userOptions = isPlainObject(config.dev?.prebundle) ? config.dev.prebundle : {}, ignoreCSSDeps = userOptions.ignoreCSS || [], packageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'package.json'), 'utf-8')), excludeDeps = [
1999
+ ...(externals = config.externals, existExternals = new Set(), Array.isArray(externals) ? externals.forEach((item)=>{
2000
+ isPlainObject(item) && Object.keys(item).forEach((key)=>{
1881
2001
  existExternals.add(key);
1882
- }), Array.from(existExternals) || []),
1883
- ...userOptions.exclude || []
1884
- ], needBundleDeps = (Array.isArray(userOptions.include) && userOptions.include.length > 0 ? userOptions.include : Object.keys(packageJson.dependencies || {})).filter((pkgName)=>!excludeDeps.includes(pkgName)).map((pkgName)=>{
1885
- let depPackageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'node_modules', pkgName, 'package.json'), 'utf-8')), version = depPackageJson.version;
1886
- if (failedCache[pkgName] === version) return;
1887
- let entry = ((packageJson)=>{
1888
- if (packageJson.module) return packageJson.module;
1889
- if (packageJson.exports) {
1890
- if (isString(packageJson.exports)) return packageJson.exports;
1891
- let defaultExport = packageJson.exports['.'];
1892
- if (defaultExport) {
1893
- if (isString(defaultExport)) return defaultExport;
1894
- if (isString(defaultExport.import)) return defaultExport.import;
1895
- if (isString(defaultExport.browser)) return defaultExport.browser;
1896
- if (isString(defaultExport.default)) return defaultExport.default;
1897
- }
1898
- if (isString(packageJson.exports.default)) return packageJson.exports.default;
1899
- }
1900
- if (packageJson.main) return packageJson.main;
1901
- })(depPackageJson);
1902
- if (!entry) {
1903
- if (SPECIAL_NO_ENTRY_DEPS.includes(pkgName)) {
1904
- let syntheticEntry = (({ root, pkgName })=>{
1905
- let pkgDir = node_path.resolve(root, 'node_modules', pkgName);
1906
- if (!node_fs.existsSync(pkgDir)) return;
1907
- let indexPath = node_path.resolve(pkgDir, 'index.ts'), content = globSync('**/*.{js,jsx,ts,tsx}', {
1908
- cwd: pkgDir,
1909
- absolute: !1
1910
- }).filter((p)=>{
1911
- let base = node_path.basename(p);
1912
- return !(p.endsWith('.d.ts') || /^index\.(t|j)sx?$/.test(base)) && 'package.json' !== base;
1913
- }).map((file)=>{
1914
- let normalized = file.split(node_path.sep).join('/'), exportName = pathToExportIdentifier(normalized);
1915
- return `export { default as ${exportName} } from './${normalized}'`;
1916
- }).join('\n');
1917
- return node_fs.writeFileSync(indexPath, content, 'utf-8'), indexPath;
1918
- })({
1919
- root,
1920
- pkgName
1921
- });
1922
- if (syntheticEntry) return shouldTransformDeepImport = !0, {
1923
- name: pkgName,
1924
- entry: syntheticEntry,
1925
- version
1926
- };
2002
+ });
2003
+ }) : isPlainObject(externals) && Object.keys(externals).forEach((key)=>{
2004
+ existExternals.add(key);
2005
+ }), Array.from(existExternals) || []),
2006
+ ...userOptions.exclude || []
2007
+ ], needBundleDeps = (Array.isArray(userOptions.include) && userOptions.include.length > 0 ? userOptions.include : Object.keys(packageJson.dependencies || {})).filter((pkgName)=>!excludeDeps.includes(pkgName)).map((pkgName)=>{
2008
+ let depPackageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'node_modules', pkgName, 'package.json'), 'utf-8')), version = depPackageJson.version;
2009
+ if (failedCache[pkgName] === version) return;
2010
+ let entry = ((packageJson)=>{
2011
+ if (packageJson.module) return packageJson.module;
2012
+ if (packageJson.exports) {
2013
+ if (isString(packageJson.exports)) return packageJson.exports;
2014
+ let defaultExport = packageJson.exports['.'];
2015
+ if (defaultExport) {
2016
+ if (isString(defaultExport)) return defaultExport;
2017
+ if (isString(defaultExport.import)) return defaultExport.import;
2018
+ if (isString(defaultExport.browser)) return defaultExport.browser;
2019
+ if (isString(defaultExport.default)) return defaultExport.default;
1927
2020
  }
1928
- failedCache[pkgName] = version;
1929
- return;
2021
+ if (isString(packageJson.exports.default)) return packageJson.exports.default;
1930
2022
  }
1931
- return {
1932
- name: pkgName,
1933
- entry: node_path.resolve(root, 'node_modules', pkgName, entry),
1934
- version
1935
- };
1936
- }).filter(Boolean), depExternals = Object.fromEntries(Array.from(new Set([
1937
- 'react',
1938
- 'react-dom',
1939
- 'react-router-dom',
1940
- ...Array.isArray(userOptions.externals) ? userOptions.externals : []
1941
- ])).map((pkg)=>[
1942
- pkg,
1943
- getExternalValue(pkg)
1944
- ])), bundledDeps = await Promise.all(needBundleDeps.map((depInfo)=>(({ name, entry, version })=>new Promise((resolve)=>{
1945
- let pkgDir = node_path.resolve(bundledDepsCachePath, name), outDir = node_path.resolve(pkgDir, version), getResult = ()=>({
1946
- name,
1947
- assets: globSync('**/index.{js,css}', {
1948
- cwd: outDir,
1949
- absolute: !0
1950
- })
1951
- });
1952
- if (node_fs.existsSync(outDir)) return void resolve(getResult());
1953
- count.total++, updateProgress();
1954
- let getSwcOptions = ({ tsx })=>({
1955
- jsc: {
1956
- parser: {
1957
- tsx,
1958
- syntax: "typescript",
1959
- dynamicImport: !0,
1960
- decorators: !0
1961
- },
1962
- transform: {
1963
- react: {
1964
- runtime: 'automatic'
1965
- }
2023
+ if (packageJson.main) return packageJson.main;
2024
+ })(depPackageJson);
2025
+ if (!entry) {
2026
+ if (SPECIAL_NO_ENTRY_DEPS.includes(pkgName)) {
2027
+ let syntheticEntry = (({ root, pkgName })=>{
2028
+ let pkgDir = node_path.resolve(root, 'node_modules', pkgName);
2029
+ if (!node_fs.existsSync(pkgDir)) return;
2030
+ let indexPath = node_path.resolve(pkgDir, 'index.ts'), content = globSync('**/*.{js,jsx,ts,tsx}', {
2031
+ cwd: pkgDir,
2032
+ absolute: !1
2033
+ }).filter((p)=>{
2034
+ let base = node_path.basename(p);
2035
+ return !(p.endsWith('.d.ts') || /^index\.(t|j)sx?$/.test(base)) && 'package.json' !== base;
2036
+ }).map((file)=>{
2037
+ let normalized = file.split(node_path.sep).join('/'), exportName = pathToExportIdentifier(normalized);
2038
+ return `export { default as ${exportName} } from './${normalized}'`;
2039
+ }).join('\n');
2040
+ return node_fs.writeFileSync(indexPath, content, 'utf-8'), indexPath;
2041
+ })({
2042
+ root,
2043
+ pkgName
2044
+ });
2045
+ if (syntheticEntry) return shouldTransformDeepImport = !0, {
2046
+ name: pkgName,
2047
+ entry: syntheticEntry,
2048
+ version
2049
+ };
2050
+ }
2051
+ failedCache[pkgName] = version;
2052
+ return;
2053
+ }
2054
+ return {
2055
+ name: pkgName,
2056
+ entry: node_path.resolve(root, 'node_modules', pkgName, entry),
2057
+ version
2058
+ };
2059
+ }).filter(Boolean), depExternals = Object.fromEntries(Array.from(new Set([
2060
+ ...FRAMEWORKS,
2061
+ ...Array.isArray(userOptions.externals) ? userOptions.externals : []
2062
+ ])).map((pkg)=>[
2063
+ pkg,
2064
+ getExternalValue(pkg)
2065
+ ])), bundledDeps = await Promise.all(needBundleDeps.map((depInfo)=>(({ name, entry, version })=>new Promise((resolve)=>{
2066
+ let pkgDir = node_path.resolve(bundledDepsCachePath, name), outDir = node_path.resolve(pkgDir, version), getResult = ()=>({
2067
+ name,
2068
+ assets: globSync('**/index.{js,css}', {
2069
+ cwd: outDir,
2070
+ absolute: !0
2071
+ })
2072
+ });
2073
+ if (node_fs.existsSync(outDir)) return void resolve(getResult());
2074
+ count.total++, updateProgress();
2075
+ let getSwcOptions = ({ tsx })=>({
2076
+ jsc: {
2077
+ parser: {
2078
+ tsx,
2079
+ syntax: "typescript",
2080
+ dynamicImport: !0,
2081
+ decorators: !0
2082
+ },
2083
+ transform: {
2084
+ react: {
2085
+ runtime: 'automatic'
1966
2086
  }
1967
2087
  }
1968
- }), compiler = rspack({
1969
- entry: {
1970
- index: entry
2088
+ }
2089
+ }), compiler = rspack({
2090
+ entry: {
2091
+ index: entry
2092
+ },
2093
+ context: root,
2094
+ mode: 'development',
2095
+ output: {
2096
+ clean: !0,
2097
+ path: outDir,
2098
+ pathinfo: !1,
2099
+ library: {
2100
+ name: getExternalLibraryName(name),
2101
+ type: 'umd',
2102
+ umdNamedDefine: !0
1971
2103
  },
1972
- context: root,
1973
- mode: 'development',
1974
- output: {
1975
- clean: !0,
1976
- path: outDir,
1977
- pathinfo: !1,
1978
- library: {
1979
- name: getExternalLibraryName(name),
1980
- type: 'umd',
1981
- umdNamedDefine: !0
2104
+ globalObject: 'this'
2105
+ },
2106
+ devtool: !1,
2107
+ module: {
2108
+ rules: [
2109
+ {
2110
+ test: /\.(png|jpe?g|gif|webp)$/i,
2111
+ type: 'asset'
1982
2112
  },
1983
- globalObject: 'this'
1984
- },
1985
- devtool: !1,
1986
- module: {
1987
- rules: [
1988
- {
1989
- test: JS_REGEX,
1990
- use: [
1991
- {
1992
- loader: 'builtin:swc-loader',
1993
- options: getSwcOptions({
1994
- tsx: !1
1995
- })
1996
- }
1997
- ]
1998
- },
1999
- {
2000
- test: JSX_REGEX,
2001
- use: [
2002
- {
2003
- loader: 'builtin:swc-loader',
2004
- options: getSwcOptions({
2005
- tsx: !0
2006
- })
2007
- }
2008
- ]
2009
- },
2010
- {
2011
- test: /\.less$/,
2012
- type: 'css/auto',
2013
- use: [
2014
- {
2015
- loader: getCompiledPkgPath('less-loader'),
2016
- options: {
2017
- lessOptions: {
2018
- javascriptEnabled: !0
2019
- },
2020
- implementation: getUserDepPath(root, 'less')
2021
- }
2113
+ {
2114
+ test: JS_REGEX,
2115
+ use: [
2116
+ {
2117
+ loader: 'builtin:swc-loader',
2118
+ options: getSwcOptions({
2119
+ tsx: !1
2120
+ })
2121
+ }
2122
+ ]
2123
+ },
2124
+ {
2125
+ test: JSX_REGEX,
2126
+ use: [
2127
+ {
2128
+ loader: 'builtin:swc-loader',
2129
+ options: getSwcOptions({
2130
+ tsx: !0
2131
+ })
2132
+ }
2133
+ ]
2134
+ },
2135
+ {
2136
+ test: /\.less$/,
2137
+ type: 'css/auto',
2138
+ use: [
2139
+ {
2140
+ loader: getCompiledPkgPath('less-loader'),
2141
+ options: {
2142
+ lessOptions: {
2143
+ javascriptEnabled: !0
2144
+ },
2145
+ implementation: getUserDepPath(root, 'less')
2022
2146
  }
2023
- ]
2024
- },
2025
- {
2026
- test: /\.s[ac]ss$/i,
2027
- type: 'css/auto',
2028
- use: [
2029
- {
2030
- loader: getCompiledPkgPath('sass-loader'),
2031
- options: {
2032
- api: 'modern-compiler',
2033
- implementation: getUserDepPath(root, [
2034
- 'sass-embedded',
2035
- 'sass'
2036
- ])
2037
- }
2147
+ }
2148
+ ]
2149
+ },
2150
+ {
2151
+ test: /\.s[ac]ss$/i,
2152
+ type: 'css/auto',
2153
+ use: [
2154
+ {
2155
+ loader: getCompiledPkgPath('sass-loader'),
2156
+ options: {
2157
+ api: 'modern-compiler',
2158
+ implementation: getUserDepPath(root, [
2159
+ 'sass-embedded',
2160
+ 'sass'
2161
+ ])
2038
2162
  }
2039
- ]
2040
- }
2041
- ]
2042
- },
2043
- optimization: {
2044
- splitChunks: !1
2045
- },
2046
- experiments: {
2047
- css: !0
2048
- },
2049
- externals: depExternals
2050
- });
2051
- compiler.run((_, stats)=>{
2052
- let isFailed = !1;
2053
- stats?.hasErrors() ? (isFailed = !0, failedDeps.push(name), failedCache[name] = version, removeDir(outDir)) : count.bundled++, updateProgress(), compiler.close(()=>{
2054
- resolve(isFailed ? void 0 : getResult());
2055
- });
2163
+ }
2164
+ ]
2165
+ }
2166
+ ]
2167
+ },
2168
+ optimization: {
2169
+ splitChunks: !1
2170
+ },
2171
+ experiments: {
2172
+ css: !0
2173
+ },
2174
+ externals: depExternals
2175
+ });
2176
+ compiler.run((_, stats)=>{
2177
+ let isFailed = !1;
2178
+ stats?.hasErrors() ? (isFailed = !0, failedDeps.push(name), failedCache[name] = version, removeDir(outDir)) : count.bundled++, updateProgress(), compiler.close(()=>{
2179
+ resolve(isFailed ? void 0 : getResult());
2056
2180
  });
2057
- }))(depInfo)));
2058
- ((cache)=>{
2059
- if (0 === Object.keys(cache).length) {
2060
- node_fs.existsSync(failedDepsJsonPath) && node_fs.unlinkSync(failedDepsJsonPath);
2061
- return;
2062
- }
2063
- let cacheDir = node_path.dirname(failedDepsJsonPath);
2064
- node_fs.existsSync(cacheDir) || node_fs.mkdirSync(cacheDir, {
2065
- recursive: !0
2066
- }), node_fs.writeFileSync(failedDepsJsonPath, JSON.stringify(cache, null, 2), 'utf-8');
2067
- })(failedCache);
2068
- let externals1 = {};
2069
- bundledDeps.filter(Boolean).forEach((dep)=>{
2070
- dep && (externals1[dep.name] = getExternalValue(dep.name), dep.assets.forEach((absPath)=>{
2071
- let relativePath = node_path.relative(bundledDepsCachePath, absPath), preDeps = [
2072
- 'react',
2073
- 'react-dom',
2074
- 'react-router-dom'
2075
- ], serverPath = `/umd/${relativePath}`;
2076
- switch(node_path.extname(relativePath)){
2077
- case '.js':
2078
- preDeps.includes(dep.name) ? preJsAssets.push({
2079
- path: serverPath,
2080
- order: preDeps.indexOf(dep.name)
2081
- }) : jsAssets.push(serverPath);
2082
- break;
2083
- case '.css':
2084
- ignoreCSSDeps.includes(dep.name) || cssAssets.push(serverPath);
2085
- }
2086
- }));
2087
- });
2088
- let existingExternals = config.externals ? Array.isArray(config.externals) ? config.externals : [
2089
- config.externals
2090
- ] : [];
2091
- return config.externals = [
2092
- externals1,
2093
- ...existingExternals
2094
- ], shouldTransformDeepImport && (plugin.transform = {
2095
- filter: {
2096
- test: JSX_REGEX
2097
- },
2098
- handler: (code)=>SPECIAL_NO_ENTRY_DEPS.some((pkg)=>code.includes(pkg)) ? code.replace(deepImportRegex, (_, localName, importPath, pkgName)=>{
2099
- let exportName = pathToExportIdentifier(importPath.slice(pkgName.length + 1));
2100
- return `import { ${exportName} as ${localName} } from '${pkgName}'`;
2101
- }) : null
2102
- }), config;
2103
- },
2104
- transformHtml: (html)=>injectToHead(html, preJsAssets.sort((a, b)=>a.order - b.order).map((item)=>item.path).map((item)=>`<script defer src="${item}"></script>`).join('')),
2105
- setupMiddlewares: (middlewares)=>[
2106
- (req, res, next)=>{
2107
- if ('string' != typeof req.url) return void next();
2108
- let url = new URL(req.url, 'http://localhost');
2109
- if (!url.pathname.startsWith("/umd/")) return void next();
2110
- let relativePath = url.pathname.replace("/umd/", '');
2111
- if (relativePath.includes('..')) {
2112
- res.statusCode = 403, res.end();
2113
- return;
2114
- }
2115
- let filePath = node_path.join(bundledDepsCachePath, relativePath);
2116
- if (!node_fs.existsSync(filePath)) return void next();
2117
- let stat = node_fs.statSync(filePath);
2118
- if (!stat.isFile()) return void next();
2119
- let mtime = stat.mtime.toUTCString(), ext = node_path.extname(filePath);
2120
- if (res.setHeader('Cache-Control', 'no-cache'), res.setHeader('Last-Modified', mtime), '.js' === ext && res.setHeader('Content-Type', "application/javascript"), '.css' === ext && res.setHeader('Content-Type', 'text/css'), req.headers['if-modified-since'] === mtime) {
2121
- res.statusCode = 304, res.end();
2122
- return;
2123
- }
2124
- res.statusCode = 200, node_fs.createReadStream(filePath).pipe(res);
2125
- },
2126
- ...middlewares
2127
- ],
2128
- bundlerConfig: (config)=>{
2129
- let PLUGIN_NAME = 'InjectAssetsPlugin';
2130
- return config.plugins.push({
2131
- apply: (compiler)=>{
2132
- compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
2133
- rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeAssetTagGeneration.tapPromise(PLUGIN_NAME, async (args)=>(args.assets.js.unshift(...jsAssets), args.assets.css.unshift(...cssAssets), args));
2134
2181
  });
2135
- }
2136
- }), config;
2137
- }
2138
- }),
2139
- (root = '', {
2140
- name: 'unpack:file-size',
2141
- apply: (config, { mode })=>'production' === mode && config.performance?.printFileSize,
2142
- configResolved (config) {
2143
- root = config.root;
2144
- },
2145
- buildEnd: async (options)=>{
2146
- let { stats } = options;
2147
- if (stats.hasErrors()) return;
2148
- let chunkGroups = [
2149
- {
2150
- type: 'HTML',
2151
- color: 'green',
2152
- chunks: []
2153
- },
2154
- {
2155
- type: 'Assets',
2156
- color: 'yellow',
2157
- chunks: []
2158
- },
2159
- {
2160
- type: 'CSS',
2161
- color: 'magenta',
2162
- chunks: []
2163
- },
2164
- {
2165
- type: 'JS',
2166
- color: 'cyan',
2167
- chunks: []
2168
- }
2169
- ], 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;
2170
- logUpdate('computing gzip size...'), await Promise.all(assets.map(async ([assetName, value])=>{
2171
- let content, compressedSize, filePath = assetName.split('?')[0];
2172
- try {
2173
- content = value.source();
2174
- } catch {
2175
- content = node_fs.readFileSync(node_path.join(distPath, filePath));
2176
- }
2177
- let size = Buffer.byteLength(content);
2178
- compressedSize = COMPRESSIBLE_REGEX.test(filePath) ? await getCompressedSize(content) : size, totalSize += size, totalCompressedSize += compressedSize;
2179
- let chunk = {
2180
- name: node_path.basename(filePath),
2181
- path: `${distFolder}/${filePath}`,
2182
- size,
2183
- compressedSize
2184
- };
2185
- switch(chunk.path.length > longest && (longest = chunk.path.length), node_path.extname(filePath)){
2186
- case '.html':
2187
- chunkGroupMap.HTML.chunks.push(chunk);
2188
- break;
2189
- case '.css':
2190
- chunkGroupMap.CSS.chunks.push(chunk);
2191
- break;
2182
+ }))(depInfo)));
2183
+ ((cache)=>{
2184
+ if (0 === Object.keys(cache).length) {
2185
+ node_fs.existsSync(failedDepsJsonPath) && node_fs.unlinkSync(failedDepsJsonPath);
2186
+ return;
2187
+ }
2188
+ let cacheDir = node_path.dirname(failedDepsJsonPath);
2189
+ node_fs.existsSync(cacheDir) || node_fs.mkdirSync(cacheDir, {
2190
+ recursive: !0
2191
+ }), node_fs.writeFileSync(failedDepsJsonPath, JSON.stringify(cache, null, 2), 'utf-8');
2192
+ })(failedCache);
2193
+ let externals1 = {};
2194
+ bundledDeps.filter(Boolean).forEach((dep)=>{
2195
+ dep && (externals1[dep.name] = getExternalValue(dep.name), dep.assets.forEach((absPath)=>{
2196
+ let relativePath = node_path.relative(bundledDepsCachePath, absPath), serverPath = `/umd/${relativePath}`;
2197
+ switch(node_path.extname(relativePath)){
2192
2198
  case '.js':
2193
- case '.wasm':
2194
- chunkGroupMap.JS.chunks.push(chunk);
2199
+ FRAMEWORKS.includes(dep.name) ? preJsAssets.push({
2200
+ path: serverPath,
2201
+ order: FRAMEWORKS.indexOf(dep.name)
2202
+ }) : jsAssets.push(serverPath);
2195
2203
  break;
2196
- default:
2197
- chunkGroupMap.Assets.chunks.push(chunk);
2204
+ case '.css':
2205
+ ignoreCSSDeps.includes(dep.name) || cssAssets.push(serverPath);
2206
+ }
2207
+ }));
2208
+ });
2209
+ let existingExternals = config.externals ? Array.isArray(config.externals) ? config.externals : [
2210
+ config.externals
2211
+ ] : [];
2212
+ return config.externals = [
2213
+ externals1,
2214
+ ...existingExternals
2215
+ ], shouldTransformDeepImport && (plugin.transform = {
2216
+ filter: {
2217
+ test: JSX_REGEX
2218
+ },
2219
+ handler: (code)=>SPECIAL_NO_ENTRY_DEPS.some((pkg)=>code.includes(pkg)) ? code.replace(deepImportRegex, (_, localName, importPath, pkgName)=>{
2220
+ let exportName = pathToExportIdentifier(importPath.slice(pkgName.length + 1));
2221
+ return `import { ${exportName} as ${localName} } from '${pkgName}'`;
2222
+ }) : null
2223
+ }), config;
2224
+ },
2225
+ transformHtml: (html)=>injectToHead(html, preJsAssets.sort((a, b)=>a.order - b.order).map((item)=>item.path).map((item)=>`<script defer src="${item}"></script>`).join('')),
2226
+ setupMiddlewares: (middlewares)=>[
2227
+ (req, res, next)=>{
2228
+ if ('string' != typeof req.url) return void next();
2229
+ let url = new URL(req.url, 'http://localhost');
2230
+ if (!url.pathname.startsWith("/umd/")) return void next();
2231
+ let relativePath = url.pathname.replace("/umd/", '');
2232
+ if (relativePath.includes('..')) {
2233
+ res.statusCode = 403, res.end();
2234
+ return;
2235
+ }
2236
+ let filePath = node_path.join(bundledDepsCachePath, relativePath);
2237
+ if (!node_fs.existsSync(filePath)) return void next();
2238
+ let stat = node_fs.statSync(filePath);
2239
+ if (!stat.isFile()) return void next();
2240
+ let mtime = stat.mtime.toUTCString(), ext = node_path.extname(filePath);
2241
+ if (res.setHeader('Cache-Control', 'no-cache'), res.setHeader('Last-Modified', mtime), '.js' === ext && res.setHeader('Content-Type', "application/javascript"), '.css' === ext && res.setHeader('Content-Type', 'text/css'), req.headers['if-modified-since'] === mtime) {
2242
+ res.statusCode = 304, res.end();
2243
+ return;
2198
2244
  }
2199
- })), logUpdate(`✓ computed gzip size (${assets.length})`), console.log();
2200
- let sizePad = displaySize(totalSize).length, compressPad = displaySize(totalCompressedSize).length;
2201
- chunkGroups.forEach((group)=>{
2202
- group.chunks.sort((a, b)=>a.size - b.size).forEach((chunk)=>{
2203
- let isLarge = 'JS' === group.type && chunk.size / 1000 > 500, relativeOutDir = node_path.dirname(chunk.path) + '/', log = colors.dim(relativeOutDir);
2204
- log += colors[group.color](chunk.name.padEnd(longest + 2 - relativeOutDir.length)), log += colors[isLarge ? 'yellow' : 'dim'](displaySize(chunk.size).padStart(sizePad)), console.log(log += colors.dim(` │ gzip: ${displaySize(chunk.compressedSize).padStart(compressPad)}`));
2245
+ res.statusCode = 200, node_fs.createReadStream(filePath).pipe(res);
2246
+ },
2247
+ ...middlewares
2248
+ ],
2249
+ bundlerConfig: (config)=>{
2250
+ let PLUGIN_NAME = 'InjectAssetsPlugin';
2251
+ return config.plugins.push({
2252
+ apply: (compiler)=>{
2253
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
2254
+ rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeAssetTagGeneration.tapPromise(PLUGIN_NAME, async (args)=>(args.assets.js.unshift(...jsAssets), args.assets.css.unshift(...cssAssets), args));
2205
2255
  });
2256
+ }
2257
+ }), config;
2258
+ }
2259
+ }),
2260
+ (root = '', {
2261
+ name: 'unpack:file-size',
2262
+ apply: (config, { mode })=>'production' === mode && config.performance?.printFileSize,
2263
+ configResolved (config) {
2264
+ root = config.root;
2265
+ },
2266
+ buildEnd: async (options)=>{
2267
+ let { stats } = options;
2268
+ if (stats.hasErrors()) return;
2269
+ let chunkGroups = [
2270
+ {
2271
+ type: 'HTML',
2272
+ color: 'green',
2273
+ chunks: []
2274
+ },
2275
+ {
2276
+ type: 'Assets',
2277
+ color: 'yellow',
2278
+ chunks: []
2279
+ },
2280
+ {
2281
+ type: 'CSS',
2282
+ color: 'magenta',
2283
+ chunks: []
2284
+ },
2285
+ {
2286
+ type: 'JS',
2287
+ color: 'cyan',
2288
+ chunks: []
2289
+ }
2290
+ ], 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;
2291
+ logUpdate('computing gzip size...'), await Promise.all(assets.map(async ([assetName, value])=>{
2292
+ let content, compressedSize, filePath = assetName.split('?')[0];
2293
+ try {
2294
+ content = value.source();
2295
+ } catch {
2296
+ content = node_fs.readFileSync(node_path.join(distPath, filePath));
2297
+ }
2298
+ let size = Buffer.byteLength(content);
2299
+ compressedSize = COMPRESSIBLE_REGEX.test(filePath) ? await getCompressedSize(content) : size, totalSize += size, totalCompressedSize += compressedSize;
2300
+ let chunk = {
2301
+ name: node_path.basename(filePath),
2302
+ path: `${distFolder}/${filePath}`,
2303
+ size,
2304
+ compressedSize
2305
+ };
2306
+ switch(chunk.path.length > longest && (longest = chunk.path.length), node_path.extname(filePath)){
2307
+ case '.html':
2308
+ chunkGroupMap.HTML.chunks.push(chunk);
2309
+ break;
2310
+ case '.css':
2311
+ chunkGroupMap.CSS.chunks.push(chunk);
2312
+ break;
2313
+ case '.js':
2314
+ case '.wasm':
2315
+ chunkGroupMap.JS.chunks.push(chunk);
2316
+ break;
2317
+ default:
2318
+ chunkGroupMap.Assets.chunks.push(chunk);
2319
+ }
2320
+ })), logUpdate(`✓ computed gzip size (${assets.length})`), console.log();
2321
+ let sizePad = displaySize(totalSize).length, compressPad = displaySize(totalCompressedSize).length;
2322
+ chunkGroups.forEach((group)=>{
2323
+ group.chunks.sort((a, b)=>a.size - b.size).forEach((chunk)=>{
2324
+ let isLarge = 'JS' === group.type && chunk.size / 1000 > 500, relativeOutDir = node_path.dirname(chunk.path) + '/', log = colors.dim(relativeOutDir);
2325
+ log += colors[group.color](chunk.name.padEnd(longest + 2 - relativeOutDir.length)), log += colors[isLarge ? 'yellow' : 'dim'](displaySize(chunk.size).padStart(sizePad)), console.log(log += colors.dim(` │ gzip: ${displaySize(chunk.compressedSize).padStart(compressPad)}`));
2206
2326
  });
2207
- let log = colors.blue('Total'.padEnd(longest + 2));
2208
- log += colors.blue(displaySize(totalSize)), console.log(log += colors.dim(` │ gzip: ${displaySize(totalCompressedSize)}`));
2327
+ });
2328
+ let log = colors.blue('Total'.padEnd(longest + 2));
2329
+ log += colors.blue(displaySize(totalSize)), console.log(log += colors.dim(` │ gzip: ${displaySize(totalCompressedSize)}`));
2330
+ }
2331
+ })
2332
+ ]
2333
+ }, userConfig);
2334
+ return mergedConfig.svgIcons && mergedConfig.plugins?.push((options = mergedConfig.svgIcons, rootPath1 = '', inject = options.inject || 'body-last', domId = options.customDomId || '__svg__icons__dom__', registerCode = '', namesCode = '', virtualModules = null, ensureVirtualModules = ()=>{
2335
+ let root;
2336
+ if (!rootPath1) return;
2337
+ let { svg, names } = ((iconDirs, symbolId, customDomId)=>{
2338
+ let symbols = [], names = [], idSet = new Set();
2339
+ for (let dir of iconDirs)for (let file of readSvgFiles(dir)){
2340
+ let { inner, viewBox } = extractSvgContent(normalizeSvg(node_fs.readFileSync(file, 'utf-8'))), id = toSymbolId(file, dir, symbolId);
2341
+ !id || idSet.has(id) || (idSet.add(id), names.push(id), symbols.push(`<symbol id="${id}"${viewBox ? ` viewBox="${viewBox}"` : ''}>${inner}</symbol>`));
2342
+ }
2343
+ return {
2344
+ svg: `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="${customDomId}" style="position: absolute; width: 0; height: 0" aria-hidden="true">${symbols.join('')}</svg>`,
2345
+ names
2346
+ };
2347
+ })((root = rootPath1, (options.iconDirs || []).map((dir)=>node_path.isAbsolute(dir) ? dir : node_path.resolve(root, dir))), options.symbolId, domId);
2348
+ registerCode = `const svgDomId = ${JSON.stringify(domId)}\nconst svgHtml = ${JSON.stringify(svg)}\nconst inject = (position) => {\n if (typeof document === 'undefined') return\n if (document.getElementById(svgDomId)) return\n const div = document.createElement('div')\n div.innerHTML = svgHtml\n const svgEl = div.firstElementChild\n if (!svgEl) return\n if (position === 'head' && document.head) {\n document.head.prepend(svgEl)\n return\n }\n const body = document.body\n if (!body) return\n if (position === 'body-first' && body.firstChild) {\n body.insertBefore(svgEl, body.firstChild)\n } else {\n body.appendChild(svgEl)\n }\n}\nconst mount = () => inject(${JSON.stringify(inject)})\nif (typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', mount)\n } else {\n mount()\n }\n}\nexport default mount`, namesCode = `export const svgIconNames = ${JSON.stringify(names)}\nexport default svgIconNames`;
2349
+ }, {
2350
+ name: 'unpack:svg-icons',
2351
+ configResolved: (config)=>{
2352
+ rootPath1 = config.root || process.cwd(), ensureVirtualModules();
2353
+ },
2354
+ bundlerConfig: (config, { mergeConfig })=>(virtualModules || (virtualModules = new rspack.experiments.VirtualModulesPlugin({
2355
+ [REGISTER_ID]: registerCode || 'export default null',
2356
+ [NAMES_ID]: namesCode || 'export default []'
2357
+ })), mergeConfig(config, {
2358
+ plugins: [
2359
+ virtualModules,
2360
+ {
2361
+ apply: (compiler)=>{
2362
+ compiler.hooks.thisCompilation.tap('UnpackSvgIconsVirtualModules', ()=>{
2363
+ ensureVirtualModules(), virtualModules?.writeModule?.(REGISTER_ID, registerCode || 'export default null'), virtualModules?.writeModule?.(NAMES_ID, namesCode || 'export default []');
2364
+ });
2365
+ }
2209
2366
  }
2210
- })
2211
- ]
2212
- }, userConfig),
2367
+ ]
2368
+ })),
2369
+ transform: {
2370
+ filter: {
2371
+ test: JS_REGEX
2372
+ },
2373
+ handler: (code)=>code.includes('virtual:svg-icons-') ? code.replace('virtual:svg-icons-', 'virtual-svg-icons-') : null
2374
+ }
2375
+ })), {
2376
+ ...mergedConfig,
2213
2377
  _context
2214
2378
  };
2215
2379
  };
@@ -2218,7 +2382,7 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
2218
2382
  let mode = watch ? 'development' : 'production';
2219
2383
  setNodeEnv(mode);
2220
2384
  let config = resolveConfig(mode);
2221
- console.log(colors.brand(`${callerName} v4.0.0${config.performance?.cache ? ' ϟ' : ''}`), colors.cyan(`building for ${mode}...`)), await unpackBuild(config);
2385
+ console.log(colors.brand(`${callerName} v4.1.0${config.performance?.cache ? ' ϟ' : ''}`), colors.cyan(`building for ${mode}...`)), await unpackBuild(config);
2222
2386
  },
2223
2387
  dev: async ()=>{
2224
2388
  setUnpackStartTime(performance.now());
@@ -2236,7 +2400,7 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
2236
2400
  let GLOB_REGEX = /[*?{}[\]()!@+|]/;
2237
2401
  async function createChokidar(pathOrGlobs, root = process.cwd(), options) {
2238
2402
  let watchFiles = new Set(), globPatterns = pathOrGlobs.filter((pathOrGlob)=>!!GLOB_REGEX.test(pathOrGlob) || (watchFiles.add(pathOrGlob), !1));
2239
- if (globPatterns.length) for (let file of (await glob(globPatterns, {
2403
+ if (globPatterns.length) for (let file of (await external_tinyglobby_glob(globPatterns, {
2240
2404
  cwd: root,
2241
2405
  absolute: !0
2242
2406
  })))watchFiles.add(file);
@@ -2246,6 +2410,14 @@ async function createChokidar(pathOrGlobs, root = process.cwd(), options) {
2246
2410
  ...options
2247
2411
  });
2248
2412
  }
2413
+ var injectFramework_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
2414
+ async function injectFrameworkPluginForDebug(userConfig) {
2415
+ var plugin;
2416
+ let raw, framework, framework1 = (raw = process.env.FRAMEWORK, (framework = raw?.trim().toLowerCase()) ? 'react' === framework || 'vue' === framework ? framework : (logger_logger.warn(`Unknown FRAMEWORK "${raw}", fallback to "react".`), 'react') : 'react'), pluginPath = node_path.resolve(injectFramework_dirname, `../../plugin-${framework1}/dist/index.js`);
2417
+ node_fs.existsSync(pluginPath) && (plugin = (0, (await import(pluginPath))[`plugin${framework1.charAt(0).toUpperCase() + framework1.slice(1)}`])(), userConfig.plugins ? userConfig.plugins.unshift(plugin) : userConfig.plugins = [
2418
+ plugin
2419
+ ]);
2420
+ }
2249
2421
  async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls, restartServer }) {
2250
2422
  let shortcuts = [
2251
2423
  restartServer ? {
@@ -2298,7 +2470,6 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
2298
2470
  for (let shortcut of shortcuts)if (input === shortcut.key) return void shortcut.action();
2299
2471
  }), addRestartCleaner(()=>rl.close());
2300
2472
  }
2301
- var cli_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
2302
2473
  let withErrorHandling = (action)=>async (options)=>{
2303
2474
  try {
2304
2475
  await action(options);
@@ -2311,14 +2482,8 @@ async function setupUnpack(cliOptions, command) {
2311
2482
  let userConfig = await loadConfig({
2312
2483
  cliOptions,
2313
2484
  command
2314
- }), pluginReactPath = node_path.resolve(cli_dirname, '../../plugin-react/dist/index.js');
2315
- if (node_fs.existsSync(pluginReactPath)) {
2316
- let { pluginReact } = await import(pluginReactPath);
2317
- userConfig.plugins ? userConfig.plugins.unshift(pluginReact()) : userConfig.plugins = [
2318
- pluginReact()
2319
- ];
2320
- }
2321
- return {
2485
+ });
2486
+ return await injectFrameworkPluginForDebug(userConfig), {
2322
2487
  unpack: createUnpack({
2323
2488
  cwd: userConfig.root,
2324
2489
  config: userConfig
@@ -2366,7 +2531,7 @@ function runCLI() {
2366
2531
  logger_logger.clear(), logger_logger.info(`${node_path.basename(file)} changed, restarting server...`), await watcher.close(), await cleanUpBeforeRestart(), startServer(options);
2367
2532
  });
2368
2533
  });
2369
- 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.0.0"), cli.parse();
2534
+ 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.1.0"), cli.parse();
2370
2535
  }
2371
2536
  var src_CSS_MODULES_NAMED_EXPORT = !1;
2372
- 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, esVersionToBrowserslist, findExists, getAddressUrls, getCompiledPkgPath, getCurrentUnpackConfig, getHtmlTemplateOrContent, getIpv4Interfaces, getNodeEnv, getOrSetDefault, getPathInJs, getPort, getTime, getUnpackStartTime, getUserDepPath, getUserDepVersion, injectToHead, isBoolean, isDebug, isDev, isEmptyDir, isFileExists, isFileSync, isFunction, isNodeVersionAtLeast, isObject, isPlainObject, isRegExp, isString, isUndefined, isWatch, isWin, launchEditor, loadConfig, 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 };
2537
+ 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, 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, isWatch, isWin, launchEditor, loadConfig, 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 };