@unpackjs/core 1.6.4 → 1.7.1

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 (58) hide show
  1. package/compiled/css-loader/index.js +48 -50
  2. package/compiled/less-loader/index.js +8 -8
  3. package/compiled/postcss-loader/index.js +11 -11
  4. package/compiled/sass-loader/index.js +8 -8
  5. package/dist/bundler-config/chunkSplit.cjs +3 -3
  6. package/dist/bundler-config/chunkSplit.d.ts +1 -1
  7. package/dist/bundler-config/chunkSplit.d.ts.map +1 -1
  8. package/dist/bundler-config/chunkSplit.js +2 -2
  9. package/dist/bundler-config/css.cjs +3 -3
  10. package/dist/bundler-config/css.d.ts +1 -1
  11. package/dist/bundler-config/css.d.ts.map +1 -1
  12. package/dist/bundler-config/css.js +2 -2
  13. package/dist/bundler-config/experimentCss.cjs +3 -3
  14. package/dist/bundler-config/experimentCss.d.ts +1 -1
  15. package/dist/bundler-config/experimentCss.d.ts.map +1 -1
  16. package/dist/bundler-config/experimentCss.js +2 -2
  17. package/dist/bundler-config/index.cjs +18 -14
  18. package/dist/bundler-config/index.d.ts.map +1 -1
  19. package/dist/bundler-config/index.js +22 -18
  20. package/dist/createUnpack.cjs +6 -3
  21. package/dist/createUnpack.d.ts.map +1 -1
  22. package/dist/createUnpack.js +7 -4
  23. package/dist/index.cjs +3 -0
  24. package/dist/index.d.ts +1 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +2 -0
  27. package/dist/logger.cjs +5 -3
  28. package/dist/logger.js +5 -3
  29. package/dist/plugin-progress/rspack.cjs +11 -2
  30. package/dist/plugin-progress/rspack.d.ts.map +1 -1
  31. package/dist/plugin-progress/rspack.js +11 -2
  32. package/dist/plugin-progress/webpack.cjs +11 -2
  33. package/dist/plugin-progress/webpack.d.ts.map +1 -1
  34. package/dist/plugin-progress/webpack.js +11 -2
  35. package/dist/prebundleDeps.cjs +349 -0
  36. package/dist/prebundleDeps.d.ts +5 -0
  37. package/dist/prebundleDeps.d.ts.map +1 -0
  38. package/dist/prebundleDeps.js +334 -0
  39. package/dist/run/dev.cjs +22 -39
  40. package/dist/run/dev.d.ts +1 -1
  41. package/dist/run/dev.d.ts.map +1 -1
  42. package/dist/run/dev.js +23 -40
  43. package/dist/thread-loader/worker.js +1 -1
  44. package/dist/types/config.d.ts +30 -8
  45. package/dist/types/config.d.ts.map +1 -1
  46. package/dist/types/logger.cjs +1 -0
  47. package/dist/types/logger.d.ts +2 -1
  48. package/dist/types/logger.d.ts.map +1 -1
  49. package/dist/types/logger.js +1 -0
  50. package/dist/utils.cjs +7 -0
  51. package/dist/utils.d.ts +3 -0
  52. package/dist/utils.d.ts.map +1 -1
  53. package/dist/utils.js +5 -0
  54. package/package.json +6 -9
  55. package/compiled/chokidar/index.d.ts +0 -327
  56. package/compiled/chokidar/index.js +0 -1773
  57. package/compiled/chokidar/license +0 -21
  58. package/compiled/chokidar/package.json +0 -1
@@ -0,0 +1,349 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+ var prebundleDeps_exports = {};
29
+ __export(prebundleDeps_exports, {
30
+ prebundleDeps: () => prebundleDeps
31
+ });
32
+ module.exports = __toCommonJS(prebundleDeps_exports);
33
+ var import_node_fs = __toESM(require("node:fs"));
34
+ var import_node_path = __toESM(require("node:path"));
35
+ var import_core = require("@rspack/core");
36
+ var import_cors = __toESM(require("cors"));
37
+ var import_express = __toESM(require("express"));
38
+ var import_html_webpack_plugin = __toESM(require("html-webpack-plugin"));
39
+ var import_tinyglobby = require("tinyglobby");
40
+ var import_colors = __toESM(require("./colors.cjs"));
41
+ var import_constants = require("./constants.cjs");
42
+ var import_logger = require("./logger.cjs");
43
+ var import_utils = require("./utils.cjs");
44
+ const app = (0, import_express.default)();
45
+ app.use((0, import_cors.default)());
46
+ const CACHE_DIR = "umd";
47
+ const externalAlias = {
48
+ react: "React",
49
+ "react-dom": "ReactDOM",
50
+ "react-router": "ReactRouter",
51
+ "react-router-dom": "ReactRouterDOM"
52
+ };
53
+ const count = {
54
+ total: 0,
55
+ bundled: 0
56
+ };
57
+ const failedDeps = [];
58
+ const noEntryDeps = [];
59
+ const updateProgress = () => {
60
+ (0, import_utils.logUpdate)(
61
+ `${import_colors.default.magenta(import_colors.default.bold("»"))} Optimizing dependencies (${count.bundled}/${count.total})`
62
+ );
63
+ if (count.total === count.bundled + failedDeps.length) {
64
+ console.log();
65
+ }
66
+ };
67
+ const getExternalLibraryName = (pkgName) => {
68
+ return externalAlias[pkgName] || pkgName;
69
+ };
70
+ const getExternalValue = (pkgName) => {
71
+ return `window ${getExternalLibraryName(pkgName)}`;
72
+ };
73
+ const bundleDep = ({
74
+ root,
75
+ name,
76
+ entry,
77
+ version
78
+ }) => {
79
+ return new Promise((resolve) => {
80
+ const pkgDir = import_node_path.default.resolve(root, import_constants.TEMP_DIR, CACHE_DIR, name);
81
+ const outDir = import_node_path.default.resolve(pkgDir, version);
82
+ const getResult = () => {
83
+ const assets = (0, import_tinyglobby.globSync)("**/index.{js,css}", {
84
+ cwd: outDir,
85
+ absolute: true
86
+ });
87
+ return {
88
+ name,
89
+ assets
90
+ };
91
+ };
92
+ if (import_node_fs.default.existsSync(outDir)) {
93
+ resolve(getResult());
94
+ return;
95
+ }
96
+ (0, import_utils.removeDir)(pkgDir);
97
+ count.total++;
98
+ updateProgress();
99
+ const getSwcOptions = ({ tsx }) => {
100
+ return {
101
+ jsc: {
102
+ parser: {
103
+ tsx,
104
+ syntax: "typescript",
105
+ dynamicImport: true,
106
+ decorators: true
107
+ },
108
+ transform: {
109
+ react: {
110
+ runtime: "automatic"
111
+ }
112
+ }
113
+ }
114
+ };
115
+ };
116
+ const compiler = (0, import_core.rspack)({
117
+ entry: {
118
+ index: entry
119
+ },
120
+ context: root,
121
+ mode: "development",
122
+ output: {
123
+ clean: true,
124
+ path: outDir,
125
+ pathinfo: false,
126
+ library: {
127
+ name: getExternalLibraryName(name),
128
+ type: "umd",
129
+ umdNamedDefine: true
130
+ },
131
+ globalObject: "this"
132
+ },
133
+ devtool: false,
134
+ module: {
135
+ rules: [
136
+ {
137
+ test: /\.(j|t)s$/,
138
+ use: [
139
+ {
140
+ loader: "builtin:swc-loader",
141
+ options: getSwcOptions({ tsx: false })
142
+ }
143
+ ]
144
+ },
145
+ {
146
+ test: /\.(j|t)sx$/,
147
+ use: [
148
+ {
149
+ loader: "builtin:swc-loader",
150
+ options: getSwcOptions({ tsx: true })
151
+ }
152
+ ]
153
+ },
154
+ {
155
+ test: /\.less$/,
156
+ type: "css/auto",
157
+ use: [
158
+ {
159
+ loader: (0, import_utils.getCompiledPkgPath)("less-loader"),
160
+ options: {
161
+ lessOptions: {
162
+ javascriptEnabled: true
163
+ },
164
+ implementation: (0, import_utils.getUserDepPath)(root, "less")
165
+ }
166
+ }
167
+ ]
168
+ },
169
+ {
170
+ test: /\.s[ac]ss$/i,
171
+ type: "css/auto",
172
+ use: [
173
+ {
174
+ loader: (0, import_utils.getCompiledPkgPath)("sass-loader"),
175
+ options: {
176
+ api: "modern-compiler",
177
+ implementation: (0, import_utils.getUserDepPath)(root, ["sass-embedded", "sass"])
178
+ }
179
+ }
180
+ ]
181
+ }
182
+ ]
183
+ },
184
+ optimization: {
185
+ splitChunks: false
186
+ },
187
+ experiments: {
188
+ css: true
189
+ },
190
+ externals: {
191
+ react: getExternalValue("react"),
192
+ "react-dom": getExternalValue("react-dom"),
193
+ "react-router": getExternalValue("react-router"),
194
+ "react-router-dom": getExternalValue("react-router-dom")
195
+ }
196
+ });
197
+ compiler.run((_, stats) => {
198
+ let isFailed = false;
199
+ if (stats?.hasErrors()) {
200
+ isFailed = true;
201
+ failedDeps.push(name);
202
+ (0, import_utils.removeDir)(outDir);
203
+ } else {
204
+ count.bundled++;
205
+ }
206
+ updateProgress();
207
+ compiler.close(() => {
208
+ resolve(!isFailed ? getResult() : void 0);
209
+ });
210
+ });
211
+ });
212
+ };
213
+ const getExistExternals = (externals) => {
214
+ const existExternals = /* @__PURE__ */ new Set();
215
+ if (Array.isArray(externals)) {
216
+ externals.forEach((item) => {
217
+ if ((0, import_utils.isPlainObject)(item)) {
218
+ Object.keys(item).forEach((key) => existExternals.add(key));
219
+ }
220
+ });
221
+ } else if ((0, import_utils.isPlainObject)(externals)) {
222
+ Object.keys(externals).forEach((key) => existExternals.add(key));
223
+ }
224
+ return Array.from(existExternals);
225
+ };
226
+ const getPkgEntry = (packageJson) => {
227
+ if (packageJson.module)
228
+ return packageJson.module;
229
+ if (packageJson.exports) {
230
+ if ((0, import_utils.isString)(packageJson.exports))
231
+ return packageJson.exports;
232
+ const defaultExport = packageJson.exports["."];
233
+ if (defaultExport) {
234
+ if ((0, import_utils.isString)(defaultExport))
235
+ return defaultExport;
236
+ if ((0, import_utils.isString)(defaultExport.import))
237
+ return defaultExport.import;
238
+ if ((0, import_utils.isString)(defaultExport.browser))
239
+ return defaultExport.browser;
240
+ if ((0, import_utils.isString)(defaultExport.default))
241
+ return defaultExport.default;
242
+ }
243
+ }
244
+ if (packageJson.main)
245
+ return packageJson.main;
246
+ };
247
+ const prebundleDeps = async ({
248
+ unpackConfig
249
+ }) => {
250
+ const userOptions = (0, import_utils.isPlainObject)(unpackConfig.dev?.prebundle) ? unpackConfig.dev.prebundle : {};
251
+ const { root } = unpackConfig;
252
+ const packageJson = JSON.parse(import_node_fs.default.readFileSync(import_node_path.default.resolve(root, "package.json"), "utf-8"));
253
+ const existExternals = getExistExternals(unpackConfig.externals);
254
+ const shouldIncludeDeps = Object.keys(packageJson.dependencies).filter(
255
+ (pkgName) => !existExternals.includes(pkgName) && !userOptions.exclude?.includes(pkgName)
256
+ );
257
+ const needBundleDeps = shouldIncludeDeps.map((pkgName) => {
258
+ const packageJson2 = JSON.parse(
259
+ import_node_fs.default.readFileSync(import_node_path.default.resolve(root, "node_modules", pkgName, "package.json"), "utf-8")
260
+ );
261
+ const entry = getPkgEntry(packageJson2);
262
+ if (!entry) {
263
+ noEntryDeps.push(pkgName);
264
+ return;
265
+ }
266
+ return {
267
+ name: pkgName,
268
+ entry: import_node_path.default.resolve(root, "node_modules", pkgName, entry),
269
+ version: packageJson2.version
270
+ };
271
+ }).filter(Boolean);
272
+ if (noEntryDeps[0]) {
273
+ import_logger.logger.warn(`Could not find entry for "${import_colors.default.bold(noEntryDeps.join(", "))}"`);
274
+ }
275
+ const bundledDeps = await Promise.all(
276
+ needBundleDeps.map((depInfo) => bundleDep({ root, ...depInfo }))
277
+ );
278
+ if (failedDeps[0]) {
279
+ import_logger.logger.warn(`Something went wrong while optimizing "${import_colors.default.bold(failedDeps.join(", "))}"`);
280
+ }
281
+ const cachePath = import_node_path.default.resolve(root, import_constants.TEMP_DIR, CACHE_DIR);
282
+ app.use(`/${CACHE_DIR}`, import_express.default.static(cachePath));
283
+ const port = await (0, import_utils.getPort)(3200);
284
+ app.listen(port, () => {
285
+ });
286
+ const externals = {};
287
+ const jsAssets = [];
288
+ const cssAssets = [];
289
+ const preJsAssets = [];
290
+ const ipv4Interfaces = (0, import_utils.getIpv4Interfaces)();
291
+ bundledDeps.filter(Boolean).forEach((dep) => {
292
+ externals[dep.name] = getExternalValue(dep.name);
293
+ dep.assets.forEach((absPath) => {
294
+ const relativePath = import_node_path.default.relative(cachePath, absPath);
295
+ const preDeps = ["react", "react-dom", "react-router", "react-router-dom"];
296
+ const serverPath = `//${ipv4Interfaces[1].address}:${port}/${CACHE_DIR}/${relativePath}`;
297
+ switch (import_node_path.default.extname(relativePath)) {
298
+ case ".js":
299
+ if (preDeps.includes(dep.name)) {
300
+ preJsAssets.push({
301
+ path: serverPath,
302
+ order: preDeps.indexOf(dep.name)
303
+ });
304
+ } else {
305
+ jsAssets.push(serverPath);
306
+ }
307
+ break;
308
+ case ".css":
309
+ cssAssets.push(serverPath);
310
+ break;
311
+ default:
312
+ break;
313
+ }
314
+ });
315
+ });
316
+ unpackConfig.externals = Array.isArray(unpackConfig.externals) ? [externals, ...unpackConfig.externals] : { ...externals, ...unpackConfig.externals };
317
+ const HtmlPlugin = unpackConfig.bundler === "rspack" ? import_core.rspack.HtmlRspackPlugin : import_html_webpack_plugin.default;
318
+ unpackConfig.plugins.push({
319
+ name: "unpack:prebundle",
320
+ bundlerConfig: (config) => {
321
+ const PLUGIN_NAME = "PluginInjectAssets";
322
+ config.plugins.push({
323
+ apply: (compiler) => {
324
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
325
+ HtmlPlugin.getCompilationHooks(compilation).beforeAssetTagGeneration.tapPromise(
326
+ PLUGIN_NAME,
327
+ async (args) => {
328
+ args.assets.js.unshift(
329
+ ...[
330
+ ...preJsAssets.sort((a, b) => a.order - b.order).map((item) => item.path),
331
+ ...jsAssets
332
+ ]
333
+ );
334
+ args.assets.css.unshift(...cssAssets);
335
+ return args;
336
+ }
337
+ );
338
+ });
339
+ }
340
+ });
341
+ return config;
342
+ }
343
+ });
344
+ return unpackConfig;
345
+ };
346
+ // Annotate the CommonJS export names for ESM import in node:
347
+ 0 && (module.exports = {
348
+ prebundleDeps
349
+ });
@@ -0,0 +1,5 @@
1
+ import type { UnpackConfig } from './types';
2
+ export declare const prebundleDeps: ({ unpackConfig, }: {
3
+ unpackConfig: UnpackConfig;
4
+ }) => Promise<UnpackConfig>;
5
+ //# sourceMappingURL=prebundleDeps.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prebundleDeps.d.ts","sourceRoot":"","sources":["../src/prebundleDeps.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AA+N3C,eAAO,MAAM,aAAa,sBAEvB;IACD,YAAY,EAAE,YAAY,CAAA;CAC3B,KAAG,OAAO,CAAC,YAAY,CA0GvB,CAAA"}
@@ -0,0 +1,334 @@
1
+ import { createRequire } from 'node:module';
2
+ var require = createRequire(import.meta['url']);
3
+
4
+ import path from "path";
5
+ import { fileURLToPath } from "url";
6
+ var getFilename = () => fileURLToPath(import.meta.url);
7
+ var getDirname = () => path.dirname(getFilename());
8
+ var __dirname = /* @__PURE__ */ getDirname();
9
+ var __filename = /* @__PURE__ */ getFilename();
10
+ import fs from "node:fs";
11
+ import path2 from "node:path";
12
+ import { rspack } from "@rspack/core";
13
+ import cors from "cors";
14
+ import express from "express";
15
+ import HtmlWebpackPlugin from "html-webpack-plugin";
16
+ import { globSync } from "tinyglobby";
17
+ import colors from "./colors.js";
18
+ import { TEMP_DIR } from "./constants.js";
19
+ import { logger } from "./logger.js";
20
+ import {
21
+ getCompiledPkgPath,
22
+ getIpv4Interfaces,
23
+ getPort,
24
+ getUserDepPath,
25
+ isPlainObject,
26
+ isString,
27
+ logUpdate,
28
+ removeDir
29
+ } from "./utils.js";
30
+ const app = express();
31
+ app.use(cors());
32
+ const CACHE_DIR = "umd";
33
+ const externalAlias = {
34
+ react: "React",
35
+ "react-dom": "ReactDOM",
36
+ "react-router": "ReactRouter",
37
+ "react-router-dom": "ReactRouterDOM"
38
+ };
39
+ const count = {
40
+ total: 0,
41
+ bundled: 0
42
+ };
43
+ const failedDeps = [];
44
+ const noEntryDeps = [];
45
+ const updateProgress = () => {
46
+ logUpdate(
47
+ `${colors.magenta(colors.bold("»"))} Optimizing dependencies (${count.bundled}/${count.total})`
48
+ );
49
+ if (count.total === count.bundled + failedDeps.length) {
50
+ console.log();
51
+ }
52
+ };
53
+ const getExternalLibraryName = (pkgName) => {
54
+ return externalAlias[pkgName] || pkgName;
55
+ };
56
+ const getExternalValue = (pkgName) => {
57
+ return `window ${getExternalLibraryName(pkgName)}`;
58
+ };
59
+ const bundleDep = ({
60
+ root,
61
+ name,
62
+ entry,
63
+ version
64
+ }) => {
65
+ return new Promise((resolve) => {
66
+ const pkgDir = path2.resolve(root, TEMP_DIR, CACHE_DIR, name);
67
+ const outDir = path2.resolve(pkgDir, version);
68
+ const getResult = () => {
69
+ const assets = globSync("**/index.{js,css}", {
70
+ cwd: outDir,
71
+ absolute: true
72
+ });
73
+ return {
74
+ name,
75
+ assets
76
+ };
77
+ };
78
+ if (fs.existsSync(outDir)) {
79
+ resolve(getResult());
80
+ return;
81
+ }
82
+ removeDir(pkgDir);
83
+ count.total++;
84
+ updateProgress();
85
+ const getSwcOptions = ({ tsx }) => {
86
+ return {
87
+ jsc: {
88
+ parser: {
89
+ tsx,
90
+ syntax: "typescript",
91
+ dynamicImport: true,
92
+ decorators: true
93
+ },
94
+ transform: {
95
+ react: {
96
+ runtime: "automatic"
97
+ }
98
+ }
99
+ }
100
+ };
101
+ };
102
+ const compiler = rspack({
103
+ entry: {
104
+ index: entry
105
+ },
106
+ context: root,
107
+ mode: "development",
108
+ output: {
109
+ clean: true,
110
+ path: outDir,
111
+ pathinfo: false,
112
+ library: {
113
+ name: getExternalLibraryName(name),
114
+ type: "umd",
115
+ umdNamedDefine: true
116
+ },
117
+ globalObject: "this"
118
+ },
119
+ devtool: false,
120
+ module: {
121
+ rules: [
122
+ {
123
+ test: /\.(j|t)s$/,
124
+ use: [
125
+ {
126
+ loader: "builtin:swc-loader",
127
+ options: getSwcOptions({ tsx: false })
128
+ }
129
+ ]
130
+ },
131
+ {
132
+ test: /\.(j|t)sx$/,
133
+ use: [
134
+ {
135
+ loader: "builtin:swc-loader",
136
+ options: getSwcOptions({ tsx: true })
137
+ }
138
+ ]
139
+ },
140
+ {
141
+ test: /\.less$/,
142
+ type: "css/auto",
143
+ use: [
144
+ {
145
+ loader: getCompiledPkgPath("less-loader"),
146
+ options: {
147
+ lessOptions: {
148
+ javascriptEnabled: true
149
+ },
150
+ implementation: getUserDepPath(root, "less")
151
+ }
152
+ }
153
+ ]
154
+ },
155
+ {
156
+ test: /\.s[ac]ss$/i,
157
+ type: "css/auto",
158
+ use: [
159
+ {
160
+ loader: getCompiledPkgPath("sass-loader"),
161
+ options: {
162
+ api: "modern-compiler",
163
+ implementation: getUserDepPath(root, ["sass-embedded", "sass"])
164
+ }
165
+ }
166
+ ]
167
+ }
168
+ ]
169
+ },
170
+ optimization: {
171
+ splitChunks: false
172
+ },
173
+ experiments: {
174
+ css: true
175
+ },
176
+ externals: {
177
+ react: getExternalValue("react"),
178
+ "react-dom": getExternalValue("react-dom"),
179
+ "react-router": getExternalValue("react-router"),
180
+ "react-router-dom": getExternalValue("react-router-dom")
181
+ }
182
+ });
183
+ compiler.run((_, stats) => {
184
+ let isFailed = false;
185
+ if (stats?.hasErrors()) {
186
+ isFailed = true;
187
+ failedDeps.push(name);
188
+ removeDir(outDir);
189
+ } else {
190
+ count.bundled++;
191
+ }
192
+ updateProgress();
193
+ compiler.close(() => {
194
+ resolve(!isFailed ? getResult() : void 0);
195
+ });
196
+ });
197
+ });
198
+ };
199
+ const getExistExternals = (externals) => {
200
+ const existExternals = /* @__PURE__ */ new Set();
201
+ if (Array.isArray(externals)) {
202
+ externals.forEach((item) => {
203
+ if (isPlainObject(item)) {
204
+ Object.keys(item).forEach((key) => existExternals.add(key));
205
+ }
206
+ });
207
+ } else if (isPlainObject(externals)) {
208
+ Object.keys(externals).forEach((key) => existExternals.add(key));
209
+ }
210
+ return Array.from(existExternals);
211
+ };
212
+ const getPkgEntry = (packageJson) => {
213
+ if (packageJson.module)
214
+ return packageJson.module;
215
+ if (packageJson.exports) {
216
+ if (isString(packageJson.exports))
217
+ return packageJson.exports;
218
+ const defaultExport = packageJson.exports["."];
219
+ if (defaultExport) {
220
+ if (isString(defaultExport))
221
+ return defaultExport;
222
+ if (isString(defaultExport.import))
223
+ return defaultExport.import;
224
+ if (isString(defaultExport.browser))
225
+ return defaultExport.browser;
226
+ if (isString(defaultExport.default))
227
+ return defaultExport.default;
228
+ }
229
+ }
230
+ if (packageJson.main)
231
+ return packageJson.main;
232
+ };
233
+ const prebundleDeps = async ({
234
+ unpackConfig
235
+ }) => {
236
+ const userOptions = isPlainObject(unpackConfig.dev?.prebundle) ? unpackConfig.dev.prebundle : {};
237
+ const { root } = unpackConfig;
238
+ const packageJson = JSON.parse(fs.readFileSync(path2.resolve(root, "package.json"), "utf-8"));
239
+ const existExternals = getExistExternals(unpackConfig.externals);
240
+ const shouldIncludeDeps = Object.keys(packageJson.dependencies).filter(
241
+ (pkgName) => !existExternals.includes(pkgName) && !userOptions.exclude?.includes(pkgName)
242
+ );
243
+ const needBundleDeps = shouldIncludeDeps.map((pkgName) => {
244
+ const packageJson2 = JSON.parse(
245
+ fs.readFileSync(path2.resolve(root, "node_modules", pkgName, "package.json"), "utf-8")
246
+ );
247
+ const entry = getPkgEntry(packageJson2);
248
+ if (!entry) {
249
+ noEntryDeps.push(pkgName);
250
+ return;
251
+ }
252
+ return {
253
+ name: pkgName,
254
+ entry: path2.resolve(root, "node_modules", pkgName, entry),
255
+ version: packageJson2.version
256
+ };
257
+ }).filter(Boolean);
258
+ if (noEntryDeps[0]) {
259
+ logger.warn(`Could not find entry for "${colors.bold(noEntryDeps.join(", "))}"`);
260
+ }
261
+ const bundledDeps = await Promise.all(
262
+ needBundleDeps.map((depInfo) => bundleDep({ root, ...depInfo }))
263
+ );
264
+ if (failedDeps[0]) {
265
+ logger.warn(`Something went wrong while optimizing "${colors.bold(failedDeps.join(", "))}"`);
266
+ }
267
+ const cachePath = path2.resolve(root, TEMP_DIR, CACHE_DIR);
268
+ app.use(`/${CACHE_DIR}`, express.static(cachePath));
269
+ const port = await getPort(3200);
270
+ app.listen(port, () => {
271
+ });
272
+ const externals = {};
273
+ const jsAssets = [];
274
+ const cssAssets = [];
275
+ const preJsAssets = [];
276
+ const ipv4Interfaces = getIpv4Interfaces();
277
+ bundledDeps.filter(Boolean).forEach((dep) => {
278
+ externals[dep.name] = getExternalValue(dep.name);
279
+ dep.assets.forEach((absPath) => {
280
+ const relativePath = path2.relative(cachePath, absPath);
281
+ const preDeps = ["react", "react-dom", "react-router", "react-router-dom"];
282
+ const serverPath = `//${ipv4Interfaces[1].address}:${port}/${CACHE_DIR}/${relativePath}`;
283
+ switch (path2.extname(relativePath)) {
284
+ case ".js":
285
+ if (preDeps.includes(dep.name)) {
286
+ preJsAssets.push({
287
+ path: serverPath,
288
+ order: preDeps.indexOf(dep.name)
289
+ });
290
+ } else {
291
+ jsAssets.push(serverPath);
292
+ }
293
+ break;
294
+ case ".css":
295
+ cssAssets.push(serverPath);
296
+ break;
297
+ default:
298
+ break;
299
+ }
300
+ });
301
+ });
302
+ unpackConfig.externals = Array.isArray(unpackConfig.externals) ? [externals, ...unpackConfig.externals] : { ...externals, ...unpackConfig.externals };
303
+ const HtmlPlugin = unpackConfig.bundler === "rspack" ? rspack.HtmlRspackPlugin : HtmlWebpackPlugin;
304
+ unpackConfig.plugins.push({
305
+ name: "unpack:prebundle",
306
+ bundlerConfig: (config) => {
307
+ const PLUGIN_NAME = "PluginInjectAssets";
308
+ config.plugins.push({
309
+ apply: (compiler) => {
310
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
311
+ HtmlPlugin.getCompilationHooks(compilation).beforeAssetTagGeneration.tapPromise(
312
+ PLUGIN_NAME,
313
+ async (args) => {
314
+ args.assets.js.unshift(
315
+ ...[
316
+ ...preJsAssets.sort((a, b) => a.order - b.order).map((item) => item.path),
317
+ ...jsAssets
318
+ ]
319
+ );
320
+ args.assets.css.unshift(...cssAssets);
321
+ return args;
322
+ }
323
+ );
324
+ });
325
+ }
326
+ });
327
+ return config;
328
+ }
329
+ });
330
+ return unpackConfig;
331
+ };
332
+ export {
333
+ prebundleDeps
334
+ };