@umijs/mfsu 4.0.0-rc.9 → 4.0.2

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.
@@ -11,9 +11,11 @@ const getAliasedPath_1 = require("./getAliasedPath");
11
11
  const isExternals_1 = require("./isExternals");
12
12
  // const UNMATCH_LIBS = ['umi', 'dumi', '@alipay/bigfish'];
13
13
  const RE_NODE_MODULES = /node_modules/;
14
- const RE_UMI_LOCAL_DEV = /umi(-next)?\/packages\//;
15
14
  function isUmiLocalDev(path) {
16
- return RE_UMI_LOCAL_DEV.test((0, utils_1.winPath)(path));
15
+ const rootPath = (0, utils_1.isLocalDev)();
16
+ return rootPath
17
+ ? (0, utils_1.winPath)(path).startsWith((0, utils_1.winPath)((0, path_1.join)(rootPath, './packages')))
18
+ : false;
17
19
  }
18
20
  function checkMatch({ value, path, opts, isExportAll, depth, cache, filename, }) {
19
21
  var _a, _b;
package/dist/dep/dep.js CHANGED
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -23,16 +14,13 @@ const trimFileContent_1 = require("../utils/trimFileContent");
23
14
  const getExposeFromContent_1 = require("./getExposeFromContent");
24
15
  const resolver = enhanced_resolve_1.default.create({
25
16
  mainFields: ['module', 'browser', 'main'],
26
- extensions: ['.js', '.json', '.mjs'],
27
- // TODO: support exports
28
- // tried to add exports, but it don't work with swr
29
- exportsFields: [],
17
+ extensions: ['.wasm', '.mjs', '.js', '.jsx', '.ts', '.tsx', '.json'],
18
+ exportsFields: ['exports'],
19
+ conditionNames: ['import', 'module', 'require', 'node'],
30
20
  });
31
- function resolve(context, path) {
32
- return __awaiter(this, void 0, void 0, function* () {
33
- return new Promise((resolve, reject) => {
34
- resolver(context, path, (err, result) => err ? reject(err) : resolve(result));
35
- });
21
+ async function resolve(context, path) {
22
+ return new Promise((resolve, reject) => {
23
+ resolver(context, path, (err, result) => err ? reject(err) : resolve(result));
36
24
  });
37
25
  }
38
26
  class Dep {
@@ -45,49 +33,49 @@ class Dep {
45
33
  this.filePath = `${constants_1.MF_VA_PREFIX}${this.normalizedFile}.js`;
46
34
  this.mfsu = opts.mfsu;
47
35
  }
48
- buildExposeContent() {
49
- return __awaiter(this, void 0, void 0, function* () {
50
- // node natives
51
- // @ts-ignore
52
- const isNodeNatives = !!process.binding('natives')[this.file];
53
- if (isNodeNatives) {
54
- return (0, trimFileContent_1.trimFileContent)(this.mfsu.opts.excludeNodeNatives
55
- ? `
36
+ async buildExposeContent() {
37
+ // node natives
38
+ // @ts-ignore
39
+ const isNodeNatives = !!process.binding('natives')[this.file];
40
+ if (isNodeNatives) {
41
+ return (0, trimFileContent_1.trimFileContent)(this.mfsu.opts.excludeNodeNatives
42
+ ? `
56
43
  const _ = require('${this.file}');
57
44
  module.exports = _;
58
45
  `
59
- : `
46
+ : `
60
47
  import _ from '${this.file}';
61
48
  export default _;
62
49
  export * from '${this.file}';
63
50
  `);
64
- }
65
- // none node natives
66
- const realFile = yield this.getRealFile();
67
- (0, assert_1.default)(realFile, `filePath not found of ${this.file}`);
68
- const content = (0, fs_1.readFileSync)(realFile, 'utf-8');
69
- return yield (0, getExposeFromContent_1.getExposeFromContent)({
70
- content,
71
- filePath: realFile,
72
- dep: this,
73
- });
51
+ }
52
+ // none node natives
53
+ const realFile = await this.getRealFile();
54
+ (0, assert_1.default)(realFile, `filePath not found of ${this.file}`);
55
+ const content = (0, fs_1.readFileSync)(realFile, 'utf-8');
56
+ return await (0, getExposeFromContent_1.getExposeFromContent)({
57
+ content,
58
+ filePath: realFile,
59
+ dep: this,
74
60
  });
75
61
  }
76
- getRealFile() {
77
- return __awaiter(this, void 0, void 0, function* () {
78
- try {
79
- // don't need to handle alias here
80
- // it's already handled by babel plugin
81
- return yield resolve(this.cwd, this.file);
82
- }
83
- catch (e) {
84
- return null;
85
- }
86
- });
62
+ async getRealFile() {
63
+ try {
64
+ // don't need to handle alias here
65
+ // it's already handled by babel plugin
66
+ return await resolve(this.cwd, this.file);
67
+ }
68
+ catch (e) {
69
+ return null;
70
+ }
87
71
  }
88
72
  static buildDeps(opts) {
89
73
  return Object.keys(opts.deps).map((file) => {
90
- return new Dep(Object.assign(Object.assign({}, opts.deps[file]), { cwd: opts.cwd, mfsu: opts.mfsu }));
74
+ return new Dep({
75
+ ...opts.deps[file],
76
+ cwd: opts.cwd,
77
+ mfsu: opts.mfsu,
78
+ });
91
79
  });
92
80
  }
93
81
  static getDepVersion(opts) {
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -16,62 +7,60 @@ exports.getExposeFromContent = void 0;
16
7
  const assert_1 = __importDefault(require("assert"));
17
8
  const path_1 = require("path");
18
9
  const getModuleExports_1 = require("./getModuleExports");
19
- function getExposeFromContent(opts) {
20
- return __awaiter(this, void 0, void 0, function* () {
21
- // Support CSS
22
- if (opts.filePath &&
23
- /\.(css|less|scss|sass|stylus|styl)$/.test(opts.filePath)) {
24
- return `import '${opts.dep.file}';`;
25
- }
26
- // Support Assets Files
27
- if (opts.filePath &&
28
- /\.(json|svg|png|jpe?g|avif|gif|webp|ico|eot|woff|woff2|ttf|txt|text|mdx?)$/.test(opts.filePath)) {
29
- return `
10
+ async function getExposeFromContent(opts) {
11
+ // Support CSS
12
+ if (opts.filePath &&
13
+ /\.(css|less|scss|sass|stylus|styl)$/.test(opts.filePath)) {
14
+ return `import '${opts.dep.file}';`;
15
+ }
16
+ // Support Assets Files
17
+ if (opts.filePath &&
18
+ /\.(json|svg|png|jpe?g|avif|gif|webp|ico|eot|woff|woff2|ttf|txt|text|mdx?)$/.test(opts.filePath)) {
19
+ return `
30
20
  import _ from '${opts.dep.file}';
31
21
  export default _;`.trim();
22
+ }
23
+ (0, assert_1.default)(/(js|jsx|mjs|ts|tsx)$/.test(opts.filePath), `file type not supported for ${(0, path_1.basename)(opts.filePath)}.`);
24
+ const { exports, isCJS } = await (0, getModuleExports_1.getModuleExports)({
25
+ content: opts.content,
26
+ filePath: opts.filePath,
27
+ });
28
+ // cjs
29
+ if (isCJS) {
30
+ return [
31
+ `import _ from '${opts.dep.file}';`,
32
+ `export default _;`,
33
+ `export * from '${opts.dep.file}';`,
34
+ ].join('\n');
35
+ }
36
+ // esm
37
+ else {
38
+ const ret = [];
39
+ let hasExports = false;
40
+ if (exports.includes('default')) {
41
+ ret.push(`import _ from '${opts.dep.file}';`);
42
+ ret.push(`export default _;`);
43
+ hasExports = true;
32
44
  }
33
- (0, assert_1.default)(/(js|jsx|mjs|ts|tsx)$/.test(opts.filePath), `file type not supported for ${(0, path_1.basename)(opts.filePath)}.`);
34
- const { exports, isCJS } = yield (0, getModuleExports_1.getModuleExports)({
35
- content: opts.content,
36
- filePath: opts.filePath,
37
- });
38
- // cjs
39
- if (isCJS) {
40
- return [
41
- `import _ from '${opts.dep.file}';`,
42
- `export default _;`,
43
- `export * from '${opts.dep.file}';`,
44
- ].join('\n');
45
+ if (hasNonDefaultExports(exports) ||
46
+ // export * from 不会有 exports,只会有 imports
47
+ /export\s+\*\s+from/.test(opts.content)) {
48
+ ret.push(`export * from '${opts.dep.file}';`);
49
+ hasExports = true;
45
50
  }
46
- // esm
47
- else {
48
- const ret = [];
49
- let hasExports = false;
50
- if (exports.includes('default')) {
51
+ if (!hasExports) {
52
+ // 只有 __esModule 的全量导出
53
+ if (exports.includes('__esModule')) {
51
54
  ret.push(`import _ from '${opts.dep.file}';`);
52
55
  ret.push(`export default _;`);
53
- hasExports = true;
54
- }
55
- if (hasNonDefaultExports(exports) ||
56
- // export * from 不会有 exports,只会有 imports
57
- /export\s+\*\s+from/.test(opts.content)) {
58
56
  ret.push(`export * from '${opts.dep.file}';`);
59
- hasExports = true;
60
57
  }
61
- if (!hasExports) {
62
- // 只有 __esModule 的全量导出
63
- if (exports.includes('__esModule')) {
64
- ret.push(`import _ from '${opts.dep.file}';`);
65
- ret.push(`export default _;`);
66
- ret.push(`export * from '${opts.dep.file}';`);
67
- }
68
- else {
69
- ret.push(`import '${opts.dep.file}';`);
70
- }
58
+ else {
59
+ ret.push(`import '${opts.dep.file}';`);
71
60
  }
72
- return ret.join('\n');
73
61
  }
74
- });
62
+ return ret.join('\n');
63
+ }
75
64
  }
76
65
  exports.getExposeFromContent = getExposeFromContent;
77
66
  function hasNonDefaultExports(exports) {
@@ -1,45 +1,34 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.getModuleExports = void 0;
13
4
  const es_module_lexer_1 = require("@umijs/bundler-utils/compiled/es-module-lexer");
14
5
  const esbuild_1 = require("@umijs/bundler-utils/compiled/esbuild");
15
6
  const path_1 = require("path");
16
7
  const getCJSExports_1 = require("./getCJSExports");
17
- function getModuleExports({ content, filePath, }) {
18
- return __awaiter(this, void 0, void 0, function* () {
19
- // Support tsx and jsx
20
- if (filePath && /\.(tsx|jsx)$/.test(filePath)) {
21
- content = (yield (0, esbuild_1.transform)(content, {
22
- sourcemap: false,
23
- sourcefile: filePath,
24
- format: 'esm',
25
- target: 'es6',
26
- loader: (0, path_1.extname)(filePath).slice(1),
27
- })).code;
8
+ async function getModuleExports({ content, filePath, }) {
9
+ // Support tsx and jsx
10
+ if (filePath && /\.(tsx|jsx)$/.test(filePath)) {
11
+ content = (await (0, esbuild_1.transform)(content, {
12
+ sourcemap: false,
13
+ sourcefile: filePath,
14
+ format: 'esm',
15
+ target: 'es6',
16
+ loader: (0, path_1.extname)(filePath).slice(1),
17
+ })).code;
18
+ }
19
+ await es_module_lexer_1.init;
20
+ const [imports, exports] = (0, es_module_lexer_1.parse)(content);
21
+ let isCJS = !imports.length && !exports.length;
22
+ let cjsEsmExports = null;
23
+ if (isCJS) {
24
+ cjsEsmExports = (0, getCJSExports_1.getCJSExports)({ content });
25
+ if (cjsEsmExports.includes('__esModule')) {
26
+ isCJS = false;
28
27
  }
29
- yield es_module_lexer_1.init;
30
- const [imports, exports] = (0, es_module_lexer_1.parse)(content);
31
- let isCJS = !imports.length && !exports.length;
32
- let cjsEsmExports = null;
33
- if (isCJS) {
34
- cjsEsmExports = (0, getCJSExports_1.getCJSExports)({ content });
35
- if (cjsEsmExports.includes('__esModule')) {
36
- isCJS = false;
37
- }
38
- }
39
- return {
40
- exports: cjsEsmExports || exports,
41
- isCJS,
42
- };
43
- });
28
+ }
29
+ return {
30
+ exports: cjsEsmExports || exports,
31
+ isCJS,
32
+ };
44
33
  }
45
34
  exports.getModuleExports = getModuleExports;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.DepBuilder = void 0;
13
4
  const bundler_esbuild_1 = require("@umijs/bundler-esbuild");
@@ -24,75 +15,77 @@ class DepBuilder {
24
15
  this.isBuilding = false;
25
16
  this.opts = opts;
26
17
  }
27
- buildWithWebpack(opts) {
28
- return __awaiter(this, void 0, void 0, function* () {
29
- const config = this.getWebpackConfig({ deps: opts.deps });
30
- return new Promise((resolve, reject) => {
31
- const compiler = this.opts.mfsu.opts.implementor(config);
32
- compiler.run((err, stats) => {
33
- opts.onBuildComplete();
34
- if (err || (stats === null || stats === void 0 ? void 0 : stats.hasErrors())) {
35
- if (err) {
36
- reject(err);
37
- }
38
- if (stats) {
39
- const errorMsg = stats.toString('errors-only');
40
- // console.error(errorMsg);
41
- reject(new Error(errorMsg));
42
- }
18
+ async buildWithWebpack(opts) {
19
+ const config = this.getWebpackConfig({ deps: opts.deps });
20
+ return new Promise((resolve, reject) => {
21
+ const compiler = this.opts.mfsu.opts.implementor(config);
22
+ compiler.run((err, stats) => {
23
+ opts.onBuildComplete();
24
+ if (err || (stats === null || stats === void 0 ? void 0 : stats.hasErrors())) {
25
+ if (err) {
26
+ reject(err);
43
27
  }
44
- else {
45
- resolve(stats);
28
+ if (stats) {
29
+ const errorMsg = stats.toString('errors-only');
30
+ // console.error(errorMsg);
31
+ reject(new Error(errorMsg));
46
32
  }
47
- compiler.close(() => { });
48
- });
33
+ }
34
+ else {
35
+ resolve(stats);
36
+ }
37
+ compiler.close(() => { });
49
38
  });
50
39
  });
51
40
  }
52
41
  // TODO: support watch and rebuild
53
- buildWithESBuild(opts) {
54
- return __awaiter(this, void 0, void 0, function* () {
55
- const entryContent = (0, getESBuildEntry_1.getESBuildEntry)({ deps: opts.deps });
56
- const ENTRY_FILE = 'esbuild-entry.js';
57
- const tmpDir = this.opts.mfsu.opts.tmpBase;
58
- const entryPath = (0, path_1.join)(tmpDir, ENTRY_FILE);
59
- (0, fs_1.writeFileSync)(entryPath, entryContent, 'utf-8');
60
- const date = new Date().getTime();
61
- yield (0, bundler_esbuild_1.build)({
62
- cwd: this.opts.mfsu.opts.cwd,
63
- entry: {
64
- [`${constants_1.MF_VA_PREFIX}remoteEntry`]: entryPath,
65
- },
66
- config: Object.assign(Object.assign({}, this.opts.mfsu.opts.depBuildConfig), { outputPath: tmpDir, alias: this.opts.mfsu.alias, externals: this.opts.mfsu.externals }),
67
- inlineStyle: true,
68
- });
69
- utils_1.logger.event(`[mfsu] compiled with esbuild successfully in ${+new Date() - date} ms`);
70
- opts.onBuildComplete();
42
+ async buildWithESBuild(opts) {
43
+ const entryContent = (0, getESBuildEntry_1.getESBuildEntry)({ deps: opts.deps });
44
+ const ENTRY_FILE = 'esbuild-entry.js';
45
+ const tmpDir = this.opts.mfsu.opts.tmpBase;
46
+ const entryPath = (0, path_1.join)(tmpDir, ENTRY_FILE);
47
+ (0, fs_1.writeFileSync)(entryPath, entryContent, 'utf-8');
48
+ const date = new Date().getTime();
49
+ await (0, bundler_esbuild_1.build)({
50
+ cwd: this.opts.mfsu.opts.cwd,
51
+ entry: {
52
+ [`${constants_1.MF_VA_PREFIX}remoteEntry`]: entryPath,
53
+ },
54
+ config: {
55
+ ...this.opts.mfsu.opts.depBuildConfig,
56
+ outputPath: tmpDir,
57
+ alias: this.opts.mfsu.alias,
58
+ externals: this.opts.mfsu.externals,
59
+ },
60
+ inlineStyle: true,
71
61
  });
62
+ utils_1.logger.event(`[mfsu] compiled with esbuild successfully in ${+new Date() - date} ms`);
63
+ opts.onBuildComplete();
72
64
  }
73
- build(opts) {
74
- return __awaiter(this, void 0, void 0, function* () {
75
- this.isBuilding = true;
76
- const onBuildComplete = () => {
77
- this.isBuilding = false;
78
- this.completeFns.forEach((fn) => fn());
79
- this.completeFns = [];
65
+ async build(opts) {
66
+ this.isBuilding = true;
67
+ const onBuildComplete = () => {
68
+ this.isBuilding = false;
69
+ this.completeFns.forEach((fn) => fn());
70
+ this.completeFns = [];
71
+ };
72
+ try {
73
+ await this.writeMFFiles({ deps: opts.deps });
74
+ const newOpts = {
75
+ ...opts,
76
+ onBuildComplete,
80
77
  };
81
- try {
82
- yield this.writeMFFiles({ deps: opts.deps });
83
- const newOpts = Object.assign(Object.assign({}, opts), { onBuildComplete });
84
- if (this.opts.mfsu.opts.buildDepWithESBuild) {
85
- yield this.buildWithESBuild(newOpts);
86
- }
87
- else {
88
- yield this.buildWithWebpack(newOpts);
89
- }
78
+ if (this.opts.mfsu.opts.buildDepWithESBuild) {
79
+ await this.buildWithESBuild(newOpts);
90
80
  }
91
- catch (e) {
92
- onBuildComplete();
93
- throw e;
81
+ else {
82
+ await this.buildWithWebpack(newOpts);
94
83
  }
95
- });
84
+ }
85
+ catch (e) {
86
+ onBuildComplete();
87
+ throw e;
88
+ }
96
89
  }
97
90
  onBuildComplete(fn) {
98
91
  if (this.isBuilding) {
@@ -102,18 +95,16 @@ class DepBuilder {
102
95
  fn();
103
96
  }
104
97
  }
105
- writeMFFiles(opts) {
106
- return __awaiter(this, void 0, void 0, function* () {
107
- const tmpBase = this.opts.mfsu.opts.tmpBase;
108
- utils_1.fsExtra.mkdirpSync(tmpBase);
109
- // expose files
110
- for (const dep of opts.deps) {
111
- const content = yield dep.buildExposeContent();
112
- (0, fs_1.writeFileSync)((0, path_1.join)(tmpBase, dep.filePath), content, 'utf-8');
113
- }
114
- // index file
115
- (0, fs_1.writeFileSync)((0, path_1.join)(tmpBase, 'index.js'), '"😛"', 'utf-8');
116
- });
98
+ async writeMFFiles(opts) {
99
+ const tmpBase = this.opts.mfsu.opts.tmpBase;
100
+ utils_1.fsExtra.mkdirpSync(tmpBase);
101
+ // expose files
102
+ for (const dep of opts.deps) {
103
+ const content = await dep.buildExposeContent();
104
+ (0, fs_1.writeFileSync)((0, path_1.join)(tmpBase, dep.filePath), content, 'utf-8');
105
+ }
106
+ // index file
107
+ (0, fs_1.writeFileSync)((0, path_1.join)(tmpBase, 'index.js'), '"😛"', 'utf-8');
117
108
  }
118
109
  getWebpackConfig(opts) {
119
110
  var _a, _b;
@@ -151,6 +142,9 @@ class DepBuilder {
151
142
  depConfig.plugins.push(new stripSourceMapUrlPlugin_1.StripSourceMapUrlPlugin({
152
143
  webpack: this.opts.mfsu.opts.implementor,
153
144
  }));
145
+ depConfig.plugins.push(new this.opts.mfsu.opts.implementor.ProgressPlugin((percent, msg) => {
146
+ this.opts.mfsu.onProgress({ percent, status: msg });
147
+ }));
154
148
  const exposes = opts.deps.reduce((memo, dep) => {
155
149
  memo[`./${dep.file}`] = (0, path_1.join)(this.opts.mfsu.opts.tmpBase, dep.filePath);
156
150
  return memo;
package/dist/depInfo.js CHANGED
@@ -27,7 +27,7 @@ class DepInfo {
27
27
  }
28
28
  loadCache() {
29
29
  if ((0, fs_1.existsSync)(this.cacheFilePath)) {
30
- utils_1.logger.info('MFSU restore cache');
30
+ utils_1.logger.info('[MFSU] restore cache');
31
31
  const { cacheDependency, moduleGraph } = JSON.parse((0, fs_1.readFileSync)(this.cacheFilePath, 'utf-8'));
32
32
  this.cacheDependency = cacheDependency;
33
33
  this.moduleGraph.restore(moduleGraph);
@@ -43,7 +43,7 @@ class DepInfo {
43
43
  (0, fs_1.readFileSync)(this.cacheFilePath, 'utf-8') === newContent) {
44
44
  return;
45
45
  }
46
- utils_1.logger.info('MFSU write cache');
46
+ utils_1.logger.info('[MFSU] write cache');
47
47
  (0, fs_1.writeFileSync)(this.cacheFilePath, newContent, 'utf-8');
48
48
  }
49
49
  }
@@ -1,54 +1,38 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
2
  Object.defineProperty(exports, "__esModule", { value: true });
23
3
  exports.esbuildLoader = void 0;
24
4
  const es_module_lexer_1 = require("@umijs/bundler-utils/compiled/es-module-lexer");
25
5
  const esbuild_1 = require("@umijs/bundler-utils/compiled/esbuild");
26
6
  const path_1 = require("path");
27
- function esbuildTranspiler(source) {
7
+ async function esbuildTranspiler(source) {
28
8
  var _a;
29
- return __awaiter(this, void 0, void 0, function* () {
30
- const done = this.async();
31
- const options = this.getOptions();
32
- const { handler = [], implementation } = options, otherOptions = __rest(options, ["handler", "implementation"]);
33
- const transform = (implementation === null || implementation === void 0 ? void 0 : implementation.transform) || esbuild_1.transform;
34
- const filePath = this.resourcePath;
35
- const ext = (0, path_1.extname)(filePath).slice(1);
36
- const transformOptions = Object.assign(Object.assign({}, otherOptions), { target: (_a = options.target) !== null && _a !== void 0 ? _a : 'es2015', loader: ext !== null && ext !== void 0 ? ext : 'js', sourcemap: this.sourceMap, sourcefile: filePath });
37
- try {
38
- let { code, map } = yield transform(source, transformOptions);
39
- if (handler.length) {
40
- yield es_module_lexer_1.init;
41
- handler.forEach((handle) => {
42
- const [imports, exports] = (0, es_module_lexer_1.parse)(code);
43
- code = handle({ code, imports, exports, filePath });
44
- });
45
- }
46
- done(null, code, map && JSON.parse(map));
47
- }
48
- catch (error) {
49
- done(error);
9
+ const done = this.async();
10
+ const options = this.getOptions();
11
+ const { handler = [], implementation, ...otherOptions } = options;
12
+ const transform = (implementation === null || implementation === void 0 ? void 0 : implementation.transform) || esbuild_1.transform;
13
+ const filePath = this.resourcePath;
14
+ const ext = (0, path_1.extname)(filePath).slice(1);
15
+ const transformOptions = {
16
+ ...otherOptions,
17
+ target: (_a = options.target) !== null && _a !== void 0 ? _a : 'es2015',
18
+ loader: ext !== null && ext !== void 0 ? ext : 'js',
19
+ sourcemap: this.sourceMap,
20
+ sourcefile: filePath,
21
+ };
22
+ try {
23
+ let { code, map } = await transform(source, transformOptions);
24
+ if (handler.length) {
25
+ await es_module_lexer_1.init;
26
+ handler.forEach((handle) => {
27
+ const [imports, exports] = (0, es_module_lexer_1.parse)(code);
28
+ code = handle({ code, imports, exports, filePath });
29
+ });
50
30
  }
51
- });
31
+ done(null, code, map && JSON.parse(map));
32
+ }
33
+ catch (error) {
34
+ done(error);
35
+ }
52
36
  }
53
37
  exports.default = esbuildTranspiler;
54
38
  exports.esbuildLoader = __filename;
package/dist/mfsu.d.ts CHANGED
@@ -9,6 +9,7 @@ interface IOpts {
9
9
  excludeNodeNatives?: boolean;
10
10
  exportAllMembers?: Record<string, string[]>;
11
11
  getCacheDependency?: Function;
12
+ onMFSUProgress?: Function;
12
13
  mfName?: string;
13
14
  mode?: Mode;
14
15
  tmpBase?: string;
@@ -26,6 +27,9 @@ export declare class MFSU {
26
27
  depBuilder: DepBuilder;
27
28
  depConfig: Configuration | null;
28
29
  buildDepsAgain: boolean;
30
+ progress: any;
31
+ onProgress: Function;
32
+ publicPath: string;
29
33
  constructor(opts: IOpts);
30
34
  asyncImport(content: string): string;
31
35
  setWebpackConfig(opts: {
package/dist/mfsu.js CHANGED
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -37,12 +28,22 @@ class MFSU {
37
28
  this.externals = [];
38
29
  this.depConfig = null;
39
30
  this.buildDepsAgain = false;
31
+ this.progress = { done: false };
32
+ this.publicPath = '/';
40
33
  this.opts = opts;
41
34
  this.opts.mfName = this.opts.mfName || constants_1.DEFAULT_MF_NAME;
42
35
  this.opts.tmpBase =
43
36
  this.opts.tmpBase || (0, path_1.join)(process.cwd(), constants_1.DEFAULT_TMP_DIR_NAME);
44
37
  this.opts.mode = this.opts.mode || types_1.Mode.development;
45
38
  this.opts.getCacheDependency = this.opts.getCacheDependency || (() => ({}));
39
+ this.onProgress = (progress) => {
40
+ var _a, _b;
41
+ this.progress = {
42
+ ...this.progress,
43
+ ...progress,
44
+ };
45
+ (_b = (_a = this.opts).onMFSUProgress) === null || _b === void 0 ? void 0 : _b.call(_a, this.progress);
46
+ };
46
47
  this.opts.cwd = this.opts.cwd || process.cwd();
47
48
  this.depInfo = new depInfo_1.DepInfo({ mfsu: this });
48
49
  this.depBuilder = new depBuilder_1.DepBuilder({ mfsu: this });
@@ -54,86 +55,88 @@ class MFSU {
54
55
  return `await import('${(0, utils_1.winPath)(content)}');`;
55
56
  // return `(async () => await import('${content}'))();`;
56
57
  }
57
- setWebpackConfig(opts) {
58
+ async setWebpackConfig(opts) {
58
59
  var _a;
59
- return __awaiter(this, void 0, void 0, function* () {
60
- const { mfName } = this.opts;
61
- /**
62
- * config
63
- */
64
- // set alias and externals with reference for babel plugin
65
- Object.assign(this.alias, ((_a = opts.config.resolve) === null || _a === void 0 ? void 0 : _a.alias) || {});
66
- this.externals.push(...(0, makeArray_1.makeArray)(opts.config.externals || []));
67
- // entry
68
- const entry = {};
69
- const virtualModules = {};
70
- // ensure entry object type
71
- const entryObject = utils_1.lodash.isString(opts.config.entry)
72
- ? { default: [opts.config.entry] }
73
- : opts.config.entry;
74
- (0, assert_1.default)(utils_1.lodash.isPlainObject(entryObject), `webpack config 'entry' value must be a string or an object.`);
75
- for (const key of Object.keys(entryObject)) {
76
- const virtualPath = `./mfsu-virtual-entry/${key}.js`;
77
- const virtualContent = [];
78
- let index = 1;
79
- let hasDefaultExport = false;
80
- const entryFiles = utils_1.lodash.isArray(entryObject[key])
81
- ? entryObject[key]
82
- : [entryObject[key]];
83
- for (let entry of entryFiles) {
84
- // ensure entry is a file
85
- if ((0, fs_1.statSync)(entry).isDirectory()) {
86
- const realEntry = (0, utils_1.tryPaths)([
87
- (0, path_1.join)(entry, 'index.tsx'),
88
- (0, path_1.join)(entry, 'index.ts'),
89
- ]);
90
- (0, assert_1.default)(realEntry, `entry file not found, please configure the specific entry path. (e.g. 'src/index.tsx')`);
91
- entry = realEntry;
92
- }
93
- const content = (0, fs_1.readFileSync)(entry, 'utf-8');
94
- const [_imports, exports] = yield (0, bundler_utils_1.parseModule)({ content, path: entry });
95
- if (exports.length) {
96
- virtualContent.push(`const k${index} = ${this.asyncImport(entry)}`);
97
- for (const exportName of exports) {
98
- if (exportName === 'default') {
99
- hasDefaultExport = true;
100
- virtualContent.push(`export default k${index}.${exportName}`);
101
- }
102
- else {
103
- virtualContent.push(`export const ${exportName} = k${index}.${exportName}`);
104
- }
60
+ const { mfName } = this.opts;
61
+ /**
62
+ * config
63
+ */
64
+ // set alias and externals with reference for babel plugin
65
+ Object.assign(this.alias, ((_a = opts.config.resolve) === null || _a === void 0 ? void 0 : _a.alias) || {});
66
+ this.externals.push(...(0, makeArray_1.makeArray)(opts.config.externals || []));
67
+ // entry
68
+ const entry = {};
69
+ const virtualModules = {};
70
+ // ensure entry object type
71
+ const entryObject = utils_1.lodash.isString(opts.config.entry)
72
+ ? { default: [opts.config.entry] }
73
+ : opts.config.entry;
74
+ (0, assert_1.default)(utils_1.lodash.isPlainObject(entryObject), `webpack config 'entry' value must be a string or an object.`);
75
+ for (const key of Object.keys(entryObject)) {
76
+ const virtualPath = `./mfsu-virtual-entry/${key}.js`;
77
+ const virtualContent = [];
78
+ let index = 1;
79
+ let hasDefaultExport = false;
80
+ const entryFiles = utils_1.lodash.isArray(entryObject[key])
81
+ ? entryObject[key]
82
+ : [entryObject[key]];
83
+ for (let entry of entryFiles) {
84
+ // ensure entry is a file
85
+ if ((0, fs_1.statSync)(entry).isDirectory()) {
86
+ const realEntry = (0, utils_1.tryPaths)([
87
+ (0, path_1.join)(entry, 'index.tsx'),
88
+ (0, path_1.join)(entry, 'index.ts'),
89
+ (0, path_1.join)(entry, 'index.jsx'),
90
+ (0, path_1.join)(entry, 'index.js'),
91
+ ]);
92
+ (0, assert_1.default)(realEntry, `entry file not found, please configure the specific entry path. (e.g. 'src/index.tsx')`);
93
+ entry = realEntry;
94
+ }
95
+ const content = (0, fs_1.readFileSync)(entry, 'utf-8');
96
+ const [_imports, exports] = await (0, bundler_utils_1.parseModule)({ content, path: entry });
97
+ if (exports.length) {
98
+ virtualContent.push(`const k${index} = ${this.asyncImport(entry)}`);
99
+ for (const exportName of exports) {
100
+ if (exportName === 'default') {
101
+ hasDefaultExport = true;
102
+ virtualContent.push(`export default k${index}.${exportName}`);
103
+ }
104
+ else {
105
+ virtualContent.push(`export const ${exportName} = k${index}.${exportName}`);
105
106
  }
106
107
  }
107
- else {
108
- virtualContent.push(this.asyncImport(entry));
109
- }
110
- index += 1;
111
108
  }
112
- if (!hasDefaultExport) {
113
- virtualContent.push(`export default 1;`);
109
+ else {
110
+ virtualContent.push(this.asyncImport(entry));
114
111
  }
115
- virtualModules[virtualPath] = virtualContent.join('\n');
116
- entry[key] = virtualPath;
112
+ index += 1;
117
113
  }
118
- opts.config.entry = entry;
119
- // plugins
120
- opts.config.plugins = opts.config.plugins || [];
121
- // support publicPath auto
122
- let publicPath = opts.config.output.publicPath;
123
- if (publicPath === 'auto') {
124
- publicPath = '/';
114
+ if (!hasDefaultExport) {
115
+ virtualContent.push(`export default 1;`);
125
116
  }
126
- opts.config.plugins.push(...[
127
- new webpack_virtual_modules_1.default(virtualModules),
128
- new this.opts.implementor.container.ModuleFederationPlugin({
129
- name: '__',
130
- remotes: {
131
- [mfName]: this.opts.runtimePublicPath
132
- ? // ref:
133
- // https://webpack.js.org/concepts/module-federation/#promise-based-dynamic-remotes
134
- `
117
+ virtualModules[virtualPath] = virtualContent.join('\n');
118
+ entry[key] = virtualPath;
119
+ }
120
+ opts.config.entry = entry;
121
+ // plugins
122
+ opts.config.plugins = opts.config.plugins || [];
123
+ // support publicPath auto
124
+ let publicPath = opts.config.output.publicPath;
125
+ if (publicPath === 'auto') {
126
+ publicPath = '/';
127
+ }
128
+ this.publicPath = publicPath;
129
+ opts.config.plugins.push(...[
130
+ new webpack_virtual_modules_1.default(virtualModules),
131
+ new this.opts.implementor.container.ModuleFederationPlugin({
132
+ name: '__',
133
+ remotes: {
134
+ [mfName]: this.opts.runtimePublicPath
135
+ ? // ref:
136
+ // https://webpack.js.org/concepts/module-federation/#promise-based-dynamic-remotes
137
+ `
135
138
  promise new Promise(resolve => {
136
- const remoteUrlWithVersion = window.publicPath + '${constants_1.REMOTE_FILE_FULL}';
139
+ const remoteUrlWithVersion = (window.publicPath || '/') + '${constants_1.REMOTE_FILE_FULL}';
137
140
  const script = document.createElement('script');
138
141
  script.src = remoteUrlWithVersion;
139
142
  script.onload = () => {
@@ -155,68 +158,74 @@ promise new Promise(resolve => {
155
158
  document.head.appendChild(script);
156
159
  })
157
160
  `.trimLeft()
158
- : `${mfName}@${publicPath}${constants_1.REMOTE_FILE_FULL}`,
159
- },
160
- }),
161
- new buildDepPlugin_1.BuildDepPlugin({
162
- onCompileDone: () => {
163
- if (this.depBuilder.isBuilding) {
164
- this.buildDepsAgain = true;
165
- }
166
- else {
167
- this.buildDeps().catch((e) => {
168
- utils_1.logger.error(e);
161
+ : `${mfName}@${publicPath}${constants_1.REMOTE_FILE_FULL}`,
162
+ },
163
+ }),
164
+ new buildDepPlugin_1.BuildDepPlugin({
165
+ onCompileDone: () => {
166
+ if (this.depBuilder.isBuilding) {
167
+ this.buildDepsAgain = true;
168
+ }
169
+ else {
170
+ this.buildDeps()
171
+ .then(() => {
172
+ this.onProgress({
173
+ done: true,
169
174
  });
170
- }
171
- },
172
- }),
173
- // new WriteCachePlugin({
174
- // onWriteCache: lodash.debounce(() => {
175
- // this.depInfo.writeCache();
176
- // }, 300),
177
- // }),
178
- ]);
179
- // ensure topLevelAwait enabled
180
- utils_1.lodash.set(opts.config, 'experiments.topLevelAwait', true);
181
- /**
182
- * depConfig
183
- */
184
- this.depConfig = opts.depConfig;
185
- });
175
+ })
176
+ .catch((e) => {
177
+ utils_1.logger.error(e);
178
+ this.onProgress({
179
+ done: true,
180
+ });
181
+ });
182
+ }
183
+ },
184
+ }),
185
+ // new WriteCachePlugin({
186
+ // onWriteCache: lodash.debounce(() => {
187
+ // this.depInfo.writeCache();
188
+ // }, 300),
189
+ // }),
190
+ ]);
191
+ // ensure topLevelAwait enabled
192
+ utils_1.lodash.set(opts.config, 'experiments.topLevelAwait', true);
193
+ /**
194
+ * depConfig
195
+ */
196
+ this.depConfig = opts.depConfig;
186
197
  }
187
- buildDeps() {
188
- return __awaiter(this, void 0, void 0, function* () {
189
- const shouldBuild = this.depInfo.shouldBuild();
190
- if (!shouldBuild) {
191
- utils_1.logger.info('MFSU skip buildDeps');
192
- return;
193
- }
194
- this.depInfo.snapshot();
195
- const deps = dep_1.Dep.buildDeps({
196
- deps: this.depInfo.moduleGraph.depSnapshotModules,
197
- cwd: this.opts.cwd,
198
- mfsu: this,
199
- });
200
- utils_1.logger.info(`MFSU buildDeps since ${shouldBuild}`);
201
- utils_1.logger.debug(deps.map((dep) => dep.file).join(', '));
202
- yield this.depBuilder.build({
203
- deps,
204
- });
205
- // Write cache
206
- this.depInfo.writeCache();
207
- if (this.buildDepsAgain) {
208
- utils_1.logger.info('MFSU buildDepsAgain');
209
- this.buildDepsAgain = false;
210
- this.buildDeps().catch((e) => {
211
- utils_1.logger.error(e);
212
- });
213
- }
198
+ async buildDeps() {
199
+ const shouldBuild = this.depInfo.shouldBuild();
200
+ if (!shouldBuild) {
201
+ utils_1.logger.info('[MFSU] skip buildDeps');
202
+ return;
203
+ }
204
+ this.depInfo.snapshot();
205
+ const deps = dep_1.Dep.buildDeps({
206
+ deps: this.depInfo.moduleGraph.depSnapshotModules,
207
+ cwd: this.opts.cwd,
208
+ mfsu: this,
214
209
  });
210
+ utils_1.logger.info(`[MFSU] buildDeps since ${shouldBuild}`);
211
+ utils_1.logger.debug(deps.map((dep) => dep.file).join(', '));
212
+ await this.depBuilder.build({
213
+ deps,
214
+ });
215
+ // Write cache
216
+ this.depInfo.writeCache();
217
+ if (this.buildDepsAgain) {
218
+ utils_1.logger.info('[MFSU] buildDepsAgain');
219
+ this.buildDepsAgain = false;
220
+ this.buildDeps().catch((e) => {
221
+ utils_1.logger.error(e);
222
+ });
223
+ }
215
224
  }
216
225
  getMiddlewares() {
217
226
  return [
218
227
  (req, res, next) => {
219
- const publicPath = '/';
228
+ const publicPath = this.publicPath;
220
229
  const isMF = req.path.startsWith(`${publicPath}${constants_1.MF_VA_PREFIX}`) ||
221
230
  req.path.startsWith(`${publicPath}${constants_1.MF_DEP_PREFIX}`) ||
222
231
  req.path.startsWith(`${publicPath}${constants_1.MF_STATIC_PREFIX}`);
@@ -151,7 +151,7 @@ class ModuleGraph {
151
151
  this.deleteNode({ mod: importedModulesMap[key], importer: opts.mod });
152
152
  });
153
153
  newDeps.forEach((dep) => {
154
- this.addNode(Object.assign(Object.assign({}, dep), { importer: opts.mod }));
154
+ this.addNode({ ...dep, importer: opts.mod });
155
155
  });
156
156
  }
157
157
  addNode(opts) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umijs/mfsu",
3
- "version": "4.0.0-rc.9",
3
+ "version": "4.0.2",
4
4
  "description": "@umijs/mfsu",
5
5
  "homepage": "https://github.com/umijs/umi-next/tree/master/packages/mfsu#readme",
6
6
  "bugs": "https://github.com/umijs/umi-next/issues",
@@ -17,19 +17,19 @@
17
17
  ],
18
18
  "scripts": {
19
19
  "build": "pnpm tsc",
20
- "build:deps": "pnpm esno ../../scripts/bundleDeps.ts",
21
- "dev": "pnpm build -- --watch",
22
- "test": "jest -c ../../jest.turbo.config.ts"
20
+ "build:deps": "umi-scripts bundleDeps",
21
+ "dev": "pnpm build --watch",
22
+ "test": "umi-scripts jest-turbo"
23
23
  },
24
24
  "dependencies": {
25
- "@umijs/bundler-esbuild": "4.0.0-rc.9",
26
- "@umijs/bundler-utils": "4.0.0-rc.9",
27
- "@umijs/utils": "4.0.0-rc.9",
28
- "enhanced-resolve": "5.9.2"
25
+ "@umijs/bundler-esbuild": "4.0.2",
26
+ "@umijs/bundler-utils": "4.0.2",
27
+ "@umijs/utils": "4.0.2",
28
+ "enhanced-resolve": "5.9.3"
29
29
  },
30
30
  "devDependencies": {
31
31
  "mrmime": "1.0.0",
32
- "webpack": "5.70.0",
32
+ "webpack": "5.72.1",
33
33
  "webpack-virtual-modules": "0.4.3"
34
34
  },
35
35
  "publishConfig": {