{"version":3,"file":"load.cjs","names":["getRemoteEntryExports","RUNTIME_001","runtimeDescMap","RUNTIME_008","globalLoading","isBrowserEnvValue","DEFAULT_REMOTE_TYPE","DEFAULT_SCOPE"],"sources":["../../src/utils/load.ts"],"sourcesContent":["import {\n  loadScript,\n  loadScriptNode,\n  composeKeyWithSeparator,\n  isBrowserEnvValue,\n} from '@module-federation/sdk';\nimport { DEFAULT_REMOTE_TYPE, DEFAULT_SCOPE } from '../constant';\nimport { ModuleFederation } from '../core';\nimport { globalLoading, getRemoteEntryExports } from '../global';\nimport {\n  Remote,\n  RemoteEntryExports,\n  RemoteInfo,\n  ResourceLoadContext,\n} from '../type';\nimport { assert, error } from './logger';\nimport {\n  RUNTIME_001,\n  RUNTIME_008,\n  runtimeDescMap,\n} from '@module-federation/error-codes';\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\nconst importCallback = '.then(callbacks[0]).catch(callbacks[1])';\n\nasync function loadEsmEntry({\n  entry,\n  remoteEntryExports,\n}: {\n  entry: string;\n  remoteEntryExports: RemoteEntryExports | undefined;\n}): Promise<RemoteEntryExports> {\n  return new Promise<RemoteEntryExports>((resolve, reject) => {\n    try {\n      if (!remoteEntryExports) {\n        if (typeof FEDERATION_ALLOW_NEW_FUNCTION !== 'undefined') {\n          new Function('callbacks', `import(\"${entry}\")${importCallback}`)([\n            resolve,\n            reject,\n          ]);\n        } else {\n          import(/* webpackIgnore: true */ /* @vite-ignore */ entry)\n            .then(resolve)\n            .catch(reject);\n        }\n      } else {\n        resolve(remoteEntryExports);\n      }\n    } catch (e) {\n      const msg = e instanceof Error ? e.message : String(e);\n      error(`Failed to load ESM entry from \"${entry}\". ${msg}`);\n    }\n  });\n}\n\nasync function loadSystemJsEntry({\n  entry,\n  remoteEntryExports,\n}: {\n  entry: string;\n  remoteEntryExports: RemoteEntryExports | undefined;\n}): Promise<RemoteEntryExports> {\n  return new Promise<RemoteEntryExports>((resolve, reject) => {\n    try {\n      if (!remoteEntryExports) {\n        //@ts-ignore\n        if (typeof __system_context__ === 'undefined') {\n          //@ts-ignore\n          System.import(entry).then(resolve).catch(reject);\n        } else {\n          new Function(\n            'callbacks',\n            `System.import(\"${entry}\")${importCallback}`,\n          )([resolve, reject]);\n        }\n      } else {\n        resolve(remoteEntryExports);\n      }\n    } catch (e) {\n      const msg = e instanceof Error ? e.message : String(e);\n      error(`Failed to load SystemJS entry from \"${entry}\". ${msg}`);\n    }\n  });\n}\n\nfunction handleRemoteEntryLoaded(\n  name: string,\n  globalName: string,\n  entry: string,\n): RemoteEntryExports {\n  const { remoteEntryKey, entryExports } = getRemoteEntryExports(\n    name,\n    globalName,\n  );\n\n  if (!entryExports) {\n    error(RUNTIME_001, runtimeDescMap, {\n      remoteName: name,\n      remoteEntryUrl: entry,\n      remoteEntryKey,\n    });\n  }\n\n  return entryExports;\n}\n\nasync function loadEntryScript({\n  name,\n  globalName,\n  entry,\n  remoteInfo,\n  loaderHook,\n  getEntryUrl,\n  resourceContext,\n}: {\n  name: string;\n  globalName: string;\n  entry: string;\n  remoteInfo: RemoteInfo;\n  loaderHook: ModuleFederation['loaderHook'];\n  getEntryUrl?: (url: string) => string;\n  resourceContext?: ResourceLoadContext;\n}): Promise<RemoteEntryExports> {\n  const { entryExports: remoteEntryExports } = getRemoteEntryExports(\n    name,\n    globalName,\n  );\n\n  if (remoteEntryExports) {\n    return remoteEntryExports;\n  }\n\n  // if getEntryUrl is passed, use the getEntryUrl to get the entry url\n  const url = getEntryUrl ? getEntryUrl(entry) : entry;\n  return loadScript(url, {\n    attrs: {},\n    createScriptHook: (url, attrs) => {\n      const res = loaderHook.lifecycle.createScript.emit({\n        url,\n        attrs,\n        remoteInfo,\n        resourceContext: resourceContext\n          ? {\n              ...resourceContext,\n              url,\n            }\n          : undefined,\n      });\n\n      if (!res) return;\n\n      if (res instanceof HTMLScriptElement) {\n        return res;\n      }\n\n      if ('script' in res || 'timeout' in res) {\n        return res;\n      }\n\n      return;\n    },\n  }).then(\n    () => {\n      // loadScript resolved: script was fetched, executed without throwing, and\n      // did not trigger a ScriptExecutionError listener. Now verify the global was registered.\n      return handleRemoteEntryLoaded(name, globalName, entry);\n    },\n    (loadError: unknown) => {\n      // loadScript rejected — one of three causes, all with descriptive messages:\n      //   ScriptNetworkError  — URL unreachable, 404, CORS, etc.\n      //   ScriptExecutionError — script fetched OK but IIFE threw during execution\n      //   timeout             — script took too long to load\n      // Errors thrown inside handleRemoteEntryLoaded above are NOT caught here.\n      const originalMsg =\n        loadError instanceof Error ? loadError.message : String(loadError);\n      error(\n        RUNTIME_008,\n        runtimeDescMap,\n        {\n          remoteName: name,\n          resourceUrl: url,\n        },\n        originalMsg,\n      );\n    },\n  );\n}\nasync function loadEntryDom({\n  remoteInfo,\n  remoteEntryExports,\n  loaderHook,\n  getEntryUrl,\n  resourceContext,\n}: {\n  remoteInfo: RemoteInfo;\n  remoteEntryExports?: RemoteEntryExports;\n  loaderHook: ModuleFederation['loaderHook'];\n  getEntryUrl?: (url: string) => string;\n  resourceContext?: ResourceLoadContext;\n}) {\n  const { entry, entryGlobalName: globalName, name, type } = remoteInfo;\n  switch (type) {\n    case 'esm':\n    case 'module':\n      return loadEsmEntry({ entry, remoteEntryExports });\n    case 'system':\n      return loadSystemJsEntry({ entry, remoteEntryExports });\n    default:\n      return loadEntryScript({\n        entry,\n        globalName,\n        name,\n        remoteInfo,\n        loaderHook,\n        getEntryUrl,\n        resourceContext,\n      });\n  }\n}\n\nasync function loadEntryNode({\n  remoteInfo,\n  loaderHook,\n  resourceContext,\n}: {\n  remoteInfo: RemoteInfo;\n  loaderHook: ModuleFederation['loaderHook'];\n  resourceContext?: ResourceLoadContext;\n}) {\n  const { entry, entryGlobalName: globalName, name, type } = remoteInfo;\n  const { entryExports: remoteEntryExports } = getRemoteEntryExports(\n    name,\n    globalName,\n  );\n\n  if (remoteEntryExports) {\n    return remoteEntryExports;\n  }\n\n  return loadScriptNode(entry, {\n    attrs: { name, globalName, type },\n    loaderHook: {\n      createScriptHook: (url: string, attrs: Record<string, any> = {}) => {\n        const res = loaderHook.lifecycle.createScript.emit({\n          url,\n          attrs,\n          remoteInfo,\n          resourceContext: resourceContext\n            ? {\n                ...resourceContext,\n                url,\n              }\n            : undefined,\n        });\n\n        if (!res) return;\n\n        if ('url' in res) {\n          return res;\n        }\n\n        return;\n      },\n    },\n  })\n    .then(() => {\n      return handleRemoteEntryLoaded(name, globalName, entry);\n    })\n    .catch((e) => {\n      const msg = e instanceof Error ? e.message : String(e);\n      error(\n        `Failed to load Node.js entry for remote \"${name}\" from \"${entry}\". ${msg}`,\n      );\n    });\n}\n\nexport function getRemoteEntryUniqueKey(remoteInfo: RemoteInfo): string {\n  const { entry, name } = remoteInfo;\n  return composeKeyWithSeparator(name, entry);\n}\n\nexport async function getRemoteEntry(params: {\n  origin: ModuleFederation;\n  remoteInfo: RemoteInfo;\n  remoteEntryExports?: RemoteEntryExports | undefined;\n  getEntryUrl?: (url: string) => string;\n  _inErrorHandling?: boolean; // Add flag to prevent recursion\n  resourceContext?: ResourceLoadContext;\n}): Promise<RemoteEntryExports | false | void> {\n  const {\n    origin,\n    remoteEntryExports,\n    remoteInfo,\n    getEntryUrl,\n    resourceContext,\n    _inErrorHandling = false,\n  } = params;\n  const uniqueKey = getRemoteEntryUniqueKey(remoteInfo);\n  if (remoteEntryExports) {\n    return remoteEntryExports;\n  }\n\n  if (!globalLoading[uniqueKey]) {\n    const loadEntryHook = origin.remoteHandler.hooks.lifecycle.loadEntry;\n    const loaderHook = origin.loaderHook;\n\n    globalLoading[uniqueKey] = loadEntryHook\n      .emit({\n        origin,\n        loaderHook,\n        remoteInfo,\n        remoteEntryExports,\n      })\n      .then((res) => {\n        if (res) {\n          return res;\n        }\n        // Use ENV_TARGET if defined, otherwise fallback to isBrowserEnvValue\n        const isWebEnvironment =\n          typeof ENV_TARGET !== 'undefined'\n            ? ENV_TARGET === 'web'\n            : isBrowserEnvValue;\n\n        return isWebEnvironment\n          ? loadEntryDom({\n              remoteInfo,\n              remoteEntryExports,\n              loaderHook,\n              getEntryUrl,\n              resourceContext,\n            })\n          : loadEntryNode({ remoteInfo, loaderHook, resourceContext });\n      })\n      .then(async (res) => {\n        await origin.loaderHook.lifecycle.afterLoadEntry.emit({\n          origin,\n          remoteInfo,\n          remoteEntryExports: res,\n        });\n        return res;\n      })\n      .catch(async (err) => {\n        const uniqueKey = getRemoteEntryUniqueKey(remoteInfo);\n        // ScriptExecutionError means the script downloaded fine but its IIFE\n        // threw at runtime — retrying would reproduce the same error, so exclude it.\n        const isScriptExecutionError =\n          err instanceof Error && err.message.includes('ScriptExecutionError');\n        const isScriptLoadError =\n          err instanceof Error &&\n          err.message.includes(RUNTIME_008) &&\n          !isScriptExecutionError;\n\n        if (isScriptLoadError && !_inErrorHandling) {\n          const wrappedGetRemoteEntry = (\n            params: Parameters<typeof getRemoteEntry>[0],\n          ) => {\n            return getRemoteEntry({ ...params, _inErrorHandling: true });\n          };\n\n          const RemoteEntryExports =\n            await origin.loaderHook.lifecycle.loadEntryError.emit({\n              getRemoteEntry: wrappedGetRemoteEntry,\n              origin,\n              remoteInfo: remoteInfo,\n              remoteEntryExports,\n              globalLoading,\n              uniqueKey,\n            });\n\n          if (RemoteEntryExports) {\n            await origin.loaderHook.lifecycle.afterLoadEntry.emit({\n              origin,\n              remoteInfo,\n              remoteEntryExports: RemoteEntryExports,\n              recovered: true,\n            });\n            return RemoteEntryExports;\n          }\n        }\n        await origin.loaderHook.lifecycle.afterLoadEntry.emit({\n          origin,\n          remoteInfo,\n          error: err,\n        });\n        throw err;\n      });\n  }\n\n  return globalLoading[uniqueKey];\n}\n\nexport function getRemoteInfo(remote: Remote): RemoteInfo {\n  return {\n    ...remote,\n    entry: 'entry' in remote ? remote.entry : '',\n    type: remote.type || DEFAULT_REMOTE_TYPE,\n    entryGlobalName: remote.entryGlobalName || remote.name,\n    shareScope: remote.shareScope || DEFAULT_SCOPE,\n  };\n}\n"],"mappings":";;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