@unpackjs/core 3.7.8 → 3.8.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.
Files changed (51) hide show
  1. package/compiled/css-loader/index.js +20 -20
  2. package/compiled/less-loader/index.js +8 -8
  3. package/compiled/postcss-loader/index.js +8 -8
  4. package/compiled/sass-loader/index.js +8 -8
  5. package/dist/index.js +834 -562
  6. package/dist/rslib-runtime.js +15 -0
  7. package/dist/transformLoader.js +11 -0
  8. package/dist/{typedCssModulesLoader.mjs → typedCssModulesLoader.js} +5 -13
  9. package/dist-types/bundler-config/cache.d.ts.map +1 -1
  10. package/dist-types/bundler-config/html.d.ts +6 -0
  11. package/dist-types/bundler-config/html.d.ts.map +1 -0
  12. package/dist-types/bundler-config/index.d.ts.map +1 -1
  13. package/dist-types/bundler-config/loaders/transformLoader.d.ts +5 -0
  14. package/dist-types/bundler-config/loaders/transformLoader.d.ts.map +1 -0
  15. package/dist-types/bundler-config/plugins/progress/helpers.d.ts.map +1 -1
  16. package/dist-types/bundler-config/plugins/progress/index.d.ts +2 -2
  17. package/dist-types/bundler-config/plugins/progress/index.d.ts.map +1 -1
  18. package/dist-types/bundler-config/plugins/registerHooks.d.ts +6 -0
  19. package/dist-types/bundler-config/plugins/registerHooks.d.ts.map +1 -0
  20. package/dist-types/constants.d.ts +3 -0
  21. package/dist-types/constants.d.ts.map +1 -1
  22. package/dist-types/createUnpack.d.ts +4 -1
  23. package/dist-types/createUnpack.d.ts.map +1 -1
  24. package/dist-types/global.d.ts +4 -2
  25. package/dist-types/global.d.ts.map +1 -1
  26. package/dist-types/index.d.ts +1 -0
  27. package/dist-types/index.d.ts.map +1 -1
  28. package/dist-types/plugin.d.ts +4 -1
  29. package/dist-types/plugin.d.ts.map +1 -1
  30. package/dist-types/plugins/browserLogs.d.ts +3 -0
  31. package/dist-types/plugins/browserLogs.d.ts.map +1 -0
  32. package/dist-types/plugins/fileSize.d.ts +3 -0
  33. package/dist-types/plugins/fileSize.d.ts.map +1 -0
  34. package/dist-types/plugins/prebundle.d.ts +3 -0
  35. package/dist-types/plugins/prebundle.d.ts.map +1 -0
  36. package/dist-types/run/dev.d.ts +4 -1
  37. package/dist-types/run/dev.d.ts.map +1 -1
  38. package/dist-types/types/config.d.ts +24 -26
  39. package/dist-types/types/config.d.ts.map +1 -1
  40. package/dist-types/types/plugin.d.ts +22 -2
  41. package/dist-types/types/plugin.d.ts.map +1 -1
  42. package/dist-types/utils.d.ts +13 -1
  43. package/dist-types/utils.d.ts.map +1 -1
  44. package/package.json +9 -7
  45. package/dist/transformDeepImportLoader.mjs +0 -82
  46. package/dist-types/bundler-config/loaders/transformDeepImportLoader.d.ts +0 -5
  47. package/dist-types/bundler-config/loaders/transformDeepImportLoader.d.ts.map +0 -1
  48. package/dist-types/prebundleDeps.d.ts +0 -5
  49. package/dist-types/prebundleDeps.d.ts.map +0 -1
  50. package/dist-types/reporter.d.ts +0 -8
  51. package/dist-types/reporter.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -5,37 +5,31 @@ import { fileURLToPath as __rspack_fileURLToPath, pathToFileURL } from "node:url
5
5
  import node_path, { dirname as __rspack_dirname, join, sep } from "node:path";
6
6
  import * as __rspack_external__compiled_launch_editor_index_js_29002383 from "../compiled/launch-editor/index.js";
7
7
  import * as __rspack_external__compiled_webpack_merge_index_js_efd91626 from "../compiled/webpack-merge/index.js";
8
+ import { __webpack_require__ } from "./rslib-runtime.js";
8
9
  import { rspack } from "@rspack/core";
9
10
  import node_readline from "node:readline";
10
11
  import node_fs from "node:fs";
11
12
  import node_net from "node:net";
12
13
  import node_os, { platform } from "node:os";
13
14
  import portfinder from "portfinder";
14
- import { expand } from "dotenv-expand";
15
- import node_assert from "node:assert";
16
- import { glob, globSync } from "tinyglobby";
17
15
  import { promisify } from "node:util";
16
+ import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
17
+ import { parse } from "stacktrace-parser";
18
18
  import node_zlib from "node:zlib";
19
+ import { glob, globSync } from "tinyglobby";
20
+ import { expand } from "dotenv-expand";
21
+ import node_assert from "node:assert";
19
22
  import { RspackDevServer } from "@rspack/dev-server";
20
23
  import { exec, spawn } from "node:child_process";
21
- import node_http from "node:http";
22
24
  import chokidar from "chokidar";
23
- var LogColor, __webpack_modules__ = {
25
+ __webpack_require__.add({
24
26
  "compiled/launch-editor" (module) {
25
27
  module.exports = __rspack_external__compiled_launch_editor_index_js_29002383;
26
28
  },
27
29
  "compiled/webpack-merge" (module) {
28
30
  module.exports = __rspack_external__compiled_webpack_merge_index_js_efd91626;
29
31
  }
30
- }, __webpack_module_cache__ = {};
31
- function __webpack_require__(moduleId) {
32
- var cachedModule = __webpack_module_cache__[moduleId];
33
- if (void 0 !== cachedModule) return cachedModule.exports;
34
- var module = __webpack_module_cache__[moduleId] = {
35
- exports: {}
36
- };
37
- return __webpack_modules__[moduleId](module, module.exports, __webpack_require__), module.exports;
38
- }
32
+ });
39
33
  let isCI = !!process.env.CI, isTTY = !!process.stdout?.isTTY, noColor = !!process.env.NO_COLOR, forceColor = !!process.env.FORCE_COLOR, disableColor = !1;
40
34
  disableColor = !!noColor || !forceColor && (isCI || !isTTY);
41
35
  let ANSI_SGR_RE = /\x1b\[[0-9;]*m/g, ANSI_OPEN_RE = /\x1b\[([0-9;]+)m/g, COLOR_HEX = {
@@ -106,10 +100,12 @@ let restartCleaners = [], addRestartCleaner = (...cleaners)=>{
106
100
  restartCleaners.push(...cleaners);
107
101
  }, cleanUpBeforeRestart = async ()=>{
108
102
  await Promise.all(restartCleaners.map((cleaner)=>cleaner())), restartCleaners.length = 0;
109
- }, currentDevUnpackConfig = {}, setCurrentDevUnpackConfig = (config)=>{
110
- currentDevUnpackConfig = config;
103
+ }, currentUnpackConfig = {}, getCurrentUnpackConfig = ()=>currentUnpackConfig, setCurrentUnpackConfig = (config)=>{
104
+ currentUnpackConfig = config;
105
+ }, unpackStartTime = 0, getUnpackStartTime = ()=>unpackStartTime, setUnpackStartTime = (time)=>{
106
+ unpackStartTime = time;
111
107
  };
112
- var logger_LogColor = ((LogColor = {}).error = "red", LogColor.warn = "yellow", LogColor.info = "cyan", LogColor.ready = "green", LogColor.event = "magenta", LogColor.wait = "blue", LogColor);
108
+ var LogColor, logger_LogColor = ((LogColor = {}).error = "red", LogColor.warn = "yellow", LogColor.info = "cyan", LogColor.ready = "green", LogColor.event = "magenta", LogColor.wait = "blue", LogColor);
113
109
  let CSS_MODULES_LOCAL_IDENT_NAME = '[path][name]__[local]--[hash:5]', CSS_MODULES_REGEX = /\.module\.\w+$/i, DEV_DEFAULT_FILENAME = {
114
110
  js: 'js/[name].js',
115
111
  jsAsync: 'js/async/[name].js',
@@ -121,22 +117,17 @@ let CSS_MODULES_LOCAL_IDENT_NAME = '[path][name]__[local]--[hash:5]', CSS_MODULE
121
117
  css: 'css/[name].[contenthash:8].css',
122
118
  cssAsync: 'css/async/[name].[contenthash:8].css'
123
119
  }, EXPORT_LOCALS_CONVENTION = 'camel-case-only', NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, DEFAULT_DEV_HOST = '0.0.0.0', TEMPLATE_CONTENT = ({ title = '', headTag = '', mountId = '' })=>`<!DOCTYPE html>
124
- <html lang="en">
125
-
126
- <head>
127
- <meta charset="UTF-8" />
128
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
129
- <title>
130
- ${title}
131
- </title>
132
- ${headTag}
133
- </head>
134
-
135
- <body>
136
- <div id="${mountId}"></div>
137
- </body>
138
-
139
- </html>`;
120
+ <html>
121
+ <head>
122
+ <meta charset="UTF-8">
123
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
124
+ <title>${title}</title>
125
+ ${headTag}
126
+ </head>
127
+ <body>
128
+ <div id="${mountId}"></div>
129
+ </body>
130
+ </html>`, JS_REGEX = /\.[jt]s$/, JSX_REGEX = /\.[jt]sx$/, SCRIPT_REGEX = /\.[jt]sx?$/;
140
131
  var utils_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
141
132
  let { merge: mergeConfig } = __webpack_require__("compiled/webpack-merge"), { default: launchEditor } = __webpack_require__("compiled/launch-editor"), getNodeEnv = ()=>process.env.NODE_ENV, setNodeEnv = (env)=>{
142
133
  process.env.NODE_ENV = env;
@@ -169,7 +160,11 @@ let { merge: mergeConfig } = __webpack_require__("compiled/webpack-merge"), { de
169
160
  }, (_, port)=>{
170
161
  resolve(port);
171
162
  });
172
- }), getCompiledPkgPath = (packageName)=>node_path.join(utils_dirname, '../compiled', packageName), getUserDepPath = (root, deps)=>{
163
+ }), normalizePublicPath = (base)=>{
164
+ if (!base) return '/';
165
+ let normalized = base;
166
+ return normalized.startsWith('/') || (normalized = `/${normalized}`), normalized.endsWith('/') || (normalized = `${normalized}/`), normalized;
167
+ }, getCompiledPkgPath = (packageName)=>node_path.join(utils_dirname, '../compiled', packageName), getUserDepPath = (root, deps)=>{
173
168
  for (let dep of Array.isArray(deps) ? deps : [
174
169
  deps
175
170
  ]){
@@ -200,14 +195,15 @@ let debounce = (fn, delay)=>{
200
195
  '127.0.0.1',
201
196
  '::1',
202
197
  '0000:0000:0000:0000:0000:0000:0000:0001'
203
- ].includes(host), concatUrl = ({ host, port, protocol })=>`${protocol}://${host}:${port}/`, LOCAL_LABEL = 'Local: ', NETWORK_LABEL = 'Network: ', getAddressUrls = ({ protocol = 'http', port, host })=>{
198
+ ].includes(host), concatUrl = ({ host, port, protocol, base })=>`${protocol}://${host}:${port}${normalizePublicPath(base)}`, LOCAL_LABEL = 'Local: ', NETWORK_LABEL = 'Network: ', getAddressUrls = ({ protocol = 'http', port, host, base })=>{
204
199
  if (host && host !== DEFAULT_DEV_HOST) return [
205
200
  {
206
201
  label: isLoopbackHost(host) ? LOCAL_LABEL : NETWORK_LABEL,
207
202
  url: concatUrl({
208
203
  port,
209
204
  host: node_net.isIPv6(host) ? '::' === host ? '[::1]' : `[${host}]` : host,
210
- protocol
205
+ protocol,
206
+ base
211
207
  })
212
208
  }
213
209
  ];
@@ -219,7 +215,8 @@ let debounce = (fn, delay)=>{
219
215
  url: concatUrl({
220
216
  host: 'localhost',
221
217
  port,
222
- protocol
218
+ protocol,
219
+ base
223
220
  })
224
221
  }), hasLocalUrl = !0;
225
222
  } else addressUrls.push({
@@ -227,7 +224,8 @@ let debounce = (fn, delay)=>{
227
224
  url: concatUrl({
228
225
  host: detail.address,
229
226
  port,
230
- protocol
227
+ protocol,
228
+ base
231
229
  })
232
230
  });
233
231
  return addressUrls;
@@ -314,7 +312,33 @@ function pLimit(concurrency = Math.max(1, node_os.cpus().length - 1)) {
314
312
  let pathToExportIdentifier = (path)=>{
315
313
  let name = path.replace(/[^a-zA-Z0-9_$]+([a-zA-Z0-9_$])/g, (_, char)=>char.toUpperCase()).replace(/[^a-zA-Z0-9_$]/g, '');
316
314
  return (!(name = name.charAt(0).toUpperCase() + name.slice(1)) || /^[^a-zA-Z_$]/.test(name)) && (name = `_${name}`), name;
317
- }, logger_prefixes = {
315
+ };
316
+ function printServerUrls({ port, host, base }) {
317
+ let addressUrls = getAddressUrls({
318
+ port,
319
+ base
320
+ }), colorPrefix = colors.brand('➜');
321
+ addressUrls.forEach((addr, index)=>{
322
+ let url;
323
+ if (!host && 0 !== index) {
324
+ 1 === index && console.log(` ${colors.dim(colorPrefix)} ${colors.bold(colors.dim('Network:'))} ${colors.dim('use')} ${colors.bold('--host')} ${colors.dim('to expose')}`);
325
+ return;
326
+ }
327
+ console.log(` ${colorPrefix} ${colors.bold(addr.label)}${(url = addr.url, colors.cyan(url.replace(/:(\d+)\//, (_, port)=>`:${colors.bold(port)}/`)))}`);
328
+ });
329
+ }
330
+ function getHtmlTemplateOrContent(rawTemplate, root) {
331
+ let template, templateContent;
332
+ if ('string' == typeof rawTemplate) {
333
+ let absPath = node_path.isAbsolute(rawTemplate) ? rawTemplate : node_path.resolve(root, rawTemplate);
334
+ node_fs.existsSync(absPath) ? template = rawTemplate : templateContent = rawTemplate;
335
+ } else templateContent = 'function' == typeof rawTemplate ? rawTemplate : TEMPLATE_CONTENT;
336
+ return {
337
+ template,
338
+ templateContent
339
+ };
340
+ }
341
+ let injectToHead = (html, script)=>html.replace(/<head(\s*[^>]*)>/i, (match)=>`${match}${script}`), logger_prefixes = {
318
342
  wait: '○',
319
343
  error: '⨯',
320
344
  warn: '⚠',
@@ -507,13 +531,44 @@ let removeDir = (dir)=>{
507
531
  recursive: !0,
508
532
  force: !0
509
533
  });
510
- }, DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
511
- function getNormalizedPluginsByHook(hook, plugins) {
534
+ }, 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', {
535
+ maximumFractionDigits: 2,
536
+ minimumFractionDigits: 2
537
+ }), displaySize = (bytes)=>`${numberFormatter.format(bytes / 1000)} kB`;
538
+ async function getCompressedSize(content) {
539
+ return (await gzip(content)).length;
540
+ }
541
+ let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i, SPECIAL_NO_ENTRY_DEPS = [
542
+ '@iconify-icons/material-symbols'
543
+ ], getExternalLibraryName = (pkgName)=>{
544
+ let externalAlias = {
545
+ react: 'React',
546
+ 'react-dom': 'ReactDOM',
547
+ 'react-router-dom': 'ReactRouterDOM'
548
+ };
549
+ return externalAlias[pkgName] ? externalAlias[pkgName] : pkgName.replace(/^@/, '').split(/[/\-.]/).filter(Boolean).map((part)=>part.charAt(0).toUpperCase() + part.slice(1)).join('');
550
+ }, getExternalValue = (pkgName)=>`window ${getExternalLibraryName(pkgName)}`, DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
551
+ function getNormalizedPluginsByHook(hook) {
512
552
  let pluginMap = new Map();
513
- return plugins?.forEach((plugin)=>{
514
- plugin[hook] && pluginMap.set(plugin.name, plugin);
553
+ return getCurrentUnpackConfig().plugins?.forEach((plugin)=>{
554
+ ((plugin, hook)=>{
555
+ if (!plugin[hook]) return !1;
556
+ let apply = plugin.apply;
557
+ if (!apply) return !0;
558
+ let env = {
559
+ mode: getNodeEnv(),
560
+ command: utils_isDevServer() ? 'dev' : 'build'
561
+ };
562
+ return 'string' == typeof apply ? apply === env.command : !!apply(getCurrentUnpackConfig(), env);
563
+ })(plugin, hook) && pluginMap.set(plugin.name, plugin);
515
564
  }), Array.from(pluginMap.values());
516
565
  }
566
+ async function applyPluginsByHook(hook, runner) {
567
+ for (let plugin of getNormalizedPluginsByHook(hook)){
568
+ let impl = plugin[hook];
569
+ await runner(impl);
570
+ }
571
+ }
517
572
  async function applyBuildAnalyzeConfig({ config }) {
518
573
  let { RsdoctorRspackPlugin } = await import("@rsdoctor/rspack-plugin");
519
574
  return config.plugins?.push(new RsdoctorRspackPlugin()), config;
@@ -542,7 +597,7 @@ async function getBuildDependencies(root) {
542
597
  ]), buildDependencies;
543
598
  }
544
599
  async function applyCacheConfig({ config, unpackConfig, envFilePaths }) {
545
- let cacheConfig = isPlainObject(unpackConfig.build.cache) ? unpackConfig.build.cache : {}, buildDependencies = await getBuildDependencies(unpackConfig.root);
600
+ let cacheConfig = isPlainObject(unpackConfig.performance.cache) ? unpackConfig.performance.cache : {}, buildDependencies = await getBuildDependencies(unpackConfig.root);
546
601
  buildDependencies.userBuildDependencies = cacheConfig.buildDependencies || [], buildDependencies.envFilePaths = envFilePaths;
547
602
  let cacheDirectory = node_path.resolve(unpackConfig.root, cacheConfig.cacheDirectory || `${unpackConfig._context.cachePath}/cache`, utils_isDevServer() ? 'dev' : 'build');
548
603
  return mergeConfig(config, {
@@ -656,20 +711,40 @@ let getOutputFilename = ({ type, hash, async })=>{
656
711
  return async ? 'js' === type ? FILENAME.jsAsync : FILENAME.cssAsync : FILENAME[type];
657
712
  };
658
713
  var css_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
659
- function _define_property(obj, key, value) {
660
- return key in obj ? Object.defineProperty(obj, key, {
661
- value: value,
662
- enumerable: !0,
663
- configurable: !0,
664
- writable: !0
665
- }) : obj[key] = value, obj;
714
+ async function applyHtmlConfig({ config, unpackConfig }) {
715
+ if (!unpackConfig.mpa) {
716
+ let htmlConfig = unpackConfig.html || {}, { template, templateContent } = getHtmlTemplateOrContent(htmlConfig.template, unpackConfig.root), templateParameters = {
717
+ mountId: htmlConfig.mountId,
718
+ title: isFunction(htmlConfig.title) ? htmlConfig.title({
719
+ entryName: 'index'
720
+ }) : htmlConfig.title || '',
721
+ headTag: htmlConfig.headTag || '',
722
+ ...htmlConfig.templateParameters
723
+ };
724
+ config.plugins.push(new rspack.HtmlRspackPlugin({
725
+ template,
726
+ templateContent,
727
+ templateParameters,
728
+ minify: !1,
729
+ chunks: [
730
+ 'main'
731
+ ]
732
+ }));
733
+ }
734
+ return config;
666
735
  }
667
- let { RawSource, SourceMapSource } = rspack.sources, isJsFile = /\.[cm]?js(\?.*)?$/i, jsMinify_PLUGIN_NAME = 'JsMinifyPlugin';
736
+ let { RawSource: RawSource, SourceMapSource: SourceMapSource } = rspack.sources, isJsFile = /\.[cm]?js(\?.*)?$/i, jsMinify_PLUGIN_NAME = 'JsMinifyPlugin';
668
737
  class JsMinifyPlugin {
738
+ minifyOptions;
739
+ customMinify;
740
+ constructor(options = {}){
741
+ let { implementation, ...minifyOptions } = options;
742
+ this.customMinify = implementation?.minify, this.minifyOptions = minifyOptions;
743
+ }
669
744
  apply(compiler) {
670
745
  let meta = JSON.stringify({
671
746
  name: jsMinify_PLUGIN_NAME,
672
- version: "3.7.8",
747
+ version: "3.8.0",
673
748
  options: this.minifyOptions
674
749
  });
675
750
  compiler.hooks.compilation.tap(jsMinify_PLUGIN_NAME, (compilation)=>{
@@ -703,21 +778,23 @@ class JsMinifyPlugin {
703
778
  }
704
779
  }));
705
780
  }
706
- constructor(options = {}){
707
- _define_property(this, "minifyOptions", void 0), _define_property(this, "customMinify", void 0);
708
- let { implementation, ...minifyOptions } = options;
709
- this.customMinify = implementation?.minify, this.minifyOptions = minifyOptions;
710
- }
711
- }
712
- function loadingAnimation_define_property(obj, key, value) {
713
- return key in obj ? Object.defineProperty(obj, key, {
714
- value: value,
715
- enumerable: !0,
716
- configurable: !0,
717
- writable: !0
718
- }) : obj[key] = value, obj;
719
781
  }
720
782
  class LoadingAnimation {
783
+ chars = [
784
+ '⠋',
785
+ '⠙',
786
+ '⠹',
787
+ '⠸',
788
+ '⠼',
789
+ '⠴',
790
+ '⠦',
791
+ '⠧',
792
+ '⠇',
793
+ '⠏'
794
+ ];
795
+ currentIndex = 0;
796
+ lastUpdateTime = 0;
797
+ interval = 100;
721
798
  getCurrentChar() {
722
799
  let now = Date.now();
723
800
  return now - this.lastUpdateTime >= this.interval && (this.currentIndex = (this.currentIndex + 1) % this.chars.length, this.lastUpdateTime = now), this.chars[this.currentIndex];
@@ -725,110 +802,16 @@ class LoadingAnimation {
725
802
  reset() {
726
803
  this.currentIndex = 0, this.lastUpdateTime = 0;
727
804
  }
728
- constructor(){
729
- loadingAnimation_define_property(this, "chars", [
730
- '⠋',
731
- '⠙',
732
- '⠹',
733
- '⠸',
734
- '⠼',
735
- '⠴',
736
- '⠦',
737
- '⠧',
738
- '⠇',
739
- '⠏'
740
- ]), loadingAnimation_define_property(this, "currentIndex", 0), loadingAnimation_define_property(this, "lastUpdateTime", 0), loadingAnimation_define_property(this, "interval", 100);
741
- }
742
- }
743
- function progressBar_define_property(obj, key, value) {
744
- return key in obj ? Object.defineProperty(obj, key, {
745
- value: value,
746
- enumerable: !0,
747
- configurable: !0,
748
- writable: !0
749
- }) : obj[key] = value, obj;
750
805
  }
751
806
  class ProgressBar {
807
+ prefix = 'transforming';
808
+ loadingAnimation = new LoadingAnimation();
752
809
  update({ current: originalCurrent, message = '' }) {
753
810
  let { columns: terminalWidth } = process.stdout, current = originalCurrent;
754
811
  originalCurrent >= 0.98 && (current = 1);
755
812
  let loadingChar = this.loadingAnimation.getCurrentChar(), messageWidth = terminalWidth - this.prefix.length - (1 === current ? 10 : 9);
756
813
  logUpdate(`${loadingChar} ${this.prefix} (${Math.floor(100 * current)}%) ${colors.dim(message.slice(0, messageWidth).padEnd(messageWidth, ' '))}`), 1 === current && clearLine();
757
814
  }
758
- constructor(){
759
- progressBar_define_property(this, "prefix", 'transforming'), progressBar_define_property(this, "loadingAnimation", new LoadingAnimation());
760
- }
761
- }
762
- let gzip = promisify(node_zlib.gzip), numberFormatter = new Intl.NumberFormat('en', {
763
- maximumFractionDigits: 2,
764
- minimumFractionDigits: 2
765
- }), displaySize = (bytes)=>`${numberFormatter.format(bytes / 1000)} kB`;
766
- async function getCompressedSize(content) {
767
- return (await gzip(content)).length;
768
- }
769
- let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i;
770
- async function printFileSize({ root, stats }) {
771
- let chunkGroups = [
772
- {
773
- type: 'HTML',
774
- color: 'green',
775
- chunks: []
776
- },
777
- {
778
- type: 'Assets',
779
- color: 'yellow',
780
- chunks: []
781
- },
782
- {
783
- type: 'CSS',
784
- color: 'magenta',
785
- chunks: []
786
- },
787
- {
788
- type: 'JS',
789
- color: 'cyan',
790
- chunks: []
791
- }
792
- ], 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;
793
- logUpdate('computing gzip size...'), await Promise.all(assets.map(async ([assetName, value])=>{
794
- let content, compressedSize, filePath = assetName.split('?')[0];
795
- try {
796
- content = value.source();
797
- } catch {
798
- content = node_fs.readFileSync(node_path.join(distPath, filePath));
799
- }
800
- let size = Buffer.byteLength(content);
801
- compressedSize = COMPRESSIBLE_REGEX.test(filePath) ? await getCompressedSize(content) : size, totalSize += size, totalCompressedSize += compressedSize;
802
- let chunk = {
803
- name: node_path.basename(filePath),
804
- path: `${distFolder}/${filePath}`,
805
- size,
806
- compressedSize
807
- };
808
- switch(chunk.path.length > longest && (longest = chunk.path.length), node_path.extname(filePath)){
809
- case '.html':
810
- chunkGroupMap.HTML.chunks.push(chunk);
811
- break;
812
- case '.css':
813
- chunkGroupMap.CSS.chunks.push(chunk);
814
- break;
815
- case '.js':
816
- case '.wasm':
817
- chunkGroupMap.JS.chunks.push(chunk);
818
- break;
819
- default:
820
- chunkGroupMap.Assets.chunks.push(chunk);
821
- }
822
- })), logUpdate(`✓ computed gzip size (${assets.length})`), console.log();
823
- let sizePad = displaySize(totalSize).length, compressPad = displaySize(totalCompressedSize).length;
824
- chunkGroups.forEach((group)=>{
825
- group.chunks.sort((a, b)=>a.size - b.size).forEach((chunk)=>{
826
- let isLarge = 'JS' === group.type && chunk.size / 1000 > 500, relativeOutDir = node_path.dirname(chunk.path) + '/', log = colors.dim(relativeOutDir);
827
- 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)}`));
828
- });
829
- });
830
- let log = colors.blue('Total'.padEnd(longest + 2));
831
- log += colors.blue(displaySize(totalSize)), console.log(log += colors.dim(` │ gzip: ${displaySize(totalCompressedSize)}`));
832
815
  }
833
816
  function isLikelyFile(filePath) {
834
817
  return (filePath.split(sep).pop() || '').includes('.');
@@ -850,10 +833,7 @@ let getCompileTime = (stats)=>stats.toJson({
850
833
  }).time / 1000, sameCount = 0;
851
834
  async function compileDone(compiler, stats) {
852
835
  let root = compiler.options.context;
853
- if (!stats.hasErrors()) if (utils_isProd()) global.__unpack_config.performance?.printFileSize && await printFileSize({
854
- root,
855
- stats
856
- }), logger_logger.ready(colors.green(`built in ${prettyTime(getCompileTime(stats))}`));
836
+ if (!stats.hasErrors()) if (utils_isProd()) logger_logger.ready(colors.green(`built in ${prettyTime(getCompileTime(stats))}`));
857
837
  else {
858
838
  let fileInfo = function(changedFiles, removedFiles, root) {
859
839
  if (!changedFiles?.length && !removedFiles?.length) return null;
@@ -877,36 +857,58 @@ async function compileDone(compiler, stats) {
877
857
  logger_logger.debug(`${colors.cyan(packageName)}: ${colors.yellow(count)} modules`);
878
858
  });
879
859
  }
880
- isDebug() || logger_logger.clear(), console.log(colors.dim(getTime()), colors.cyan(`[${global.__unpack_caller_name}]`), colors.brand(utils_isDevServer() ? 'hmr update' : 'build'), `${colors.dim(fileInfo)}${sameCount > 1 ? ` ${colors.yellow(`(x${sameCount})`)}` : ''}`, isDebug() ? colors.dim(`| ${prettyTime(getCompileTime(stats))} (${stats.compilation.modules.size} modules)`) : '');
860
+ isDebug() || logger_logger.clear(), console.log(colors.dim(getTime()), colors.cyan(`[${getCurrentUnpackConfig()._context.callerName}]`), colors.brand(utils_isDevServer() ? 'hmr update' : 'build'), `${colors.dim(fileInfo)}${sameCount > 1 ? ` ${colors.yellow(`(x${sameCount})`)}` : ''}`, isDebug() ? colors.dim(`| ${prettyTime(getCompileTime(stats))} (${stats.compilation.modules.size} modules)`) : '');
881
861
  }
882
862
  }
883
863
  let progress_PLUGIN_NAME = 'ProgressPlugin';
884
- class ProgressLiteRspackPlugin {
864
+ class ProgressLitePlugin {
885
865
  apply(compiler) {
886
866
  compiler.hooks.afterDone.tap(progress_PLUGIN_NAME, async (stats)=>{
887
867
  await compileDone(compiler, stats);
888
868
  });
889
869
  }
890
870
  }
891
- class ProgressRspackPlugin extends rspack.ProgressPlugin {
892
- apply(compiler) {
893
- super.apply(compiler), compiler.hooks.afterDone.tap(progress_PLUGIN_NAME, async (stats)=>{
894
- await compileDone(compiler, stats);
895
- });
896
- }
871
+ class ProgressPlugin extends rspack.ProgressPlugin {
872
+ progressBar = new ProgressBar();
897
873
  constructor(){
898
- var key, value;
899
874
  super((percentage, msg, ...args)=>{
900
875
  utils_isProd() && this.progressBar.update({
901
876
  current: percentage,
902
877
  message: `${msg} ${args.join(' ')}`
903
878
  });
904
- }), key = "progressBar", value = new ProgressBar(), key in this ? Object.defineProperty(this, key, {
905
- value: value,
906
- enumerable: !0,
907
- configurable: !0,
908
- writable: !0
909
- }) : this[key] = value;
879
+ });
880
+ }
881
+ apply(compiler) {
882
+ super.apply(compiler), compiler.hooks.afterDone.tap(progress_PLUGIN_NAME, async (stats)=>{
883
+ await compileDone(compiler, stats);
884
+ });
885
+ }
886
+ }
887
+ let registerHooks_PLUGIN_NAME = 'RegisterHooksPlugin';
888
+ class RegisterHooksPlugin {
889
+ isFirstCompile = !0;
890
+ apply(compiler) {
891
+ compiler.hooks.beforeCompile.tapPromise(registerHooks_PLUGIN_NAME, async ()=>{
892
+ await applyPluginsByHook('buildStart', async (impl)=>{
893
+ await impl({
894
+ compiler,
895
+ isFirstCompile: this.isFirstCompile
896
+ });
897
+ });
898
+ }), compiler.hooks.done.tapPromise(registerHooks_PLUGIN_NAME, async (stats)=>{
899
+ await applyPluginsByHook('buildEnd', async (impl)=>{
900
+ await impl({
901
+ compiler,
902
+ isFirstCompile: this.isFirstCompile,
903
+ isWatch: isWatch(),
904
+ stats
905
+ });
906
+ }), this.isFirstCompile = !1;
907
+ }), compiler.hooks.compilation.tap(registerHooks_PLUGIN_NAME, (compilation)=>{
908
+ rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeEmit.tapPromise(registerHooks_PLUGIN_NAME, async (data)=>(await applyPluginsByHook('transformHtml', async (impl)=>{
909
+ data.html = await impl(data.html);
910
+ }), data));
911
+ });
910
912
  }
911
913
  }
912
914
  async function applyTypeCheckConfig({ config, unpackConfig }) {
@@ -938,19 +940,25 @@ async function applyTypeCheckConfig({ config, unpackConfig }) {
938
940
  }
939
941
  })), config;
940
942
  }
943
+ var bundler_config_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
941
944
  async function getBundlerConfig(originalUnpackConfig) {
945
+ setCurrentUnpackConfig(originalUnpackConfig);
942
946
  let { plugins, bundlerConfig, ...rest } = originalUnpackConfig;
943
- for (let plugin of getNormalizedPluginsByHook('config', plugins))rest = await plugin.config(rest, {
944
- ...originalUnpackConfig._context,
945
- mergeConfig: mergeConfig
947
+ await applyPluginsByHook('config', async (impl)=>{
948
+ rest = await impl(rest, {
949
+ ...originalUnpackConfig._context,
950
+ mergeConfig: mergeConfig
951
+ });
946
952
  });
947
953
  let unpackConfig = {
948
954
  ...rest,
949
955
  plugins,
950
956
  bundlerConfig
951
957
  };
952
- global.__unpack_config = unpackConfig;
953
- let tsconfigPath = node_path.resolve(unpackConfig.root, 'tsconfig.json'), isTs = node_fs.existsSync(tsconfigPath), minifyOptions = isPlainObject(unpackConfig.build?.minify) ? unpackConfig.build?.minify : {}, ProgressPlugin = unpackConfig.build?.progressBar ? ProgressRspackPlugin : ProgressLiteRspackPlugin, { publicVars, filePaths: envFilePaths } = function({ cwd = process.cwd(), mode = getNodeEnv(), prefixes = [
958
+ setCurrentUnpackConfig(unpackConfig), await applyPluginsByHook('configResolved', async (impl)=>{
959
+ await impl(unpackConfig);
960
+ });
961
+ 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 = [
954
962
  'PUBLIC_'
955
963
  ], processEnv = process.env } = {}) {
956
964
  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.`);
@@ -1018,14 +1026,14 @@ async function getBundlerConfig(originalUnpackConfig) {
1018
1026
  }),
1019
1027
  crossOriginLoading: 'anonymous',
1020
1028
  pathinfo: !1,
1021
- publicPath: unpackConfig.build?.publicPath,
1029
+ publicPath: unpackConfig.base,
1022
1030
  webassemblyModuleFilename: 'wasm/[contenthash:8].module.wasm',
1023
1031
  assetModuleFilename: 'assets/[name].[contenthash:8][ext]'
1024
1032
  },
1025
1033
  infrastructureLogging: {
1026
1034
  level: 'error'
1027
1035
  },
1028
- devtool: unpackConfig.build?.sourceMap,
1036
+ devtool: unpackConfig.sourceMap,
1029
1037
  module: {
1030
1038
  rules: [
1031
1039
  {
@@ -1055,22 +1063,6 @@ async function getBundlerConfig(originalUnpackConfig) {
1055
1063
  ...publicVars,
1056
1064
  ...unpackConfig.define
1057
1065
  }),
1058
- !unpackConfig.mpa && new rspack.HtmlRspackPlugin({
1059
- template: unpackConfig.html?.template || void 0,
1060
- templateContent: unpackConfig.html?.templateContent || (unpackConfig.html?.template ? void 0 : TEMPLATE_CONTENT),
1061
- templateParameters: {
1062
- mountId: unpackConfig.html.mountId,
1063
- title: isFunction(unpackConfig.html?.title) ? unpackConfig.html?.title({
1064
- entryName: 'index'
1065
- }) : unpackConfig.html?.title || '',
1066
- headTag: unpackConfig.html?.headTag || '',
1067
- ...unpackConfig.html?.templateParameters
1068
- },
1069
- minify: !1,
1070
- chunks: [
1071
- 'main'
1072
- ]
1073
- }),
1074
1066
  unpackConfig.performance?.removeMomentLocale && new rspack.IgnorePlugin({
1075
1067
  resourceRegExp: /^\.\/locale$/,
1076
1068
  contextRegExp: /moment$/
@@ -1078,7 +1070,8 @@ async function getBundlerConfig(originalUnpackConfig) {
1078
1070
  unpackConfig.build?.copy && new rspack.CopyRspackPlugin({
1079
1071
  patterns: unpackConfig.build.copy
1080
1072
  }),
1081
- new ProgressPlugin()
1073
+ new RegisterHooksPlugin(),
1074
+ unpackConfig.build?.progressBar ? new ProgressPlugin() : new ProgressLitePlugin()
1082
1075
  ].filter(Boolean),
1083
1076
  externals: unpackConfig.externals,
1084
1077
  resolve: {
@@ -1119,7 +1112,7 @@ async function getBundlerConfig(originalUnpackConfig) {
1119
1112
  },
1120
1113
  optimization: {
1121
1114
  moduleIds: isDev() ? 'named' : 'deterministic',
1122
- minimize: !!unpackConfig.build?.minify,
1115
+ minimize: !!unpackConfig.build?.minify && utils_isProd(),
1123
1116
  minimizer: [
1124
1117
  new JsMinifyPlugin(mergeConfig({
1125
1118
  compress: {
@@ -1139,8 +1132,23 @@ async function getBundlerConfig(originalUnpackConfig) {
1139
1132
  performance: {
1140
1133
  hints: !1
1141
1134
  }
1142
- };
1143
- for (let plugin of (config = (({ config, unpackConfig })=>{
1135
+ }, transformPlugins = getNormalizedPluginsByHook('transform');
1136
+ return transformPlugins.length && config.module.rules.push({
1137
+ test: SCRIPT_REGEX,
1138
+ enforce: 'pre',
1139
+ exclude: /node_modules/,
1140
+ use: [
1141
+ {
1142
+ loader: node_path.resolve(bundler_config_dirname, './transformLoader.js'),
1143
+ options: {
1144
+ plugins: transformPlugins
1145
+ }
1146
+ }
1147
+ ]
1148
+ }), config = await applyHtmlConfig({
1149
+ config,
1150
+ unpackConfig
1151
+ }), config = (({ config, unpackConfig })=>{
1144
1152
  let { chunkSplit } = unpackConfig.performance || {};
1145
1153
  if (chunkSplit?.strategy) {
1146
1154
  let forceSplittingGroups = {};
@@ -1304,7 +1312,7 @@ async function getBundlerConfig(originalUnpackConfig) {
1304
1312
  }
1305
1313
  },
1306
1314
  isDev() && {
1307
- loader: node_path.resolve(css_dirname, './typedCssModulesLoader.mjs'),
1315
+ loader: node_path.resolve(css_dirname, './typedCssModulesLoader.js'),
1308
1316
  options: {
1309
1317
  modules
1310
1318
  }
@@ -1404,7 +1412,7 @@ async function getBundlerConfig(originalUnpackConfig) {
1404
1412
  unpackConfig
1405
1413
  }),
1406
1414
  unpackConfig
1407
- }), unpackConfig.build?.cache && (config = await applyCacheConfig({
1415
+ }), unpackConfig.performance?.cache && (config = await applyCacheConfig({
1408
1416
  config,
1409
1417
  unpackConfig,
1410
1418
  envFilePaths
@@ -1454,12 +1462,13 @@ async function getBundlerConfig(originalUnpackConfig) {
1454
1462
  }({
1455
1463
  config,
1456
1464
  unpackConfig
1457
- })), getNormalizedPluginsByHook('bundlerConfig', unpackConfig.plugins)))config = await plugin.bundlerConfig(config, {
1458
- ...unpackConfig._context,
1459
- unpackConfig,
1460
- mergeConfig: mergeConfig
1461
- });
1462
- return unpackConfig.bundlerConfig && (config = isFunction(unpackConfig.bundlerConfig) ? await unpackConfig.bundlerConfig(config, {
1465
+ })), await applyPluginsByHook('bundlerConfig', async (impl)=>{
1466
+ config = await impl(config, {
1467
+ ...unpackConfig._context,
1468
+ unpackConfig,
1469
+ mergeConfig: mergeConfig
1470
+ });
1471
+ }), unpackConfig.bundlerConfig && (config = isFunction(unpackConfig.bundlerConfig) ? await unpackConfig.bundlerConfig(config, {
1463
1472
  mergeConfig: mergeConfig
1464
1473
  }) : mergeConfig(config, unpackConfig.bundlerConfig)), config;
1465
1474
  }
@@ -1539,302 +1548,7 @@ function execAsync(command, options) {
1539
1548
  });
1540
1549
  });
1541
1550
  }
1542
- var prebundleDeps_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
1543
- let SPECIAL_NO_ENTRY_DEPS = [
1544
- '@iconify-icons/material-symbols'
1545
- ], getExternalLibraryName = (pkgName)=>{
1546
- let externalAlias = {
1547
- react: 'React',
1548
- 'react-dom': 'ReactDOM',
1549
- 'react-router-dom': 'ReactRouterDOM'
1550
- };
1551
- return externalAlias[pkgName] ? externalAlias[pkgName] : pkgName.replace(/^@/, '').split(/[/\-.]/).filter(Boolean).map((part)=>part.charAt(0).toUpperCase() + part.slice(1)).join('');
1552
- }, getExternalValue = (pkgName)=>`window ${getExternalLibraryName(pkgName)}`, prebundleDeps = async ({ unpackConfig })=>{
1553
- var externals;
1554
- let existExternals, cacheDir, shouldTransformDeepImport = !1, count = {
1555
- total: 0,
1556
- bundled: 0
1557
- }, failedDeps = [], root = unpackConfig.root, CACHE_PATH = unpackConfig._context.cachePath, failedDepsCachePath = node_path.resolve(root, CACHE_PATH, 'failed-deps.json'), failedCache = node_fs.existsSync(failedDepsCachePath) ? JSON.parse(node_fs.readFileSync(failedDepsCachePath, 'utf-8')) : {}, updateProgress = ()=>{
1558
- let errMsg = failedDeps.length > 0 ? ` failed: ${failedDeps.join(', ')}` : '';
1559
- logUpdate(`${colors.magenta('»')} optimizing dependencies (${count.bundled}/${count.total})${errMsg}`), count.total === count.bundled + failedDeps.length && console.log();
1560
- }, userOptions = isPlainObject(unpackConfig.dev?.prebundle) ? unpackConfig.dev.prebundle : {}, ignoreCSSDeps = userOptions.ignoreCSS || [], packageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'package.json'), 'utf-8')), excludeDeps = [
1561
- ...(externals = unpackConfig.externals, existExternals = new Set(), Array.isArray(externals) ? externals.forEach((item)=>{
1562
- isPlainObject(item) && Object.keys(item).forEach((key)=>{
1563
- existExternals.add(key);
1564
- });
1565
- }) : isPlainObject(externals) && Object.keys(externals).forEach((key)=>{
1566
- existExternals.add(key);
1567
- }), Array.from(existExternals) || []),
1568
- ...userOptions.exclude || []
1569
- ], needBundleDeps = (Array.isArray(userOptions.include) && userOptions.include.length > 0 ? userOptions.include : Object.keys(packageJson.dependencies || {})).filter((pkgName)=>!excludeDeps.includes(pkgName)).map((pkgName)=>{
1570
- let packageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'node_modules', pkgName, 'package.json'), 'utf-8')), version = packageJson.version;
1571
- if (failedCache[pkgName] === version) return;
1572
- let entry = ((packageJson)=>{
1573
- if (packageJson.module) return packageJson.module;
1574
- if (packageJson.exports) {
1575
- if (isString(packageJson.exports)) return packageJson.exports;
1576
- let defaultExport = packageJson.exports['.'];
1577
- if (defaultExport) {
1578
- if (isString(defaultExport)) return defaultExport;
1579
- if (isString(defaultExport.import)) return defaultExport.import;
1580
- if (isString(defaultExport.browser)) return defaultExport.browser;
1581
- if (isString(defaultExport.default)) return defaultExport.default;
1582
- }
1583
- if (isString(packageJson.exports.default)) return packageJson.exports.default;
1584
- }
1585
- if (packageJson.main) return packageJson.main;
1586
- })(packageJson);
1587
- if (!entry) {
1588
- if (SPECIAL_NO_ENTRY_DEPS.includes(pkgName)) {
1589
- let syntheticEntry = (({ root, pkgName })=>{
1590
- let pkgDir = node_path.resolve(root, 'node_modules', pkgName);
1591
- if (!node_fs.existsSync(pkgDir)) return;
1592
- let indexPath = node_path.resolve(pkgDir, 'index.ts'), content = globSync('**/*.{js,jsx,ts,tsx}', {
1593
- cwd: pkgDir,
1594
- absolute: !1
1595
- }).filter((p)=>{
1596
- let base = node_path.basename(p);
1597
- return !(p.endsWith('.d.ts') || /^index\.(t|j)sx?$/.test(base)) && 'package.json' !== base;
1598
- }).map((file)=>{
1599
- let normalized = file.split(node_path.sep).join('/'), exportName = pathToExportIdentifier(normalized);
1600
- return `export { default as ${exportName} } from './${normalized}'`;
1601
- }).join('\n');
1602
- return node_fs.writeFileSync(indexPath, content, 'utf-8'), indexPath;
1603
- })({
1604
- root,
1605
- pkgName
1606
- });
1607
- if (syntheticEntry) return shouldTransformDeepImport = !0, {
1608
- name: pkgName,
1609
- entry: syntheticEntry,
1610
- version
1611
- };
1612
- }
1613
- failedCache[pkgName] = version;
1614
- return;
1615
- }
1616
- return {
1617
- name: pkgName,
1618
- entry: node_path.resolve(root, 'node_modules', pkgName, entry),
1619
- version
1620
- };
1621
- }).filter(Boolean), depExternals = Object.fromEntries(Array.from(new Set([
1622
- 'react',
1623
- 'react-dom',
1624
- 'react-router-dom',
1625
- ...Array.isArray(userOptions.externals) ? userOptions.externals : []
1626
- ])).map((pkg)=>[
1627
- pkg,
1628
- getExternalValue(pkg)
1629
- ])), bundledDeps = await Promise.all(needBundleDeps.map((depInfo)=>(({ name, entry, version })=>new Promise((resolve)=>{
1630
- let pkgDir = node_path.resolve(root, CACHE_PATH, 'umd', name), outDir = node_path.resolve(pkgDir, version), getResult = ()=>({
1631
- name,
1632
- assets: globSync('**/index.{js,css}', {
1633
- cwd: outDir,
1634
- absolute: !0
1635
- })
1636
- });
1637
- if (node_fs.existsSync(outDir)) return void resolve(getResult());
1638
- count.total++, updateProgress();
1639
- let getSwcOptions = ({ tsx })=>({
1640
- jsc: {
1641
- parser: {
1642
- tsx,
1643
- syntax: "typescript",
1644
- dynamicImport: !0,
1645
- decorators: !0
1646
- },
1647
- transform: {
1648
- react: {
1649
- runtime: 'automatic'
1650
- }
1651
- }
1652
- }
1653
- }), compiler = rspack({
1654
- entry: {
1655
- index: entry
1656
- },
1657
- context: root,
1658
- mode: 'development',
1659
- output: {
1660
- clean: !0,
1661
- path: outDir,
1662
- pathinfo: !1,
1663
- library: {
1664
- name: getExternalLibraryName(name),
1665
- type: 'umd',
1666
- umdNamedDefine: !0
1667
- },
1668
- globalObject: 'this'
1669
- },
1670
- devtool: !1,
1671
- module: {
1672
- rules: [
1673
- {
1674
- test: /\.(j|t)s$/,
1675
- use: [
1676
- {
1677
- loader: 'builtin:swc-loader',
1678
- options: getSwcOptions({
1679
- tsx: !1
1680
- })
1681
- }
1682
- ]
1683
- },
1684
- {
1685
- test: /\.(j|t)sx$/,
1686
- use: [
1687
- {
1688
- loader: 'builtin:swc-loader',
1689
- options: getSwcOptions({
1690
- tsx: !0
1691
- })
1692
- }
1693
- ]
1694
- },
1695
- {
1696
- test: /\.less$/,
1697
- type: 'css/auto',
1698
- use: [
1699
- {
1700
- loader: getCompiledPkgPath('less-loader'),
1701
- options: {
1702
- lessOptions: {
1703
- javascriptEnabled: !0
1704
- },
1705
- implementation: getUserDepPath(root, 'less')
1706
- }
1707
- }
1708
- ]
1709
- },
1710
- {
1711
- test: /\.s[ac]ss$/i,
1712
- type: 'css/auto',
1713
- use: [
1714
- {
1715
- loader: getCompiledPkgPath('sass-loader'),
1716
- options: {
1717
- api: 'modern-compiler',
1718
- implementation: getUserDepPath(root, [
1719
- 'sass-embedded',
1720
- 'sass'
1721
- ])
1722
- }
1723
- }
1724
- ]
1725
- }
1726
- ]
1727
- },
1728
- optimization: {
1729
- splitChunks: !1
1730
- },
1731
- experiments: {
1732
- css: !0
1733
- },
1734
- externals: depExternals
1735
- });
1736
- compiler.run((_, stats)=>{
1737
- let isFailed = !1;
1738
- stats?.hasErrors() ? (isFailed = !0, failedDeps.push(name), failedCache[name] = version, removeDir(outDir)) : count.bundled++, updateProgress(), compiler.close(()=>{
1739
- resolve(isFailed ? void 0 : getResult());
1740
- });
1741
- });
1742
- }))(depInfo)));
1743
- cacheDir = node_path.dirname(failedDepsCachePath), node_fs.existsSync(cacheDir) || node_fs.mkdirSync(cacheDir, {
1744
- recursive: !0
1745
- }), node_fs.writeFileSync(failedDepsCachePath, JSON.stringify(failedCache, null, 2), 'utf-8');
1746
- let cachePath = node_path.resolve(root, CACHE_PATH, 'umd'), staticServer = node_http.createServer((req, res)=>{
1747
- if (res.setHeader('Access-Control-Allow-Origin', '*'), 'OPTIONS' === req.method) {
1748
- res.writeHead(204), res.end();
1749
- return;
1750
- }
1751
- let url = req.url || '';
1752
- if (url.startsWith("/umd/")) {
1753
- let relativePath = url.replace("/umd/", '');
1754
- if (relativePath.includes('..')) {
1755
- res.writeHead(403), res.end();
1756
- return;
1757
- }
1758
- let filePath = node_path.join(cachePath, relativePath);
1759
- if (node_fs.existsSync(filePath)) {
1760
- let stat = node_fs.statSync(filePath);
1761
- if (stat.isFile()) {
1762
- let mtime = stat.mtime.toUTCString(), ext = node_path.extname(filePath);
1763
- 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) {
1764
- res.writeHead(304), res.end();
1765
- return;
1766
- }
1767
- res.writeHead(200), node_fs.createReadStream(filePath).pipe(res);
1768
- return;
1769
- }
1770
- }
1771
- }
1772
- res.writeHead(404), res.end();
1773
- }), port = await getPort();
1774
- staticServer.listen(port), addRestartCleaner(()=>new Promise((resolve)=>staticServer.close(()=>resolve(void 0))));
1775
- let externals1 = {}, jsAssets = [], cssAssets = [], preJsAssets = [];
1776
- bundledDeps.filter(Boolean).forEach((dep)=>{
1777
- dep && (externals1[dep.name] = getExternalValue(dep.name), dep.assets.forEach((absPath)=>{
1778
- let relativePath = node_path.relative(cachePath, absPath), preDeps = [
1779
- 'react',
1780
- 'react-dom',
1781
- 'react-router-dom'
1782
- ], serverPath = `//localhost:${port}/umd/${relativePath}`;
1783
- switch(node_path.extname(relativePath)){
1784
- case '.js':
1785
- preDeps.includes(dep.name) ? preJsAssets.push({
1786
- path: serverPath,
1787
- order: preDeps.indexOf(dep.name)
1788
- }) : jsAssets.push(serverPath);
1789
- break;
1790
- case '.css':
1791
- ignoreCSSDeps.includes(dep.name) || cssAssets.push(serverPath);
1792
- }
1793
- }));
1794
- });
1795
- let existingExternals = unpackConfig.externals ? Array.isArray(unpackConfig.externals) ? unpackConfig.externals : [
1796
- unpackConfig.externals
1797
- ] : [];
1798
- return unpackConfig.externals = [
1799
- externals1,
1800
- ...existingExternals
1801
- ], unpackConfig.plugins.push({
1802
- name: 'unpack:prebundle',
1803
- config: (config)=>{
1804
- let originalHeadTag = config.html?.headTag || '', sortedPreTags = preJsAssets.sort((a, b)=>a.order - b.order).map((item)=>item.path).map((item)=>`<script defer src="${item}"></script>`);
1805
- return set(config, [
1806
- 'html',
1807
- 'headTag'
1808
- ], `${sortedPreTags.join('')}${originalHeadTag}`), config;
1809
- },
1810
- bundlerConfig: (config)=>{
1811
- let PLUGIN_NAME = 'PluginInjectAssets';
1812
- return config.plugins.push({
1813
- apply: (compiler)=>{
1814
- compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
1815
- rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeAssetTagGeneration.tapPromise(PLUGIN_NAME, async (args)=>(args.assets.js.unshift(...jsAssets), args.assets.css.unshift(...cssAssets), args));
1816
- });
1817
- }
1818
- }), shouldTransformDeepImport && config.module.rules.push({
1819
- test: /\.[jt]sx?$/,
1820
- exclude: /node_modules/,
1821
- use: [
1822
- {
1823
- loader: node_path.resolve(prebundleDeps_dirname, './transformDeepImportLoader.mjs'),
1824
- options: {
1825
- packages: SPECIAL_NO_ENTRY_DEPS
1826
- }
1827
- }
1828
- ]
1829
- }), config;
1830
- }
1831
- }), unpackConfig;
1832
- };
1833
- async function unpackDev(originalUnpackConfig) {
1834
- let unpackConfig = originalUnpackConfig;
1835
- unpackConfig.dev?.prebundle && (unpackConfig = await prebundleDeps({
1836
- unpackConfig
1837
- }));
1551
+ async function unpackDev(unpackConfig) {
1838
1552
  let compiler = rspack(await getBundlerConfig(unpackConfig)), port = await getPort(unpackConfig.server?.port), proxyConfig = unpackConfig.server?.proxy;
1839
1553
  isPlainObject(proxyConfig) && (proxyConfig = Object.entries(proxyConfig).map(([contextStr, target])=>{
1840
1554
  let baseConfig = {
@@ -1849,7 +1563,7 @@ async function unpackDev(originalUnpackConfig) {
1849
1563
  target
1850
1564
  };
1851
1565
  }));
1852
- let devServerOptions = {
1566
+ let devPublicPath = normalizePublicPath(unpackConfig.base), devServerOptions = {
1853
1567
  hot: !0,
1854
1568
  port,
1855
1569
  open: !1,
@@ -1858,62 +1572,50 @@ async function unpackDev(originalUnpackConfig) {
1858
1572
  },
1859
1573
  proxy: proxyConfig,
1860
1574
  devMiddleware: {
1575
+ publicPath: devPublicPath,
1861
1576
  writeToDisk: unpackConfig.dev?.writeToDisk
1862
1577
  }
1863
- };
1864
- devServerOptions.setupMiddlewares = (middlewares)=>(middlewares.unshift((req, _, next)=>{
1865
- req.headers.accept?.includes('html') && (req.url = '/index.html'), next();
1866
- }), middlewares.unshift(rspack.lazyCompilationMiddleware(compiler)), middlewares);
1578
+ }, pluginMiddlewares = [];
1579
+ await applyPluginsByHook('setupMiddlewares', async (impl)=>{
1580
+ pluginMiddlewares = await impl(pluginMiddlewares);
1581
+ }), devServerOptions.setupMiddlewares = (middlewares)=>(middlewares.unshift((req, _, next)=>{
1582
+ let accept = req.headers.accept;
1583
+ if ('string' == typeof accept && accept.includes('html')) {
1584
+ let url = req.url || '/';
1585
+ '/' === devPublicPath ? req.url = '/index.html' : (url === devPublicPath.slice(0, -1) || url.startsWith(devPublicPath)) && (req.url = `${devPublicPath}index.html`);
1586
+ }
1587
+ next();
1588
+ }), middlewares.unshift(rspack.lazyCompilationMiddleware(compiler)), [
1589
+ ...pluginMiddlewares,
1590
+ ...middlewares
1591
+ ]);
1867
1592
  let server = new RspackDevServer(devServerOptions, compiler);
1868
- await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v3.7.8${unpackConfig.build?.cache ? ' ϟ' : ''}`)} ${colors.dim('ready in')} ${colors.bold(Math.ceil(performance.now() - global.__unpack_start_time))} ${colors.dim('ms')}\n`), printAddressUrls(port, unpackConfig.server?.host), addRestartCleaner(()=>server.stop(), ()=>new Promise((resolve)=>compiler.close(()=>resolve())));
1869
- let open = unpackConfig.server?.open, url = isString(open) ? open : `http://localhost:${port}`;
1870
- open && openBrowser(url), setupCliShortcuts({
1871
- openPage: async ()=>{
1872
- await openBrowser(url);
1873
- },
1874
- closeServer: async ()=>{
1875
- await cleanUpBeforeRestart(), process.exit(0);
1876
- },
1877
- printUrls: ()=>{
1878
- printAddressUrls(port, unpackConfig.server?.host);
1879
- },
1880
- restartServer: async ()=>{
1881
- logger_logger.clear(), await cleanUpBeforeRestart(), createUnpack({
1882
- cwd: currentDevUnpackConfig.root,
1883
- config: currentDevUnpackConfig
1884
- }).dev();
1885
- }
1886
- });
1887
- }
1888
- function printAddressUrls(port, host) {
1889
- let addressUrls = getAddressUrls({
1890
- port
1891
- }), colorPrefix = colors.brand('➜');
1892
- addressUrls.forEach((addr, index)=>{
1893
- let url;
1894
- if (!host && 0 !== index) {
1895
- 1 === index && console.log(` ${colors.dim(colorPrefix)} ${colors.bold(colors.dim('Network:'))} ${colors.dim('use')} ${colors.bold('--host')} ${colors.dim('to expose')}`);
1896
- return;
1897
- }
1898
- console.log(` ${colorPrefix} ${colors.bold(addr.label)}${(url = addr.url, colors.cyan(url.replace(/:(\d+)\//, (_, port)=>`:${colors.bold(port)}/`)))}`);
1899
- });
1593
+ await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v3.8.0${unpackConfig.performance?.cache ? ' ϟ' : ''}`)} ${colors.dim('ready in')} ${colors.bold(Math.ceil(performance.now() - getUnpackStartTime()))} ${colors.dim('ms')}\n`), printServerUrls({
1594
+ port,
1595
+ host: unpackConfig.server?.host,
1596
+ base: unpackConfig.base
1597
+ }), addRestartCleaner(()=>server.stop(), ()=>new Promise((resolve)=>compiler.close(()=>resolve())));
1598
+ let open = unpackConfig.server?.open, url = isString(open) ? open : `http://localhost:${port}${devPublicPath}`;
1599
+ return open && openBrowser(url), {
1600
+ port,
1601
+ url
1602
+ };
1900
1603
  }
1901
1604
  function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'unpack' }) {
1902
1605
  let _context = {
1903
1606
  callerName,
1904
- version: "3.7.8",
1607
+ version: "3.8.0",
1905
1608
  cachePath: 'node_modules/.unpack'
1906
- };
1907
- global.__unpack_caller_name = callerName;
1908
- let resolveConfig = (mode)=>{
1909
- let isProd;
1609
+ }, resolveConfig = (mode)=>{
1610
+ let rootPath, outputPath, basePath, cachedTraceMap, fs, isValidMethodName, parseFrame, formatOriginalLocation, formatFullStack, resolveErrorLocationAndStack, shouldTransformDeepImport, preJsAssets, jsAssets, cssAssets, bundledDepsCachePath, deepImportPkgPattern, deepImportRegex, root;
1910
1611
  return {
1911
1612
  ...mergeConfig({
1912
1613
  root: cwd,
1614
+ base: '/',
1615
+ sourceMap: 'production' !== mode && 'cheap-module-source-map',
1913
1616
  build: {
1914
1617
  outDir: 'dist',
1915
- minify: isProd = 'production' === mode,
1916
- sourceMap: !isProd && 'cheap-module-source-map',
1618
+ minify: !0,
1917
1619
  filenameHash: !0,
1918
1620
  target: 'es2022'
1919
1621
  },
@@ -1932,11 +1634,581 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
1932
1634
  chunkSplit: {
1933
1635
  strategy: 'single-vendor'
1934
1636
  },
1935
- printFileSize: !0
1637
+ printFileSize: !0,
1638
+ cache: !0
1936
1639
  },
1937
1640
  typeCheck: !0,
1938
1641
  envPrefix: [
1939
1642
  'PUBLIC_'
1643
+ ],
1644
+ plugins: [
1645
+ (rootPath = '', outputPath = '', basePath = '/', cachedTraceMap = new Map(), fs = null, isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName), parseFrame = async (frame)=>{
1646
+ let { file, column, lineNumber } = frame;
1647
+ if (!file || null == lineNumber || null == column) return;
1648
+ let localPath = file;
1649
+ try {
1650
+ let pathname = new URL(file).pathname;
1651
+ if ('/' !== basePath) {
1652
+ let normalizedBase = basePath;
1653
+ pathname.startsWith(normalizedBase) && (pathname = pathname.slice(normalizedBase.length));
1654
+ }
1655
+ localPath = node_path.join(outputPath, pathname);
1656
+ } catch {
1657
+ node_path.isAbsolute(file) || (localPath = node_path.join(outputPath, file));
1658
+ }
1659
+ let sourceMapPath = `${localPath}.map`;
1660
+ try {
1661
+ if (!fs.existsSync(sourceMapPath)) return;
1662
+ let tracer = cachedTraceMap.get(sourceMapPath);
1663
+ if (!tracer) {
1664
+ let readFile = promisify(fs.readFile), sourceMapContent = await readFile(sourceMapPath, 'utf-8');
1665
+ if (!sourceMapContent) return;
1666
+ tracer = new TraceMap(sourceMapContent), cachedTraceMap.set(sourceMapPath, tracer);
1667
+ }
1668
+ let originalPosition = originalPositionFor(tracer, {
1669
+ line: lineNumber,
1670
+ column: column
1671
+ });
1672
+ return {
1673
+ sourceMapPath,
1674
+ originalPosition
1675
+ };
1676
+ } catch {
1677
+ return;
1678
+ }
1679
+ }, formatOriginalLocation = (originalMapping)=>{
1680
+ let { source, line, column } = originalMapping;
1681
+ if (!source) return;
1682
+ let relativeSource = source;
1683
+ if (source.includes('webpack://')) {
1684
+ let segments = (relativeSource = source.replace(/webpack:\/\/\/?/, '')).split(/[\\/]/);
1685
+ [
1686
+ 'src',
1687
+ 'node_modules'
1688
+ ].includes(segments[1]) && (segments.shift(), relativeSource = segments.join('/'));
1689
+ }
1690
+ let result = relativeSource;
1691
+ return null !== line && (result += null === column ? `:${line}` : `:${line}:${column}`), result;
1692
+ }, formatFullStack = async (stackFrames)=>{
1693
+ let allLines = [], srcLines = [];
1694
+ for (let frame of stackFrames){
1695
+ let parsedFrame = await parseFrame(frame), { methodName } = frame, parts = [];
1696
+ methodName && isValidMethodName(methodName) && parts.push(methodName);
1697
+ let parsed = !1;
1698
+ if (parsedFrame) {
1699
+ let { originalPosition } = parsedFrame, originalLocation = formatOriginalLocation(originalPosition);
1700
+ originalLocation && (parts.push(originalLocation), parsed = !0);
1701
+ }
1702
+ if (!parsed && frame.file) try {
1703
+ let url = new URL(frame.file);
1704
+ parts.push(`${url.pathname}:${frame.lineNumber}:${frame.column}`);
1705
+ } catch {
1706
+ parts.push(`${frame.file}:${frame.lineNumber}:${frame.column}`);
1707
+ }
1708
+ if (parts.length > 0) {
1709
+ 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}`;
1710
+ allLines.push(line);
1711
+ let locationText = loc.startsWith('(') && loc.endsWith(')') ? loc.slice(1, -1) : loc;
1712
+ /(^|[\\/])src[\\/]/.test(locationText) && srcLines.push(line);
1713
+ }
1714
+ }
1715
+ return srcLines.length > 0 ? srcLines.join('') : allLines.join('');
1716
+ }, resolveErrorLocationAndStack = async (item)=>{
1717
+ let locationFromMsg = item.message ? ((message)=>{
1718
+ let match = message.match(/((?:[A-Za-z]:)?\/[^\s:]+):(\d+):(\d+)/);
1719
+ if (!match) return;
1720
+ let [, absPath, line, column] = match, source = absPath;
1721
+ return absPath.startsWith(rootPath + node_path.sep) && (source = node_path.relative(rootPath, absPath)), `${source}:${Number(line)}:${Number(column)}`;
1722
+ })(item.message) : null;
1723
+ if (locationFromMsg) return {
1724
+ locationSuffix: colors.dim(` (${locationFromMsg})`),
1725
+ stackString: ''
1726
+ };
1727
+ if (!item.stack) return {
1728
+ locationSuffix: '',
1729
+ stackString: ''
1730
+ };
1731
+ let parsedFrames = parse(item.stack), userFrame = parsedFrames.find((frame)=>frame.file && null !== frame.lineNumber && null !== frame.column && browserLogs_SCRIPT_REGEX.test(frame.file));
1732
+ if (userFrame) {
1733
+ let parsedUserFrame = await parseFrame(userFrame), loc = parsedUserFrame ? formatOriginalLocation(parsedUserFrame.originalPosition) : null;
1734
+ if (loc) return {
1735
+ locationSuffix: colors.dim(` (${loc})`),
1736
+ stackString: ''
1737
+ };
1738
+ }
1739
+ let formattedStack = await formatFullStack(parsedFrames);
1740
+ return {
1741
+ locationSuffix: '',
1742
+ stackString: colors.dim(formattedStack)
1743
+ };
1744
+ }, {
1745
+ name: 'unpack:browser-logs',
1746
+ apply: (config, { command })=>'dev' === command && config.dev?.browserLogs,
1747
+ buildStart: async ({ isFirstCompile, compiler })=>{
1748
+ isFirstCompile && (fs = compiler.outputFileSystem);
1749
+ },
1750
+ configResolved: (config)=>{
1751
+ rootPath = config.root, outputPath = node_path.join(rootPath, config.build.outDir), basePath = normalizePublicPath(config.base);
1752
+ },
1753
+ transformHtml: (html)=>injectToHead(html, `<script>
1754
+ ;(() => {
1755
+ if (typeof window === 'undefined' || typeof console === 'undefined') return
1756
+ const endpoint = '${BROWSER_LOGS_ENDPOINT}'
1757
+ const levels = ['log', 'info', 'warn', 'error', 'debug']
1758
+
1759
+ const send = (level, args) => {
1760
+ try {
1761
+ const payload = {
1762
+ level,
1763
+ time: new Date().toLocaleTimeString(),
1764
+ args: Array.prototype.slice.call(args).map((item) => {
1765
+ try {
1766
+ if (item instanceof Error) {
1767
+ const name = item.name || ''
1768
+ const msg = item.message ? ': ' + item.message : ''
1769
+ return {
1770
+ type: 'error',
1771
+ message: name + msg,
1772
+ stack: item.stack,
1773
+ }
1774
+ }
1775
+ if (item === null) {
1776
+ return { type: 'null', message: 'null' }
1777
+ }
1778
+ const t = typeof item
1779
+ if (['string', 'number', 'boolean'].includes(t)) {
1780
+ return { type: t, message: item }
1781
+ }
1782
+ if (['undefined', 'function', 'symbol', 'bigint'].includes(t)) {
1783
+ return { type: t, message: String(item) }
1784
+ }
1785
+ return { type: 'object', message: JSON.stringify(item) }
1786
+ } catch (e) {
1787
+ return { type: 'unknown', message: String(item) }
1788
+ }
1789
+ }),
1790
+ }
1791
+ const body = JSON.stringify(payload)
1792
+ if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
1793
+ navigator.sendBeacon(endpoint, body)
1794
+ } else if (typeof fetch === 'function') {
1795
+ fetch(endpoint, {
1796
+ method: 'POST',
1797
+ headers: { 'Content-Type': 'application/json' },
1798
+ body,
1799
+ keepalive: true,
1800
+ }).catch(() => {})
1801
+ }
1802
+ } catch (e) {}
1803
+ }
1804
+
1805
+ levels.forEach((level) => {
1806
+ const original = console[level]
1807
+ if (!original || typeof original !== 'function') return
1808
+ console[level] = (...args) => {
1809
+ try {
1810
+ original.apply(console, args)
1811
+ } finally {
1812
+ send(level, args)
1813
+ }
1814
+ }
1815
+ })
1816
+
1817
+ window.addEventListener('error', (event) => {
1818
+ send('error', [event.error || event.message])
1819
+ })
1820
+ window.addEventListener('unhandledrejection', (event) => {
1821
+ send('error', [event.reason])
1822
+ })
1823
+ })()
1824
+ </script>`),
1825
+ setupMiddlewares: (middlewares)=>[
1826
+ (req, res, next)=>{
1827
+ if ('POST' !== req.method || !req.url?.startsWith(BROWSER_LOGS_ENDPOINT)) return next();
1828
+ let raw = '';
1829
+ req.on('data', (chunk)=>{
1830
+ raw += chunk.toString();
1831
+ }), req.on('end', async ()=>{
1832
+ try {
1833
+ let { level = 'log', time = '', args = [] } = JSON.parse(raw || '{}'), prefix = time ? colors.dim(`[browser ${time}]`) : colors.dim('[browser]'), formattedArgs = await Promise.all(args.map(async (item)=>{
1834
+ if (!item) return '';
1835
+ if ('error' === item.type) {
1836
+ let { locationSuffix, stackString } = await resolveErrorLocationAndStack(item);
1837
+ return `${item.message}${locationSuffix}${stackString}`;
1838
+ }
1839
+ switch(item.type){
1840
+ case 'null':
1841
+ return null;
1842
+ case 'undefined':
1843
+ return;
1844
+ case 'object':
1845
+ return JSON.parse(item.message || '');
1846
+ default:
1847
+ return item.message;
1848
+ }
1849
+ }));
1850
+ switch(level){
1851
+ case 'error':
1852
+ logger_logger.error(`${prefix} ${formattedArgs.join(' ')}`);
1853
+ break;
1854
+ case 'warn':
1855
+ logger_logger.warn(`${prefix} ${formattedArgs.join(' ')}`);
1856
+ break;
1857
+ case 'info':
1858
+ default:
1859
+ logger_logger.info(prefix, ...formattedArgs);
1860
+ break;
1861
+ case 'debug':
1862
+ logger_logger.debug(prefix, ...formattedArgs);
1863
+ }
1864
+ } catch (e) {
1865
+ logger_logger.error('Failed to parse browser log payload', e);
1866
+ } finally{
1867
+ res.statusCode = 204, res.end();
1868
+ }
1869
+ });
1870
+ },
1871
+ ...middlewares
1872
+ ]
1873
+ }),
1874
+ (shouldTransformDeepImport = !1, preJsAssets = [], jsAssets = [], cssAssets = [], bundledDepsCachePath = '', deepImportPkgPattern = [
1875
+ ...SPECIAL_NO_ENTRY_DEPS
1876
+ ].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'), {
1877
+ name: 'unpack:prebundle',
1878
+ apply: (config, { command })=>'dev' === command && !!config.dev?.prebundle,
1879
+ config: async (config, context)=>{
1880
+ var externals;
1881
+ let existExternals, cacheDir, root = config.root;
1882
+ bundledDepsCachePath = node_path.resolve(root, context.cachePath, 'umd');
1883
+ let count = {
1884
+ total: 0,
1885
+ bundled: 0
1886
+ }, 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 = ()=>{
1887
+ let errMsg = failedDeps.length > 0 ? ` failed: ${failedDeps.join(', ')}` : '';
1888
+ logUpdate(`${colors.magenta('»')} optimizing dependencies (${count.bundled}/${count.total})${errMsg}`), count.total === count.bundled + failedDeps.length && console.log();
1889
+ }, 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 = [
1890
+ ...(externals = config.externals, existExternals = new Set(), Array.isArray(externals) ? externals.forEach((item)=>{
1891
+ isPlainObject(item) && Object.keys(item).forEach((key)=>{
1892
+ existExternals.add(key);
1893
+ });
1894
+ }) : isPlainObject(externals) && Object.keys(externals).forEach((key)=>{
1895
+ existExternals.add(key);
1896
+ }), Array.from(existExternals) || []),
1897
+ ...userOptions.exclude || []
1898
+ ], needBundleDeps = (Array.isArray(userOptions.include) && userOptions.include.length > 0 ? userOptions.include : Object.keys(packageJson.dependencies || {})).filter((pkgName)=>!excludeDeps.includes(pkgName)).map((pkgName)=>{
1899
+ let depPackageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'node_modules', pkgName, 'package.json'), 'utf-8')), version = depPackageJson.version;
1900
+ if (failedCache[pkgName] === version) return;
1901
+ let entry = ((packageJson)=>{
1902
+ if (packageJson.module) return packageJson.module;
1903
+ if (packageJson.exports) {
1904
+ if (isString(packageJson.exports)) return packageJson.exports;
1905
+ let defaultExport = packageJson.exports['.'];
1906
+ if (defaultExport) {
1907
+ if (isString(defaultExport)) return defaultExport;
1908
+ if (isString(defaultExport.import)) return defaultExport.import;
1909
+ if (isString(defaultExport.browser)) return defaultExport.browser;
1910
+ if (isString(defaultExport.default)) return defaultExport.default;
1911
+ }
1912
+ if (isString(packageJson.exports.default)) return packageJson.exports.default;
1913
+ }
1914
+ if (packageJson.main) return packageJson.main;
1915
+ })(depPackageJson);
1916
+ if (!entry) {
1917
+ if (SPECIAL_NO_ENTRY_DEPS.includes(pkgName)) {
1918
+ let syntheticEntry = (({ root, pkgName })=>{
1919
+ let pkgDir = node_path.resolve(root, 'node_modules', pkgName);
1920
+ if (!node_fs.existsSync(pkgDir)) return;
1921
+ let indexPath = node_path.resolve(pkgDir, 'index.ts'), content = globSync('**/*.{js,jsx,ts,tsx}', {
1922
+ cwd: pkgDir,
1923
+ absolute: !1
1924
+ }).filter((p)=>{
1925
+ let base = node_path.basename(p);
1926
+ return !(p.endsWith('.d.ts') || /^index\.(t|j)sx?$/.test(base)) && 'package.json' !== base;
1927
+ }).map((file)=>{
1928
+ let normalized = file.split(node_path.sep).join('/'), exportName = pathToExportIdentifier(normalized);
1929
+ return `export { default as ${exportName} } from './${normalized}'`;
1930
+ }).join('\n');
1931
+ return node_fs.writeFileSync(indexPath, content, 'utf-8'), indexPath;
1932
+ })({
1933
+ root,
1934
+ pkgName
1935
+ });
1936
+ if (syntheticEntry) return shouldTransformDeepImport = !0, {
1937
+ name: pkgName,
1938
+ entry: syntheticEntry,
1939
+ version
1940
+ };
1941
+ }
1942
+ failedCache[pkgName] = version;
1943
+ return;
1944
+ }
1945
+ return {
1946
+ name: pkgName,
1947
+ entry: node_path.resolve(root, 'node_modules', pkgName, entry),
1948
+ version
1949
+ };
1950
+ }).filter(Boolean), depExternals = Object.fromEntries(Array.from(new Set([
1951
+ 'react',
1952
+ 'react-dom',
1953
+ 'react-router-dom',
1954
+ ...Array.isArray(userOptions.externals) ? userOptions.externals : []
1955
+ ])).map((pkg)=>[
1956
+ pkg,
1957
+ getExternalValue(pkg)
1958
+ ])), bundledDeps = await Promise.all(needBundleDeps.map((depInfo)=>(({ name, entry, version })=>new Promise((resolve)=>{
1959
+ let pkgDir = node_path.resolve(bundledDepsCachePath, name), outDir = node_path.resolve(pkgDir, version), getResult = ()=>({
1960
+ name,
1961
+ assets: globSync('**/index.{js,css}', {
1962
+ cwd: outDir,
1963
+ absolute: !0
1964
+ })
1965
+ });
1966
+ if (node_fs.existsSync(outDir)) return void resolve(getResult());
1967
+ count.total++, updateProgress();
1968
+ let getSwcOptions = ({ tsx })=>({
1969
+ jsc: {
1970
+ parser: {
1971
+ tsx,
1972
+ syntax: "typescript",
1973
+ dynamicImport: !0,
1974
+ decorators: !0
1975
+ },
1976
+ transform: {
1977
+ react: {
1978
+ runtime: 'automatic'
1979
+ }
1980
+ }
1981
+ }
1982
+ }), compiler = rspack({
1983
+ entry: {
1984
+ index: entry
1985
+ },
1986
+ context: root,
1987
+ mode: 'development',
1988
+ output: {
1989
+ clean: !0,
1990
+ path: outDir,
1991
+ pathinfo: !1,
1992
+ library: {
1993
+ name: getExternalLibraryName(name),
1994
+ type: 'umd',
1995
+ umdNamedDefine: !0
1996
+ },
1997
+ globalObject: 'this'
1998
+ },
1999
+ devtool: !1,
2000
+ module: {
2001
+ rules: [
2002
+ {
2003
+ test: JS_REGEX,
2004
+ use: [
2005
+ {
2006
+ loader: 'builtin:swc-loader',
2007
+ options: getSwcOptions({
2008
+ tsx: !1
2009
+ })
2010
+ }
2011
+ ]
2012
+ },
2013
+ {
2014
+ test: JSX_REGEX,
2015
+ use: [
2016
+ {
2017
+ loader: 'builtin:swc-loader',
2018
+ options: getSwcOptions({
2019
+ tsx: !0
2020
+ })
2021
+ }
2022
+ ]
2023
+ },
2024
+ {
2025
+ test: /\.less$/,
2026
+ type: 'css/auto',
2027
+ use: [
2028
+ {
2029
+ loader: getCompiledPkgPath('less-loader'),
2030
+ options: {
2031
+ lessOptions: {
2032
+ javascriptEnabled: !0
2033
+ },
2034
+ implementation: getUserDepPath(root, 'less')
2035
+ }
2036
+ }
2037
+ ]
2038
+ },
2039
+ {
2040
+ test: /\.s[ac]ss$/i,
2041
+ type: 'css/auto',
2042
+ use: [
2043
+ {
2044
+ loader: getCompiledPkgPath('sass-loader'),
2045
+ options: {
2046
+ api: 'modern-compiler',
2047
+ implementation: getUserDepPath(root, [
2048
+ 'sass-embedded',
2049
+ 'sass'
2050
+ ])
2051
+ }
2052
+ }
2053
+ ]
2054
+ }
2055
+ ]
2056
+ },
2057
+ optimization: {
2058
+ splitChunks: !1
2059
+ },
2060
+ experiments: {
2061
+ css: !0
2062
+ },
2063
+ externals: depExternals
2064
+ });
2065
+ compiler.run((_, stats)=>{
2066
+ let isFailed = !1;
2067
+ stats?.hasErrors() ? (isFailed = !0, failedDeps.push(name), failedCache[name] = version, removeDir(outDir)) : count.bundled++, updateProgress(), compiler.close(()=>{
2068
+ resolve(isFailed ? void 0 : getResult());
2069
+ });
2070
+ });
2071
+ }))(depInfo)));
2072
+ cacheDir = node_path.dirname(failedDepsJsonPath), node_fs.existsSync(cacheDir) || node_fs.mkdirSync(cacheDir, {
2073
+ recursive: !0
2074
+ }), node_fs.writeFileSync(failedDepsJsonPath, JSON.stringify(failedCache, null, 2), 'utf-8');
2075
+ let externals1 = {};
2076
+ bundledDeps.filter(Boolean).forEach((dep)=>{
2077
+ dep && (externals1[dep.name] = getExternalValue(dep.name), dep.assets.forEach((absPath)=>{
2078
+ let relativePath = node_path.relative(bundledDepsCachePath, absPath), preDeps = [
2079
+ 'react',
2080
+ 'react-dom',
2081
+ 'react-router-dom'
2082
+ ], serverPath = `/umd/${relativePath}`;
2083
+ switch(node_path.extname(relativePath)){
2084
+ case '.js':
2085
+ preDeps.includes(dep.name) ? preJsAssets.push({
2086
+ path: serverPath,
2087
+ order: preDeps.indexOf(dep.name)
2088
+ }) : jsAssets.push(serverPath);
2089
+ break;
2090
+ case '.css':
2091
+ ignoreCSSDeps.includes(dep.name) || cssAssets.push(serverPath);
2092
+ }
2093
+ }));
2094
+ });
2095
+ let existingExternals = config.externals ? Array.isArray(config.externals) ? config.externals : [
2096
+ config.externals
2097
+ ] : [];
2098
+ return config.externals = [
2099
+ externals1,
2100
+ ...existingExternals
2101
+ ], config;
2102
+ },
2103
+ transform: (code, id)=>shouldTransformDeepImport && JSX_REGEX.test(id) && code.includes('import') && SPECIAL_NO_ENTRY_DEPS.some((pkg)=>code.includes(pkg)) ? code.replace(deepImportRegex, (_, localName, importPath, pkgName)=>{
2104
+ let exportName = pathToExportIdentifier(importPath.slice(pkgName.length + 1));
2105
+ return `import { ${exportName} as ${localName} } from '${pkgName}'`;
2106
+ }) : null,
2107
+ transformHtml: (html)=>injectToHead(html, preJsAssets.sort((a, b)=>a.order - b.order).map((item)=>item.path).map((item)=>`<script defer src="${item}"></script>`).join('')),
2108
+ setupMiddlewares: (middlewares)=>[
2109
+ (req, res, next)=>{
2110
+ if ('string' != typeof req.url) return void next();
2111
+ let url = new URL(req.url, 'http://localhost');
2112
+ if (!url.pathname.startsWith("/umd/")) return void next();
2113
+ let relativePath = url.pathname.replace("/umd/", '');
2114
+ if (relativePath.includes('..')) {
2115
+ res.statusCode = 403, res.end();
2116
+ return;
2117
+ }
2118
+ let filePath = node_path.join(bundledDepsCachePath, relativePath);
2119
+ if (!node_fs.existsSync(filePath)) return void next();
2120
+ let stat = node_fs.statSync(filePath);
2121
+ if (!stat.isFile()) return void next();
2122
+ let mtime = stat.mtime.toUTCString(), ext = node_path.extname(filePath);
2123
+ 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) {
2124
+ res.statusCode = 304, res.end();
2125
+ return;
2126
+ }
2127
+ res.statusCode = 200, node_fs.createReadStream(filePath).pipe(res);
2128
+ },
2129
+ ...middlewares
2130
+ ],
2131
+ bundlerConfig: (config)=>{
2132
+ let PLUGIN_NAME = 'InjectAssetsPlugin';
2133
+ return config.plugins.push({
2134
+ apply: (compiler)=>{
2135
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
2136
+ rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeAssetTagGeneration.tapPromise(PLUGIN_NAME, async (args)=>(args.assets.js.unshift(...jsAssets), args.assets.css.unshift(...cssAssets), args));
2137
+ });
2138
+ }
2139
+ }), config;
2140
+ }
2141
+ }),
2142
+ (root = '', {
2143
+ name: 'unpack:file-size',
2144
+ apply: (config, { mode })=>'production' === mode && config.performance?.printFileSize,
2145
+ configResolved (config) {
2146
+ root = config.root;
2147
+ },
2148
+ buildEnd: async (options)=>{
2149
+ let { stats } = options, chunkGroups = [
2150
+ {
2151
+ type: 'HTML',
2152
+ color: 'green',
2153
+ chunks: []
2154
+ },
2155
+ {
2156
+ type: 'Assets',
2157
+ color: 'yellow',
2158
+ chunks: []
2159
+ },
2160
+ {
2161
+ type: 'CSS',
2162
+ color: 'magenta',
2163
+ chunks: []
2164
+ },
2165
+ {
2166
+ type: 'JS',
2167
+ color: 'cyan',
2168
+ chunks: []
2169
+ }
2170
+ ], 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;
2171
+ logUpdate('computing gzip size...'), await Promise.all(assets.map(async ([assetName, value])=>{
2172
+ let content, compressedSize, filePath = assetName.split('?')[0];
2173
+ try {
2174
+ content = value.source();
2175
+ } catch {
2176
+ content = node_fs.readFileSync(node_path.join(distPath, filePath));
2177
+ }
2178
+ let size = Buffer.byteLength(content);
2179
+ compressedSize = COMPRESSIBLE_REGEX.test(filePath) ? await getCompressedSize(content) : size, totalSize += size, totalCompressedSize += compressedSize;
2180
+ let chunk = {
2181
+ name: node_path.basename(filePath),
2182
+ path: `${distFolder}/${filePath}`,
2183
+ size,
2184
+ compressedSize
2185
+ };
2186
+ switch(chunk.path.length > longest && (longest = chunk.path.length), node_path.extname(filePath)){
2187
+ case '.html':
2188
+ chunkGroupMap.HTML.chunks.push(chunk);
2189
+ break;
2190
+ case '.css':
2191
+ chunkGroupMap.CSS.chunks.push(chunk);
2192
+ break;
2193
+ case '.js':
2194
+ case '.wasm':
2195
+ chunkGroupMap.JS.chunks.push(chunk);
2196
+ break;
2197
+ default:
2198
+ chunkGroupMap.Assets.chunks.push(chunk);
2199
+ }
2200
+ })), logUpdate(`✓ computed gzip size (${assets.length})`), console.log();
2201
+ let sizePad = displaySize(totalSize).length, compressPad = displaySize(totalCompressedSize).length;
2202
+ chunkGroups.forEach((group)=>{
2203
+ group.chunks.sort((a, b)=>a.size - b.size).forEach((chunk)=>{
2204
+ let isLarge = 'JS' === group.type && chunk.size / 1000 > 500, relativeOutDir = node_path.dirname(chunk.path) + '/', log = colors.dim(relativeOutDir);
2205
+ 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
+ });
2207
+ });
2208
+ let log = colors.blue('Total'.padEnd(longest + 2));
2209
+ log += colors.blue(displaySize(totalSize)), console.log(log += colors.dim(` │ gzip: ${displaySize(totalCompressedSize)}`));
2210
+ }
2211
+ })
1940
2212
  ]
1941
2213
  }, userConfig),
1942
2214
  _context
@@ -1947,14 +2219,14 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
1947
2219
  let mode = watch ? 'development' : 'production';
1948
2220
  setNodeEnv(mode);
1949
2221
  let config = resolveConfig(mode);
1950
- console.log(colors.brand(`${callerName} v3.7.8${config.build?.cache ? ' ϟ' : ''}`), colors.cyan(`building for ${mode}...`)), await unpackBuild(config);
2222
+ console.log(colors.brand(`${callerName} v3.8.0${config.performance?.cache ? ' ϟ' : ''}`), colors.cyan(`building for ${mode}...`)), await unpackBuild(config);
1951
2223
  },
1952
2224
  dev: async ()=>{
1953
- global.__unpack_start_time = performance.now();
2225
+ setUnpackStartTime(performance.now());
1954
2226
  let mode = 'development';
1955
2227
  setNodeEnv(mode), setDevServer(!0);
1956
2228
  let config = resolveConfig(mode);
1957
- await unpackDev(config);
2229
+ return await unpackDev(config);
1958
2230
  },
1959
2231
  clean: ()=>{
1960
2232
  let root = userConfig.root || cwd, relativeDir = _context.cachePath, absDir = node_path.resolve(root, relativeDir);
@@ -1975,5 +2247,5 @@ async function createChokidar(pathOrGlobs, root = process.cwd(), options) {
1975
2247
  ...options
1976
2248
  });
1977
2249
  }
1978
- var __webpack_exports__CSS_NAMED_EXPORT = !1;
1979
- export { CSS_MODULES_LOCAL_IDENT_NAME, CSS_MODULES_REGEX, DEFAULT_DEV_HOST, DEV_DEFAULT_FILENAME, EXPORT_LOCALS_CONVENTION, logger_LogColor as LogColor, NODE_MODULES_REGEX, PROD_DEFAULT_FILENAME, TEMPLATE_CONTENT, addRestartCleaner, cleanUpBeforeRestart, clearLine, colors, convertBasicAnsiColors, createChokidar, createUnpack, currentDevUnpackConfig, debounce, defineConfig, esVersionToBrowserslist, findExists, getAddressUrls, getCompiledPkgPath, getIpv4Interfaces, getNodeEnv, getOrSetDefault, getPathInJs, getPort, getTime, getUserDepPath, getUserDepVersion, isBoolean, isCSSModules, isDebug, isDev, utils_isDevServer as isDevServer, isEmptyDir, isFileExists, isFileSync, isFunction, isNodeVersionAtLeast, isObject, isPlainObject, utils_isProd as isProd, isRegExp, isString, isUndefined, isWatch, isWin, launchEditor, loadConfig, logUpdate, logger_logger as logger, mergeConfig, pLimit, pathExists, pathToExportIdentifier, prettyTime, removeDir, resolveConfigPath, rspack, set, setCurrentDevUnpackConfig, setDevServer, setNodeEnv, setupCliShortcuts, trackPerformance, __webpack_exports__CSS_NAMED_EXPORT as CSS_NAMED_EXPORT };
2250
+ var src_CSS_NAMED_EXPORT = !1;
2251
+ export { CSS_MODULES_LOCAL_IDENT_NAME, CSS_MODULES_REGEX, DEFAULT_DEV_HOST, DEV_DEFAULT_FILENAME, EXPORT_LOCALS_CONVENTION, JSX_REGEX, JS_REGEX, 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, isCSSModules, 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, set, setCurrentUnpackConfig, setDevServer, setNodeEnv, setUnpackStartTime, setupCliShortcuts, src_CSS_NAMED_EXPORT as CSS_NAMED_EXPORT, trackPerformance, utils_isDevServer as isDevServer, utils_isProd as isProd };