@module-federation/sdk 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.cjs CHANGED
@@ -12,16 +12,12 @@ function importNodeModule(name) {
12
12
  sdkImportCache.set(name, promise);
13
13
  return promise;
14
14
  }
15
- const loadNodeFetch = async () => {
16
- const fetchModule = await importNodeModule("node-fetch");
17
- return fetchModule.default || fetchModule;
18
- };
19
15
  const lazyLoaderHookFetch = async (input, init, loaderHook) => {
20
16
  const hook = (url, init) => {
21
17
  return loaderHook.lifecycle.fetch.emit(url, init);
22
18
  };
23
19
  const res = await hook(input, init || {});
24
- if (!res || !(res instanceof Response)) return (typeof fetch === "undefined" ? await loadNodeFetch() : fetch)(input, init || {});
20
+ if (!res || !(res instanceof Response)) return fetch(input, init || {});
25
21
  return res;
26
22
  };
27
23
  const createScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url, cb, attrs, loaderHook) => {
@@ -39,7 +35,7 @@ const createScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "we
39
35
  }
40
36
  const getFetch = async () => {
41
37
  if (loaderHook?.fetch) return (input, init) => lazyLoaderHookFetch(input, init, loaderHook);
42
- return typeof fetch === "undefined" ? loadNodeFetch() : fetch;
38
+ return fetch;
43
39
  };
44
40
  const handleScriptFetch = async (f, urlObj) => {
45
41
  try {
@@ -100,20 +96,82 @@ const loadScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web"
100
96
  throw new Error("loadScriptNode is disabled in non-Node.js environment");
101
97
  };
102
98
  const esmModuleCache = /* @__PURE__ */ new Map();
99
+ const isFetchableRemoteModuleUrl = (url) => url.startsWith("http:") || url.startsWith("https:");
100
+ const isBareModuleSpecifier = (specifier) => !specifier.startsWith("./") && !specifier.startsWith("../") && !specifier.startsWith("/") && !specifier.includes(":");
101
+ function encodeRemoteModulePath(url) {
102
+ const remoteUrl = new URL(url);
103
+ const encodedProtocol = encodeURIComponent(remoteUrl.protocol.slice(0, -1));
104
+ const encodedHost = encodeURIComponent(remoteUrl.host);
105
+ const encodedPathname = remoteUrl.pathname.split("/").map((segment) => encodeURIComponent(segment)).join("/");
106
+ const encodedSearchHash = encodeURIComponent(`${remoteUrl.search}${remoteUrl.hash}`);
107
+ return `/${encodedProtocol}/${encodedHost}${encodedPathname}${encodedSearchHash ? `/${encodedSearchHash}` : ""}`;
108
+ }
109
+ function createImportMetaUrl(url, baseFileUrl) {
110
+ const baseUrl = baseFileUrl.endsWith("/") ? baseFileUrl : `${baseFileUrl}/`;
111
+ return new URL(`__module_federation_remote__${encodeRemoteModulePath(url)}`, baseUrl).href;
112
+ }
113
+ async function isNodeBuiltinSpecifier(specifier) {
114
+ if (specifier.startsWith("node:")) return true;
115
+ if (!isBareModuleSpecifier(specifier)) return false;
116
+ return (await importNodeModule("node:module")).builtinModules.includes(specifier);
117
+ }
118
+ function getSyntheticModuleExports(moduleExports) {
119
+ const namespaceObject = moduleExports && (typeof moduleExports === "object" || typeof moduleExports === "function") ? moduleExports : { default: moduleExports };
120
+ const effectiveExports = { ...namespaceObject };
121
+ if (!Object.prototype.hasOwnProperty.call(effectiveExports, "default")) effectiveExports.default = namespaceObject;
122
+ return effectiveExports;
123
+ }
124
+ async function createSyntheticModuleFromExports(identifier, moduleExports, vm) {
125
+ if (typeof vm.SyntheticModule !== "function") throw new Error("vm.SyntheticModule is required to load Node.js built-in modules in ESM remote entries.");
126
+ const effectiveExports = getSyntheticModuleExports(moduleExports);
127
+ const exportNames = Object.keys(effectiveExports);
128
+ const syntheticModule = new vm.SyntheticModule(exportNames, function setSyntheticModuleExports() {
129
+ for (const name of exportNames) this.setExport(name, effectiveExports[name]);
130
+ }, { identifier });
131
+ esmModuleCache.set(identifier, syntheticModule);
132
+ await syntheticModule.link(async () => {
133
+ throw new Error(`Node.js built-in module "${identifier}" should not request child modules.`);
134
+ });
135
+ await syntheticModule.evaluate();
136
+ return syntheticModule;
137
+ }
138
+ async function loadNodeBuiltinModule(specifier, vm) {
139
+ const cacheKey = `node-builtin:${specifier}`;
140
+ if (esmModuleCache.has(cacheKey)) return esmModuleCache.get(cacheKey);
141
+ return createSyntheticModuleFromExports(cacheKey, await importNodeModule(specifier), vm);
142
+ }
143
+ async function loadResolvedModule(specifier, parentUrl, options) {
144
+ if (await isNodeBuiltinSpecifier(specifier)) return loadNodeBuiltinModule(specifier, options.vm);
145
+ if (isBareModuleSpecifier(specifier)) throw new Error(`Unsupported ESM module specifier "${specifier}". Only relative or absolute http(s) remote modules and Node.js built-in modules are supported.`);
146
+ const resolvedUrl = new URL(specifier, parentUrl).href;
147
+ if (!isFetchableRemoteModuleUrl(resolvedUrl)) throw new Error(`Unsupported ESM module specifier "${specifier}" resolved to "${resolvedUrl}". Only http(s) remote modules and Node.js built-in modules are supported.`);
148
+ return loadModule(resolvedUrl, options);
149
+ }
150
+ async function evaluateDynamicModule(module) {
151
+ if (module.status === "linked") await module.evaluate();
152
+ if (module.status === "errored") throw module.error;
153
+ return module;
154
+ }
103
155
  async function loadModule(url, options) {
104
156
  if (esmModuleCache.has(url)) return esmModuleCache.get(url);
105
157
  const { fetch, vm } = options;
158
+ if (!isFetchableRemoteModuleUrl(url)) throw new Error(`Unsupported ESM module URL "${url}". Only http(s) remote modules and Node.js built-in modules are supported.`);
106
159
  const code = await (await fetch(url)).text();
107
- const module = new vm.SourceTextModule(code, { importModuleDynamically: async (specifier, script) => {
108
- const resolvedUrl = new URL(specifier, url).href;
109
- return loadModule(resolvedUrl, options);
110
- } });
111
- esmModuleCache.set(url, module);
112
- await module.link(async (specifier) => {
113
- const resolvedUrl = new URL(specifier, url).href;
114
- return await loadModule(resolvedUrl, options);
160
+ const cwdFileUrl = (await importNodeModule("node:url")).pathToFileURL(process.cwd()).href;
161
+ const sourceTextModule = new vm.SourceTextModule(code, {
162
+ identifier: url,
163
+ initializeImportMeta: (meta) => {
164
+ meta.url = createImportMetaUrl(url, cwdFileUrl);
165
+ },
166
+ importModuleDynamically: async (specifier) => {
167
+ return evaluateDynamicModule(await loadResolvedModule(specifier, url, options));
168
+ }
115
169
  });
116
- return module;
170
+ esmModuleCache.set(url, sourceTextModule);
171
+ await sourceTextModule.link(async (specifier) => {
172
+ return loadResolvedModule(specifier, url, options);
173
+ });
174
+ return sourceTextModule;
117
175
  }
118
176
 
119
177
  //#endregion
package/dist/node.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.cjs","names":[],"sources":["../src/node.ts"],"sourcesContent":["import { CreateScriptHookNode, FetchHook } from './types';\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst sdkImportCache = new Map<string, Promise<any>>();\n\nfunction importNodeModule<T>(name: string): Promise<T> {\n if (!name) {\n throw new Error('import specifier is required');\n }\n\n // Check cache to prevent infinite recursion\n if (sdkImportCache.has(name)) {\n return sdkImportCache.get(name)!;\n }\n\n const importModule = new Function('name', `return import(name)`);\n const promise = importModule(name)\n .then((res: any) => res as T)\n .catch((error: any) => {\n console.error(`Error importing module ${name}:`, error);\n // Remove from cache on error so it can be retried\n sdkImportCache.delete(name);\n throw error;\n });\n\n // Cache the promise to prevent recursive calls\n sdkImportCache.set(name, promise);\n return promise;\n}\n\nconst loadNodeFetch = async (): Promise<typeof fetch> => {\n const fetchModule =\n await importNodeModule<typeof import('node-fetch')>('node-fetch');\n return (fetchModule.default || fetchModule) as unknown as typeof fetch;\n};\n\nconst lazyLoaderHookFetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n loaderHook?: any,\n): Promise<Response> => {\n const hook = (url: RequestInfo | URL, init: RequestInit) => {\n return loaderHook.lifecycle.fetch.emit(url, init);\n };\n\n const res = await hook(input, init || {});\n if (!res || !(res instanceof Response)) {\n const fetchFunction =\n typeof fetch === 'undefined' ? await loadNodeFetch() : fetch;\n return fetchFunction(input, init || {});\n }\n\n return res;\n};\n\nexport const createScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n if (loaderHook?.createScriptHook) {\n const hookResult = loaderHook.createScriptHook(url);\n if (\n hookResult &&\n typeof hookResult === 'object' &&\n 'url' in hookResult\n ) {\n url = hookResult.url;\n }\n }\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch (e) {\n console.error('Error constructing URL:', e);\n cb(new Error(`Invalid URL: ${e}`));\n return;\n }\n\n const getFetch = async (): Promise<typeof fetch> => {\n if (loaderHook?.fetch) {\n return (input: RequestInfo | URL, init?: RequestInit) =>\n lazyLoaderHookFetch(input, init, loaderHook);\n }\n\n return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;\n };\n\n const handleScriptFetch = async (f: typeof fetch, urlObj: URL) => {\n try {\n const res = await f(urlObj.href);\n const data = await res.text();\n const [path, vm] = await Promise.all([\n importNodeModule<typeof import('path')>('path'),\n importNodeModule<typeof import('vm')>('vm'),\n ]);\n\n const scriptContext = { exports: {}, module: { exports: {} } };\n const urlDirname = urlObj.pathname\n .split('/')\n .slice(0, -1)\n .join('/');\n const filename = path.basename(urlObj.pathname);\n\n const script = new vm.Script(\n `(function(exports, module, require, __dirname, __filename) {${data}\\n})`,\n {\n filename,\n importModuleDynamically:\n //@ts-ignore\n vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ??\n importNodeModule,\n },\n );\n\n let requireFn: NodeRequire;\n if (process.env.IS_ESM_BUILD === 'true') {\n const nodeModule =\n await importNodeModule<typeof import('node:module')>(\n 'node:module',\n );\n requireFn = nodeModule.createRequire(\n urlObj.protocol === 'file:' || urlObj.protocol === 'node:'\n ? urlObj.href\n : path.join(process.cwd(), '__mf_require_base__.js'),\n );\n } else {\n requireFn = eval('require') as NodeRequire;\n }\n\n script.runInThisContext()(\n scriptContext.exports,\n scriptContext.module,\n requireFn,\n urlDirname,\n filename,\n );\n const exportedInterface: Record<string, any> =\n scriptContext.module.exports || scriptContext.exports;\n\n if (attrs && exportedInterface && attrs['globalName']) {\n const container =\n exportedInterface[attrs['globalName']] || exportedInterface;\n cb(\n undefined,\n container as keyof typeof scriptContext.module.exports,\n );\n return;\n }\n\n cb(\n undefined,\n exportedInterface as keyof typeof scriptContext.module.exports,\n );\n } catch (e) {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n }\n };\n\n getFetch()\n .then(async (f) => {\n if (attrs?.['type'] === 'esm' || attrs?.['type'] === 'module') {\n return loadModule(urlObj.href, {\n fetch: f,\n vm: await importNodeModule<typeof import('vm')>('vm'),\n })\n .then(async (module) => {\n await module.evaluate();\n cb(undefined, module.namespace);\n })\n .catch((e) => {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n });\n }\n handleScriptFetch(f, urlObj);\n })\n .catch((err) => {\n cb(err);\n });\n }\n : (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n cb(\n new Error('createScriptNode is disabled in non-Node.js environment'),\n );\n };\n\nexport const loadScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n return new Promise<void>((resolve, reject) => {\n createScriptNode(\n url,\n (error, scriptContext) => {\n if (error) {\n reject(error);\n } else {\n const remoteEntryKey =\n info?.attrs?.['globalName'] ||\n `__FEDERATION_${info?.attrs?.['name']}:custom__`;\n const entryExports = ((globalThis as any)[remoteEntryKey] =\n scriptContext);\n resolve(entryExports);\n }\n },\n info.attrs,\n info.loaderHook,\n );\n });\n }\n : (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n throw new Error(\n 'loadScriptNode is disabled in non-Node.js environment',\n );\n };\n\nconst esmModuleCache = new Map<string, any>();\n\nasync function loadModule(\n url: string,\n options: {\n vm: any;\n fetch: any;\n },\n) {\n // Check cache to prevent infinite recursion in ESM loading\n if (esmModuleCache.has(url)) {\n return esmModuleCache.get(url)!;\n }\n\n const { fetch, vm } = options;\n const response = await fetch(url);\n const code = await response.text();\n\n const module: any = new vm.SourceTextModule(code, {\n // @ts-ignore\n importModuleDynamically: async (specifier, script) => {\n const resolvedUrl = new URL(specifier, url).href;\n return loadModule(resolvedUrl, options);\n },\n });\n\n // Cache the module before linking to prevent cycles\n esmModuleCache.set(url, module);\n\n await module.link(async (specifier: string) => {\n const resolvedUrl = new URL(specifier, url).href;\n const module = await loadModule(resolvedUrl, options);\n return module;\n });\n\n return module;\n}\n"],"mappings":";;AAKA,MAAM,iCAAiB,IAAI,KAA2B;AAEtD,SAAS,iBAAoB,MAA0B;AACrD,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,+BAA+B;AAIjD,KAAI,eAAe,IAAI,KAAK,CAC1B,QAAO,eAAe,IAAI,KAAK;CAIjC,MAAM,UADe,IAAI,SAAS,QAAQ,sBAAsB,CACnC,KAAK,CAC/B,MAAM,QAAa,IAAS,CAC5B,OAAO,UAAe;AACrB,UAAQ,MAAM,0BAA0B,KAAK,IAAI,MAAM;AAEvD,iBAAe,OAAO,KAAK;AAC3B,QAAM;GACN;AAGJ,gBAAe,IAAI,MAAM,QAAQ;AACjC,QAAO;;AAGT,MAAM,gBAAgB,YAAmC;CACvD,MAAM,cACJ,MAAM,iBAA8C,aAAa;AACnE,QAAQ,YAAY,WAAW;;AAGjC,MAAM,sBAAsB,OAC1B,OACA,MACA,eACsB;CACtB,MAAM,QAAQ,KAAwB,SAAsB;AAC1D,SAAO,WAAW,UAAU,MAAM,KAAK,KAAK,KAAK;;CAGnD,MAAM,MAAM,MAAM,KA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CAGhC,MAAM,EAAE,OAAO,OAAO;CAEtB,MAAM,OAAO,OADI,MAAM,MAAM,IAAI,EACL,MAAM;CAElC,MAAM,SAAc,IAAI,GAAG,iBAAiB,MAAM,EAEhD,yBAAyB,OAAO,WAAW,WAAW;EACpD,MAAM,cAAc,IAAI,IAAI,WAAW,IAAI,CAAC;AAC5C,SAAO,WAAW,aAAa,QAAQ;IAE1C,CAAC;AAGF,gBAAe,IAAI,KAAK,OAAO;AAE/B,OAAM,OAAO,KAAK,OAAO,cAAsB;EAC7C,MAAM,cAAc,IAAI,IAAI,WAAW,IAAI,CAAC;AAE5C,SADe,MAAM,WAAW,aAAa,QAAQ;GAErD;AAEF,QAAO"}
1
+ {"version":3,"file":"node.cjs","names":[],"sources":["../src/node.ts"],"sourcesContent":["import { CreateScriptHookNode, FetchHook } from './types';\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst sdkImportCache = new Map<string, Promise<any>>();\n\nfunction importNodeModule<T>(name: string): Promise<T> {\n if (!name) {\n throw new Error('import specifier is required');\n }\n\n // Check cache to prevent infinite recursion\n if (sdkImportCache.has(name)) {\n return sdkImportCache.get(name)!;\n }\n\n const importModule = new Function('name', `return import(name)`);\n const promise = importModule(name)\n .then((res: any) => res as T)\n .catch((error: any) => {\n console.error(`Error importing module ${name}:`, error);\n // Remove from cache on error so it can be retried\n sdkImportCache.delete(name);\n throw error;\n });\n\n // Cache the promise to prevent recursive calls\n sdkImportCache.set(name, promise);\n return promise;\n}\n\nconst lazyLoaderHookFetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n loaderHook?: any,\n): Promise<Response> => {\n const hook = (url: RequestInfo | URL, init: RequestInit) => {\n return loaderHook.lifecycle.fetch.emit(url, init);\n };\n\n const res = await hook(input, init || {});\n if (!res || !(res instanceof Response)) {\n return fetch(input, init || {});\n }\n\n return res;\n};\n\nexport const createScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n if (loaderHook?.createScriptHook) {\n const hookResult = loaderHook.createScriptHook(url);\n if (\n hookResult &&\n typeof hookResult === 'object' &&\n 'url' in hookResult\n ) {\n url = hookResult.url;\n }\n }\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch (e) {\n console.error('Error constructing URL:', e);\n cb(new Error(`Invalid URL: ${e}`));\n return;\n }\n\n const getFetch = async (): Promise<typeof fetch> => {\n if (loaderHook?.fetch) {\n return (input: RequestInfo | URL, init?: RequestInit) =>\n lazyLoaderHookFetch(input, init, loaderHook);\n }\n\n return fetch;\n };\n\n const handleScriptFetch = async (f: typeof fetch, urlObj: URL) => {\n try {\n const res = await f(urlObj.href);\n const data = await res.text();\n const [path, vm] = await Promise.all([\n importNodeModule<typeof import('path')>('path'),\n importNodeModule<typeof import('vm')>('vm'),\n ]);\n\n const scriptContext = { exports: {}, module: { exports: {} } };\n const urlDirname = urlObj.pathname\n .split('/')\n .slice(0, -1)\n .join('/');\n const filename = path.basename(urlObj.pathname);\n\n const script = new vm.Script(\n `(function(exports, module, require, __dirname, __filename) {${data}\\n})`,\n {\n filename,\n importModuleDynamically:\n //@ts-ignore\n vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ??\n importNodeModule,\n },\n );\n\n let requireFn: NodeRequire;\n if (process.env.IS_ESM_BUILD === 'true') {\n const nodeModule =\n await importNodeModule<typeof import('node:module')>(\n 'node:module',\n );\n requireFn = nodeModule.createRequire(\n urlObj.protocol === 'file:' || urlObj.protocol === 'node:'\n ? urlObj.href\n : path.join(process.cwd(), '__mf_require_base__.js'),\n );\n } else {\n requireFn = eval('require') as NodeRequire;\n }\n\n script.runInThisContext()(\n scriptContext.exports,\n scriptContext.module,\n requireFn,\n urlDirname,\n filename,\n );\n const exportedInterface: Record<string, any> =\n scriptContext.module.exports || scriptContext.exports;\n\n if (attrs && exportedInterface && attrs['globalName']) {\n const container =\n exportedInterface[attrs['globalName']] || exportedInterface;\n cb(\n undefined,\n container as keyof typeof scriptContext.module.exports,\n );\n return;\n }\n\n cb(\n undefined,\n exportedInterface as keyof typeof scriptContext.module.exports,\n );\n } catch (e) {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n }\n };\n\n getFetch()\n .then(async (f) => {\n if (attrs?.['type'] === 'esm' || attrs?.['type'] === 'module') {\n return loadModule(urlObj.href, {\n fetch: f,\n vm: await importNodeModule<typeof import('vm')>('vm'),\n })\n .then(async (module) => {\n await module.evaluate();\n cb(undefined, module.namespace);\n })\n .catch((e) => {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n });\n }\n handleScriptFetch(f, urlObj);\n })\n .catch((err) => {\n cb(err);\n });\n }\n : (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n cb(\n new Error('createScriptNode is disabled in non-Node.js environment'),\n );\n };\n\nexport const loadScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n return new Promise<void>((resolve, reject) => {\n createScriptNode(\n url,\n (error, scriptContext) => {\n if (error) {\n reject(error);\n } else {\n const remoteEntryKey =\n info?.attrs?.['globalName'] ||\n `__FEDERATION_${info?.attrs?.['name']}:custom__`;\n const entryExports = ((globalThis as any)[remoteEntryKey] =\n scriptContext);\n resolve(entryExports);\n }\n },\n info.attrs,\n info.loaderHook,\n );\n });\n }\n : (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n throw new Error(\n 'loadScriptNode is disabled in non-Node.js environment',\n );\n };\n\nconst esmModuleCache = new Map<string, any>();\n\ntype LoadModuleOptions = {\n vm: typeof import('vm') & {\n SourceTextModule: any;\n SyntheticModule: any;\n };\n fetch: typeof fetch;\n};\n\nconst isFetchableRemoteModuleUrl = (url: string): boolean =>\n url.startsWith('http:') || url.startsWith('https:');\n\nconst isBareModuleSpecifier = (specifier: string): boolean =>\n !specifier.startsWith('./') &&\n !specifier.startsWith('../') &&\n !specifier.startsWith('/') &&\n !specifier.includes(':');\n\nfunction encodeRemoteModulePath(url: string): string {\n const remoteUrl = new URL(url);\n const encodedProtocol = encodeURIComponent(remoteUrl.protocol.slice(0, -1));\n const encodedHost = encodeURIComponent(remoteUrl.host);\n const encodedPathname = remoteUrl.pathname\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n const encodedSearchHash = encodeURIComponent(\n `${remoteUrl.search}${remoteUrl.hash}`,\n );\n const encodedSuffix = encodedSearchHash ? `/${encodedSearchHash}` : '';\n\n return `/${encodedProtocol}/${encodedHost}${encodedPathname}${encodedSuffix}`;\n}\n\nfunction createImportMetaUrl(url: string, baseFileUrl: string): string {\n const baseUrl = baseFileUrl.endsWith('/') ? baseFileUrl : `${baseFileUrl}/`;\n return new URL(\n `__module_federation_remote__${encodeRemoteModulePath(url)}`,\n baseUrl,\n ).href;\n}\n\nasync function isNodeBuiltinSpecifier(specifier: string): Promise<boolean> {\n if (specifier.startsWith('node:')) {\n return true;\n }\n\n if (!isBareModuleSpecifier(specifier)) {\n return false;\n }\n\n const nodeModule =\n await importNodeModule<typeof import('node:module')>('node:module');\n\n return nodeModule.builtinModules.includes(specifier);\n}\n\nfunction getSyntheticModuleExports(moduleExports: any): Record<string, any> {\n const namespaceObject =\n moduleExports &&\n (typeof moduleExports === 'object' || typeof moduleExports === 'function')\n ? moduleExports\n : { default: moduleExports };\n const effectiveExports = { ...namespaceObject };\n\n if (!Object.prototype.hasOwnProperty.call(effectiveExports, 'default')) {\n effectiveExports.default = namespaceObject;\n }\n\n return effectiveExports;\n}\n\nasync function createSyntheticModuleFromExports(\n identifier: string,\n moduleExports: any,\n vm: LoadModuleOptions['vm'],\n) {\n if (typeof vm.SyntheticModule !== 'function') {\n throw new Error(\n 'vm.SyntheticModule is required to load Node.js built-in modules in ESM remote entries.',\n );\n }\n\n const effectiveExports = getSyntheticModuleExports(moduleExports);\n const exportNames = Object.keys(effectiveExports);\n const syntheticModule = new vm.SyntheticModule(\n exportNames,\n function setSyntheticModuleExports(this: {\n setExport: (name: string, value: any) => void;\n }) {\n for (const name of exportNames) {\n this.setExport(name, effectiveExports[name]);\n }\n },\n { identifier },\n );\n\n esmModuleCache.set(identifier, syntheticModule);\n await syntheticModule.link(async () => {\n throw new Error(\n `Node.js built-in module \"${identifier}\" should not request child modules.`,\n );\n });\n await syntheticModule.evaluate();\n\n return syntheticModule;\n}\n\nasync function loadNodeBuiltinModule(\n specifier: string,\n vm: LoadModuleOptions['vm'],\n) {\n const cacheKey = `node-builtin:${specifier}`;\n if (esmModuleCache.has(cacheKey)) {\n return esmModuleCache.get(cacheKey)!;\n }\n\n const moduleExports = await importNodeModule(specifier);\n return createSyntheticModuleFromExports(cacheKey, moduleExports, vm);\n}\n\nasync function loadResolvedModule(\n specifier: string,\n parentUrl: string,\n options: LoadModuleOptions,\n) {\n if (await isNodeBuiltinSpecifier(specifier)) {\n return loadNodeBuiltinModule(specifier, options.vm);\n }\n\n if (isBareModuleSpecifier(specifier)) {\n throw new Error(\n `Unsupported ESM module specifier \"${specifier}\". Only relative or absolute http(s) remote modules and Node.js built-in modules are supported.`,\n );\n }\n\n const resolvedUrl = new URL(specifier, parentUrl).href;\n if (!isFetchableRemoteModuleUrl(resolvedUrl)) {\n throw new Error(\n `Unsupported ESM module specifier \"${specifier}\" resolved to \"${resolvedUrl}\". Only http(s) remote modules and Node.js built-in modules are supported.`,\n );\n }\n\n return loadModule(resolvedUrl, options);\n}\n\nasync function evaluateDynamicModule(module: any) {\n if (module.status === 'linked') {\n await module.evaluate();\n }\n\n if (module.status === 'errored') {\n throw module.error;\n }\n\n return module;\n}\n\nasync function loadModule(url: string, options: LoadModuleOptions) {\n // Check cache to prevent infinite recursion in ESM loading\n if (esmModuleCache.has(url)) {\n return esmModuleCache.get(url)!;\n }\n\n const { fetch, vm } = options;\n if (!isFetchableRemoteModuleUrl(url)) {\n throw new Error(\n `Unsupported ESM module URL \"${url}\". Only http(s) remote modules and Node.js built-in modules are supported.`,\n );\n }\n\n const response = await fetch(url);\n const code = await response.text();\n const nodeUrl = await importNodeModule<typeof import('node:url')>('node:url');\n const cwdFileUrl = nodeUrl.pathToFileURL(process.cwd()).href;\n\n const sourceTextModule: any = new vm.SourceTextModule(code, {\n identifier: url,\n initializeImportMeta: (meta: { url: string }) => {\n meta.url = createImportMetaUrl(url, cwdFileUrl);\n },\n importModuleDynamically: async (specifier: string) => {\n return evaluateDynamicModule(\n await loadResolvedModule(specifier, url, options),\n );\n },\n });\n\n // Cache the module before linking to prevent cycles\n esmModuleCache.set(url, sourceTextModule);\n\n await sourceTextModule.link(async (specifier: string) => {\n return loadResolvedModule(specifier, url, options);\n });\n\n return sourceTextModule;\n}\n"],"mappings":";;AAKA,MAAM,iCAAiB,IAAI,KAA2B;AAEtD,SAAS,iBAAoB,MAA0B;AACrD,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,+BAA+B;AAIjD,KAAI,eAAe,IAAI,KAAK,CAC1B,QAAO,eAAe,IAAI,KAAK;CAIjC,MAAM,UADe,IAAI,SAAS,QAAQ,sBAAsB,CACnC,KAAK,CAC/B,MAAM,QAAa,IAAS,CAC5B,OAAO,UAAe;AACrB,UAAQ,MAAM,0BAA0B,KAAK,IAAI,MAAM;AAEvD,iBAAe,OAAO,KAAK;AAC3B,QAAM;GACN;AAGJ,gBAAe,IAAI,MAAM,QAAQ;AACjC,QAAO;;AAGT,MAAM,sBAAsB,OAC1B,OACA,MACA,eACsB;CACtB,MAAM,QAAQ,K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I,4EACpC;CAIH,MAAM,OAAO,OADI,MAAM,MAAM,IAAI,EACL,MAAM;CAElC,MAAM,cADU,MAAM,iBAA4C,WAAW,EAClD,cAAc,QAAQ,KAAK,CAAC,CAAC;CAExD,MAAM,mBAAwB,IAAI,GAAG,iBAAiB,MAAM;EAC1D,YAAY;EACZ,uBAAuB,SAA0B;AAC/C,QAAK,MAAM,oBAAoB,KAAK,WAAW;;EAEjD,yBAAyB,OAAO,cAAsB;AACpD,UAAO,sBACL,MAAM,mBAAmB,WAAW,KAAK,QAAQ,CAClD;;EAEJ,CAAC;AAGF,gBAAe,IAAI,KAAK,iBAAiB;AAEzC,OAAM,iBAAiB,KAAK,OAAO,cAAsB;AACvD,SAAO,mBAAmB,WAAW,KAAK,QAAQ;GAClD;AAEF,QAAO"}
package/dist/node.js CHANGED
@@ -11,16 +11,12 @@ function importNodeModule(name) {
11
11
  sdkImportCache.set(name, promise);
12
12
  return promise;
13
13
  }
14
- const loadNodeFetch = async () => {
15
- const fetchModule = await importNodeModule("node-fetch");
16
- return fetchModule.default || fetchModule;
17
- };
18
14
  const lazyLoaderHookFetch = async (input, init, loaderHook) => {
19
15
  const hook = (url, init) => {
20
16
  return loaderHook.lifecycle.fetch.emit(url, init);
21
17
  };
22
18
  const res = await hook(input, init || {});
23
- if (!res || !(res instanceof Response)) return (typeof fetch === "undefined" ? await loadNodeFetch() : fetch)(input, init || {});
19
+ if (!res || !(res instanceof Response)) return fetch(input, init || {});
24
20
  return res;
25
21
  };
26
22
  const createScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url, cb, attrs, loaderHook) => {
@@ -38,7 +34,7 @@ const createScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "we
38
34
  }
39
35
  const getFetch = async () => {
40
36
  if (loaderHook?.fetch) return (input, init) => lazyLoaderHookFetch(input, init, loaderHook);
41
- return typeof fetch === "undefined" ? loadNodeFetch() : fetch;
37
+ return fetch;
42
38
  };
43
39
  const handleScriptFetch = async (f, urlObj) => {
44
40
  try {
@@ -99,20 +95,82 @@ const loadScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web"
99
95
  throw new Error("loadScriptNode is disabled in non-Node.js environment");
100
96
  };
101
97
  const esmModuleCache = /* @__PURE__ */ new Map();
98
+ const isFetchableRemoteModuleUrl = (url) => url.startsWith("http:") || url.startsWith("https:");
99
+ const isBareModuleSpecifier = (specifier) => !specifier.startsWith("./") && !specifier.startsWith("../") && !specifier.startsWith("/") && !specifier.includes(":");
100
+ function encodeRemoteModulePath(url) {
101
+ const remoteUrl = new URL(url);
102
+ const encodedProtocol = encodeURIComponent(remoteUrl.protocol.slice(0, -1));
103
+ const encodedHost = encodeURIComponent(remoteUrl.host);
104
+ const encodedPathname = remoteUrl.pathname.split("/").map((segment) => encodeURIComponent(segment)).join("/");
105
+ const encodedSearchHash = encodeURIComponent(`${remoteUrl.search}${remoteUrl.hash}`);
106
+ return `/${encodedProtocol}/${encodedHost}${encodedPathname}${encodedSearchHash ? `/${encodedSearchHash}` : ""}`;
107
+ }
108
+ function createImportMetaUrl(url, baseFileUrl) {
109
+ const baseUrl = baseFileUrl.endsWith("/") ? baseFileUrl : `${baseFileUrl}/`;
110
+ return new URL(`__module_federation_remote__${encodeRemoteModulePath(url)}`, baseUrl).href;
111
+ }
112
+ async function isNodeBuiltinSpecifier(specifier) {
113
+ if (specifier.startsWith("node:")) return true;
114
+ if (!isBareModuleSpecifier(specifier)) return false;
115
+ return (await importNodeModule("node:module")).builtinModules.includes(specifier);
116
+ }
117
+ function getSyntheticModuleExports(moduleExports) {
118
+ const namespaceObject = moduleExports && (typeof moduleExports === "object" || typeof moduleExports === "function") ? moduleExports : { default: moduleExports };
119
+ const effectiveExports = { ...namespaceObject };
120
+ if (!Object.prototype.hasOwnProperty.call(effectiveExports, "default")) effectiveExports.default = namespaceObject;
121
+ return effectiveExports;
122
+ }
123
+ async function createSyntheticModuleFromExports(identifier, moduleExports, vm) {
124
+ if (typeof vm.SyntheticModule !== "function") throw new Error("vm.SyntheticModule is required to load Node.js built-in modules in ESM remote entries.");
125
+ const effectiveExports = getSyntheticModuleExports(moduleExports);
126
+ const exportNames = Object.keys(effectiveExports);
127
+ const syntheticModule = new vm.SyntheticModule(exportNames, function setSyntheticModuleExports() {
128
+ for (const name of exportNames) this.setExport(name, effectiveExports[name]);
129
+ }, { identifier });
130
+ esmModuleCache.set(identifier, syntheticModule);
131
+ await syntheticModule.link(async () => {
132
+ throw new Error(`Node.js built-in module "${identifier}" should not request child modules.`);
133
+ });
134
+ await syntheticModule.evaluate();
135
+ return syntheticModule;
136
+ }
137
+ async function loadNodeBuiltinModule(specifier, vm) {
138
+ const cacheKey = `node-builtin:${specifier}`;
139
+ if (esmModuleCache.has(cacheKey)) return esmModuleCache.get(cacheKey);
140
+ return createSyntheticModuleFromExports(cacheKey, await importNodeModule(specifier), vm);
141
+ }
142
+ async function loadResolvedModule(specifier, parentUrl, options) {
143
+ if (await isNodeBuiltinSpecifier(specifier)) return loadNodeBuiltinModule(specifier, options.vm);
144
+ if (isBareModuleSpecifier(specifier)) throw new Error(`Unsupported ESM module specifier "${specifier}". Only relative or absolute http(s) remote modules and Node.js built-in modules are supported.`);
145
+ const resolvedUrl = new URL(specifier, parentUrl).href;
146
+ if (!isFetchableRemoteModuleUrl(resolvedUrl)) throw new Error(`Unsupported ESM module specifier "${specifier}" resolved to "${resolvedUrl}". Only http(s) remote modules and Node.js built-in modules are supported.`);
147
+ return loadModule(resolvedUrl, options);
148
+ }
149
+ async function evaluateDynamicModule(module) {
150
+ if (module.status === "linked") await module.evaluate();
151
+ if (module.status === "errored") throw module.error;
152
+ return module;
153
+ }
102
154
  async function loadModule(url, options) {
103
155
  if (esmModuleCache.has(url)) return esmModuleCache.get(url);
104
156
  const { fetch, vm } = options;
157
+ if (!isFetchableRemoteModuleUrl(url)) throw new Error(`Unsupported ESM module URL "${url}". Only http(s) remote modules and Node.js built-in modules are supported.`);
105
158
  const code = await (await fetch(url)).text();
106
- const module = new vm.SourceTextModule(code, { importModuleDynamically: async (specifier, script) => {
107
- const resolvedUrl = new URL(specifier, url).href;
108
- return loadModule(resolvedUrl, options);
109
- } });
110
- esmModuleCache.set(url, module);
111
- await module.link(async (specifier) => {
112
- const resolvedUrl = new URL(specifier, url).href;
113
- return await loadModule(resolvedUrl, options);
159
+ const cwdFileUrl = (await importNodeModule("node:url")).pathToFileURL(process.cwd()).href;
160
+ const sourceTextModule = new vm.SourceTextModule(code, {
161
+ identifier: url,
162
+ initializeImportMeta: (meta) => {
163
+ meta.url = createImportMetaUrl(url, cwdFileUrl);
164
+ },
165
+ importModuleDynamically: async (specifier) => {
166
+ return evaluateDynamicModule(await loadResolvedModule(specifier, url, options));
167
+ }
114
168
  });
115
- return module;
169
+ esmModuleCache.set(url, sourceTextModule);
170
+ await sourceTextModule.link(async (specifier) => {
171
+ return loadResolvedModule(specifier, url, options);
172
+ });
173
+ return sourceTextModule;
116
174
  }
117
175
 
118
176
  //#endregion
package/dist/node.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","names":[],"sources":["../src/node.ts"],"sourcesContent":["import { CreateScriptHookNode, FetchHook } from './types';\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst sdkImportCache = new Map<string, Promise<any>>();\n\nfunction importNodeModule<T>(name: string): Promise<T> {\n if (!name) {\n throw new Error('import specifier is required');\n }\n\n // Check cache to prevent infinite recursion\n if (sdkImportCache.has(name)) {\n return sdkImportCache.get(name)!;\n }\n\n const importModule = new Function('name', `return import(name)`);\n const promise = importModule(name)\n .then((res: any) => res as T)\n .catch((error: any) => {\n console.error(`Error importing module ${name}:`, error);\n // Remove from cache on error so it can be retried\n sdkImportCache.delete(name);\n throw error;\n });\n\n // Cache the promise to prevent recursive calls\n sdkImportCache.set(name, promise);\n return promise;\n}\n\nconst loadNodeFetch = async (): Promise<typeof fetch> => {\n const fetchModule =\n await importNodeModule<typeof import('node-fetch')>('node-fetch');\n return (fetchModule.default || fetchModule) as unknown as typeof fetch;\n};\n\nconst lazyLoaderHookFetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n loaderHook?: any,\n): Promise<Response> => {\n const hook = (url: RequestInfo | URL, init: RequestInit) => {\n return loaderHook.lifecycle.fetch.emit(url, init);\n };\n\n const res = await hook(input, init || {});\n if (!res || !(res instanceof Response)) {\n const fetchFunction =\n typeof fetch === 'undefined' ? await loadNodeFetch() : fetch;\n return fetchFunction(input, init || {});\n }\n\n return res;\n};\n\nexport const createScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n if (loaderHook?.createScriptHook) {\n const hookResult = loaderHook.createScriptHook(url);\n if (\n hookResult &&\n typeof hookResult === 'object' &&\n 'url' in hookResult\n ) {\n url = hookResult.url;\n }\n }\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch (e) {\n console.error('Error constructing URL:', e);\n cb(new Error(`Invalid URL: ${e}`));\n return;\n }\n\n const getFetch = async (): Promise<typeof fetch> => {\n if (loaderHook?.fetch) {\n return (input: RequestInfo | URL, init?: RequestInit) =>\n lazyLoaderHookFetch(input, init, loaderHook);\n }\n\n return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;\n };\n\n const handleScriptFetch = async (f: typeof fetch, urlObj: URL) => {\n try {\n const res = await f(urlObj.href);\n const data = await res.text();\n const [path, vm] = await Promise.all([\n importNodeModule<typeof import('path')>('path'),\n importNodeModule<typeof import('vm')>('vm'),\n ]);\n\n const scriptContext = { exports: {}, module: { exports: {} } };\n const urlDirname = urlObj.pathname\n .split('/')\n .slice(0, -1)\n .join('/');\n const filename = path.basename(urlObj.pathname);\n\n const script = new vm.Script(\n `(function(exports, module, require, __dirname, __filename) {${data}\\n})`,\n {\n filename,\n importModuleDynamically:\n //@ts-ignore\n vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ??\n importNodeModule,\n },\n );\n\n let requireFn: NodeRequire;\n if (process.env.IS_ESM_BUILD === 'true') {\n const nodeModule =\n await importNodeModule<typeof import('node:module')>(\n 'node:module',\n );\n requireFn = nodeModule.createRequire(\n urlObj.protocol === 'file:' || urlObj.protocol === 'node:'\n ? urlObj.href\n : path.join(process.cwd(), '__mf_require_base__.js'),\n );\n } else {\n requireFn = eval('require') as NodeRequire;\n }\n\n script.runInThisContext()(\n scriptContext.exports,\n scriptContext.module,\n requireFn,\n urlDirname,\n filename,\n );\n const exportedInterface: Record<string, any> =\n scriptContext.module.exports || scriptContext.exports;\n\n if (attrs && exportedInterface && attrs['globalName']) {\n const container =\n exportedInterface[attrs['globalName']] || exportedInterface;\n cb(\n undefined,\n container as keyof typeof scriptContext.module.exports,\n );\n return;\n }\n\n cb(\n undefined,\n exportedInterface as keyof typeof scriptContext.module.exports,\n );\n } catch (e) {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n }\n };\n\n getFetch()\n .then(async (f) => {\n if (attrs?.['type'] === 'esm' || attrs?.['type'] === 'module') {\n return loadModule(urlObj.href, {\n fetch: f,\n vm: await importNodeModule<typeof import('vm')>('vm'),\n })\n .then(async (module) => {\n await module.evaluate();\n cb(undefined, module.namespace);\n })\n .catch((e) => {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n });\n }\n handleScriptFetch(f, urlObj);\n })\n .catch((err) => {\n cb(err);\n });\n }\n : (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n cb(\n new Error('createScriptNode is disabled in non-Node.js environment'),\n );\n };\n\nexport const loadScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n return new Promise<void>((resolve, reject) => {\n createScriptNode(\n url,\n (error, scriptContext) => {\n if (error) {\n reject(error);\n } else {\n const remoteEntryKey =\n info?.attrs?.['globalName'] ||\n `__FEDERATION_${info?.attrs?.['name']}:custom__`;\n const entryExports = ((globalThis as any)[remoteEntryKey] =\n scriptContext);\n resolve(entryExports);\n }\n },\n info.attrs,\n info.loaderHook,\n );\n });\n }\n : (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n throw new Error(\n 'loadScriptNode is disabled in non-Node.js environment',\n );\n };\n\nconst esmModuleCache = new Map<string, any>();\n\nasync function loadModule(\n url: string,\n options: {\n vm: any;\n fetch: any;\n },\n) {\n // Check cache to prevent infinite recursion in ESM loading\n if (esmModuleCache.has(url)) {\n return esmModuleCache.get(url)!;\n }\n\n const { fetch, vm } = options;\n const response = await fetch(url);\n const code = await response.text();\n\n const module: any = new vm.SourceTextModule(code, {\n // @ts-ignore\n importModuleDynamically: async (specifier, script) => {\n const resolvedUrl = new URL(specifier, url).href;\n return loadModule(resolvedUrl, options);\n },\n });\n\n // Cache the module before linking to prevent cycles\n esmModuleCache.set(url, module);\n\n await module.link(async (specifier: string) => {\n const resolvedUrl = new URL(specifier, url).href;\n const module = await loadModule(resolvedUrl, options);\n return module;\n });\n\n return module;\n}\n"],"mappings":";AAKA,MAAM,iCAAiB,IAAI,KAA2B;AAEtD,SAAS,iBAAoB,MAA0B;AACrD,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,+BAA+B;AAIjD,KAAI,eAAe,IAAI,KAAK,CAC1B,QAAO,eAAe,IAAI,KAAK;CAIjC,MAAM,UADe,IAAI,SAAS,QAAQ,sBAAsB,CACnC,KAAK,CAC/B,MAAM,QAAa,IAAS,CAC5B,OAAO,UAAe;AACrB,UAAQ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DAA0D,CACrE;;AAGT,MAAa,iBACX,OAAO,eAAe,eAAe,eAAe,SAE9C,KACA,SAMG;AACH,QAAO,IAAI,SAAe,SAAS,WAAW;AAC5C,mBACE,MACC,OAAO,kBAAkB;AACxB,OAAI,MACF,QAAO,MAAM;QACR;IACL,MAAM,iBACJ,MAAM,QAAQ,iBACd,gBAAgB,MAAM,QAAQ,QAAQ;AAGxC,YAFsB,AAAC,WAAmB,kBACxC,cACmB;;KAGzB,KAAK,OACL,KAAK,WACN;GACD;KAGF,KACA,SAMG;AACH,OAAM,IAAI,MACR,wDACD;;AAGT,MAAM,iCAAiB,IAAI,KAAkB;AAE7C,eAAe,WACb,KACA,SAIA;AAEA,KAAI,eAAe,IAAI,IAAI,CACzB,QAAO,eAAe,IAAI,IAAI;CAGhC,MAAM,EAAE,OAAO,OAAO;CAEtB,MAAM,OAAO,OADI,MAAM,MAAM,IAAI,EACL,MAAM;CAElC,MAAM,SAAc,IAAI,GAAG,iBAAiB,MAAM,EAEhD,yBAAyB,OAAO,WAAW,WAAW;EACpD,MAAM,cAAc,IAAI,IAAI,WAAW,IAAI,CAAC;AAC5C,SAAO,WAAW,aAAa,QAAQ;IAE1C,CAAC;AAGF,gBAAe,IAAI,KAAK,OAAO;AAE/B,OAAM,OAAO,KAAK,OAAO,cAAsB;EAC7C,MAAM,cAAc,IAAI,IAAI,WAAW,IAAI,CAAC;AAE5C,SADe,MAAM,WAAW,aAAa,QAAQ;GAErD;AAEF,QAAO"}
1
+ {"version":3,"file":"node.js","names":[],"sources":["../src/node.ts"],"sourcesContent":["import { CreateScriptHookNode, FetchHook } from './types';\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst sdkImportCache = new Map<string, Promise<any>>();\n\nfunction importNodeModule<T>(name: string): Promise<T> {\n if (!name) {\n throw new Error('import specifier is required');\n }\n\n // Check cache to prevent infinite recursion\n if (sdkImportCache.has(name)) {\n return sdkImportCache.get(name)!;\n }\n\n const importModule = new Function('name', `return import(name)`);\n const promise = importModule(name)\n .then((res: any) => res as T)\n .catch((error: any) => {\n console.error(`Error importing module ${name}:`, error);\n // Remove from cache on error so it can be retried\n sdkImportCache.delete(name);\n throw error;\n });\n\n // Cache the promise to prevent recursive calls\n sdkImportCache.set(name, promise);\n return promise;\n}\n\nconst lazyLoaderHookFetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n loaderHook?: any,\n): Promise<Response> => {\n const hook = (url: RequestInfo | URL, init: RequestInit) => {\n return loaderHook.lifecycle.fetch.emit(url, init);\n };\n\n const res = await hook(input, init || {});\n if (!res || !(res instanceof Response)) {\n return fetch(input, init || {});\n }\n\n return res;\n};\n\nexport const createScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n if (loaderHook?.createScriptHook) {\n const hookResult = loaderHook.createScriptHook(url);\n if (\n hookResult &&\n typeof hookResult === 'object' &&\n 'url' in hookResult\n ) {\n url = hookResult.url;\n }\n }\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch (e) {\n console.error('Error constructing URL:', e);\n cb(new Error(`Invalid URL: ${e}`));\n return;\n }\n\n const getFetch = async (): Promise<typeof fetch> => {\n if (loaderHook?.fetch) {\n return (input: RequestInfo | URL, init?: RequestInit) =>\n lazyLoaderHookFetch(input, init, loaderHook);\n }\n\n return fetch;\n };\n\n const handleScriptFetch = async (f: typeof fetch, urlObj: URL) => {\n try {\n const res = await f(urlObj.href);\n const data = await res.text();\n const [path, vm] = await Promise.all([\n importNodeModule<typeof import('path')>('path'),\n importNodeModule<typeof import('vm')>('vm'),\n ]);\n\n const scriptContext = { exports: {}, module: { exports: {} } };\n const urlDirname = urlObj.pathname\n .split('/')\n .slice(0, -1)\n .join('/');\n const filename = path.basename(urlObj.pathname);\n\n const script = new vm.Script(\n `(function(exports, module, require, __dirname, __filename) {${data}\\n})`,\n {\n filename,\n importModuleDynamically:\n //@ts-ignore\n vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ??\n importNodeModule,\n },\n );\n\n let requireFn: NodeRequire;\n if (process.env.IS_ESM_BUILD === 'true') {\n const nodeModule =\n await importNodeModule<typeof import('node:module')>(\n 'node:module',\n );\n requireFn = nodeModule.createRequire(\n urlObj.protocol === 'file:' || urlObj.protocol === 'node:'\n ? urlObj.href\n : path.join(process.cwd(), '__mf_require_base__.js'),\n );\n } else {\n requireFn = eval('require') as NodeRequire;\n }\n\n script.runInThisContext()(\n scriptContext.exports,\n scriptContext.module,\n requireFn,\n urlDirname,\n filename,\n );\n const exportedInterface: Record<string, any> =\n scriptContext.module.exports || scriptContext.exports;\n\n if (attrs && exportedInterface && attrs['globalName']) {\n const container =\n exportedInterface[attrs['globalName']] || exportedInterface;\n cb(\n undefined,\n container as keyof typeof scriptContext.module.exports,\n );\n return;\n }\n\n cb(\n undefined,\n exportedInterface as keyof typeof scriptContext.module.exports,\n );\n } catch (e) {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n }\n };\n\n getFetch()\n .then(async (f) => {\n if (attrs?.['type'] === 'esm' || attrs?.['type'] === 'module') {\n return loadModule(urlObj.href, {\n fetch: f,\n vm: await importNodeModule<typeof import('vm')>('vm'),\n })\n .then(async (module) => {\n await module.evaluate();\n cb(undefined, module.namespace);\n })\n .catch((e) => {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n });\n }\n handleScriptFetch(f, urlObj);\n })\n .catch((err) => {\n cb(err);\n });\n }\n : (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n cb(\n new Error('createScriptNode is disabled in non-Node.js environment'),\n );\n };\n\nexport const loadScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n return new Promise<void>((resolve, reject) => {\n createScriptNode(\n url,\n (error, scriptContext) => {\n if (error) {\n reject(error);\n } else {\n const remoteEntryKey =\n info?.attrs?.['globalName'] ||\n `__FEDERATION_${info?.attrs?.['name']}:custom__`;\n const entryExports = ((globalThis as any)[remoteEntryKey] =\n scriptContext);\n resolve(entryExports);\n }\n },\n info.attrs,\n info.loaderHook,\n );\n });\n }\n : (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n throw new Error(\n 'loadScriptNode is disabled in non-Node.js environment',\n );\n };\n\nconst esmModuleCache = new Map<string, any>();\n\ntype LoadModuleOptions = {\n vm: typeof import('vm') & {\n SourceTextModule: any;\n SyntheticModule: any;\n };\n fetch: typeof fetch;\n};\n\nconst isFetchableRemoteModuleUrl = (url: string): boolean =>\n url.startsWith('http:') || url.startsWith('https:');\n\nconst isBareModuleSpecifier = (specifier: string): boolean =>\n !specifier.startsWith('./') &&\n !specifier.startsWith('../') &&\n !specifier.startsWith('/') &&\n !specifier.includes(':');\n\nfunction encodeRemoteModulePath(url: string): string {\n const remoteUrl = new URL(url);\n const encodedProtocol = encodeURIComponent(remoteUrl.protocol.slice(0, -1));\n const encodedHost = encodeURIComponent(remoteUrl.host);\n const encodedPathname = remoteUrl.pathname\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n const encodedSearchHash = encodeURIComponent(\n `${remoteUrl.search}${remoteUrl.hash}`,\n );\n const encodedSuffix = encodedSearchHash ? `/${encodedSearchHash}` : '';\n\n return `/${encodedProtocol}/${encodedHost}${encodedPathname}${encodedSuffix}`;\n}\n\nfunction createImportMetaUrl(url: string, baseFileUrl: string): string {\n const baseUrl = baseFileUrl.endsWith('/') ? baseFileUrl : `${baseFileUrl}/`;\n return new URL(\n `__module_federation_remote__${encodeRemoteModulePath(url)}`,\n baseUrl,\n ).href;\n}\n\nasync function isNodeBuiltinSpecifier(specifier: string): Promise<boolean> {\n if (specifier.startsWith('node:')) {\n return true;\n }\n\n if (!isBareModuleSpecifier(specifier)) {\n return false;\n }\n\n const nodeModule =\n await importNodeModule<typeof import('node:module')>('node:module');\n\n return nodeModule.builtinModules.includes(specifier);\n}\n\nfunction getSyntheticModuleExports(moduleExports: any): Record<string, any> {\n const namespaceObject =\n moduleExports &&\n (typeof moduleExports === 'object' || typeof moduleExports === 'function')\n ? moduleExports\n : { default: moduleExports };\n const effectiveExports = { ...namespaceObject };\n\n if (!Object.prototype.hasOwnProperty.call(effectiveExports, 'default')) {\n effectiveExports.default = namespaceObject;\n }\n\n return effectiveExports;\n}\n\nasync function createSyntheticModuleFromExports(\n identifier: string,\n moduleExports: any,\n vm: LoadModuleOptions['vm'],\n) {\n if (typeof vm.SyntheticModule !== 'function') {\n throw new Error(\n 'vm.SyntheticModule is required to load Node.js built-in modules in ESM remote entries.',\n );\n }\n\n const effectiveExports = getSyntheticModuleExports(moduleExports);\n const exportNames = Object.keys(effectiveExports);\n const syntheticModule = new vm.SyntheticModule(\n exportNames,\n function setSyntheticModuleExports(this: {\n setExport: (name: string, value: any) => void;\n }) {\n for (const name of exportNames) {\n this.setExport(name, effectiveExports[name]);\n }\n },\n { identifier },\n );\n\n esmModuleCache.set(identifier, syntheticModule);\n await syntheticModule.link(async () => {\n throw new Error(\n `Node.js built-in module \"${identifier}\" should not request child modules.`,\n );\n });\n await syntheticModule.evaluate();\n\n return syntheticModule;\n}\n\nasync function loadNodeBuiltinModule(\n specifier: string,\n vm: LoadModuleOptions['vm'],\n) {\n const cacheKey = `node-builtin:${specifier}`;\n if (esmModuleCache.has(cacheKey)) {\n return esmModuleCache.get(cacheKey)!;\n }\n\n const moduleExports = await importNodeModule(specifier);\n return createSyntheticModuleFromExports(cacheKey, moduleExports, vm);\n}\n\nasync function loadResolvedModule(\n specifier: string,\n parentUrl: string,\n options: LoadModuleOptions,\n) {\n if (await isNodeBuiltinSpecifier(specifier)) {\n return loadNodeBuiltinModule(specifier, options.vm);\n }\n\n if (isBareModuleSpecifier(specifier)) {\n throw new Error(\n `Unsupported ESM module specifier \"${specifier}\". Only relative or absolute http(s) remote modules and Node.js built-in modules are supported.`,\n );\n }\n\n const resolvedUrl = new URL(specifier, parentUrl).href;\n if (!isFetchableRemoteModuleUrl(resolvedUrl)) {\n throw new Error(\n `Unsupported ESM module specifier \"${specifier}\" resolved to \"${resolvedUrl}\". Only http(s) remote modules and Node.js built-in modules are supported.`,\n );\n }\n\n return loadModule(resolvedUrl, options);\n}\n\nasync function evaluateDynamicModule(module: any) {\n if (module.status === 'linked') {\n await module.evaluate();\n }\n\n if (module.status === 'errored') {\n throw module.error;\n }\n\n return module;\n}\n\nasync function loadModule(url: string, options: LoadModuleOptions) {\n // Check cache to prevent infinite recursion in ESM loading\n if (esmModuleCache.has(url)) {\n return esmModuleCache.get(url)!;\n }\n\n const { fetch, vm } = options;\n if (!isFetchableRemoteModuleUrl(url)) {\n throw new Error(\n `Unsupported ESM module URL \"${url}\". Only http(s) remote modules and Node.js built-in modules are supported.`,\n );\n }\n\n const response = await fetch(url);\n const code = await response.text();\n const nodeUrl = await importNodeModule<typeof import('node:url')>('node:url');\n const cwdFileUrl = nodeUrl.pathToFileURL(process.cwd()).href;\n\n const sourceTextModule: any = new vm.SourceTextModule(code, {\n identifier: url,\n initializeImportMeta: (meta: { url: string }) => {\n meta.url = createImportMetaUrl(url, cwdFileUrl);\n },\n importModuleDynamically: async (specifier: string) => {\n return evaluateDynamicModule(\n await loadResolvedModule(specifier, url, options),\n );\n },\n });\n\n // Cache the module before linking to prevent cycles\n esmModuleCache.set(url, sourceTextModule);\n\n await sourceTextModule.link(async (specifier: string) => {\n return loadResolvedModule(specifier, url, options);\n });\n\n return sourceTextModule;\n}\n"],"m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AsB,WAAW,QAAQ,GAAG;AAGrD,KAAI,sBAAsB,UAAU,CAClC,OAAM,IAAI,MACR,qCAAqC,UAAU,iGAChD;CAGH,MAAM,cAAc,IAAI,IAAI,WAAW,UAAU,CAAC;AAClD,KAAI,CAAC,2BAA2B,YAAY,CAC1C,OAAM,IAAI,MACR,qCAAqC,UAAU,iBAAiB,YAAY,4EAC7E;AAGH,QAAO,WAAW,aAAa,QAAQ;;AAGzC,eAAe,sBAAsB,QAAa;AAChD,KAAI,OAAO,WAAW,SACpB,OAAM,OAAO,UAAU;AAGzB,KAAI,OAAO,WAAW,UACpB,OAAM,OAAO;AAGf,QAAO;;AAGT,eAAe,WAAW,KAAa,SAA4B;AAEjE,KAAI,eAAe,IAAI,IAAI,CACzB,QAAO,eAAe,IAAI,IAAI;CAGhC,MAAM,EAAE,OAAO,OAAO;AACtB,KAAI,CAAC,2BAA2B,IAAI,CAClC,OAAM,IAAI,MACR,+BAA+B,IAAI,4EACpC;CAIH,MAAM,OAAO,OADI,MAAM,MAAM,IAAI,EACL,MAAM;CAElC,MAAM,cADU,MAAM,iBAA4C,WAAW,EAClD,cAAc,QAAQ,KAAK,CAAC,CAAC;CAExD,MAAM,mBAAwB,IAAI,GAAG,iBAAiB,MAAM;EAC1D,YAAY;EACZ,uBAAuB,SAA0B;AAC/C,QAAK,MAAM,oBAAoB,KAAK,WAAW;;EAEjD,yBAAyB,OAAO,cAAsB;AACpD,UAAO,sBACL,MAAM,mBAAmB,WAAW,KAAK,QAAQ,CAClD;;EAEJ,CAAC;AAGF,gBAAe,IAAI,KAAK,iBAAiB;AAEzC,OAAM,iBAAiB,KAAK,OAAO,cAAsB;AACvD,SAAO,mBAAmB,WAAW,KAAK,QAAQ;GAClD;AAEF,QAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@module-federation/sdk",
3
- "version": "2.6.0",
3
+ "version": "2.7.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "A sdk for support module federation",
@@ -65,19 +65,11 @@
65
65
  "@jest/globals": "29.7.0",
66
66
  "webpack": "^5.0.0"
67
67
  },
68
- "peerDependencies": {
69
- "node-fetch": "^2.7.0 || ^3.3.2"
70
- },
71
- "peerDependenciesMeta": {
72
- "node-fetch": {
73
- "optional": true
74
- }
75
- },
76
68
  "scripts": {
77
69
  "build": "tsdown --config tsdown.config.ts",
78
70
  "lint": "ESLINT_USE_FLAT_CONFIG=false pnpm exec eslint --ignore-pattern node_modules \"**/*.ts\" \"package.json\"",
79
- "test": "pnpm exec jest --config jest.config.cjs --passWithNoTests",
80
- "test:ci": "pnpm exec jest --config jest.config.cjs --passWithNoTests --ci --coverage",
71
+ "test": "NODE_OPTIONS=--experimental-vm-modules pnpm exec jest --config jest.config.cjs --passWithNoTests",
72
+ "test:ci": "NODE_OPTIONS=--experimental-vm-modules pnpm exec jest --config jest.config.cjs --passWithNoTests --ci --coverage",
81
73
  "pre-release": "pnpm run test && pnpm run build"
82
74
  }
83
75
  }