@module-federation/esbuild 0.0.0-next-20240524225331 → 0.0.0-next-20240528203231

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/build.cjs.js CHANGED
@@ -2,13 +2,13 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var federationBuilder = require('./federation-builder.cjs.js');
5
+ var npmlog = require('npmlog');
6
6
  var path = require('path');
7
7
  var fs = require('fs');
8
+ var getExternals = require('./get-externals.cjs.js');
8
9
  var process = require('process');
9
10
  var JSON5 = require('json5');
10
11
  var crypto = require('crypto');
11
- require('npmlog');
12
12
 
13
13
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14
14
 
@@ -30,14 +30,105 @@ function _interopNamespace(e) {
30
30
  return Object.freeze(n);
31
31
  }
32
32
 
33
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
33
+ var npmlog__default = /*#__PURE__*/_interopDefaultLegacy(npmlog);
34
34
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
35
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
35
+ var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
36
36
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
37
+ var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
37
38
  var process__default = /*#__PURE__*/_interopDefaultLegacy(process);
38
39
  var JSON5__namespace = /*#__PURE__*/_interopNamespace(JSON5);
39
40
  var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
40
41
 
42
+ const levels = npmlog__default["default"].levels;
43
+ npmlog__default["default"].addLevel('error', levels.error, {
44
+ fg: 'brightWhite',
45
+ bg: 'red'
46
+ }, ' ERR! ');
47
+ npmlog__default["default"].addLevel('warn', levels.info, {
48
+ fg: 'brightWhite',
49
+ bg: 'yellow'
50
+ }, ' WARN ');
51
+ npmlog__default["default"].addLevel('info', levels.warn, {
52
+ fg: 'brightWhite',
53
+ bg: 'green'
54
+ }, ' INFO ');
55
+ npmlog__default["default"].addLevel('notice', levels.notice, {
56
+ fg: 'black',
57
+ bg: 'brightYellow'
58
+ }, ' NOTE ');
59
+ npmlog__default["default"].addLevel('verbose', levels.verbose, {
60
+ fg: 'brightWhite',
61
+ bg: 'brightBlue'
62
+ }, ' VRB! ');
63
+ npmlog__default["default"].addLevel('silly', levels.silly, {
64
+ fg: 'black',
65
+ bg: 'white'
66
+ }, ' DBG! ');
67
+ const logger = {
68
+ error: (msg)=>npmlog__default["default"].error('', msg),
69
+ warn: (msg)=>npmlog__default["default"].warn('', msg),
70
+ notice: (msg)=>npmlog__default["default"].notice('', msg),
71
+ info: (msg)=>npmlog__default["default"].info('', msg),
72
+ verbose: (msg)=>npmlog__default["default"].verbose('', msg),
73
+ debug: (msg)=>npmlog__default["default"].silly('', msg)
74
+ };
75
+ const setLogLevel = (level)=>{
76
+ npmlog__default["default"].level = level === 'debug' ? 'silly' : level;
77
+ };
78
+ setLogLevel('info');
79
+
80
+ let _buildAdapter = async ()=>{
81
+ logger.error('Please set a BuildAdapter!');
82
+ return [];
83
+ };
84
+ function setBuildAdapter(buildAdapter) {
85
+ _buildAdapter = buildAdapter;
86
+ }
87
+ function getBuildAdapter() {
88
+ return _buildAdapter;
89
+ }
90
+
91
+ function _extends$3() {
92
+ _extends$3 = Object.assign || function(target) {
93
+ for(var i = 1; i < arguments.length; i++){
94
+ var source = arguments[i];
95
+ for(var key in source){
96
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
97
+ target[key] = source[key];
98
+ }
99
+ }
100
+ }
101
+ return target;
102
+ };
103
+ return _extends$3.apply(this, arguments);
104
+ }
105
+ function writeImportMap(sharedInfo, fedOption) {
106
+ const imports = sharedInfo.reduce((acc, cur)=>{
107
+ return _extends$3({}, acc, {
108
+ [cur.packageName]: cur.outFileName
109
+ });
110
+ }, {});
111
+ const importMap = {
112
+ imports
113
+ };
114
+ const importMapPath = path__namespace.join(fedOption.workspaceRoot, fedOption.outputPath, 'importmap.json');
115
+ fs__namespace.writeFileSync(importMapPath, JSON.stringify(importMap, null, 2));
116
+ }
117
+
118
+ function writeFederationInfo(federationInfo, fedOptions) {
119
+ const metaDataPath = path__namespace.join(fedOptions.workspaceRoot, fedOptions.outputPath, 'remoteEntry.json');
120
+ fs__namespace.writeFileSync(metaDataPath, JSON.stringify(federationInfo, null, 2));
121
+ }
122
+
123
+ async function loadFederationConfig(fedOptions) {
124
+ const fullConfigPath = path__namespace.join(fedOptions.workspaceRoot, fedOptions.federationConfig);
125
+ if (!fs__namespace.existsSync(fullConfigPath)) {
126
+ throw new Error('Expected ' + fullConfigPath);
127
+ }
128
+ const config = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(`${fullConfigPath}`);
129
+ return config;
130
+ }
131
+
41
132
  const DEFAULT_SKIP_LIST = [
42
133
  '@module-federation/native-federation-runtime',
43
134
  '@module-federation/native-federation',
@@ -82,6 +173,307 @@ function isInSkipList(entry, skipList) {
82
173
  return false;
83
174
  }
84
175
 
176
+ function normalize(path, trailingSlash) {
177
+ let cand = path.replace(/\\/g, '/');
178
+ if (typeof trailingSlash === 'undefined') {
179
+ return cand;
180
+ }
181
+ while(cand.endsWith('/')){
182
+ cand = cand.substring(0, cand.length - 1);
183
+ }
184
+ if (trailingSlash) {
185
+ return cand + '/';
186
+ }
187
+ return cand;
188
+ }
189
+
190
+ function _extends$2() {
191
+ _extends$2 = Object.assign || function(target) {
192
+ for(var i = 1; i < arguments.length; i++){
193
+ var source = arguments[i];
194
+ for(var key in source){
195
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
196
+ target[key] = source[key];
197
+ }
198
+ }
199
+ }
200
+ return target;
201
+ };
202
+ return _extends$2.apply(this, arguments);
203
+ }
204
+ const packageCache = {};
205
+ function findPackageJsonFiles(project, workspace) {
206
+ return expandFolders(project, workspace).map((f)=>path__namespace.join(f, 'package.json')).filter((f)=>fs__namespace.existsSync(f));
207
+ }
208
+ function expandFolders(child, parent) {
209
+ const result = [];
210
+ parent = normalize(parent, true);
211
+ child = normalize(child, true);
212
+ if (!child.startsWith(parent)) {
213
+ throw new Error(`Workspace folder ${path__namespace} needs to be a parent of the project folder ${child}`);
214
+ }
215
+ let current = child;
216
+ while(current !== parent){
217
+ result.push(current);
218
+ const cand = normalize(path__namespace.dirname(current), true);
219
+ if (cand === current) {
220
+ break;
221
+ }
222
+ current = cand;
223
+ }
224
+ result.push(parent);
225
+ return result;
226
+ }
227
+ function getPackageInfo(packageName, workspaceRoot) {
228
+ workspaceRoot = normalize(workspaceRoot, true);
229
+ const packageJsonInfos = getPackageJsonFiles(workspaceRoot, workspaceRoot);
230
+ for (const info of packageJsonInfos){
231
+ const cand = _getPackageInfo(packageName, info.directory);
232
+ if (cand) {
233
+ return cand;
234
+ }
235
+ }
236
+ logger.warn('No meta data found for shared lib ' + packageName);
237
+ return null;
238
+ }
239
+ function getVersionMapCacheKey(project, workspace) {
240
+ return `${project}**${workspace}`;
241
+ }
242
+ function getVersionMaps(project, workspace) {
243
+ return getPackageJsonFiles(project, workspace).map((json)=>_extends$2({}, json.content['dependencies']));
244
+ }
245
+ function getPackageJsonFiles(project, workspace) {
246
+ const cacheKey = getVersionMapCacheKey(project, workspace);
247
+ let maps = packageCache[cacheKey];
248
+ if (maps) {
249
+ return maps;
250
+ }
251
+ maps = findPackageJsonFiles(project, workspace).map((f)=>{
252
+ const content = JSON.parse(fs__namespace.readFileSync(f, 'utf-8'));
253
+ const directory = normalize(path__namespace.dirname(f), true);
254
+ const result = {
255
+ content,
256
+ directory
257
+ };
258
+ return result;
259
+ });
260
+ packageCache[cacheKey] = maps;
261
+ return maps;
262
+ }
263
+ function findDepPackageJson(packageName, projectRoot) {
264
+ const mainPkgName = getPkgFolder(packageName);
265
+ let mainPkgPath = path__namespace.join(projectRoot, 'node_modules', mainPkgName);
266
+ let mainPkgJsonPath = path__namespace.join(mainPkgPath, 'package.json');
267
+ let directory = projectRoot;
268
+ while(path__namespace.dirname(directory) !== directory){
269
+ if (fs__namespace.existsSync(mainPkgJsonPath)) {
270
+ break;
271
+ }
272
+ directory = normalize(path__namespace.dirname(directory), true);
273
+ mainPkgPath = path__namespace.join(directory, 'node_modules', mainPkgName);
274
+ mainPkgJsonPath = path__namespace.join(mainPkgPath, 'package.json');
275
+ }
276
+ if (!fs__namespace.existsSync(mainPkgJsonPath)) {
277
+ logger.verbose('No package.json found for ' + packageName + ' in ' + mainPkgPath);
278
+ return null;
279
+ }
280
+ return mainPkgJsonPath;
281
+ }
282
+ function _getPackageInfo(packageName, directory) {
283
+ var _mainPkgJson_exports, _mainPkgJson_exports_relSecondaryPath, _mainPkgJson_exports1, _mainPkgJson_exports_relSecondaryPath1, _mainPkgJson_exports2, _mainPkgJson_exports_relSecondaryPath2, _mainPkgJson_exports3;
284
+ const mainPkgName = getPkgFolder(packageName);
285
+ const mainPkgJsonPath = findDepPackageJson(packageName, directory);
286
+ if (!mainPkgJsonPath) {
287
+ return null;
288
+ }
289
+ const mainPkgPath = path__namespace.dirname(mainPkgJsonPath);
290
+ const mainPkgJson = readJson(mainPkgJsonPath);
291
+ const version = mainPkgJson['version'];
292
+ const esm = mainPkgJson['type'] === 'module';
293
+ if (!version) {
294
+ logger.warn('No version found for ' + packageName);
295
+ return null;
296
+ }
297
+ let relSecondaryPath = path__namespace.relative(mainPkgName, packageName);
298
+ if (!relSecondaryPath) {
299
+ relSecondaryPath = '.';
300
+ } else {
301
+ relSecondaryPath = './' + relSecondaryPath.replace(/\\/g, '/');
302
+ }
303
+ let cand = mainPkgJson == null ? void 0 : (_mainPkgJson_exports = mainPkgJson.exports) == null ? void 0 : _mainPkgJson_exports[relSecondaryPath];
304
+ if (typeof cand === 'string') {
305
+ return {
306
+ entryPoint: path__namespace.join(mainPkgPath, cand),
307
+ packageName,
308
+ version,
309
+ esm
310
+ };
311
+ }
312
+ cand = mainPkgJson == null ? void 0 : (_mainPkgJson_exports1 = mainPkgJson.exports) == null ? void 0 : (_mainPkgJson_exports_relSecondaryPath = _mainPkgJson_exports1[relSecondaryPath]) == null ? void 0 : _mainPkgJson_exports_relSecondaryPath.import;
313
+ if (typeof cand === 'object') {
314
+ if (cand.module) {
315
+ cand = cand.module;
316
+ } else if (cand.import) {
317
+ cand = cand.import;
318
+ } else if (cand.default) {
319
+ cand = cand.default;
320
+ } else {
321
+ cand = null;
322
+ }
323
+ }
324
+ if (cand) {
325
+ if (typeof cand === 'object') {
326
+ if (cand.module) {
327
+ cand = cand.module;
328
+ } else if (cand.import) {
329
+ cand = cand.import;
330
+ } else if (cand.default) {
331
+ cand = cand.default;
332
+ } else {
333
+ cand = null;
334
+ }
335
+ }
336
+ return {
337
+ entryPoint: path__namespace.join(mainPkgPath, cand),
338
+ packageName,
339
+ version,
340
+ esm
341
+ };
342
+ }
343
+ cand = mainPkgJson == null ? void 0 : (_mainPkgJson_exports2 = mainPkgJson.exports) == null ? void 0 : (_mainPkgJson_exports_relSecondaryPath1 = _mainPkgJson_exports2[relSecondaryPath]) == null ? void 0 : _mainPkgJson_exports_relSecondaryPath1.module;
344
+ if (typeof cand === 'object') {
345
+ if (cand.module) {
346
+ cand = cand.module;
347
+ } else if (cand.import) {
348
+ cand = cand.import;
349
+ } else if (cand.default) {
350
+ cand = cand.default;
351
+ } else {
352
+ cand = null;
353
+ }
354
+ }
355
+ if (cand) {
356
+ return {
357
+ entryPoint: path__namespace.join(mainPkgPath, cand),
358
+ packageName,
359
+ version,
360
+ esm
361
+ };
362
+ }
363
+ cand = mainPkgJson == null ? void 0 : (_mainPkgJson_exports3 = mainPkgJson.exports) == null ? void 0 : (_mainPkgJson_exports_relSecondaryPath2 = _mainPkgJson_exports3[relSecondaryPath]) == null ? void 0 : _mainPkgJson_exports_relSecondaryPath2.default;
364
+ if (cand) {
365
+ if (typeof cand === 'object') {
366
+ if (cand.module) {
367
+ cand = cand.module;
368
+ } else if (cand.import) {
369
+ cand = cand.import;
370
+ } else if (cand.default) {
371
+ cand = cand.default;
372
+ } else {
373
+ cand = null;
374
+ }
375
+ }
376
+ return {
377
+ entryPoint: path__namespace.join(mainPkgPath, cand),
378
+ packageName,
379
+ version,
380
+ esm
381
+ };
382
+ }
383
+ cand = mainPkgJson['module'];
384
+ if (cand && relSecondaryPath === '.') {
385
+ return {
386
+ entryPoint: path__namespace.join(mainPkgPath, cand),
387
+ packageName,
388
+ version,
389
+ esm: true
390
+ };
391
+ }
392
+ const secondaryPgkPath = path__namespace.join(mainPkgPath, relSecondaryPath);
393
+ const secondaryPgkJsonPath = path__namespace.join(secondaryPgkPath, 'package.json');
394
+ let secondaryPgkJson = null;
395
+ if (fs__namespace.existsSync(secondaryPgkJsonPath)) {
396
+ secondaryPgkJson = readJson(secondaryPgkJsonPath);
397
+ }
398
+ if (secondaryPgkJson && secondaryPgkJson.module) {
399
+ return {
400
+ entryPoint: path__namespace.join(secondaryPgkPath, secondaryPgkJson.module),
401
+ packageName,
402
+ version,
403
+ esm: true
404
+ };
405
+ }
406
+ cand = path__namespace.join(secondaryPgkPath, 'index.mjs');
407
+ if (fs__namespace.existsSync(cand)) {
408
+ return {
409
+ entryPoint: cand,
410
+ packageName,
411
+ version,
412
+ esm: true
413
+ };
414
+ }
415
+ if (secondaryPgkJson && secondaryPgkJson.main) {
416
+ return {
417
+ entryPoint: path__namespace.join(secondaryPgkPath, secondaryPgkJson.main),
418
+ packageName,
419
+ version,
420
+ esm
421
+ };
422
+ }
423
+ cand = path__namespace.join(secondaryPgkPath, 'index.js');
424
+ if (fs__namespace.existsSync(cand)) {
425
+ return {
426
+ entryPoint: cand,
427
+ packageName,
428
+ version,
429
+ esm
430
+ };
431
+ }
432
+ logger.warn('No entry point found for ' + packageName);
433
+ logger.warn("If you don't need this package, skip it in your federation.config.js or consider moving it into depDependencies in your package.json");
434
+ return null;
435
+ }
436
+ function readJson(mainPkgJsonPath) {
437
+ return JSON.parse(fs__namespace.readFileSync(mainPkgJsonPath, 'utf-8'));
438
+ }
439
+ function getPkgFolder(packageName) {
440
+ const parts = packageName.split('/');
441
+ let folder = parts[0];
442
+ if (folder.startsWith('@')) {
443
+ folder += '/' + parts[1];
444
+ }
445
+ return folder;
446
+ }
447
+
448
+ function _extends$1() {
449
+ _extends$1 = Object.assign || function(target) {
450
+ for(var i = 1; i < arguments.length; i++){
451
+ var source = arguments[i];
452
+ for(var key in source){
453
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
454
+ target[key] = source[key];
455
+ }
456
+ }
457
+ }
458
+ return target;
459
+ };
460
+ return _extends$1.apply(this, arguments);
461
+ }
462
+ let _context = {};
463
+ function useWorkspace(workspaceRoot) {
464
+ _context = _extends$1({}, _context, {
465
+ workspaceRoot
466
+ });
467
+ }
468
+ function usePackageJson(packageJson) {
469
+ _context = _extends$1({}, _context, {
470
+ packageJson
471
+ });
472
+ }
473
+ function getConfigContext() {
474
+ return _context;
475
+ }
476
+
85
477
  let inferVersion = false;
86
478
  const DEFAULT_SECONARIES_SKIP_LIST = [
87
479
  '@angular/router/upgrade',
@@ -110,7 +502,7 @@ function findPackageJson(folder) {
110
502
  throw new Error('no package.json found. Searched the following folder and all parents: ' + folder);
111
503
  }
112
504
  function lookupVersion(key, workspaceRoot) {
113
- const versionMaps = federationBuilder.getVersionMaps(workspaceRoot, workspaceRoot);
505
+ const versionMaps = getVersionMaps(workspaceRoot, workspaceRoot);
114
506
  for (const versionMap of versionMaps){
115
507
  const version = lookupVersionInMap(key, versionMap);
116
508
  if (version) {
@@ -232,7 +624,7 @@ function shareAll(config = {}, skip = DEFAULT_SKIP_LIST, projectPath = '') {
232
624
  // if (!workspacePath) {
233
625
  // workspacePath = projectPath;
234
626
  // }
235
- const versionMaps = federationBuilder.getVersionMaps(projectPath, projectPath);
627
+ const versionMaps = getVersionMaps(projectPath, projectPath);
236
628
  const share = {};
237
629
  for (const versions of versionMaps){
238
630
  const preparedSkipList = prepareSkipList(skip);
@@ -252,11 +644,11 @@ function shareAll(config = {}, skip = DEFAULT_SKIP_LIST, projectPath = '') {
252
644
  return module.exports.share(share, projectPath);
253
645
  }
254
646
  function inferProjectPath(projectPath) {
255
- if (!projectPath && federationBuilder.getConfigContext().packageJson) {
256
- projectPath = path__default["default"].dirname(federationBuilder.getConfigContext().packageJson || '');
647
+ if (!projectPath && getConfigContext().packageJson) {
648
+ projectPath = path__default["default"].dirname(getConfigContext().packageJson || '');
257
649
  }
258
- if (!projectPath && federationBuilder.getConfigContext().workspaceRoot) {
259
- projectPath = federationBuilder.getConfigContext().workspaceRoot || '';
650
+ if (!projectPath && getConfigContext().workspaceRoot) {
651
+ projectPath = getConfigContext().workspaceRoot || '';
260
652
  }
261
653
  if (!projectPath) {
262
654
  projectPath = process__default["default"].cwd();
@@ -289,9 +681,9 @@ function share(shareObjects, projectPath = '') {
289
681
  }
290
682
  result[key] = shareObject;
291
683
  if (includeSecondaries) {
292
- const libPackageJson = federationBuilder.findDepPackageJson(key, path__default["default"].dirname(packagePath));
684
+ const libPackageJson = findDepPackageJson(key, path__default["default"].dirname(packagePath));
293
685
  if (!libPackageJson) {
294
- federationBuilder.logger.error('Could not find folder containing dep ' + key);
686
+ logger.error('Could not find folder containing dep ' + key);
295
687
  continue;
296
688
  }
297
689
  const libPath = path__default["default"].dirname(libPackageJson);
@@ -404,10 +796,293 @@ function normalizeSharedMappings(config, skip) {
404
796
  });
405
797
  const result = paths.filter((p)=>!isInSkipList(p.key, skip) && !p.key.includes('*'));
406
798
  if (paths.find((p)=>p.key.includes('*'))) {
407
- federationBuilder.logger.warn('Sharing mapped paths with wildcards (*) not supported');
799
+ logger.warn('Sharing mapped paths with wildcards (*) not supported');
800
+ }
801
+ return result;
802
+ }
803
+
804
+ async function bundle(options) {
805
+ const adapter = await getBuildAdapter();
806
+ return await adapter(options);
807
+ }
808
+
809
+ function copySrcMapIfExists(cachedFile, fullOutputPath) {
810
+ const mapSrc = cachedFile + '.map';
811
+ const mapDest = fullOutputPath + '.map';
812
+ if (fs__namespace.existsSync(mapSrc)) {
813
+ fs__namespace.copyFileSync(mapSrc, mapDest);
814
+ }
815
+ }
816
+
817
+ async function bundleShared(config, fedOptions, externals) {
818
+ const folder = fedOptions.packageJson ? path__namespace.dirname(fedOptions.packageJson) : fedOptions.workspaceRoot;
819
+ const cachePath = path__namespace.join(fedOptions.workspaceRoot, 'node_modules/.cache/native-federation');
820
+ fs__namespace.mkdirSync(cachePath, {
821
+ recursive: true
822
+ });
823
+ const packageInfos = Object.keys(config.shared).map((packageName)=>getPackageInfo(packageName, folder)).filter((pi)=>!!pi);
824
+ const allEntryPoints = packageInfos.map((pi)=>{
825
+ const encName = pi.packageName.replace(/[^A-Za-z0-9]/g, '_');
826
+ const encVersion = pi.version.replace(/[^A-Za-z0-9]/g, '_');
827
+ const outName = fedOptions.dev ? `${encName}-${encVersion}-dev.js` : `${encName}-${encVersion}.js`;
828
+ return {
829
+ fileName: pi.entryPoint,
830
+ outName
831
+ };
832
+ });
833
+ const fullOutputPath = path__namespace.join(fedOptions.workspaceRoot, fedOptions.outputPath);
834
+ const exptedResults = allEntryPoints.map((ep)=>path__namespace.join(fullOutputPath, ep.outName));
835
+ const entryPoints = allEntryPoints.filter((ep)=>!fs__namespace.existsSync(path__namespace.join(cachePath, ep.outName)));
836
+ if (entryPoints.length > 0) {
837
+ logger.info('Preparing shared npm packages');
838
+ logger.notice('This only needs to be done once, as results are cached');
839
+ logger.notice("Skip packages you don't want to share in your federation config");
840
+ }
841
+ try {
842
+ const build = await bundle({
843
+ entryPoints,
844
+ tsConfigPath: fedOptions.tsConfig,
845
+ external: externals,
846
+ outdir: cachePath,
847
+ mappedPaths: config.sharedMappings,
848
+ dev: fedOptions.dev,
849
+ kind: 'shared-package',
850
+ hash: false,
851
+ packageInfos: packageInfos,
852
+ name: config.name
853
+ });
854
+ for (const fileName of exptedResults){
855
+ const outFileName = path__namespace.basename(fileName);
856
+ const cachedFile = path__namespace.join(cachePath, outFileName);
857
+ const realoutFileName = 'mf_' + path__namespace.basename(fileName);
858
+ const realcachedFile = path__namespace.join(cachePath, realoutFileName);
859
+ copyFileIfExists(cachedFile, fileName);
860
+ copySrcMapIfExists(cachedFile, fileName);
861
+ copyFileIfExists(realcachedFile, fileName.replace(outFileName, realoutFileName));
862
+ copySrcMapIfExists(realcachedFile, fileName.replace(outFileName, realoutFileName));
863
+ }
864
+ } catch (e) {
865
+ logger.error('Error bundling shared npm package ');
866
+ if (e instanceof Error) {
867
+ logger.error(e.message);
868
+ }
869
+ logger.error('For more information, run in verbose mode');
870
+ logger.notice('');
871
+ logger.notice('');
872
+ logger.notice('** Important Information: ***');
873
+ logger.notice('The error message above shows an issue with bundling a node_module.');
874
+ logger.notice('In most cases this is because you (indirectly) shared a Node.js package,');
875
+ logger.notice('while Native Federation builds for the browser.');
876
+ logger.notice('You can move such packages into devDependencies or skip them in your federation.config.js.');
877
+ logger.notice('');
878
+ logger.notice('More Details: https://bit.ly/nf-issue');
879
+ logger.notice('');
880
+ logger.notice('');
881
+ logger.verbose(e);
882
+ }
883
+ const outFileNames = [
884
+ ...exptedResults
885
+ ];
886
+ return packageInfos.map((pi)=>{
887
+ const shared = config.shared[pi.packageName];
888
+ return {
889
+ packageName: pi.packageName,
890
+ outFileName: path__namespace.basename(outFileNames.shift() || ''),
891
+ requiredVersion: shared.requiredVersion,
892
+ singleton: shared.singleton,
893
+ strictVersion: shared.strictVersion,
894
+ version: pi.version,
895
+ dev: !fedOptions.dev ? undefined : {
896
+ entryPoint: normalize(pi.entryPoint)
897
+ }
898
+ };
899
+ });
900
+ }
901
+ function copyFileIfExists(cachedFile, fullOutputPath) {
902
+ fs__namespace.mkdirSync(path__namespace.dirname(fullOutputPath), {
903
+ recursive: true
904
+ });
905
+ if (fs__namespace.existsSync(cachedFile)) {
906
+ fs__namespace.copyFileSync(cachedFile, fullOutputPath);
907
+ }
908
+ }
909
+
910
+ function createBuildResultMap(buildResult, isHashed) {
911
+ const map = {};
912
+ for (const item of buildResult){
913
+ const resultName = path__default["default"].basename(item.fileName);
914
+ let requestName = resultName;
915
+ if (isHashed) {
916
+ const start = resultName.lastIndexOf('-');
917
+ const end = resultName.lastIndexOf('.');
918
+ const part1 = resultName.substring(0, start);
919
+ const part2 = resultName.substring(end);
920
+ requestName = part1 + part2;
921
+ }
922
+ map[requestName] = resultName;
923
+ }
924
+ return map;
925
+ }
926
+ function lookupInResultMap(map, requestName) {
927
+ const key = path__default["default"].basename(requestName);
928
+ return map[key];
929
+ }
930
+
931
+ async function bundleExposedAndMappings(config, fedOptions, externals) {
932
+ const shared = config.sharedMappings.map((sm)=>{
933
+ const entryPoint = sm.path;
934
+ const tmp = sm.key.replace(/[^A-Za-z0-9]/g, '_');
935
+ const outFilePath = tmp + '.js';
936
+ return {
937
+ fileName: entryPoint,
938
+ outName: outFilePath,
939
+ key: sm.key
940
+ };
941
+ });
942
+ const exposes = Object.keys(config.exposes).map((key)=>{
943
+ const entryPoint = config.exposes[key];
944
+ const outFilePath = key + '.js';
945
+ return {
946
+ fileName: entryPoint,
947
+ outName: outFilePath,
948
+ key
949
+ };
950
+ });
951
+ const entryPoints = [
952
+ ...shared,
953
+ ...exposes
954
+ ];
955
+ const hash = !fedOptions.dev;
956
+ logger.info('Building federation artefacts');
957
+ const result = await bundle({
958
+ entryPoints,
959
+ outdir: fedOptions.outputPath,
960
+ tsConfigPath: fedOptions.tsConfig,
961
+ external: externals,
962
+ dev: !!fedOptions.dev,
963
+ watch: fedOptions.watch,
964
+ mappedPaths: config.sharedMappings,
965
+ kind: 'mapping-or-exposed',
966
+ hash
967
+ });
968
+ const resultMap = createBuildResultMap(result, hash);
969
+ const sharedResult = [];
970
+ for (const item of shared){
971
+ sharedResult.push({
972
+ packageName: item.key,
973
+ outFileName: lookupInResultMap(resultMap, item.outName),
974
+ requiredVersion: '',
975
+ singleton: true,
976
+ strictVersion: false,
977
+ version: '',
978
+ dev: !fedOptions.dev ? undefined : {
979
+ entryPoint: normalize(path__default["default"].normalize(item.fileName))
980
+ }
981
+ });
982
+ }
983
+ const exposedResult = [];
984
+ for (const item of exposes){
985
+ exposedResult.push({
986
+ key: item.key,
987
+ outFileName: lookupInResultMap(resultMap, item.outName),
988
+ dev: !fedOptions.dev ? undefined : {
989
+ entryPoint: normalize(path__default["default"].join(fedOptions.workspaceRoot, item.fileName))
990
+ }
991
+ });
992
+ }
993
+ return {
994
+ mappings: sharedResult,
995
+ exposes: exposedResult
996
+ };
997
+ }
998
+ function describeExposed(config, options) {
999
+ const result = [];
1000
+ for(const key in config.exposes){
1001
+ const localPath = normalize(path__default["default"].normalize(path__default["default"].join(options.workspaceRoot, config.exposes[key])));
1002
+ result.push({
1003
+ key,
1004
+ outFileName: '',
1005
+ dev: !options.dev ? undefined : {
1006
+ entryPoint: localPath
1007
+ }
1008
+ });
408
1009
  }
409
1010
  return result;
410
1011
  }
1012
+ function describeSharedMappings(config, fedOptions) {
1013
+ const result = [];
1014
+ for (const m of config.sharedMappings){
1015
+ result.push({
1016
+ packageName: m.key,
1017
+ outFileName: '',
1018
+ requiredVersion: '',
1019
+ singleton: true,
1020
+ strictVersion: false,
1021
+ version: '',
1022
+ dev: !fedOptions.dev ? undefined : {
1023
+ entryPoint: normalize(path__default["default"].normalize(m.path))
1024
+ }
1025
+ });
1026
+ }
1027
+ return result;
1028
+ }
1029
+
1030
+ const defaultBuildParams = {
1031
+ skipMappingsAndExposed: false
1032
+ };
1033
+ async function buildForFederation(config, fedOptions, externals, buildParams = defaultBuildParams) {
1034
+ let artefactInfo;
1035
+ if (!buildParams.skipMappingsAndExposed) {
1036
+ artefactInfo = await bundleExposedAndMappings(config, fedOptions, externals);
1037
+ }
1038
+ const exposedInfo = !artefactInfo ? describeExposed(config, fedOptions) : artefactInfo.exposes;
1039
+ const sharedPackageInfo = await bundleShared(config, fedOptions, externals);
1040
+ const sharedMappingInfo = !artefactInfo ? describeSharedMappings(config, fedOptions) : artefactInfo.mappings;
1041
+ const sharedInfo = [
1042
+ ...sharedPackageInfo,
1043
+ ...sharedMappingInfo
1044
+ ];
1045
+ const federationInfo = {
1046
+ name: config.name,
1047
+ shared: sharedInfo,
1048
+ exposes: exposedInfo
1049
+ };
1050
+ writeFederationInfo(federationInfo, fedOptions);
1051
+ writeImportMap(sharedInfo, fedOptions);
1052
+ return federationInfo;
1053
+ }
1054
+
1055
+ let externals = [];
1056
+ let config;
1057
+ let fedOptions;
1058
+ let fedInfo;
1059
+ async function init(params) {
1060
+ var _getConfigContext;
1061
+ setBuildAdapter(params.adapter);
1062
+ fedOptions = params.options;
1063
+ useWorkspace(params.options.workspaceRoot);
1064
+ usePackageJson(params.options.packageJson);
1065
+ config = await loadFederationConfig(fedOptions);
1066
+ var _getConfigContext_workspaceRoot;
1067
+ params.options.workspaceRoot = (_getConfigContext_workspaceRoot = (_getConfigContext = getConfigContext()) == null ? void 0 : _getConfigContext.workspaceRoot) != null ? _getConfigContext_workspaceRoot : params.options.workspaceRoot;
1068
+ externals = getExternals.getExternals(config);
1069
+ }
1070
+ async function build(buildParams = defaultBuildParams) {
1071
+ fedInfo = await buildForFederation(config, fedOptions, externals, buildParams);
1072
+ }
1073
+ const federationBuilder = {
1074
+ init,
1075
+ build,
1076
+ get federationInfo () {
1077
+ return fedInfo;
1078
+ },
1079
+ get externals () {
1080
+ return externals;
1081
+ },
1082
+ get config () {
1083
+ return config;
1084
+ }
1085
+ };
411
1086
 
412
1087
  function hashFile(fileName) {
413
1088
  const fileBuffer = fs__namespace.readFileSync(fileName);
@@ -416,36 +1091,36 @@ function hashFile(fileName) {
416
1091
  return hashSum.digest('hex');
417
1092
  }
418
1093
 
419
- exports.buildForFederation = federationBuilder.buildForFederation;
420
- exports.bundleExposedAndMappings = federationBuilder.bundleExposedAndMappings;
421
- exports.createBuildResultMap = federationBuilder.createBuildResultMap;
422
- exports.defaultBuildParams = federationBuilder.defaultBuildParams;
423
- exports.describeExposed = federationBuilder.describeExposed;
424
- exports.describeSharedMappings = federationBuilder.describeSharedMappings;
425
- exports.federationBuilder = federationBuilder.federationBuilder;
426
- exports.getBuildAdapter = federationBuilder.getBuildAdapter;
427
- exports.getExternals = federationBuilder.getExternals;
428
- exports.loadFederationConfig = federationBuilder.loadFederationConfig;
429
- exports.logger = federationBuilder.logger;
430
- exports.lookupInResultMap = federationBuilder.lookupInResultMap;
431
- exports.setBuildAdapter = federationBuilder.setBuildAdapter;
432
- exports.setLogLevel = federationBuilder.setLogLevel;
433
- exports.writeFederationInfo = federationBuilder.writeFederationInfo;
434
- exports.writeImportMap = federationBuilder.writeImportMap;
1094
+ exports.getExternals = getExternals.getExternals;
435
1095
  exports.DEFAULT_SECONARIES_SKIP_LIST = DEFAULT_SECONARIES_SKIP_LIST;
436
1096
  exports._findSecondaries = _findSecondaries;
437
1097
  exports.addSecondaries = addSecondaries;
1098
+ exports.buildForFederation = buildForFederation;
1099
+ exports.bundleExposedAndMappings = bundleExposedAndMappings;
1100
+ exports.createBuildResultMap = createBuildResultMap;
1101
+ exports.defaultBuildParams = defaultBuildParams;
1102
+ exports.describeExposed = describeExposed;
1103
+ exports.describeSharedMappings = describeSharedMappings;
1104
+ exports.federationBuilder = federationBuilder;
438
1105
  exports.findPackageJson = findPackageJson;
439
1106
  exports.findRootTsConfigJson = findRootTsConfigJson;
440
1107
  exports.findSecondaries = findSecondaries;
1108
+ exports.getBuildAdapter = getBuildAdapter;
441
1109
  exports.getDefaultEntry = getDefaultEntry;
442
1110
  exports.getSecondaries = getSecondaries;
443
1111
  exports.hashFile = hashFile;
444
1112
  exports.inferProjectPath = inferProjectPath;
1113
+ exports.loadFederationConfig = loadFederationConfig;
1114
+ exports.logger = logger;
1115
+ exports.lookupInResultMap = lookupInResultMap;
445
1116
  exports.lookupVersion = lookupVersion;
446
1117
  exports.lookupVersionInMap = lookupVersionInMap;
447
1118
  exports.readConfiguredSecondaries = readConfiguredSecondaries;
1119
+ exports.setBuildAdapter = setBuildAdapter;
448
1120
  exports.setInferVersion = setInferVersion;
1121
+ exports.setLogLevel = setLogLevel;
449
1122
  exports.share = share;
450
1123
  exports.shareAll = shareAll;
451
1124
  exports.withFederation = withFederation;
1125
+ exports.writeFederationInfo = writeFederationInfo;
1126
+ exports.writeImportMap = writeImportMap;