remote-components 0.0.9 → 0.0.11

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.
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/next/config/index.ts
@@ -25,8 +35,10 @@ __export(config_exports, {
25
35
  module.exports = __toCommonJS(config_exports);
26
36
  var import_node_path3 = require("path");
27
37
  var import_node_fs = require("fs");
38
+ var import_enhanced_resolve = __toESM(require("enhanced-resolve"), 1);
28
39
  var import_find_up = require("find-up");
29
40
  var import_config_schema = require("next/dist/server/config-schema.js");
41
+ var import_tsconfig_paths_webpack_plugin = __toESM(require("tsconfig-paths-webpack-plugin"), 1);
30
42
 
31
43
  // src/next/config/webpack/index.ts
32
44
  var import_node_path2 = require("path");
@@ -303,13 +315,36 @@ function withRemoteComponents(nextConfig, options) {
303
315
  "react/jsx-runtime": `'/react/jsx-runtime.js'`,
304
316
  "react-dom": `'/react-dom/index.js'`
305
317
  };
318
+ const resolve = import_enhanced_resolve.default.create.sync({
319
+ conditionNames: ["browser", "import", "module", "require"],
320
+ ...(0, import_node_fs.existsSync)((0, import_node_path3.join)(process.cwd(), "tsconfig.json")) ? {
321
+ extensions: [".js", ".jsx", ".ts", ".tsx"],
322
+ plugins: [
323
+ new import_tsconfig_paths_webpack_plugin.default({
324
+ configFile: (0, import_node_path3.join)(process.cwd(), "tsconfig.json")
325
+ })
326
+ ]
327
+ } : {}
328
+ });
306
329
  const sharedRemote = `'use client';
307
330
  module.exports = { shared: { ${Array.from(
308
331
  shared
309
332
  ).reduce((acc, curr) => {
333
+ let path;
334
+ try {
335
+ path = resolve(process.cwd(), curr);
336
+ if (path) {
337
+ path = (0, import_node_path3.relative)(process.cwd(), path).replace(
338
+ /^(?<relative>\.\.\/)+/,
339
+ ""
340
+ );
341
+ }
342
+ } catch {
343
+ }
310
344
  acc.push(
311
- `[${vendorShared[curr] ?? `require.resolve('${curr}')`}]: '${curr}',`
345
+ `[${vendorShared[curr] ?? (path ? `'${path}'` : `require.resolve('${curr}')`)}]: '${curr}',`
312
346
  );
347
+ acc.push(`['__remote_shared_module_${curr}']: () => import('${curr}'),`);
313
348
  return acc;
314
349
  }, []).join("\n")} } };
315
350
  `;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/next/config/index.ts","../../src/next/config/webpack/index.ts","../../src/next/config/webpack/plugins/remote-webpack-require-runtime-module.ts","../../src/next/config/webpack/plugins/remote-webpack-require.ts","../../src/next/config/webpack/plugins/module-id-embed.ts","../../src/next/config/webpack/plugins/module-id-embed-runtime-module.ts","../../src/next/config/webpack/plugins/conditional-exec.ts","../../src/next/config/webpack/plugins/patch-require.ts"],"sourcesContent":["import { basename, dirname, join, relative } from 'node:path';\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { findUpSync } from 'find-up';\nimport type { NextConfig } from 'next';\nimport { configSchema } from 'next/dist/server/config-schema.js';\nimport { transform as webpackTransform } from './webpack';\n\ninterface ZodSchema {\n safeParse: (data: unknown) => { success: boolean };\n}\n\ninterface WithRemoteComponentsOptions {\n /**\n * An array of package names that should be shared between the host and remote components.\n * This is useful for ensuring that both the host and remote components use the same version\n * of shared libraries.\n *\n * Essential packages are included by default: `react`, `react-dom`, `next/navigation`, `next/link`, `next/form`, `next/image`, and `next/script`.\n */\n shared?: string[];\n}\n\n/**\n * This function configures Next.js to support Remote Components.\n * You need to also use the `withMicrofrontends` function to extend your Next.js configuration.\n *\n * @param nextConfig - The Next.js configuration object.\n * @param options - Optional configuration for remote components.\n * @returns The modified Next.js configuration object with remote components support.\n *\n * @example\n *\n * ```js\n * import { withMicrofrontends } from '@vercel/microfrontends/next/config';\n * import { withRemoteComponents } from 'remote-components/next/config';\n *\n * const nextConfig = {\n * // your Next.js configuration\n * };\n *\n * export default withRemoteComponents(\n * withMicrofrontends(nextConfig),\n * {\n * shared: ['some-package', 'another-package'],\n * },\n * );\n * ```\n */\nexport function withRemoteComponents(\n nextConfig: NextConfig,\n options?: WithRemoteComponentsOptions,\n) {\n const virtualRemoteComponentSharedRemote = join(\n process.cwd(),\n nextConfig.distDir ?? '.next',\n 'remote-components/shared/remote.tsx',\n );\n const virtualRemoteComponentSharedHost = join(\n process.cwd(),\n nextConfig.distDir ?? '.next',\n 'remote-components/shared/host.tsx',\n );\n\n const shared = new Set([\n ...[\n 'react',\n 'react/jsx-dev-runtime',\n 'react/jsx-runtime',\n 'react-dom',\n 'react-dom/client',\n 'next/navigation',\n 'next/link',\n 'next/form',\n 'next/image',\n 'next/script',\n ],\n ...(options?.shared ?? []),\n ]);\n\n const vendorShared: Record<string, string> = {\n react: `'/react/index.js'`,\n 'react/jsx-dev-runtime': `'/react/jsx-dev-runtime.js'`,\n 'react/jsx-runtime': `'/react/jsx-runtime.js'`,\n 'react-dom': `'/react-dom/index.js'`,\n };\n\n const sharedRemote = `'use client';\\nmodule.exports = { shared: { ${Array.from(\n shared,\n )\n .reduce<string[]>((acc, curr) => {\n acc.push(\n `[${vendorShared[curr] ?? `require.resolve('${curr}')`}]: '${curr}',`,\n );\n return acc;\n }, [])\n .join('\\n')} } };\\n`;\n\n const sharedHost = `'use client';\\nmodule.exports = { shared: { ${Array.from(\n shared,\n )\n .reduce<string[]>((acc, curr) => {\n acc.push(`['${curr}']: () => import('${curr}'),`);\n return acc;\n }, [])\n .join('\\n')} } };\\n`;\n\n const emitSharedFiles = () => {\n mkdirSync(dirname(virtualRemoteComponentSharedRemote), {\n recursive: true,\n });\n\n writeFileSync(virtualRemoteComponentSharedRemote, sharedRemote, 'utf-8');\n writeFileSync(virtualRemoteComponentSharedHost, sharedHost, 'utf-8');\n };\n\n nextConfig.transpilePackages = [\n ...(nextConfig.transpilePackages ?? []),\n 'remote-components/next/remote',\n 'remote-components/next/host',\n '@remote-components/shared/remote',\n '@remote-components/shared/host',\n ];\n\n const alias = {\n '@remote-components/shared/remote': `./${relative(\n process.cwd(),\n virtualRemoteComponentSharedRemote,\n )}`,\n '@remote-components/shared/host': `./${relative(\n process.cwd(),\n virtualRemoteComponentSharedHost,\n )}`,\n };\n\n let projectId =\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID;\n\n if (!projectId) {\n try {\n const projectPath = findUpSync('.vercel/project.json', {\n cwd: process.cwd(),\n });\n if (projectPath) {\n projectId = (\n JSON.parse(readFileSync(projectPath, 'utf8')) as { projectId: string }\n ).projectId;\n }\n } catch {\n // fallback to env‑var above\n }\n }\n\n if (!projectId) {\n const packageJsonPath = findUpSync('package.json', {\n cwd: process.cwd(),\n });\n if (packageJsonPath) {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8')) as {\n name?: string;\n };\n projectId = packageJson.name || basename(process.cwd());\n } else {\n projectId = basename(process.cwd());\n }\n }\n\n process.env.REMOTE_COMPONENTS_PROJECT_ID = projectId;\n\n if (process.env.TURBOPACK) {\n if (\n !(configSchema as ZodSchema).safeParse({\n turbopack: {\n moduleIds: 'named',\n resolveAlias: {\n ...alias,\n },\n },\n compiler: {\n defineServer: {\n REMOTE_COMPONENTS_PROJECT_ID: projectId,\n },\n },\n }).success\n ) {\n // eslint-disable-next-line no-console\n console.error(\n 'You need to use a Next.js version which supports the `turbopack` and `compiler.defineServer` configuration for Turbopack support with Remote Components.',\n );\n process.exit(1);\n }\n nextConfig.turbopack = {\n ...nextConfig.turbopack,\n moduleIds: 'named',\n resolveAlias: {\n ...nextConfig.turbopack?.resolveAlias,\n ...alias,\n },\n };\n nextConfig.compiler = {\n ...nextConfig.compiler,\n defineServer: {\n ...nextConfig.compiler?.defineServer,\n 'process.env.REMOTE_COMPONENTS_PROJECT_ID': projectId,\n },\n };\n emitSharedFiles();\n return nextConfig;\n }\n\n // apply the webpack transform\n return webpackTransform(nextConfig, {\n app: { name: projectId },\n alias,\n emitSharedFiles,\n });\n}\n","import { join } from 'node:path';\nimport type { NextConfig } from 'next';\nimport type { WebpackOptionsNormalized } from 'webpack';\nimport { RemoteWebpackRequirePlugin } from './plugins/remote-webpack-require';\nimport { ModuleIdEmbedPlugin } from './plugins/module-id-embed';\nimport { ConditionalExecPlugin } from './plugins/conditional-exec';\nimport { PatchRequirePlugin } from './plugins/patch-require';\n\nexport function transform(\n nextConfig: NextConfig,\n {\n app,\n alias = {},\n emitSharedFiles = () => {\n // no-op by default\n },\n }: {\n app: { name: string };\n alias?: Record<string, string>;\n emitSharedFiles?: () => void;\n },\n) {\n const webpackConfig = nextConfig.webpack;\n\n nextConfig.webpack = (\n baseConfig: WebpackOptionsNormalized,\n webpackContext,\n ) => {\n // execute the client config first, otherwise their config may accidentally\n // overwrite our required config - leading to unexpected errors.\n const config = (\n typeof webpackConfig === 'function'\n ? (webpackConfig(baseConfig, webpackContext) ?? baseConfig)\n : baseConfig\n ) as WebpackOptionsNormalized;\n\n // remote component specific plugins\n config.plugins.push(\n new RemoteWebpackRequirePlugin(app.name),\n new ModuleIdEmbedPlugin(app.name),\n new ConditionalExecPlugin(),\n new PatchRequirePlugin(),\n );\n if (!webpackContext.isServer) {\n // change the chunk loading global to avoid conflicts with other remote components\n config.output.chunkLoadingGlobal = `__remote_chunk_loading_global_${app.name}__`;\n }\n\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve.alias,\n ...Object.fromEntries(\n Object.entries(alias).map(([key, value]) => [\n key,\n join(process.cwd(), value),\n ]),\n ),\n },\n };\n\n emitSharedFiles();\n return config;\n };\n\n return nextConfig;\n}\n","export function createRemoteWebpackRequireRuntimeModule(webpack: {\n RuntimeModule: new (name: string, stage?: number) => object;\n}) {\n return class RemoteWebpackRequireRuntimeModule extends webpack.RuntimeModule {\n appName: string;\n\n constructor(appName: string) {\n super('remote-webpack-require');\n this.appName = appName;\n }\n\n generate(): null | string {\n return `globalThis.__remote_webpack_require__ = globalThis.__remote_webpack_require__ || {}; globalThis.__remote_webpack_require__[\"${this.appName}\"] = __webpack_require__;`;\n }\n };\n}\n","import type { Compiler, RuntimeModule } from 'webpack';\nimport { createRemoteWebpackRequireRuntimeModule } from './remote-webpack-require-runtime-module';\n\nexport class RemoteWebpackRequirePlugin {\n appName: string;\n\n constructor(appName: string) {\n this.appName = appName;\n }\n\n apply(compiler: Compiler) {\n const RemoteWebpackRequireRuntimeModule =\n createRemoteWebpackRequireRuntimeModule(compiler.webpack);\n\n compiler.hooks.thisCompilation.tap(\n 'RemoteWebpackRequirePlugin',\n (compilation) => {\n compilation.hooks.runtimeRequirementInTree\n .for('__webpack_require__')\n .tap('RemoteWebpackRequirePlugin', (chunk) => {\n compilation.addRuntimeModule(\n chunk,\n new RemoteWebpackRequireRuntimeModule(\n this.appName,\n ) as unknown as RuntimeModule,\n );\n });\n },\n );\n }\n}\n","import { relative } from 'node:path';\nimport type { NormalModule, Compiler, RuntimeModule } from 'webpack';\nimport { createModuleIdEmbedRuntimeModule } from './module-id-embed-runtime-module';\n\nconst cwd = process.cwd();\n\nexport class ModuleIdEmbedPlugin {\n appName: string;\n\n constructor(appName: string) {\n this.appName = appName;\n }\n\n apply(compiler: Compiler) {\n const ModuleIdEmbedRuntimeModule = createModuleIdEmbedRuntimeModule(\n compiler.webpack,\n );\n\n compiler.hooks.thisCompilation.tap('ModuleIdEmbedPlugin', (compilation) => {\n const moduleMap = {} as Record<string, string | number>;\n\n compilation.hooks.runtimeRequirementInTree\n .for(compiler.webpack.RuntimeGlobals.require)\n .tap('ModuleIdEmbedPlugin', (chunk, set) => {\n for (const [key, entry] of compilation.entrypoints) {\n for (const entryChunk of entry.chunks) {\n if (key.includes('nextjs-pages-remote')) {\n for (const mod of compilation.chunkGraph.getChunkModulesIterable(\n entryChunk,\n )) {\n const id = compilation.chunkGraph.getModuleId(mod);\n const normalModule = mod as NormalModule;\n if (id && (normalModule.resource || normalModule.request)) {\n moduleMap[\n relative(\n cwd,\n normalModule.resource || normalModule.request,\n )\n ] = id;\n }\n }\n }\n }\n }\n for (const mod of compilation.modules) {\n const id = compilation.chunkGraph.getModuleId(mod);\n if (id && mod.layer?.endsWith('browser')) {\n const normalModule = mod as NormalModule;\n if (normalModule.resource || normalModule.request) {\n moduleMap[\n relative(cwd, normalModule.resource || normalModule.request)\n ] = id;\n }\n }\n }\n\n if (Object.keys(moduleMap).length > 0) {\n compilation.addRuntimeModule(\n chunk,\n new ModuleIdEmbedRuntimeModule(\n this.appName,\n moduleMap,\n ) as unknown as RuntimeModule,\n );\n\n set.add(compiler.webpack.RuntimeGlobals.require);\n }\n });\n });\n }\n}\n","export function createModuleIdEmbedRuntimeModule(webpack: {\n RuntimeModule: new (name: string, stage?: number) => object;\n}) {\n return class ModuleIdEmbedRuntimeModule extends webpack.RuntimeModule {\n appName: string;\n moduleMap: Record<string | number, unknown>;\n\n constructor(appName: string, moduleMap: Record<string | number, unknown>) {\n super('remote-webpack-module-id-embed');\n this.appName = appName;\n this.moduleMap = moduleMap;\n }\n\n generate(): null | string {\n return `globalThis.__remote_webpack_module_map__ = globalThis.__remote_webpack_module_map__ || {}; globalThis.__remote_webpack_module_map__[\"${this.appName}\"] = ${JSON.stringify(this.moduleMap)};`;\n }\n };\n}\n","import type { Compiler } from 'webpack';\n\nexport class ConditionalExecPlugin {\n apply(compiler: Compiler) {\n const { Compilation, sources } = compiler.webpack;\n\n compiler.hooks.thisCompilation.tap(\n 'ConditionalExecPlugin',\n (compilation) => {\n compilation.hooks.processAssets.tap(\n {\n name: 'ConditionalExecPlugin',\n stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,\n },\n (assets) => {\n for (const [name, source] of Object.entries(assets)) {\n if (name.endsWith('.js')) {\n const patchedSource = source\n .source()\n .toString()\n .replace(\n `var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))`,\n `var __webpack_exec__ = (moduleId) => { if (globalThis.__DISABLE_WEBPACK_EXEC__) return; return __webpack_require__(__webpack_require__.s = moduleId); }`,\n );\n compilation.updateAsset(\n name,\n new sources.RawSource(patchedSource),\n );\n }\n }\n },\n );\n },\n );\n }\n}\n","import type { Compiler } from 'webpack';\n\n// This plugin patches the webpack require function to support loading remote components in Next.js\nexport class PatchRequirePlugin {\n apply(compiler: Compiler) {\n const { sources } = compiler.webpack;\n\n compiler.hooks.thisCompilation.tap('PatchRequirePlugin', (compilation) => {\n compilation.mainTemplate.hooks.requireExtensions.tap(\n 'PatchRequirePlugin',\n (source) => {\n return new sources.ConcatSource(\n source,\n `const __webpack_require_orig__ = __webpack_require__;\nconst REMOTE_RE = /\\\\[(?<bundle>[a-zA-Z0-9-_]+)\\\\] (?<id>.*)/;\n__webpack_require__ = function __remote_webpack_require__(remoteId) {\n const match = REMOTE_RE.exec(remoteId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_orig__(remoteId);\n }\n if (typeof self.__remote_webpack_require__?.[bundle] !== 'function') {\n throw new Error(\\`Remote component loading error: \"\\${bundle}\"\\`);\n }\n return self.__remote_webpack_require__[bundle](self.__remote_webpack_require__[bundle].type === 'turbopack' ? remoteId : id);\n};\nObject.assign(__webpack_require__, __webpack_require_orig__);\nconst __webpack_require_l__ = __webpack_require__.l;\n__webpack_require__.l = function __remote_webpack_require_l__(url, done, key, chunkId) {\n const match = REMOTE_RE.exec(chunkId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_l__(url, done, key, chunkId);\n }\n return done();\n};\nconst __webpack_require_o__ = __webpack_require__.o;\n__webpack_require__.o = function __remote_webpack_require_o__(installedChunks, chunkId) {\n const match = REMOTE_RE.exec(chunkId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_o__(installedChunks, chunkId);\n }\n return installedChunks[chunkId] = 0;\n};\nconst __webpack_require_e__ = __webpack_require__.e;\n__webpack_require__.e = function __remote_webpack_require_e__(chunkId) {\n const match = REMOTE_RE.exec(chunkId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_e__(chunkId);\n }\n return Promise.resolve([]);\n};`,\n )\n .source()\n .toString();\n },\n );\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,oBAAkD;AAClD,qBAAuD;AACvD,qBAA2B;AAE3B,2BAA6B;;;ACJ7B,IAAAC,oBAAqB;;;ACAd,SAAS,wCAAwC,SAErD;AACD,SAAO,MAAM,0CAA0C,QAAQ,cAAc;AAAA,IAG3E,YAAY,SAAiB;AAC3B,YAAM,wBAAwB;AAC9B,WAAK,UAAU;AAAA,IACjB;AAAA,IAEA,WAA0B;AACxB,aAAO,+HAA+H,KAAK;AAAA,IAC7I;AAAA,EACF;AACF;;;ACZO,IAAM,6BAAN,MAAiC;AAAA,EAGtC,YAAY,SAAiB;AAC3B,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,MAAM,UAAoB;AACxB,UAA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AA,QACT,WAAW;AAAA,QACX,cAAc;AAAA,UACZ,GAAG;AAAA,QACL;AAAA,MACF;AAAA,MACA,UAAU;AAAA,QACR,cAAc;AAAA,UACZ,8BAA8B;AAAA,QAChC;AAAA,MACF;AAAA,IACF,CAAC,EAAE,SACH;AAEA,cAAQ;AAAA,QACN;AAAA,MACF;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,eAAW,YAAY;AAAA,MACrB,GAAG,WAAW;AAAA,MACd,WAAW;AAAA,MACX,cAAc;AAAA,QACZ,GAAG,WAAW,WAAW;AAAA,QACzB,GAAG;AAAA,MACL;AAAA,IACF;AACA,eAAW,WAAW;AAAA,MACpB,GAAG,WAAW;AAAA,MACd,cAAc;AAAA,QACZ,GAAG,WAAW,UAAU;AAAA,QACxB,4CAA4C;AAAA,MAC9C;AAAA,IACF;AACA,oBAAgB;AAChB,WAAO;AAAA,EACT;AAGA,SAAO,UAAiB,YAAY;AAAA,IAClC,KAAK,EAAE,MAAM,UAAU;AAAA,IACvB;AAAA,IACA;AAAA,EACF,CAAC;AACH;","names":["import_node_path","import_node_path"]}
1
+ {"version":3,"sources":["../../src/next/config/index.ts","../../src/next/config/webpack/index.ts","../../src/next/config/webpack/plugins/remote-webpack-require-runtime-module.ts","../../src/next/config/webpack/plugins/remote-webpack-require.ts","../../src/next/config/webpack/plugins/module-id-embed.ts","../../src/next/config/webpack/plugins/module-id-embed-runtime-module.ts","../../src/next/config/webpack/plugins/conditional-exec.ts","../../src/next/config/webpack/plugins/patch-require.ts"],"sourcesContent":["import { basename, dirname, join, relative } from 'node:path';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport enhancedResolve from 'enhanced-resolve';\nimport { findUpSync } from 'find-up';\nimport type { NextConfig } from 'next';\nimport { configSchema } from 'next/dist/server/config-schema.js';\nimport TsConfigPathsWebpackPlugin from 'tsconfig-paths-webpack-plugin';\nimport { transform as webpackTransform } from './webpack';\n\ninterface ZodSchema {\n safeParse: (data: unknown) => { success: boolean };\n}\n\ninterface WithRemoteComponentsOptions {\n /**\n * An array of package names that should be shared between the host and remote components.\n * This is useful for ensuring that both the host and remote components use the same version\n * of shared libraries.\n *\n * Essential packages are included by default: `react`, `react-dom`, `next/navigation`, `next/link`, `next/form`, `next/image`, and `next/script`.\n */\n shared?: string[];\n}\n\n/**\n * This function configures Next.js to support Remote Components.\n * You need to also use the `withMicrofrontends` function to extend your Next.js configuration.\n *\n * @param nextConfig - The Next.js configuration object.\n * @param options - Optional configuration for remote components.\n * @returns The modified Next.js configuration object with remote components support.\n *\n * @example\n *\n * ```js\n * import { withMicrofrontends } from '@vercel/microfrontends/next/config';\n * import { withRemoteComponents } from 'remote-components/next/config';\n *\n * const nextConfig = {\n * // your Next.js configuration\n * };\n *\n * export default withRemoteComponents(\n * withMicrofrontends(nextConfig),\n * {\n * shared: ['some-package', 'another-package'],\n * },\n * );\n * ```\n */\nexport function withRemoteComponents(\n nextConfig: NextConfig,\n options?: WithRemoteComponentsOptions,\n) {\n const virtualRemoteComponentSharedRemote = join(\n process.cwd(),\n nextConfig.distDir ?? '.next',\n 'remote-components/shared/remote.tsx',\n );\n const virtualRemoteComponentSharedHost = join(\n process.cwd(),\n nextConfig.distDir ?? '.next',\n 'remote-components/shared/host.tsx',\n );\n\n const shared = new Set([\n ...[\n 'react',\n 'react/jsx-dev-runtime',\n 'react/jsx-runtime',\n 'react-dom',\n 'react-dom/client',\n 'next/navigation',\n 'next/link',\n 'next/form',\n 'next/image',\n 'next/script',\n ],\n ...(options?.shared ?? []),\n ]);\n\n const vendorShared: Record<string, string> = {\n react: `'/react/index.js'`,\n 'react/jsx-dev-runtime': `'/react/jsx-dev-runtime.js'`,\n 'react/jsx-runtime': `'/react/jsx-runtime.js'`,\n 'react-dom': `'/react-dom/index.js'`,\n };\n\n // resolve using enhanced-resolve\n // named import does not work with enhanced-resolve when using cjs\n // eslint-disable-next-line import/no-named-as-default-member\n const resolve = enhancedResolve.create.sync({\n conditionNames: ['browser', 'import', 'module', 'require'],\n ...(existsSync(join(process.cwd(), 'tsconfig.json'))\n ? {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n plugins: [\n new TsConfigPathsWebpackPlugin({\n configFile: join(process.cwd(), 'tsconfig.json'),\n }) as unknown as enhancedResolve.Plugin,\n ],\n }\n : {}),\n });\n const sharedRemote = `'use client';\\nmodule.exports = { shared: { ${Array.from(\n shared,\n )\n .reduce<string[]>((acc, curr) => {\n let path;\n try {\n path = resolve(process.cwd(), curr);\n if (path) {\n path = relative(process.cwd(), path).replace(\n /^(?<relative>\\.\\.\\/)+/,\n '',\n );\n }\n } catch {\n // noop\n // if module resolution using enhanced-resolve fails, fallback to require.resolve called in the shared/remote file\n }\n acc.push(\n `[${vendorShared[curr] ?? (path ? `'${path}'` : `require.resolve('${curr}')`)}]: '${curr}',`,\n );\n acc.push(`['__remote_shared_module_${curr}']: () => import('${curr}'),`);\n return acc;\n }, [])\n .join('\\n')} } };\\n`;\n\n const sharedHost = `'use client';\\nmodule.exports = { shared: { ${Array.from(\n shared,\n )\n .reduce<string[]>((acc, curr) => {\n acc.push(`['${curr}']: () => import('${curr}'),`);\n return acc;\n }, [])\n .join('\\n')} } };\\n`;\n\n const emitSharedFiles = () => {\n mkdirSync(dirname(virtualRemoteComponentSharedRemote), {\n recursive: true,\n });\n\n writeFileSync(virtualRemoteComponentSharedRemote, sharedRemote, 'utf-8');\n writeFileSync(virtualRemoteComponentSharedHost, sharedHost, 'utf-8');\n };\n\n nextConfig.transpilePackages = [\n ...(nextConfig.transpilePackages ?? []),\n 'remote-components/next/remote',\n 'remote-components/next/host',\n '@remote-components/shared/remote',\n '@remote-components/shared/host',\n ];\n\n const alias = {\n '@remote-components/shared/remote': `./${relative(\n process.cwd(),\n virtualRemoteComponentSharedRemote,\n )}`,\n '@remote-components/shared/host': `./${relative(\n process.cwd(),\n virtualRemoteComponentSharedHost,\n )}`,\n };\n\n let projectId =\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID;\n\n if (!projectId) {\n try {\n const projectPath = findUpSync('.vercel/project.json', {\n cwd: process.cwd(),\n });\n if (projectPath) {\n projectId = (\n JSON.parse(readFileSync(projectPath, 'utf8')) as { projectId: string }\n ).projectId;\n }\n } catch {\n // fallback to env‑var above\n }\n }\n\n if (!projectId) {\n const packageJsonPath = findUpSync('package.json', {\n cwd: process.cwd(),\n });\n if (packageJsonPath) {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8')) as {\n name?: string;\n };\n projectId = packageJson.name || basename(process.cwd());\n } else {\n projectId = basename(process.cwd());\n }\n }\n\n process.env.REMOTE_COMPONENTS_PROJECT_ID = projectId;\n\n if (process.env.TURBOPACK) {\n if (\n !(configSchema as ZodSchema).safeParse({\n turbopack: {\n moduleIds: 'named',\n resolveAlias: {\n ...alias,\n },\n },\n compiler: {\n defineServer: {\n REMOTE_COMPONENTS_PROJECT_ID: projectId,\n },\n },\n }).success\n ) {\n // eslint-disable-next-line no-console\n console.error(\n 'You need to use a Next.js version which supports the `turbopack` and `compiler.defineServer` configuration for Turbopack support with Remote Components.',\n );\n process.exit(1);\n }\n nextConfig.turbopack = {\n ...nextConfig.turbopack,\n moduleIds: 'named',\n resolveAlias: {\n ...nextConfig.turbopack?.resolveAlias,\n ...alias,\n },\n };\n nextConfig.compiler = {\n ...nextConfig.compiler,\n defineServer: {\n ...nextConfig.compiler?.defineServer,\n 'process.env.REMOTE_COMPONENTS_PROJECT_ID': projectId,\n },\n };\n emitSharedFiles();\n return nextConfig;\n }\n\n // apply the webpack transform\n return webpackTransform(nextConfig, {\n app: { name: projectId },\n alias,\n emitSharedFiles,\n });\n}\n","import { join } from 'node:path';\nimport type { NextConfig } from 'next';\nimport type { WebpackOptionsNormalized } from 'webpack';\nimport { RemoteWebpackRequirePlugin } from './plugins/remote-webpack-require';\nimport { ModuleIdEmbedPlugin } from './plugins/module-id-embed';\nimport { ConditionalExecPlugin } from './plugins/conditional-exec';\nimport { PatchRequirePlugin } from './plugins/patch-require';\n\nexport function transform(\n nextConfig: NextConfig,\n {\n app,\n alias = {},\n emitSharedFiles = () => {\n // no-op by default\n },\n }: {\n app: { name: string };\n alias?: Record<string, string>;\n emitSharedFiles?: () => void;\n },\n) {\n const webpackConfig = nextConfig.webpack;\n\n nextConfig.webpack = (\n baseConfig: WebpackOptionsNormalized,\n webpackContext,\n ) => {\n // execute the client config first, otherwise their config may accidentally\n // overwrite our required config - leading to unexpected errors.\n const config = (\n typeof webpackConfig === 'function'\n ? (webpackConfig(baseConfig, webpackContext) ?? baseConfig)\n : baseConfig\n ) as WebpackOptionsNormalized;\n\n // remote component specific plugins\n config.plugins.push(\n new RemoteWebpackRequirePlugin(app.name),\n new ModuleIdEmbedPlugin(app.name),\n new ConditionalExecPlugin(),\n new PatchRequirePlugin(),\n );\n if (!webpackContext.isServer) {\n // change the chunk loading global to avoid conflicts with other remote components\n config.output.chunkLoadingGlobal = `__remote_chunk_loading_global_${app.name}__`;\n }\n\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve.alias,\n ...Object.fromEntries(\n Object.entries(alias).map(([key, value]) => [\n key,\n join(process.cwd(), value),\n ]),\n ),\n },\n };\n\n emitSharedFiles();\n return config;\n };\n\n return nextConfig;\n}\n","export function createRemoteWebpackRequireRuntimeModule(webpack: {\n RuntimeModule: new (name: string, stage?: number) => object;\n}) {\n return class RemoteWebpackRequireRuntimeModule extends webpack.RuntimeModule {\n appName: string;\n\n constructor(appName: string) {\n super('remote-webpack-require');\n this.appName = appName;\n }\n\n generate(): null | string {\n return `globalThis.__remote_webpack_require__ = globalThis.__remote_webpack_require__ || {}; globalThis.__remote_webpack_require__[\"${this.appName}\"] = __webpack_require__;`;\n }\n };\n}\n","import type { Compiler, RuntimeModule } from 'webpack';\nimport { createRemoteWebpackRequireRuntimeModule } from './remote-webpack-require-runtime-module';\n\nexport class RemoteWebpackRequirePlugin {\n appName: string;\n\n constructor(appName: string) {\n this.appName = appName;\n }\n\n apply(compiler: Compiler) {\n const RemoteWebpackRequireRuntimeModule =\n createRemoteWebpackRequireRuntimeModule(compiler.webpack);\n\n compiler.hooks.thisCompilation.tap(\n 'RemoteWebpackRequirePlugin',\n (compilation) => {\n compilation.hooks.runtimeRequirementInTree\n .for('__webpack_require__')\n .tap('RemoteWebpackRequirePlugin', (chunk) => {\n compilation.addRuntimeModule(\n chunk,\n new RemoteWebpackRequireRuntimeModule(\n this.appName,\n ) as unknown as RuntimeModule,\n );\n });\n },\n );\n }\n}\n","import { relative } from 'node:path';\nimport type { NormalModule, Compiler, RuntimeModule } from 'webpack';\nimport { createModuleIdEmbedRuntimeModule } from './module-id-embed-runtime-module';\n\nconst cwd = process.cwd();\n\nexport class ModuleIdEmbedPlugin {\n appName: string;\n\n constructor(appName: string) {\n this.appName = appName;\n }\n\n apply(compiler: Compiler) {\n const ModuleIdEmbedRuntimeModule = createModuleIdEmbedRuntimeModule(\n compiler.webpack,\n );\n\n compiler.hooks.thisCompilation.tap('ModuleIdEmbedPlugin', (compilation) => {\n const moduleMap = {} as Record<string, string | number>;\n\n compilation.hooks.runtimeRequirementInTree\n .for(compiler.webpack.RuntimeGlobals.require)\n .tap('ModuleIdEmbedPlugin', (chunk, set) => {\n for (const [key, entry] of compilation.entrypoints) {\n for (const entryChunk of entry.chunks) {\n if (key.includes('nextjs-pages-remote')) {\n for (const mod of compilation.chunkGraph.getChunkModulesIterable(\n entryChunk,\n )) {\n const id = compilation.chunkGraph.getModuleId(mod);\n const normalModule = mod as NormalModule;\n if (id && (normalModule.resource || normalModule.request)) {\n moduleMap[\n relative(\n cwd,\n normalModule.resource || normalModule.request,\n )\n ] = id;\n }\n }\n }\n }\n }\n for (const mod of compilation.modules) {\n const id = compilation.chunkGraph.getModuleId(mod);\n if (id && mod.layer?.endsWith('browser')) {\n const normalModule = mod as NormalModule;\n if (normalModule.resource || normalModule.request) {\n moduleMap[\n relative(cwd, normalModule.resource || normalModule.request)\n ] = id;\n }\n }\n }\n\n if (Object.keys(moduleMap).length > 0) {\n compilation.addRuntimeModule(\n chunk,\n new ModuleIdEmbedRuntimeModule(\n this.appName,\n moduleMap,\n ) as unknown as RuntimeModule,\n );\n\n set.add(compiler.webpack.RuntimeGlobals.require);\n }\n });\n });\n }\n}\n","export function createModuleIdEmbedRuntimeModule(webpack: {\n RuntimeModule: new (name: string, stage?: number) => object;\n}) {\n return class ModuleIdEmbedRuntimeModule extends webpack.RuntimeModule {\n appName: string;\n moduleMap: Record<string | number, unknown>;\n\n constructor(appName: string, moduleMap: Record<string | number, unknown>) {\n super('remote-webpack-module-id-embed');\n this.appName = appName;\n this.moduleMap = moduleMap;\n }\n\n generate(): null | string {\n return `globalThis.__remote_webpack_module_map__ = globalThis.__remote_webpack_module_map__ || {}; globalThis.__remote_webpack_module_map__[\"${this.appName}\"] = ${JSON.stringify(this.moduleMap)};`;\n }\n };\n}\n","import type { Compiler } from 'webpack';\n\nexport class ConditionalExecPlugin {\n apply(compiler: Compiler) {\n const { Compilation, sources } = compiler.webpack;\n\n compiler.hooks.thisCompilation.tap(\n 'ConditionalExecPlugin',\n (compilation) => {\n compilation.hooks.processAssets.tap(\n {\n name: 'ConditionalExecPlugin',\n stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,\n },\n (assets) => {\n for (const [name, source] of Object.entries(assets)) {\n if (name.endsWith('.js')) {\n const patchedSource = source\n .source()\n .toString()\n .replace(\n `var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))`,\n `var __webpack_exec__ = (moduleId) => { if (globalThis.__DISABLE_WEBPACK_EXEC__) return; return __webpack_require__(__webpack_require__.s = moduleId); }`,\n );\n compilation.updateAsset(\n name,\n new sources.RawSource(patchedSource),\n );\n }\n }\n },\n );\n },\n );\n }\n}\n","import type { Compiler } from 'webpack';\n\n// This plugin patches the webpack require function to support loading remote components in Next.js\nexport class PatchRequirePlugin {\n apply(compiler: Compiler) {\n const { sources } = compiler.webpack;\n\n compiler.hooks.thisCompilation.tap('PatchRequirePlugin', (compilation) => {\n compilation.mainTemplate.hooks.requireExtensions.tap(\n 'PatchRequirePlugin',\n (source) => {\n return new sources.ConcatSource(\n source,\n `const __webpack_require_orig__ = __webpack_require__;\nconst REMOTE_RE = /\\\\[(?<bundle>[a-zA-Z0-9-_]+)\\\\] (?<id>.*)/;\n__webpack_require__ = function __remote_webpack_require__(remoteId) {\n const match = REMOTE_RE.exec(remoteId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_orig__(remoteId);\n }\n if (typeof self.__remote_webpack_require__?.[bundle] !== 'function') {\n throw new Error(\\`Remote component loading error: \"\\${bundle}\"\\`);\n }\n return self.__remote_webpack_require__[bundle](self.__remote_webpack_require__[bundle].type === 'turbopack' ? remoteId : id);\n};\nObject.assign(__webpack_require__, __webpack_require_orig__);\nconst __webpack_require_l__ = __webpack_require__.l;\n__webpack_require__.l = function __remote_webpack_require_l__(url, done, key, chunkId) {\n const match = REMOTE_RE.exec(chunkId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_l__(url, done, key, chunkId);\n }\n return done();\n};\nconst __webpack_require_o__ = __webpack_require__.o;\n__webpack_require__.o = function __remote_webpack_require_o__(installedChunks, chunkId) {\n const match = REMOTE_RE.exec(chunkId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_o__(installedChunks, chunkId);\n }\n return installedChunks[chunkId] = 0;\n};\nconst __webpack_require_e__ = __webpack_require__.e;\n__webpack_require__.e = function __remote_webpack_require_e__(chunkId) {\n const match = REMOTE_RE.exec(chunkId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_e__(chunkId);\n }\n return Promise.resolve([]);\n};`,\n )\n .source()\n .toString();\n },\n );\n });\n }\n}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A,UACZ,GAAG;AAAA,QACL;AAAA,MACF;AAAA,MACA,UAAU;AAAA,QACR,cAAc;AAAA,UACZ,8BAA8B;AAAA,QAChC;AAAA,MACF;AAAA,IACF,CAAC,EAAE,SACH;AAEA,cAAQ;AAAA,QACN;AAAA,MACF;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,eAAW,YAAY;AAAA,MACrB,GAAG,WAAW;AAAA,MACd,WAAW;AAAA,MACX,cAAc;AAAA,QACZ,GAAG,WAAW,WAAW;AAAA,QACzB,GAAG;AAAA,MACL;AAAA,IACF;AACA,eAAW,WAAW;AAAA,MACpB,GAAG,WAAW;AAAA,MACd,cAAc;AAAA,QACZ,GAAG,WAAW,UAAU;AAAA,QACxB,4CAA4C;AAAA,MAC9C;AAAA,IACF;AACA,oBAAgB;AAChB,WAAO;AAAA,EACT;AAGA,SAAO,UAAiB,YAAY;AAAA,IAClC,KAAK,EAAE,MAAM,UAAU;AAAA,IACvB;AAAA,IACA;AAAA,EACF,CAAC;AACH;","names":["import_node_path","import_node_path","enhancedResolve","TsConfigPathsWebpackPlugin"]}
@@ -1,8 +1,10 @@
1
1
  // src/next/config/index.ts
2
2
  import { basename, dirname, join as join2, relative as relative2 } from "node:path";
3
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import enhancedResolve from "enhanced-resolve";
4
5
  import { findUpSync } from "find-up";
5
6
  import { configSchema } from "next/dist/server/config-schema.js";
7
+ import TsConfigPathsWebpackPlugin from "tsconfig-paths-webpack-plugin";
6
8
 
7
9
  // src/next/config/webpack/index.ts
8
10
  import { join } from "node:path";
@@ -279,13 +281,36 @@ function withRemoteComponents(nextConfig, options) {
279
281
  "react/jsx-runtime": `'/react/jsx-runtime.js'`,
280
282
  "react-dom": `'/react-dom/index.js'`
281
283
  };
284
+ const resolve = enhancedResolve.create.sync({
285
+ conditionNames: ["browser", "import", "module", "require"],
286
+ ...existsSync(join2(process.cwd(), "tsconfig.json")) ? {
287
+ extensions: [".js", ".jsx", ".ts", ".tsx"],
288
+ plugins: [
289
+ new TsConfigPathsWebpackPlugin({
290
+ configFile: join2(process.cwd(), "tsconfig.json")
291
+ })
292
+ ]
293
+ } : {}
294
+ });
282
295
  const sharedRemote = `'use client';
283
296
  module.exports = { shared: { ${Array.from(
284
297
  shared
285
298
  ).reduce((acc, curr) => {
299
+ let path;
300
+ try {
301
+ path = resolve(process.cwd(), curr);
302
+ if (path) {
303
+ path = relative2(process.cwd(), path).replace(
304
+ /^(?<relative>\.\.\/)+/,
305
+ ""
306
+ );
307
+ }
308
+ } catch {
309
+ }
286
310
  acc.push(
287
- `[${vendorShared[curr] ?? `require.resolve('${curr}')`}]: '${curr}',`
311
+ `[${vendorShared[curr] ?? (path ? `'${path}'` : `require.resolve('${curr}')`)}]: '${curr}',`
288
312
  );
313
+ acc.push(`['__remote_shared_module_${curr}']: () => import('${curr}'),`);
289
314
  return acc;
290
315
  }, []).join("\n")} } };
291
316
  `;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/next/config/index.ts","../../src/next/config/webpack/index.ts","../../src/next/config/webpack/plugins/remote-webpack-require-runtime-module.ts","../../src/next/config/webpack/plugins/remote-webpack-require.ts","../../src/next/config/webpack/plugins/module-id-embed.ts","../../src/next/config/webpack/plugins/module-id-embed-runtime-module.ts","../../src/next/config/webpack/plugins/conditional-exec.ts","../../src/next/config/webpack/plugins/patch-require.ts"],"sourcesContent":["import { basename, dirname, join, relative } from 'node:path';\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { findUpSync } from 'find-up';\nimport type { NextConfig } from 'next';\nimport { configSchema } from 'next/dist/server/config-schema.js';\nimport { transform as webpackTransform } from './webpack';\n\ninterface ZodSchema {\n safeParse: (data: unknown) => { success: boolean };\n}\n\ninterface WithRemoteComponentsOptions {\n /**\n * An array of package names that should be shared between the host and remote components.\n * This is useful for ensuring that both the host and remote components use the same version\n * of shared libraries.\n *\n * Essential packages are included by default: `react`, `react-dom`, `next/navigation`, `next/link`, `next/form`, `next/image`, and `next/script`.\n */\n shared?: string[];\n}\n\n/**\n * This function configures Next.js to support Remote Components.\n * You need to also use the `withMicrofrontends` function to extend your Next.js configuration.\n *\n * @param nextConfig - The Next.js configuration object.\n * @param options - Optional configuration for remote components.\n * @returns The modified Next.js configuration object with remote components support.\n *\n * @example\n *\n * ```js\n * import { withMicrofrontends } from '@vercel/microfrontends/next/config';\n * import { withRemoteComponents } from 'remote-components/next/config';\n *\n * const nextConfig = {\n * // your Next.js configuration\n * };\n *\n * export default withRemoteComponents(\n * withMicrofrontends(nextConfig),\n * {\n * shared: ['some-package', 'another-package'],\n * },\n * );\n * ```\n */\nexport function withRemoteComponents(\n nextConfig: NextConfig,\n options?: WithRemoteComponentsOptions,\n) {\n const virtualRemoteComponentSharedRemote = join(\n process.cwd(),\n nextConfig.distDir ?? '.next',\n 'remote-components/shared/remote.tsx',\n );\n const virtualRemoteComponentSharedHost = join(\n process.cwd(),\n nextConfig.distDir ?? '.next',\n 'remote-components/shared/host.tsx',\n );\n\n const shared = new Set([\n ...[\n 'react',\n 'react/jsx-dev-runtime',\n 'react/jsx-runtime',\n 'react-dom',\n 'react-dom/client',\n 'next/navigation',\n 'next/link',\n 'next/form',\n 'next/image',\n 'next/script',\n ],\n ...(options?.shared ?? []),\n ]);\n\n const vendorShared: Record<string, string> = {\n react: `'/react/index.js'`,\n 'react/jsx-dev-runtime': `'/react/jsx-dev-runtime.js'`,\n 'react/jsx-runtime': `'/react/jsx-runtime.js'`,\n 'react-dom': `'/react-dom/index.js'`,\n };\n\n const sharedRemote = `'use client';\\nmodule.exports = { shared: { ${Array.from(\n shared,\n )\n .reduce<string[]>((acc, curr) => {\n acc.push(\n `[${vendorShared[curr] ?? `require.resolve('${curr}')`}]: '${curr}',`,\n );\n return acc;\n }, [])\n .join('\\n')} } };\\n`;\n\n const sharedHost = `'use client';\\nmodule.exports = { shared: { ${Array.from(\n shared,\n )\n .reduce<string[]>((acc, curr) => {\n acc.push(`['${curr}']: () => import('${curr}'),`);\n return acc;\n }, [])\n .join('\\n')} } };\\n`;\n\n const emitSharedFiles = () => {\n mkdirSync(dirname(virtualRemoteComponentSharedRemote), {\n recursive: true,\n });\n\n writeFileSync(virtualRemoteComponentSharedRemote, sharedRemote, 'utf-8');\n writeFileSync(virtualRemoteComponentSharedHost, sharedHost, 'utf-8');\n };\n\n nextConfig.transpilePackages = [\n ...(nextConfig.transpilePackages ?? []),\n 'remote-components/next/remote',\n 'remote-components/next/host',\n '@remote-components/shared/remote',\n '@remote-components/shared/host',\n ];\n\n const alias = {\n '@remote-components/shared/remote': `./${relative(\n process.cwd(),\n virtualRemoteComponentSharedRemote,\n )}`,\n '@remote-components/shared/host': `./${relative(\n process.cwd(),\n virtualRemoteComponentSharedHost,\n )}`,\n };\n\n let projectId =\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID;\n\n if (!projectId) {\n try {\n const projectPath = findUpSync('.vercel/project.json', {\n cwd: process.cwd(),\n });\n if (projectPath) {\n projectId = (\n JSON.parse(readFileSync(projectPath, 'utf8')) as { projectId: string }\n ).projectId;\n }\n } catch {\n // fallback to env‑var above\n }\n }\n\n if (!projectId) {\n const packageJsonPath = findUpSync('package.json', {\n cwd: process.cwd(),\n });\n if (packageJsonPath) {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8')) as {\n name?: string;\n };\n projectId = packageJson.name || basename(process.cwd());\n } else {\n projectId = basename(process.cwd());\n }\n }\n\n process.env.REMOTE_COMPONENTS_PROJECT_ID = projectId;\n\n if (process.env.TURBOPACK) {\n if (\n !(configSchema as ZodSchema).safeParse({\n turbopack: {\n moduleIds: 'named',\n resolveAlias: {\n ...alias,\n },\n },\n compiler: {\n defineServer: {\n REMOTE_COMPONENTS_PROJECT_ID: projectId,\n },\n },\n }).success\n ) {\n // eslint-disable-next-line no-console\n console.error(\n 'You need to use a Next.js version which supports the `turbopack` and `compiler.defineServer` configuration for Turbopack support with Remote Components.',\n );\n process.exit(1);\n }\n nextConfig.turbopack = {\n ...nextConfig.turbopack,\n moduleIds: 'named',\n resolveAlias: {\n ...nextConfig.turbopack?.resolveAlias,\n ...alias,\n },\n };\n nextConfig.compiler = {\n ...nextConfig.compiler,\n defineServer: {\n ...nextConfig.compiler?.defineServer,\n 'process.env.REMOTE_COMPONENTS_PROJECT_ID': projectId,\n },\n };\n emitSharedFiles();\n return nextConfig;\n }\n\n // apply the webpack transform\n return webpackTransform(nextConfig, {\n app: { name: projectId },\n alias,\n emitSharedFiles,\n });\n}\n","import { join } from 'node:path';\nimport type { NextConfig } from 'next';\nimport type { WebpackOptionsNormalized } from 'webpack';\nimport { RemoteWebpackRequirePlugin } from './plugins/remote-webpack-require';\nimport { ModuleIdEmbedPlugin } from './plugins/module-id-embed';\nimport { ConditionalExecPlugin } from './plugins/conditional-exec';\nimport { PatchRequirePlugin } from './plugins/patch-require';\n\nexport function transform(\n nextConfig: NextConfig,\n {\n app,\n alias = {},\n emitSharedFiles = () => {\n // no-op by default\n },\n }: {\n app: { name: string };\n alias?: Record<string, string>;\n emitSharedFiles?: () => void;\n },\n) {\n const webpackConfig = nextConfig.webpack;\n\n nextConfig.webpack = (\n baseConfig: WebpackOptionsNormalized,\n webpackContext,\n ) => {\n // execute the client config first, otherwise their config may accidentally\n // overwrite our required config - leading to unexpected errors.\n const config = (\n typeof webpackConfig === 'function'\n ? (webpackConfig(baseConfig, webpackContext) ?? baseConfig)\n : baseConfig\n ) as WebpackOptionsNormalized;\n\n // remote component specific plugins\n config.plugins.push(\n new RemoteWebpackRequirePlugin(app.name),\n new ModuleIdEmbedPlugin(app.name),\n new ConditionalExecPlugin(),\n new PatchRequirePlugin(),\n );\n if (!webpackContext.isServer) {\n // change the chunk loading global to avoid conflicts with other remote components\n config.output.chunkLoadingGlobal = `__remote_chunk_loading_global_${app.name}__`;\n }\n\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve.alias,\n ...Object.fromEntries(\n Object.entries(alias).map(([key, value]) => [\n key,\n join(process.cwd(), value),\n ]),\n ),\n },\n };\n\n emitSharedFiles();\n return config;\n };\n\n return nextConfig;\n}\n","export function createRemoteWebpackRequireRuntimeModule(webpack: {\n RuntimeModule: new (name: string, stage?: number) => object;\n}) {\n return class RemoteWebpackRequireRuntimeModule extends webpack.RuntimeModule {\n appName: string;\n\n constructor(appName: string) {\n super('remote-webpack-require');\n this.appName = appName;\n }\n\n generate(): null | string {\n return `globalThis.__remote_webpack_require__ = globalThis.__remote_webpack_require__ || {}; globalThis.__remote_webpack_require__[\"${this.appName}\"] = __webpack_require__;`;\n }\n };\n}\n","import type { Compiler, RuntimeModule } from 'webpack';\nimport { createRemoteWebpackRequireRuntimeModule } from './remote-webpack-require-runtime-module';\n\nexport class RemoteWebpackRequirePlugin {\n appName: string;\n\n constructor(appName: string) {\n this.appName = appName;\n }\n\n apply(compiler: Compiler) {\n const RemoteWebpackRequireRuntimeModule =\n createRemoteWebpackRequireRuntimeModule(compiler.webpack);\n\n compiler.hooks.thisCompilation.tap(\n 'RemoteWebpackRequirePlugin',\n (compilation) => {\n compilation.hooks.runtimeRequirementInTree\n .for('__webpack_require__')\n .tap('RemoteWebpackRequirePlugin', (chunk) => {\n compilation.addRuntimeModule(\n chunk,\n new RemoteWebpackRequireRuntimeModule(\n this.appName,\n ) as unknown as RuntimeModule,\n );\n });\n },\n );\n }\n}\n","import { relative } from 'node:path';\nimport type { NormalModule, Compiler, RuntimeModule } from 'webpack';\nimport { createModuleIdEmbedRuntimeModule } from './module-id-embed-runtime-module';\n\nconst cwd = process.cwd();\n\nexport class ModuleIdEmbedPlugin {\n appName: string;\n\n constructor(appName: string) {\n this.appName = appName;\n }\n\n apply(compiler: Compiler) {\n const ModuleIdEmbedRuntimeModule = createModuleIdEmbedRuntimeModule(\n compiler.webpack,\n );\n\n compiler.hooks.thisCompilation.tap('ModuleIdEmbedPlugin', (compilation) => {\n const moduleMap = {} as Record<string, string | number>;\n\n compilation.hooks.runtimeRequirementInTree\n .for(compiler.webpack.RuntimeGlobals.require)\n .tap('ModuleIdEmbedPlugin', (chunk, set) => {\n for (const [key, entry] of compilation.entrypoints) {\n for (const entryChunk of entry.chunks) {\n if (key.includes('nextjs-pages-remote')) {\n for (const mod of compilation.chunkGraph.getChunkModulesIterable(\n entryChunk,\n )) {\n const id = compilation.chunkGraph.getModuleId(mod);\n const normalModule = mod as NormalModule;\n if (id && (normalModule.resource || normalModule.request)) {\n moduleMap[\n relative(\n cwd,\n normalModule.resource || normalModule.request,\n )\n ] = id;\n }\n }\n }\n }\n }\n for (const mod of compilation.modules) {\n const id = compilation.chunkGraph.getModuleId(mod);\n if (id && mod.layer?.endsWith('browser')) {\n const normalModule = mod as NormalModule;\n if (normalModule.resource || normalModule.request) {\n moduleMap[\n relative(cwd, normalModule.resource || normalModule.request)\n ] = id;\n }\n }\n }\n\n if (Object.keys(moduleMap).length > 0) {\n compilation.addRuntimeModule(\n chunk,\n new ModuleIdEmbedRuntimeModule(\n this.appName,\n moduleMap,\n ) as unknown as RuntimeModule,\n );\n\n set.add(compiler.webpack.RuntimeGlobals.require);\n }\n });\n });\n }\n}\n","export function createModuleIdEmbedRuntimeModule(webpack: {\n RuntimeModule: new (name: string, stage?: number) => object;\n}) {\n return class ModuleIdEmbedRuntimeModule extends webpack.RuntimeModule {\n appName: string;\n moduleMap: Record<string | number, unknown>;\n\n constructor(appName: string, moduleMap: Record<string | number, unknown>) {\n super('remote-webpack-module-id-embed');\n this.appName = appName;\n this.moduleMap = moduleMap;\n }\n\n generate(): null | string {\n return `globalThis.__remote_webpack_module_map__ = globalThis.__remote_webpack_module_map__ || {}; globalThis.__remote_webpack_module_map__[\"${this.appName}\"] = ${JSON.stringify(this.moduleMap)};`;\n }\n };\n}\n","import type { Compiler } from 'webpack';\n\nexport class ConditionalExecPlugin {\n apply(compiler: Compiler) {\n const { Compilation, sources } = compiler.webpack;\n\n compiler.hooks.thisCompilation.tap(\n 'ConditionalExecPlugin',\n (compilation) => {\n compilation.hooks.processAssets.tap(\n {\n name: 'ConditionalExecPlugin',\n stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,\n },\n (assets) => {\n for (const [name, source] of Object.entries(assets)) {\n if (name.endsWith('.js')) {\n const patchedSource = source\n .source()\n .toString()\n .replace(\n `var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))`,\n `var __webpack_exec__ = (moduleId) => { if (globalThis.__DISABLE_WEBPACK_EXEC__) return; return __webpack_require__(__webpack_require__.s = moduleId); }`,\n );\n compilation.updateAsset(\n name,\n new sources.RawSource(patchedSource),\n );\n }\n }\n },\n );\n },\n );\n }\n}\n","import type { Compiler } from 'webpack';\n\n// This plugin patches the webpack require function to support loading remote components in Next.js\nexport class PatchRequirePlugin {\n apply(compiler: Compiler) {\n const { sources } = compiler.webpack;\n\n compiler.hooks.thisCompilation.tap('PatchRequirePlugin', (compilation) => {\n compilation.mainTemplate.hooks.requireExtensions.tap(\n 'PatchRequirePlugin',\n (source) => {\n return new sources.ConcatSource(\n source,\n `const __webpack_require_orig__ = __webpack_require__;\nconst REMOTE_RE = /\\\\[(?<bundle>[a-zA-Z0-9-_]+)\\\\] (?<id>.*)/;\n__webpack_require__ = function __remote_webpack_require__(remoteId) {\n const match = REMOTE_RE.exec(remoteId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_orig__(remoteId);\n }\n if (typeof self.__remote_webpack_require__?.[bundle] !== 'function') {\n throw new Error(\\`Remote component loading error: \"\\${bundle}\"\\`);\n }\n return self.__remote_webpack_require__[bundle](self.__remote_webpack_require__[bundle].type === 'turbopack' ? remoteId : id);\n};\nObject.assign(__webpack_require__, __webpack_require_orig__);\nconst __webpack_require_l__ = __webpack_require__.l;\n__webpack_require__.l = function __remote_webpack_require_l__(url, done, key, chunkId) {\n const match = REMOTE_RE.exec(chunkId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_l__(url, done, key, chunkId);\n }\n return done();\n};\nconst __webpack_require_o__ = __webpack_require__.o;\n__webpack_require__.o = function __remote_webpack_require_o__(installedChunks, chunkId) {\n const match = REMOTE_RE.exec(chunkId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_o__(installedChunks, chunkId);\n }\n return installedChunks[chunkId] = 0;\n};\nconst __webpack_require_e__ = __webpack_require__.e;\n__webpack_require__.e = function __remote_webpack_require_e__(chunkId) {\n const match = REMOTE_RE.exec(chunkId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_e__(chunkId);\n }\n return Promise.resolve([]);\n};`,\n )\n .source()\n .toString();\n },\n );\n });\n }\n}\n"],"mappings":";AAAA,SAAS,UAAU,SAAS,QAAAA,OAAM,YAAAC,iBAAgB;AAClD,SAAS,WAAW,cAAc,qBAAqB;AACvD,SAAS,kBAAkB;AAE3B,SAAS,oBAAoB;;;ACJ7B,SAAS,YAAY;;;ACAd,SAAS,wCAAwC,SAErD;AACD,SAAO,MAAM,0CAA0C,QAAQ,cAAc;AAAA,IAG3E,YAAY,SAAiB;AAC3B,YAAM,wBAAwB;AAC9B,WAAK,UAAU;AAAA,IACjB;AAAA,IAEA,WAA0B;AACxB,aAAO,+HAA+H,KAAK;AAAA,IAC7I;AAAA,EACF;AACF;;;ACZO,IAAM,6BAAN,MAAiC;AAAA,EAGtC,YAAY,SAAiB;AAC3B,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,MAAM,UAAoB;AACxB,UAAM,oCACJ,wCAAwC,SAAS,OAAO;AAE1D,aAAS,MAAM,gBAAgB;AAAA,MAC7B;AAAA,MACA,CAAC,gBAAgB;AACf,oBAAY,MAAM,yBACf,IAAI,qBAAqB,EACzB,IAAI,8BA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ACF,CAAC,EAAE,SACH;AAEA,cAAQ;AAAA,QACN;AAAA,MACF;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,eAAW,YAAY;AAAA,MACrB,GAAG,WAAW;AAAA,MACd,WAAW;AAAA,MACX,cAAc;AAAA,QACZ,GAAG,WAAW,WAAW;AAAA,QACzB,GAAG;AAAA,MACL;AAAA,IACF;AACA,eAAW,WAAW;AAAA,MACpB,GAAG,WAAW;AAAA,MACd,cAAc;AAAA,QACZ,GAAG,WAAW,UAAU;AAAA,QACxB,4CAA4C;AAAA,MAC9C;AAAA,IACF;AACA,oBAAgB;AAChB,WAAO;AAAA,EACT;AAGA,SAAO,UAAiB,YAAY;AAAA,IAClC,KAAK,EAAE,MAAM,UAAU;AAAA,IACvB;AAAA,IACA;AAAA,EACF,CAAC;AACH;","names":["join","relative","join","relative"]}
1
+ {"version":3,"sources":["../../src/next/config/index.ts","../../src/next/config/webpack/index.ts","../../src/next/config/webpack/plugins/remote-webpack-require-runtime-module.ts","../../src/next/config/webpack/plugins/remote-webpack-require.ts","../../src/next/config/webpack/plugins/module-id-embed.ts","../../src/next/config/webpack/plugins/module-id-embed-runtime-module.ts","../../src/next/config/webpack/plugins/conditional-exec.ts","../../src/next/config/webpack/plugins/patch-require.ts"],"sourcesContent":["import { basename, dirname, join, relative } from 'node:path';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport enhancedResolve from 'enhanced-resolve';\nimport { findUpSync } from 'find-up';\nimport type { NextConfig } from 'next';\nimport { configSchema } from 'next/dist/server/config-schema.js';\nimport TsConfigPathsWebpackPlugin from 'tsconfig-paths-webpack-plugin';\nimport { transform as webpackTransform } from './webpack';\n\ninterface ZodSchema {\n safeParse: (data: unknown) => { success: boolean };\n}\n\ninterface WithRemoteComponentsOptions {\n /**\n * An array of package names that should be shared between the host and remote components.\n * This is useful for ensuring that both the host and remote components use the same version\n * of shared libraries.\n *\n * Essential packages are included by default: `react`, `react-dom`, `next/navigation`, `next/link`, `next/form`, `next/image`, and `next/script`.\n */\n shared?: string[];\n}\n\n/**\n * This function configures Next.js to support Remote Components.\n * You need to also use the `withMicrofrontends` function to extend your Next.js configuration.\n *\n * @param nextConfig - The Next.js configuration object.\n * @param options - Optional configuration for remote components.\n * @returns The modified Next.js configuration object with remote components support.\n *\n * @example\n *\n * ```js\n * import { withMicrofrontends } from '@vercel/microfrontends/next/config';\n * import { withRemoteComponents } from 'remote-components/next/config';\n *\n * const nextConfig = {\n * // your Next.js configuration\n * };\n *\n * export default withRemoteComponents(\n * withMicrofrontends(nextConfig),\n * {\n * shared: ['some-package', 'another-package'],\n * },\n * );\n * ```\n */\nexport function withRemoteComponents(\n nextConfig: NextConfig,\n options?: WithRemoteComponentsOptions,\n) {\n const virtualRemoteComponentSharedRemote = join(\n process.cwd(),\n nextConfig.distDir ?? '.next',\n 'remote-components/shared/remote.tsx',\n );\n const virtualRemoteComponentSharedHost = join(\n process.cwd(),\n nextConfig.distDir ?? '.next',\n 'remote-components/shared/host.tsx',\n );\n\n const shared = new Set([\n ...[\n 'react',\n 'react/jsx-dev-runtime',\n 'react/jsx-runtime',\n 'react-dom',\n 'react-dom/client',\n 'next/navigation',\n 'next/link',\n 'next/form',\n 'next/image',\n 'next/script',\n ],\n ...(options?.shared ?? []),\n ]);\n\n const vendorShared: Record<string, string> = {\n react: `'/react/index.js'`,\n 'react/jsx-dev-runtime': `'/react/jsx-dev-runtime.js'`,\n 'react/jsx-runtime': `'/react/jsx-runtime.js'`,\n 'react-dom': `'/react-dom/index.js'`,\n };\n\n // resolve using enhanced-resolve\n // named import does not work with enhanced-resolve when using cjs\n // eslint-disable-next-line import/no-named-as-default-member\n const resolve = enhancedResolve.create.sync({\n conditionNames: ['browser', 'import', 'module', 'require'],\n ...(existsSync(join(process.cwd(), 'tsconfig.json'))\n ? {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n plugins: [\n new TsConfigPathsWebpackPlugin({\n configFile: join(process.cwd(), 'tsconfig.json'),\n }) as unknown as enhancedResolve.Plugin,\n ],\n }\n : {}),\n });\n const sharedRemote = `'use client';\\nmodule.exports = { shared: { ${Array.from(\n shared,\n )\n .reduce<string[]>((acc, curr) => {\n let path;\n try {\n path = resolve(process.cwd(), curr);\n if (path) {\n path = relative(process.cwd(), path).replace(\n /^(?<relative>\\.\\.\\/)+/,\n '',\n );\n }\n } catch {\n // noop\n // if module resolution using enhanced-resolve fails, fallback to require.resolve called in the shared/remote file\n }\n acc.push(\n `[${vendorShared[curr] ?? (path ? `'${path}'` : `require.resolve('${curr}')`)}]: '${curr}',`,\n );\n acc.push(`['__remote_shared_module_${curr}']: () => import('${curr}'),`);\n return acc;\n }, [])\n .join('\\n')} } };\\n`;\n\n const sharedHost = `'use client';\\nmodule.exports = { shared: { ${Array.from(\n shared,\n )\n .reduce<string[]>((acc, curr) => {\n acc.push(`['${curr}']: () => import('${curr}'),`);\n return acc;\n }, [])\n .join('\\n')} } };\\n`;\n\n const emitSharedFiles = () => {\n mkdirSync(dirname(virtualRemoteComponentSharedRemote), {\n recursive: true,\n });\n\n writeFileSync(virtualRemoteComponentSharedRemote, sharedRemote, 'utf-8');\n writeFileSync(virtualRemoteComponentSharedHost, sharedHost, 'utf-8');\n };\n\n nextConfig.transpilePackages = [\n ...(nextConfig.transpilePackages ?? []),\n 'remote-components/next/remote',\n 'remote-components/next/host',\n '@remote-components/shared/remote',\n '@remote-components/shared/host',\n ];\n\n const alias = {\n '@remote-components/shared/remote': `./${relative(\n process.cwd(),\n virtualRemoteComponentSharedRemote,\n )}`,\n '@remote-components/shared/host': `./${relative(\n process.cwd(),\n virtualRemoteComponentSharedHost,\n )}`,\n };\n\n let projectId =\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID;\n\n if (!projectId) {\n try {\n const projectPath = findUpSync('.vercel/project.json', {\n cwd: process.cwd(),\n });\n if (projectPath) {\n projectId = (\n JSON.parse(readFileSync(projectPath, 'utf8')) as { projectId: string }\n ).projectId;\n }\n } catch {\n // fallback to env‑var above\n }\n }\n\n if (!projectId) {\n const packageJsonPath = findUpSync('package.json', {\n cwd: process.cwd(),\n });\n if (packageJsonPath) {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8')) as {\n name?: string;\n };\n projectId = packageJson.name || basename(process.cwd());\n } else {\n projectId = basename(process.cwd());\n }\n }\n\n process.env.REMOTE_COMPONENTS_PROJECT_ID = projectId;\n\n if (process.env.TURBOPACK) {\n if (\n !(configSchema as ZodSchema).safeParse({\n turbopack: {\n moduleIds: 'named',\n resolveAlias: {\n ...alias,\n },\n },\n compiler: {\n defineServer: {\n REMOTE_COMPONENTS_PROJECT_ID: projectId,\n },\n },\n }).success\n ) {\n // eslint-disable-next-line no-console\n console.error(\n 'You need to use a Next.js version which supports the `turbopack` and `compiler.defineServer` configuration for Turbopack support with Remote Components.',\n );\n process.exit(1);\n }\n nextConfig.turbopack = {\n ...nextConfig.turbopack,\n moduleIds: 'named',\n resolveAlias: {\n ...nextConfig.turbopack?.resolveAlias,\n ...alias,\n },\n };\n nextConfig.compiler = {\n ...nextConfig.compiler,\n defineServer: {\n ...nextConfig.compiler?.defineServer,\n 'process.env.REMOTE_COMPONENTS_PROJECT_ID': projectId,\n },\n };\n emitSharedFiles();\n return nextConfig;\n }\n\n // apply the webpack transform\n return webpackTransform(nextConfig, {\n app: { name: projectId },\n alias,\n emitSharedFiles,\n });\n}\n","import { join } from 'node:path';\nimport type { NextConfig } from 'next';\nimport type { WebpackOptionsNormalized } from 'webpack';\nimport { RemoteWebpackRequirePlugin } from './plugins/remote-webpack-require';\nimport { ModuleIdEmbedPlugin } from './plugins/module-id-embed';\nimport { ConditionalExecPlugin } from './plugins/conditional-exec';\nimport { PatchRequirePlugin } from './plugins/patch-require';\n\nexport function transform(\n nextConfig: NextConfig,\n {\n app,\n alias = {},\n emitSharedFiles = () => {\n // no-op by default\n },\n }: {\n app: { name: string };\n alias?: Record<string, string>;\n emitSharedFiles?: () => void;\n },\n) {\n const webpackConfig = nextConfig.webpack;\n\n nextConfig.webpack = (\n baseConfig: WebpackOptionsNormalized,\n webpackContext,\n ) => {\n // execute the client config first, otherwise their config may accidentally\n // overwrite our required config - leading to unexpected errors.\n const config = (\n typeof webpackConfig === 'function'\n ? (webpackConfig(baseConfig, webpackContext) ?? baseConfig)\n : baseConfig\n ) as WebpackOptionsNormalized;\n\n // remote component specific plugins\n config.plugins.push(\n new RemoteWebpackRequirePlugin(app.name),\n new ModuleIdEmbedPlugin(app.name),\n new ConditionalExecPlugin(),\n new PatchRequirePlugin(),\n );\n if (!webpackContext.isServer) {\n // change the chunk loading global to avoid conflicts with other remote components\n config.output.chunkLoadingGlobal = `__remote_chunk_loading_global_${app.name}__`;\n }\n\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve.alias,\n ...Object.fromEntries(\n Object.entries(alias).map(([key, value]) => [\n key,\n join(process.cwd(), value),\n ]),\n ),\n },\n };\n\n emitSharedFiles();\n return config;\n };\n\n return nextConfig;\n}\n","export function createRemoteWebpackRequireRuntimeModule(webpack: {\n RuntimeModule: new (name: string, stage?: number) => object;\n}) {\n return class RemoteWebpackRequireRuntimeModule extends webpack.RuntimeModule {\n appName: string;\n\n constructor(appName: string) {\n super('remote-webpack-require');\n this.appName = appName;\n }\n\n generate(): null | string {\n return `globalThis.__remote_webpack_require__ = globalThis.__remote_webpack_require__ || {}; globalThis.__remote_webpack_require__[\"${this.appName}\"] = __webpack_require__;`;\n }\n };\n}\n","import type { Compiler, RuntimeModule } from 'webpack';\nimport { createRemoteWebpackRequireRuntimeModule } from './remote-webpack-require-runtime-module';\n\nexport class RemoteWebpackRequirePlugin {\n appName: string;\n\n constructor(appName: string) {\n this.appName = appName;\n }\n\n apply(compiler: Compiler) {\n const RemoteWebpackRequireRuntimeModule =\n createRemoteWebpackRequireRuntimeModule(compiler.webpack);\n\n compiler.hooks.thisCompilation.tap(\n 'RemoteWebpackRequirePlugin',\n (compilation) => {\n compilation.hooks.runtimeRequirementInTree\n .for('__webpack_require__')\n .tap('RemoteWebpackRequirePlugin', (chunk) => {\n compilation.addRuntimeModule(\n chunk,\n new RemoteWebpackRequireRuntimeModule(\n this.appName,\n ) as unknown as RuntimeModule,\n );\n });\n },\n );\n }\n}\n","import { relative } from 'node:path';\nimport type { NormalModule, Compiler, RuntimeModule } from 'webpack';\nimport { createModuleIdEmbedRuntimeModule } from './module-id-embed-runtime-module';\n\nconst cwd = process.cwd();\n\nexport class ModuleIdEmbedPlugin {\n appName: string;\n\n constructor(appName: string) {\n this.appName = appName;\n }\n\n apply(compiler: Compiler) {\n const ModuleIdEmbedRuntimeModule = createModuleIdEmbedRuntimeModule(\n compiler.webpack,\n );\n\n compiler.hooks.thisCompilation.tap('ModuleIdEmbedPlugin', (compilation) => {\n const moduleMap = {} as Record<string, string | number>;\n\n compilation.hooks.runtimeRequirementInTree\n .for(compiler.webpack.RuntimeGlobals.require)\n .tap('ModuleIdEmbedPlugin', (chunk, set) => {\n for (const [key, entry] of compilation.entrypoints) {\n for (const entryChunk of entry.chunks) {\n if (key.includes('nextjs-pages-remote')) {\n for (const mod of compilation.chunkGraph.getChunkModulesIterable(\n entryChunk,\n )) {\n const id = compilation.chunkGraph.getModuleId(mod);\n const normalModule = mod as NormalModule;\n if (id && (normalModule.resource || normalModule.request)) {\n moduleMap[\n relative(\n cwd,\n normalModule.resource || normalModule.request,\n )\n ] = id;\n }\n }\n }\n }\n }\n for (const mod of compilation.modules) {\n const id = compilation.chunkGraph.getModuleId(mod);\n if (id && mod.layer?.endsWith('browser')) {\n const normalModule = mod as NormalModule;\n if (normalModule.resource || normalModule.request) {\n moduleMap[\n relative(cwd, normalModule.resource || normalModule.request)\n ] = id;\n }\n }\n }\n\n if (Object.keys(moduleMap).length > 0) {\n compilation.addRuntimeModule(\n chunk,\n new ModuleIdEmbedRuntimeModule(\n this.appName,\n moduleMap,\n ) as unknown as RuntimeModule,\n );\n\n set.add(compiler.webpack.RuntimeGlobals.require);\n }\n });\n });\n }\n}\n","export function createModuleIdEmbedRuntimeModule(webpack: {\n RuntimeModule: new (name: string, stage?: number) => object;\n}) {\n return class ModuleIdEmbedRuntimeModule extends webpack.RuntimeModule {\n appName: string;\n moduleMap: Record<string | number, unknown>;\n\n constructor(appName: string, moduleMap: Record<string | number, unknown>) {\n super('remote-webpack-module-id-embed');\n this.appName = appName;\n this.moduleMap = moduleMap;\n }\n\n generate(): null | string {\n return `globalThis.__remote_webpack_module_map__ = globalThis.__remote_webpack_module_map__ || {}; globalThis.__remote_webpack_module_map__[\"${this.appName}\"] = ${JSON.stringify(this.moduleMap)};`;\n }\n };\n}\n","import type { Compiler } from 'webpack';\n\nexport class ConditionalExecPlugin {\n apply(compiler: Compiler) {\n const { Compilation, sources } = compiler.webpack;\n\n compiler.hooks.thisCompilation.tap(\n 'ConditionalExecPlugin',\n (compilation) => {\n compilation.hooks.processAssets.tap(\n {\n name: 'ConditionalExecPlugin',\n stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,\n },\n (assets) => {\n for (const [name, source] of Object.entries(assets)) {\n if (name.endsWith('.js')) {\n const patchedSource = source\n .source()\n .toString()\n .replace(\n `var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))`,\n `var __webpack_exec__ = (moduleId) => { if (globalThis.__DISABLE_WEBPACK_EXEC__) return; return __webpack_require__(__webpack_require__.s = moduleId); }`,\n );\n compilation.updateAsset(\n name,\n new sources.RawSource(patchedSource),\n );\n }\n }\n },\n );\n },\n );\n }\n}\n","import type { Compiler } from 'webpack';\n\n// This plugin patches the webpack require function to support loading remote components in Next.js\nexport class PatchRequirePlugin {\n apply(compiler: Compiler) {\n const { sources } = compiler.webpack;\n\n compiler.hooks.thisCompilation.tap('PatchRequirePlugin', (compilation) => {\n compilation.mainTemplate.hooks.requireExtensions.tap(\n 'PatchRequirePlugin',\n (source) => {\n return new sources.ConcatSource(\n source,\n `const __webpack_require_orig__ = __webpack_require__;\nconst REMOTE_RE = /\\\\[(?<bundle>[a-zA-Z0-9-_]+)\\\\] (?<id>.*)/;\n__webpack_require__ = function __remote_webpack_require__(remoteId) {\n const match = REMOTE_RE.exec(remoteId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_orig__(remoteId);\n }\n if (typeof self.__remote_webpack_require__?.[bundle] !== 'function') {\n throw new Error(\\`Remote component loading error: \"\\${bundle}\"\\`);\n }\n return self.__remote_webpack_require__[bundle](self.__remote_webpack_require__[bundle].type === 'turbopack' ? remoteId : id);\n};\nObject.assign(__webpack_require__, __webpack_require_orig__);\nconst __webpack_require_l__ = __webpack_require__.l;\n__webpack_require__.l = function __remote_webpack_require_l__(url, done, key, chunkId) {\n const match = REMOTE_RE.exec(chunkId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_l__(url, done, key, chunkId);\n }\n return done();\n};\nconst __webpack_require_o__ = __webpack_require__.o;\n__webpack_require__.o = function __remote_webpack_require_o__(installedChunks, chunkId) {\n const match = REMOTE_RE.exec(chunkId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_o__(installedChunks, chunkId);\n }\n return installedChunks[chunkId] = 0;\n};\nconst __webpack_require_e__ = __webpack_require__.e;\n__webpack_require__.e = function __remote_webpack_require_e__(chunkId) {\n const match = REMOTE_RE.exec(chunkId);\n const bundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && bundle)) {\n return __webpack_require_e__(chunkId);\n }\n return Promise.resolve([]);\n};`,\n )\n .source()\n .toString();\n },\n );\n });\n }\n}\n"],"mappings":";AAAA,SAAS,UAAU,SAAS,QAAAA,OAAM,YAAAC,iBAAgB;AAClD,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,OAAO,qBAAqB;AAC5B,SAAS,kBAAkB;AAE3B,SAAS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,MACF;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,eAAW,YAAY;AAAA,MACrB,GAAG,WAAW;AAAA,MACd,WAAW;AAAA,MACX,cAAc;AAAA,QACZ,GAAG,WAAW,WAAW;AAAA,QACzB,GAAG;AAAA,MACL;AAAA,IACF;AACA,eAAW,WAAW;AAAA,MACpB,GAAG,WAAW;AAAA,MACd,cAAc;AAAA,QACZ,GAAG,WAAW,UAAU;AAAA,QACxB,4CAA4C;AAAA,MAC9C;AAAA,IACF;AACA,oBAAgB;AAChB,WAAO;AAAA,EACT;AAGA,SAAO,UAAiB,YAAY;AAAA,IAClC,KAAK,EAAE,MAAM,UAAU;AAAA,IACvB;AAAA,IACA;AAAA,EACF,CAAC;AACH;","names":["join","relative","join","relative"]}
@@ -1,28 +1,7 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import * as react from 'react';
3
- import { R as RemoteComponentMetadata } from '../../types-280a3640.js';
4
-
5
- interface RemoteComponentProps {
6
- url: string;
7
- name: string;
8
- bundle: string;
9
- route?: string;
10
- runtime?: RemoteComponentMetadata['runtime'];
11
- data: string[];
12
- nextData?: {
13
- props: {
14
- pageProps: Record<string, unknown>;
15
- };
16
- buildId?: string;
17
- };
18
- scripts?: {
19
- src: string;
20
- }[];
21
- links?: Record<string, string | boolean | undefined>[];
22
- remoteShared?: Record<string, string>;
23
- isolate?: boolean;
24
- children: react.ReactNode;
25
- }
2
+ import { R as RemoteComponentProps } from '../../types-d04035e6.js';
3
+ import 'react';
4
+ import '../../types-280a3640.js';
26
5
 
27
6
  declare module 'react/jsx-runtime' {
28
7
  namespace JSX {
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ "use client";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+ var client_exports = {};
31
+ __export(client_exports, {
32
+ RemoteComponent: () => RemoteComponent
33
+ });
34
+ module.exports = __toCommonJS(client_exports);
35
+ var import_jsx_runtime = require("react/jsx-runtime");
36
+ var import_react = require("react");
37
+ var import_react_dom = require("react-dom");
38
+ var import_remote_component = require("../../../shared/client/remote-component");
39
+ async function tryImportShared() {
40
+ try {
41
+ const { shared } = await import("@remote-components/shared/host");
42
+ return shared;
43
+ } catch {
44
+ return {};
45
+ }
46
+ }
47
+ function RemoteComponent({
48
+ src,
49
+ isolate,
50
+ credentials = "same-origin",
51
+ name = "__vercel_remote_component",
52
+ children
53
+ }) {
54
+ const [data, setData] = (0, import_react.useState)(null);
55
+ const [remoteComponent, setRemoteComponent] = (0, import_react.useState)(null);
56
+ const shadowRootContainerRef = (0, import_react.useRef)(null);
57
+ const [shadowRoot, setShadowRoot] = (0, import_react.useState)(null);
58
+ (0, import_react.useEffect)(() => {
59
+ if (shadowRootContainerRef.current) {
60
+ const shadow = shadowRootContainerRef.current.attachShadow({
61
+ mode: "open"
62
+ });
63
+ setShadowRoot(shadow);
64
+ }
65
+ }, [shadowRootContainerRef]);
66
+ const url = (0, import_react.useMemo)(
67
+ () => typeof document !== "undefined" ? new URL(src, location.href) : new URL(src),
68
+ [src]
69
+ );
70
+ (0, import_react.useEffect)(() => {
71
+ let mounted = true;
72
+ (async () => {
73
+ const fetchInit = {
74
+ method: "GET",
75
+ headers: {
76
+ Accept: "text/html",
77
+ // pass the public address of the remote component to the server used for module map mutation
78
+ "Vercel-Remote-Component-Url": url.href
79
+ },
80
+ credentials
81
+ };
82
+ const res = await fetch(url, fetchInit);
83
+ if (!res.ok) {
84
+ throw new Error(
85
+ `Failed to fetch remote component "${name}": ${res.status}`
86
+ );
87
+ }
88
+ const html = await res.text();
89
+ const doc = document.createElement("div");
90
+ doc.innerHTML = html;
91
+ const component = doc.querySelector(`div[data-bundle][data-route][id^="${name}"]`) ?? // fallback to the first element with the data-bundle and data-route attributes when not using a named remote component
92
+ doc.querySelector("div[data-bundle][data-route]") ?? // fallback to Next.js Pages Router
93
+ doc.querySelector("div#__next");
94
+ const nextData = JSON.parse(
95
+ (doc.querySelector("#__NEXT_DATA__") ?? doc.querySelector("#__REMOTE_NEXT_DATA__"))?.textContent ?? "null"
96
+ );
97
+ const remoteName = component?.getAttribute("id")?.replace(/_ssr$/, "") || (nextData ? "__next" : name);
98
+ const rsc = doc.querySelector(`#${remoteName}_rsc`);
99
+ const bundle = component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle || "default";
100
+ const metadata = {
101
+ name: remoteName,
102
+ bundle,
103
+ route: component?.getAttribute("data-route") ?? nextData?.page ?? import_remote_component.DEFAULT_ROUTE,
104
+ runtime: component?.getAttribute("data-runtime") ?? (nextData?.props.__REMOTE_COMPONENT__?.runtime || import_remote_component.RUNTIME_WEBPACK)
105
+ };
106
+ const remoteSharedEl = doc.querySelector(`#${remoteName}_shared`);
107
+ const remoteShared = JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {};
108
+ remoteSharedEl?.parentElement?.removeChild(remoteSharedEl);
109
+ if (!component || !(rsc || nextData)) {
110
+ throw new Error(`Failed to find component with id "${remoteName}"`);
111
+ }
112
+ const links = Array.from(
113
+ doc.querySelectorAll("link[href]")
114
+ ).map((link) => ({
115
+ rel: link.rel,
116
+ href: new URL(link.getAttribute("href") ?? link.href, url).href,
117
+ as: link.getAttribute("as") || void 0
118
+ }));
119
+ const scripts = doc.querySelectorAll(
120
+ "script[src],script[data-src]"
121
+ );
122
+ if (mounted) {
123
+ if (rsc) {
124
+ document.body.appendChild(rsc);
125
+ }
126
+ const newData = {
127
+ ...metadata,
128
+ links,
129
+ remoteShared,
130
+ url: url.href,
131
+ data: rsc ? (rsc.textContent ?? "").split("\n").filter(Boolean) : []
132
+ };
133
+ setData(newData);
134
+ (0, import_remote_component.loadRemoteComponent)({
135
+ url: new URL(url, location.origin),
136
+ name,
137
+ bundle,
138
+ route: metadata.route,
139
+ runtime: metadata.runtime,
140
+ data: newData.data,
141
+ nextData: void 0,
142
+ scripts: Array.from(scripts).map((script) => ({
143
+ src: new URL(
144
+ script.getAttribute("data-src") || script.getAttribute("src") || script.src,
145
+ url
146
+ ).href
147
+ })),
148
+ shared: tryImportShared(),
149
+ remoteShared,
150
+ container: void 0
151
+ }).then((result) => {
152
+ if (mounted) {
153
+ if (result.error) {
154
+ setRemoteComponent(result.error);
155
+ } else {
156
+ setRemoteComponent(result.component);
157
+ }
158
+ }
159
+ }).catch((error) => {
160
+ if (mounted) {
161
+ setRemoteComponent(error);
162
+ }
163
+ });
164
+ }
165
+ })().catch((error) => {
166
+ if (mounted) {
167
+ setRemoteComponent(error);
168
+ }
169
+ });
170
+ return () => {
171
+ mounted = false;
172
+ };
173
+ }, [url, src, isolate, credentials, name]);
174
+ if (remoteComponent instanceof Error) {
175
+ throw remoteComponent;
176
+ }
177
+ const linksToRender = data?.links?.map((link) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
178
+ "link",
179
+ {
180
+ as: link.as,
181
+ href: new URL(link.href, url).href,
182
+ rel: link.rel
183
+ },
184
+ `${link.href}_${link.rel}`
185
+ )) || null;
186
+ const componentToRender = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
187
+ linksToRender,
188
+ remoteComponent ?? children
189
+ ] });
190
+ if (isolate !== false) {
191
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { id: `shadowroot_${name}`, ref: shadowRootContainerRef, children: shadowRoot ? (0, import_react_dom.createPortal)(componentToRender, shadowRoot) : null });
192
+ }
193
+ return componentToRender;
194
+ }
195
+ // Annotate the CommonJS export names for ESM import in node:
196
+ 0 && (module.exports = {
197
+ RemoteComponent
198
+ });
199
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/next/host/client/index.tsx"],"sourcesContent":["'use client';\n\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport type { RemoteComponentProps } from '../../../shared/client/types';\nimport {\n loadRemoteComponent,\n DEFAULT_ROUTE,\n RUNTIME_WEBPACK,\n} from '../../../shared/client/remote-component';\n\nasync function tryImportShared() {\n try {\n const { shared } = await import('@remote-components/shared/host');\n return shared;\n } catch {\n return {};\n }\n}\n\nexport function RemoteComponent({\n src,\n isolate,\n credentials = 'same-origin',\n name = '__vercel_remote_component',\n children,\n}: {\n src: string | URL;\n isolate?: boolean;\n credentials?: RequestCredentials;\n name?: string;\n children?: React.ReactNode;\n}) {\n const [data, setData] = useState<Omit<\n RemoteComponentProps,\n 'children'\n > | null>(null);\n const [remoteComponent, setRemoteComponent] = useState<\n React.ReactNode | Error\n >(null);\n const shadowRootContainerRef = useRef<HTMLDivElement | null>(null);\n const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(null);\n\n useEffect(() => {\n if (shadowRootContainerRef.current) {\n // create a shadow root for the remote component\n const shadow = shadowRootContainerRef.current.attachShadow({\n mode: 'open',\n });\n setShadowRoot(shadow);\n }\n }, [shadowRootContainerRef]);\n\n const url = useMemo(\n () =>\n typeof document !== 'undefined'\n ? new URL(src, location.href)\n : new URL(src),\n [src],\n );\n\n useEffect(() => {\n let mounted = true;\n\n (async () => {\n // fetch the remote component\n const fetchInit = {\n method: 'GET',\n headers: {\n Accept: 'text/html',\n // pass the public address of the remote component to the server used for module map mutation\n 'Vercel-Remote-Component-Url': url.href,\n },\n credentials,\n } as RequestInit;\n\n const res = await fetch(url, fetchInit);\n\n if (!res.ok) {\n throw new Error(\n `Failed to fetch remote component \"${name}\": ${res.status}`,\n );\n }\n\n // get the full HTML content as a string\n const html = await res.text();\n\n // create a virtual element which will be used to parse the HTML and extract the component and RSC flight data\n const doc = document.createElement('div');\n doc.innerHTML = html;\n\n // reference to the remote component content\n const component =\n doc.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`) ??\n // fallback to the first element with the data-bundle and data-route attributes when not using a named remote component\n doc.querySelector('div[data-bundle][data-route]') ??\n // fallback to Next.js Pages Router\n doc.querySelector('div#__next');\n const nextData = JSON.parse(\n (\n doc.querySelector('#__NEXT_DATA__') ??\n doc.querySelector('#__REMOTE_NEXT_DATA__')\n )?.textContent ?? 'null',\n ) as {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: 'turbopack' | 'webpack';\n };\n };\n page: string;\n buildId: string;\n } | null;\n\n const remoteName =\n component?.getAttribute('id')?.replace(/_ssr$/, '') ||\n (nextData ? '__next' : name);\n // reference to the RSC flight data\n const rsc = doc.querySelector(`#${remoteName}_rsc`);\n\n // reference to the bundle containing the client components\n const bundle =\n component?.getAttribute('data-bundle') ||\n nextData?.props.__REMOTE_COMPONENT__?.bundle ||\n 'default';\n\n const metadata = {\n name: remoteName,\n bundle,\n route:\n component?.getAttribute('data-route') ??\n nextData?.page ??\n DEFAULT_ROUTE,\n runtime: (component?.getAttribute('data-runtime') ??\n (nextData?.props.__REMOTE_COMPONENT__?.runtime ||\n RUNTIME_WEBPACK)) as RemoteComponentProps['runtime'],\n };\n\n const remoteSharedEl = doc.querySelector(`#${remoteName}_shared`);\n const remoteShared = (JSON.parse(remoteSharedEl?.textContent ?? '{}') ??\n {}) as Record<string, string>;\n remoteSharedEl?.parentElement?.removeChild(remoteSharedEl);\n\n if (!component || !(rsc || nextData)) {\n throw new Error(`Failed to find component with id \"${remoteName}\"`);\n }\n\n // reference to all link elements in the remote component\n const links = Array.from(\n doc.querySelectorAll<HTMLLinkElement>('link[href]'),\n ).map((link) => ({\n rel: link.rel,\n href: new URL(link.getAttribute('href') ?? link.href, url).href,\n as: link.getAttribute('as') || undefined,\n }));\n\n const scripts = doc.querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src]',\n );\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (mounted) {\n if (rsc) {\n document.body.appendChild(rsc);\n }\n\n const newData = {\n ...metadata,\n links,\n remoteShared,\n url: url.href,\n data: rsc ? (rsc.textContent ?? '').split('\\n').filter(Boolean) : [],\n };\n setData(newData);\n\n loadRemoteComponent({\n url: new URL(url, location.origin),\n name,\n bundle,\n route: metadata.route,\n runtime: metadata.runtime,\n data: newData.data,\n nextData: undefined,\n scripts: Array.from(scripts).map((script) => ({\n src: new URL(\n script.getAttribute('data-src') ||\n script.getAttribute('src') ||\n script.src,\n url,\n ).href,\n })),\n shared: tryImportShared(),\n remoteShared,\n container: undefined,\n })\n .then((result) => {\n if (mounted) {\n if (result.error) {\n setRemoteComponent(result.error);\n } else {\n setRemoteComponent(result.component);\n }\n }\n })\n .catch((error: Error) => {\n if (mounted) {\n setRemoteComponent(error);\n }\n });\n }\n })().catch((error: Error) => {\n if (mounted) {\n setRemoteComponent(error);\n }\n });\n\n return () => {\n mounted = false;\n };\n }, [url, src, isolate, credentials, name]);\n\n if (remoteComponent instanceof Error) {\n throw remoteComponent;\n }\n\n const linksToRender: React.ReactNode[] | null =\n data?.links?.map((link) => (\n <link\n as={link.as as string}\n href={new URL(link.href as string, url).href}\n key={`${link.href as string}_${link.rel}`}\n rel={link.rel as string}\n />\n )) || null;\n const componentToRender = (\n <>\n {linksToRender}\n {remoteComponent ?? children}\n </>\n );\n\n if (isolate !== false) {\n return (\n <div id={`shadowroot_${name}`} ref={shadowRootContainerRef}>\n {shadowRoot ? createPortal(componentToRender, shadowRoot) : null}\n </div>\n );\n }\n\n return componentToRender;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAoOM;AAlON,mBAAqD;AACrD,uBAA6B;AAE7B,8BAIO;AAEP,eAAe,kBAAkB;AAC/B,MAAI;AACF,UAAM,EAAE,OAAO,IAAI,MAAM,OAAO,gCAAgC;AAChE,WAAO;AAAA,EACT,QAAE;AACA,WAAO,CAAC;AAAA,EACV;AACF;AAEO,SAAS,gBAAgB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd,OAAO;AAAA,EACP;AACF,GAMG;AACD,QAAM,CAAC,MAAM,OAAO,QAAI,uBAGd,IAAI;AACd,QAAM,CAAC,iBAAiB,kBAAkB,QAAI,uBAE5C,IAAI;AACN,QAAM,6BAAyB,qBAA8B,IAAI;AACjE,QAAM,CAAC,YAAY,aAAa,QAAI,uBAA4B,IAAI;AAEpE,8BAAU,MAAM;AACd,QAAI,uBAAuB,SAAS;AAElC,YAAM,SAAS,uBAAuB,QAAQ,aAAa;AAAA,QACzD,MAAM;AAAA,MACR,CAAC;AACD,oBAAc,MAAM;AAAA,IACtB;AAAA,EACF,GAAG,CAAC,sBAAsB,CAAC;AAE3B,QAAM,UAAM;AAAA,IACV,MACE,OAAO,aAAa,cAChB,IAAI,IAAI,KAAK,SAAS,IAAI,IAC1B,IAAI,IAAI,GAAG;AAAA,IACjB,CAAC,GAAG;AAAA,EACN;AAEA,8BAAU,MAAM;AACd,QAAI,U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