@module-federation/esbuild 0.0.0-next-20240530210646 → 0.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.
@@ -12,6 +12,24 @@ var getExternals = require('./get-externals.cjs.js');
12
12
 
13
13
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14
14
 
15
+ function _interopNamespace(e) {
16
+ if (e && e.__esModule) return e;
17
+ var n = Object.create(null);
18
+ if (e) {
19
+ Object.keys(e).forEach(function (k) {
20
+ if (k !== 'default') {
21
+ var d = Object.getOwnPropertyDescriptor(e, k);
22
+ Object.defineProperty(n, k, d.get ? d : {
23
+ enumerable: true,
24
+ get: function () { return e[k]; }
25
+ });
26
+ }
27
+ });
28
+ }
29
+ n["default"] = e;
30
+ return Object.freeze(n);
31
+ }
32
+
15
33
  var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
16
34
  var enhancedResolve__default = /*#__PURE__*/_interopDefaultLegacy(enhancedResolve);
17
35
  var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
@@ -59,7 +77,7 @@ async function getExports(modulePath) {
59
77
  }
60
78
  }
61
79
 
62
- var version = "0.0.1";
80
+ var version = "0.0.2";
63
81
 
64
82
  function _extends$1() {
65
83
  _extends$1 = Object.assign || function(target) {
@@ -515,7 +533,9 @@ const createContainerPlugin = (config)=>({
515
533
  const filter = new RegExp([
516
534
  filename
517
535
  ].map((name)=>`${name}$`).join('|'));
518
- const sharedExternals = new RegExp(Object.keys(config.shared || {}).map((name)=>`${name}$`).join('|'));
536
+ const hasShared = Object.keys(config.shared || {}).length;
537
+ const shared = Object.keys(config.shared || {}).map((name)=>`${name}$`).join('|');
538
+ const sharedExternals = new RegExp(shared);
519
539
  build.onResolve({
520
540
  filter
521
541
  }, async (args)=>({
@@ -536,24 +556,11 @@ const createContainerPlugin = (config)=>({
536
556
  resolveDir: args.resolveDir
537
557
  }
538
558
  }));
539
- build.onResolve({
540
- filter: sharedExternals
541
- }, (args)=>{
542
- if (args.namespace === 'esm-shares') return null;
543
- return {
544
- path: args.path,
545
- namespace: 'virtual-share-module',
546
- pluginData: {
547
- kind: args.kind,
548
- resolveDir: args.resolveDir
549
- }
550
- };
551
- });
552
- build.onResolve({
553
- filter: /.*/,
554
- namespace: 'esm-shares'
555
- }, async (args)=>{
556
- if (sharedExternals.test(args.path)) {
559
+ if (hasShared) {
560
+ build.onResolve({
561
+ filter: sharedExternals
562
+ }, (args)=>{
563
+ if (args.namespace === 'esm-shares') return null;
557
564
  return {
558
565
  path: args.path,
559
566
  namespace: 'virtual-share-module',
@@ -562,9 +569,24 @@ const createContainerPlugin = (config)=>({
562
569
  resolveDir: args.resolveDir
563
570
  }
564
571
  };
565
- }
566
- return undefined;
567
- });
572
+ });
573
+ build.onResolve({
574
+ filter: /.*/,
575
+ namespace: 'esm-shares'
576
+ }, async (args)=>{
577
+ if (sharedExternals.test(args.path)) {
578
+ return {
579
+ path: args.path,
580
+ namespace: 'virtual-share-module',
581
+ pluginData: {
582
+ kind: args.kind,
583
+ resolveDir: args.resolveDir
584
+ }
585
+ };
586
+ }
587
+ return undefined;
588
+ });
589
+ }
568
590
  build.onLoad({
569
591
  filter,
570
592
  namespace: 'container'
@@ -605,7 +627,7 @@ const buildFederationHost = (config)=>{
605
627
  return `
606
628
  import { init as initFederationHost } from "@module-federation/runtime";
607
629
 
608
- export const createVirtualRemoteModule = (name, ref, exports) => {
630
+ const createVirtualRemoteModule = (name, ref, exports) => {
609
631
  const genExports = exports.map(e =>
610
632
  e === 'default'
611
633
  ? 'export default mfLsZJ92.default;'
@@ -656,14 +678,14 @@ const buildFederationHost = (config)=>{
656
678
  }
657
679
  });
658
680
 
659
- const host = initFederationHost({
681
+ const mfHoZJ92 = initFederationHost({
660
682
  name: ${JSON.stringify(name)},
661
683
  remotes: ${remoteConfigs},
662
684
  shared: ${sharedConfig},
663
685
  plugins: [runtimePlugin()],
664
686
  });
665
687
 
666
- await Promise.all(host.initializeSharing('default', 'version-first'));
688
+ await Promise.all(mfHoZJ92.initializeSharing('default', 'version-first'));
667
689
 
668
690
 
669
691
  `;
@@ -766,6 +788,331 @@ const linkRemotesPlugin = (config)=>({
766
788
  }
767
789
  });
768
790
 
791
+ // simplified from acorn (MIT license)
792
+ function isNewLine(code) {
793
+ return code === 10 || code === 13 || code === 0x2028 || code === 0x2029;
794
+ }
795
+ function codePointToString(ch) {
796
+ if (ch <= 0xffff) return String.fromCharCode(ch);
797
+ ch -= 0x10000;
798
+ return String.fromCharCode((ch >> 10) + 0xd800, (ch & 0x03ff) + 0xdc00);
799
+ }
800
+ class Lexer {
801
+ readString(input, pos) {
802
+ if (pos >= input.length) return null;
803
+ this.input = input;
804
+ this.pos = pos;
805
+ const quote = this.input.charCodeAt(pos);
806
+ if (!(quote === 34 || quote === 39)) return null;
807
+ let out = '';
808
+ let chunkStart = ++this.pos;
809
+ //eslint-disable-next-line no-constant-condition
810
+ while(true){
811
+ if (this.pos >= this.input.length) return null;
812
+ const ch = this.input.charCodeAt(this.pos);
813
+ if (ch === quote) break;
814
+ if (ch === 92) {
815
+ out += this.input.slice(chunkStart, this.pos);
816
+ const escaped = this.readEscapedChar();
817
+ if (escaped === null) return null;
818
+ out += escaped;
819
+ chunkStart = this.pos;
820
+ } else {
821
+ if (isNewLine(ch)) return null;
822
+ ++this.pos;
823
+ }
824
+ }
825
+ out += this.input.slice(chunkStart, this.pos++);
826
+ return out;
827
+ }
828
+ readEscapedChar() {
829
+ const ch = this.input.charCodeAt(++this.pos);
830
+ let code;
831
+ ++this.pos;
832
+ switch(ch){
833
+ case 110:
834
+ return '\n';
835
+ case 114:
836
+ return '\r';
837
+ case 120:
838
+ code = this.readHexChar(2);
839
+ if (code === null) return null;
840
+ return String.fromCharCode(code);
841
+ case 117:
842
+ code = this.readCodePoint();
843
+ if (code === null) return null;
844
+ return codePointToString(code);
845
+ case 116:
846
+ return '\t';
847
+ case 98:
848
+ return '\b';
849
+ case 118:
850
+ return '\u000b';
851
+ case 102:
852
+ return '\f';
853
+ //@ts-ignore
854
+ case 13:
855
+ if (this.input.charCodeAt(this.pos) === 10) {
856
+ ++this.pos;
857
+ }
858
+ // fall through
859
+ case 10:
860
+ return '';
861
+ case 56:
862
+ case 57:
863
+ return null;
864
+ default:
865
+ if (ch >= 48 && ch <= 55) {
866
+ const match = this.input.slice(this.pos - 1, this.pos + 2).match(/^[0-7]+/);
867
+ if (match === null) return null;
868
+ let octalStr = match[0];
869
+ let octal = parseInt(octalStr, 8);
870
+ if (octal > 255) {
871
+ octalStr = octalStr.slice(0, -1);
872
+ octal = parseInt(octalStr, 8);
873
+ }
874
+ this.pos += octalStr.length - 1;
875
+ const nextCh = this.input.charCodeAt(this.pos);
876
+ if (octalStr !== '0' || nextCh === 56 || nextCh === 57) return null;
877
+ return String.fromCharCode(octal);
878
+ }
879
+ if (isNewLine(ch)) return '';
880
+ return String.fromCharCode(ch);
881
+ }
882
+ }
883
+ readInt(radix, len) {
884
+ const start = this.pos;
885
+ let total = 0;
886
+ for(let i = 0; i < len; ++i, ++this.pos){
887
+ const code = this.input.charCodeAt(this.pos);
888
+ let val;
889
+ if (code >= 97) {
890
+ val = code - 97 + 10;
891
+ } else if (code >= 65) {
892
+ val = code - 65 + 10;
893
+ } else if (code >= 48 && code <= 57) {
894
+ val = code - 48;
895
+ } else {
896
+ val = Infinity;
897
+ }
898
+ if (val >= radix) break;
899
+ total = total * radix + val;
900
+ }
901
+ if (this.pos === start || len != null && this.pos - start !== len) return null;
902
+ return total;
903
+ }
904
+ readHexChar(len) {
905
+ return this.readInt(16, len);
906
+ }
907
+ readCodePoint() {
908
+ const ch = this.input.charCodeAt(this.pos);
909
+ let code;
910
+ if (ch === 123) {
911
+ ++this.pos;
912
+ code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos);
913
+ ++this.pos;
914
+ if (code && code > 0x10ffff) return null;
915
+ } else {
916
+ code = this.readHexChar(4);
917
+ }
918
+ return code;
919
+ }
920
+ constructor(){
921
+ this.input = '';
922
+ this.pos = 0;
923
+ }
924
+ }
925
+
926
+ function orderedUniq(array) {
927
+ // prettier-ignore
928
+ const ret = [], visited = new Set();
929
+ for (const val of array)if (!visited.has(val)) visited.add(val), ret.push(val);
930
+ return ret;
931
+ }
932
+ function cachedReduce(array, reducer, s) {
933
+ // prettier-ignore
934
+ const cache = [
935
+ s
936
+ ];
937
+ let cacheLen = 1, last = s;
938
+ return (len)=>{
939
+ while(cacheLen <= len)cacheLen = cache.push(last = reducer(last, array[cacheLen - 1]));
940
+ return cache[len];
941
+ };
942
+ }
943
+ // from @rollup/pluginutils
944
+ const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
945
+ const builtin = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
946
+ const forbiddenIdentifiers = new Set(`${reservedWords} ${builtin}`.split(' '));
947
+ forbiddenIdentifiers.add('');
948
+ const makeLegalIdentifier = function makeLegalIdentifier(str) {
949
+ let identifier = str.replace(/-(\w)/g, (_, letter)=>letter.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g, '_');
950
+ if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
951
+ identifier = `_${identifier}`;
952
+ }
953
+ return identifier || '_';
954
+ };
955
+
956
+ function commonjs({ filter = /\.c?js$/, transform = true, transformConfig, requireReturnsDefault = true, ignore } = {}) {
957
+ const init_cjs_module_lexer = transform ? Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('cjs-module-lexer')); }) : undefined;
958
+ const use_default_export = typeof requireReturnsDefault === 'function' ? requireReturnsDefault : (_path)=>requireReturnsDefault;
959
+ const is_ignored = typeof ignore === 'function' ? ignore : Array.isArray(ignore) ? (path)=>ignore.includes(path) : ()=>false;
960
+ return {
961
+ name: 'commonjs',
962
+ setup ({ onLoad, esbuild, initialOptions }) {
963
+ let esbuild_shim;
964
+ const require_esbuild = ()=>esbuild || esbuild_shim || (esbuild_shim = require('esbuild'));
965
+ const read = fs.promises.readFile;
966
+ const lexer = new Lexer();
967
+ //@ts-ignore
968
+ onLoad({
969
+ filter: filter
970
+ }, async (args)=>{
971
+ let parseCJS;
972
+ if (init_cjs_module_lexer) {
973
+ const { init, parse } = await init_cjs_module_lexer;
974
+ await init();
975
+ parseCJS = parse;
976
+ }
977
+ let contents;
978
+ try {
979
+ //@ts-ignore
980
+ contents = await read(args.path, 'utf8');
981
+ } catch (e) {
982
+ return null;
983
+ }
984
+ const willTransform = transform === true || typeof transform === 'function' && transform(args.path);
985
+ let cjsExports;
986
+ try {
987
+ if (parseCJS && willTransform) {
988
+ // move sourcemap to the end of the transformed file
989
+ const sourcemapIndex = contents.lastIndexOf('//# sourceMappingURL=');
990
+ let sourcemap;
991
+ if (sourcemapIndex !== -1) {
992
+ sourcemap = contents.slice(sourcemapIndex);
993
+ const sourcemapEnd = sourcemap.indexOf('\n');
994
+ if (sourcemapEnd !== -1 && sourcemap.slice(sourcemapEnd + 1).trimStart().length > 0) {
995
+ // if there's code after sourcemap, it is invalid, don't do this.
996
+ sourcemap = undefined;
997
+ } else {
998
+ contents = contents.slice(0, sourcemapIndex);
999
+ }
1000
+ }
1001
+ // transform commonjs to es modules, easy mode
1002
+ cjsExports = parseCJS(contents);
1003
+ let { behavior, exports, sideEffects } = typeof willTransform === 'object' ? willTransform : {};
1004
+ var _transformConfig_behavior;
1005
+ behavior != null ? behavior : behavior = (_transformConfig_behavior = transformConfig == null ? void 0 : transformConfig.behavior) != null ? _transformConfig_behavior : 'node';
1006
+ exports = orderedUniq(cjsExports.exports.concat(exports != null ? exports : []));
1007
+ var _transformConfig_sideEffects;
1008
+ sideEffects != null ? sideEffects : sideEffects = (_transformConfig_sideEffects = transformConfig == null ? void 0 : transformConfig.sideEffects) != null ? _transformConfig_sideEffects : true;
1009
+ let exportDefault = behavior === 'node' ? 'export default exports;' : 'export default exports.__esModule ? exports.default : exports;';
1010
+ let exportsMap = exports.map((e)=>[
1011
+ e,
1012
+ makeLegalIdentifier(e)
1013
+ ]);
1014
+ if (exportsMap.some(([e])=>e === 'default')) {
1015
+ if (behavior === 'node') {
1016
+ exportsMap = exportsMap.filter(([e])=>e !== 'default');
1017
+ } else {
1018
+ exportDefault = '';
1019
+ }
1020
+ }
1021
+ const reexports = cjsExports.reexports.map((e)=>`export * from ${JSON.stringify(e)};`).join('');
1022
+ let transformed;
1023
+ if (sideEffects === false) {
1024
+ transformed = [
1025
+ // make sure we don't manipulate the first line so that sourcemap is fine
1026
+ reexports + 'var mod, exports = /* @__PURE__ */ ((exports, module) => {' + contents,
1027
+ 'return module.exports})((mod = { exports: {} }).exports, mod); ' + exportDefault
1028
+ ];
1029
+ if (exportsMap.length > 0) {
1030
+ for (const [e, name] of exportsMap){
1031
+ transformed.push(`var ${name} = /* @__PURE__ */ (() => exports[${JSON.stringify(e)}])();`);
1032
+ }
1033
+ transformed.push(`export { ${exportsMap.map(([e, name])=>e === name ? e : `${name} as ${JSON.stringify(e)}`).join(', ')} };`);
1034
+ }
1035
+ } else {
1036
+ transformed = [
1037
+ reexports + 'var exports = {}, module = { exports }; {' + contents,
1038
+ '}; exports = module.exports; ' + exportDefault
1039
+ ];
1040
+ if (exportsMap.length > 0) {
1041
+ transformed.push(`var { ${exportsMap.map(([e, name])=>e === name ? e : `${JSON.stringify(e)}: ${name}`).join(', ')} } = exports;`, `export { ${exportsMap.map(([e, name])=>e === name ? e : `${name} as ${JSON.stringify(e)}`).join(', ')} };`);
1042
+ }
1043
+ }
1044
+ contents = transformed.join('\n') + (sourcemap ? '\n' + sourcemap : '');
1045
+ }
1046
+ } catch (e) {
1047
+ return null;
1048
+ }
1049
+ function makeName(path) {
1050
+ let name = `__import_${makeLegalIdentifier(path)}`;
1051
+ if (contents.includes(name)) {
1052
+ let suffix = 2;
1053
+ while(contents.includes(`${name}${suffix}`))suffix++;
1054
+ name = `${name}${suffix}`;
1055
+ }
1056
+ return name;
1057
+ }
1058
+ let warnings;
1059
+ try {
1060
+ ({ warnings } = await require_esbuild().transform(contents, {
1061
+ format: 'esm',
1062
+ logLevel: 'silent'
1063
+ }));
1064
+ } catch (err) {
1065
+ ({ warnings } = err);
1066
+ }
1067
+ const lines = contents.split('\n');
1068
+ const getOffset = cachedReduce(lines, (a, b)=>a + 1 + b.length, 0);
1069
+ if (warnings && (warnings = warnings.filter((e)=>e.text.includes('"require" to "esm"'))).length) {
1070
+ const edits = [];
1071
+ let imports = [];
1072
+ for (const { location } of warnings){
1073
+ if (location === null) continue;
1074
+ const { line, lineText, column, length } = location;
1075
+ const leftBrace = column + length + 1;
1076
+ const path = lexer.readString(lineText, leftBrace);
1077
+ if (path === null || is_ignored(path)) continue;
1078
+ const rightBrace = lineText.indexOf(')', leftBrace + 2 + path.length) + 1;
1079
+ const name = makeName(path);
1080
+ let import_statement;
1081
+ if (use_default_export(path)) {
1082
+ import_statement = `import ${name} from ${JSON.stringify(path)};`;
1083
+ } else {
1084
+ import_statement = `import * as ${name} from ${JSON.stringify(path)};`;
1085
+ }
1086
+ const offset = getOffset(line - 1);
1087
+ edits.push([
1088
+ offset + column,
1089
+ offset + rightBrace,
1090
+ name
1091
+ ]);
1092
+ imports.push(import_statement);
1093
+ }
1094
+ if (imports.length === 0) return null;
1095
+ imports = orderedUniq(imports);
1096
+ let offset = 0;
1097
+ for (const [start, end, name] of edits){
1098
+ contents = contents.slice(0, start + offset) + name + contents.slice(end + offset);
1099
+ offset += name.length - (end - start);
1100
+ }
1101
+ // if we have transformed this module (i.e. having `cjsExports`), don't make the file commonjs
1102
+ contents = [
1103
+ ...imports,
1104
+ cjsExports ? 'exports;' : '',
1105
+ contents
1106
+ ].join('');
1107
+ return {
1108
+ contents
1109
+ };
1110
+ }
1111
+ });
1112
+ }
1113
+ };
1114
+ }
1115
+
769
1116
  function _extends() {
770
1117
  _extends = Object.assign || function(target) {
771
1118
  for(var i = 1; i < arguments.length; i++){
@@ -799,36 +1146,32 @@ const cjsToEsmPlugin = {
799
1146
  filter: /.*/,
800
1147
  namespace: 'esm-shares'
801
1148
  }, async (args)=>{
802
- const { transform } = await new Function('return import("@chialab/cjs-to-esm")')();
803
- const resolver = await resolve(args.pluginData.resolveDir, args.path);
804
- if (typeof resolver !== 'string') {
805
- throw new Error(`Unable to resolve path: ${args.path}`);
806
- }
807
- const fileContent = fs__default["default"].readFileSync(resolver, 'utf-8');
808
- try {
809
- const result = await transform(fileContent);
810
- if (result) {
811
- const { code } = result;
812
- return {
813
- contents: code,
814
- loader: 'js',
815
- resolveDir: path__default["default"].dirname(resolver),
816
- pluginData: _extends({}, args.pluginData, {
817
- path: resolver
818
- })
819
- };
820
- }
821
- } catch (e) {
822
- return {
823
- contents: fileContent,
824
- loader: 'js',
825
- resolveDir: path__default["default"].dirname(resolver),
826
- pluginData: _extends({}, args.pluginData, {
827
- path: resolver
1149
+ var _build_initialOptions_external;
1150
+ let esbuild_shim;
1151
+ const require_esbuild = ()=>build.esbuild || esbuild_shim || (esbuild_shim = require('esbuild'));
1152
+ const packageBuilder = await require_esbuild().build(_extends({}, build.initialOptions, {
1153
+ external: (_build_initialOptions_external = build.initialOptions.external) == null ? void 0 : _build_initialOptions_external.filter((e)=>{
1154
+ if (e.includes('*')) {
1155
+ const prefix = e.split('*')[0];
1156
+ return !args.path.startsWith(prefix);
1157
+ }
1158
+ return e !== args.path;
1159
+ }),
1160
+ entryPoints: [
1161
+ args.path
1162
+ ],
1163
+ plugins: [
1164
+ commonjs({
1165
+ filter: /.*/
828
1166
  })
829
- };
830
- }
831
- return undefined;
1167
+ ],
1168
+ write: false
1169
+ }));
1170
+ return {
1171
+ contents: packageBuilder.outputFiles[0].text,
1172
+ loader: 'js',
1173
+ resolveDir: args.pluginData.resolveDir
1174
+ };
832
1175
  });
833
1176
  }
834
1177
  };