remote-components 0.3.3 → 0.3.4

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.
Files changed (157) hide show
  1. package/dist/config/nextjs.cjs +86 -37
  2. package/dist/config/nextjs.cjs.map +1 -1
  3. package/dist/config/nextjs.js +86 -37
  4. package/dist/config/nextjs.js.map +1 -1
  5. package/dist/config/webpack.cjs +5 -1
  6. package/dist/config/webpack.cjs.map +1 -1
  7. package/dist/config/webpack.js +5 -1
  8. package/dist/config/webpack.js.map +1 -1
  9. package/dist/host/html.cjs +524 -338
  10. package/dist/host/html.cjs.map +1 -1
  11. package/dist/host/html.js +524 -338
  12. package/dist/host/html.js.map +1 -1
  13. package/dist/host/nextjs/app/client-only.cjs +462 -259
  14. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  15. package/dist/host/nextjs/app/client-only.js +436 -233
  16. package/dist/host/nextjs/app/client-only.js.map +1 -1
  17. package/dist/host/react.cjs +403 -228
  18. package/dist/host/react.cjs.map +1 -1
  19. package/dist/host/react.js +403 -228
  20. package/dist/host/react.js.map +1 -1
  21. package/dist/internal/config/webpack/apply-shared-modules.cjs +6 -4
  22. package/dist/internal/config/webpack/apply-shared-modules.cjs.map +1 -1
  23. package/dist/internal/config/webpack/apply-shared-modules.js +6 -4
  24. package/dist/internal/config/webpack/apply-shared-modules.js.map +1 -1
  25. package/dist/internal/config/webpack/next-client-pages-loader.cjs +6 -7
  26. package/dist/internal/config/webpack/next-client-pages-loader.cjs.map +1 -1
  27. package/dist/internal/config/webpack/next-client-pages-loader.js +6 -7
  28. package/dist/internal/config/webpack/next-client-pages-loader.js.map +1 -1
  29. package/dist/internal/host/nextjs/app-client.cjs +4 -3
  30. package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
  31. package/dist/internal/host/nextjs/app-client.js +4 -3
  32. package/dist/internal/host/nextjs/app-client.js.map +1 -1
  33. package/dist/internal/host/nextjs/dom-flight.cjs +19 -39
  34. package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
  35. package/dist/internal/host/nextjs/dom-flight.js +31 -39
  36. package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
  37. package/dist/internal/host/nextjs/image-shared.cjs +39 -3
  38. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  39. package/dist/internal/host/nextjs/image-shared.d.ts +5 -10
  40. package/dist/internal/host/nextjs/image-shared.js +29 -3
  41. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  42. package/dist/internal/host/server/fetch-remote-component.cjs +2 -1
  43. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  44. package/dist/internal/host/server/fetch-remote-component.js +2 -1
  45. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  46. package/dist/internal/host/shared/polyfill.cjs +8 -7
  47. package/dist/internal/host/shared/polyfill.cjs.map +1 -1
  48. package/dist/internal/host/shared/polyfill.js +8 -7
  49. package/dist/internal/host/shared/polyfill.js.map +1 -1
  50. package/dist/internal/host/shared/shared-module-resolver.cjs +117 -0
  51. package/dist/internal/host/shared/shared-module-resolver.cjs.map +1 -0
  52. package/dist/internal/host/shared/shared-module-resolver.d.ts +64 -0
  53. package/dist/internal/host/shared/shared-module-resolver.js +78 -0
  54. package/dist/internal/host/shared/shared-module-resolver.js.map +1 -0
  55. package/dist/internal/remote/nextjs/next-internals.cjs +53 -0
  56. package/dist/internal/remote/nextjs/next-internals.cjs.map +1 -0
  57. package/dist/internal/remote/nextjs/next-internals.d.ts +42 -0
  58. package/dist/internal/remote/nextjs/next-internals.js +26 -0
  59. package/dist/internal/remote/nextjs/next-internals.js.map +1 -0
  60. package/dist/internal/runtime/html/apply-origin.cjs +11 -32
  61. package/dist/internal/runtime/html/apply-origin.cjs.map +1 -1
  62. package/dist/internal/runtime/html/apply-origin.js +11 -32
  63. package/dist/internal/runtime/html/apply-origin.js.map +1 -1
  64. package/dist/internal/runtime/html/html-spec.cjs +78 -0
  65. package/dist/internal/runtime/html/html-spec.cjs.map +1 -0
  66. package/dist/internal/runtime/html/html-spec.d.ts +23 -0
  67. package/dist/internal/runtime/html/html-spec.js +41 -0
  68. package/dist/internal/runtime/html/html-spec.js.map +1 -0
  69. package/dist/internal/runtime/html/parse-remote-html.cjs +15 -12
  70. package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
  71. package/dist/internal/runtime/html/parse-remote-html.js +29 -12
  72. package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
  73. package/dist/internal/runtime/html/rewrite-srcset.cjs +38 -0
  74. package/dist/internal/runtime/html/rewrite-srcset.cjs.map +1 -0
  75. package/dist/internal/runtime/html/rewrite-srcset.d.ts +12 -0
  76. package/dist/internal/runtime/html/rewrite-srcset.js +14 -0
  77. package/dist/internal/runtime/html/rewrite-srcset.js.map +1 -0
  78. package/dist/internal/runtime/loaders/component-loader.cjs +25 -44
  79. package/dist/internal/runtime/loaders/component-loader.cjs.map +1 -1
  80. package/dist/internal/runtime/loaders/component-loader.d.ts +3 -1
  81. package/dist/internal/runtime/loaders/component-loader.js +28 -44
  82. package/dist/internal/runtime/loaders/component-loader.js.map +1 -1
  83. package/dist/internal/runtime/loaders/static-loader.cjs +15 -21
  84. package/dist/internal/runtime/loaders/static-loader.cjs.map +1 -1
  85. package/dist/internal/runtime/loaders/static-loader.d.ts +3 -1
  86. package/dist/internal/runtime/loaders/static-loader.js +15 -21
  87. package/dist/internal/runtime/loaders/static-loader.js.map +1 -1
  88. package/dist/internal/runtime/namespace.cjs +82 -0
  89. package/dist/internal/runtime/namespace.cjs.map +1 -0
  90. package/dist/internal/runtime/namespace.d.ts +5 -0
  91. package/dist/internal/runtime/namespace.js +58 -0
  92. package/dist/internal/runtime/namespace.js.map +1 -0
  93. package/dist/internal/runtime/rsc-imports.cjs +86 -0
  94. package/dist/internal/runtime/rsc-imports.cjs.map +1 -0
  95. package/dist/internal/runtime/rsc-imports.d.ts +39 -0
  96. package/dist/internal/runtime/rsc-imports.js +50 -0
  97. package/dist/internal/runtime/rsc-imports.js.map +1 -0
  98. package/dist/internal/runtime/rsc-runtime.cjs +17 -0
  99. package/dist/internal/runtime/rsc-runtime.cjs.map +1 -0
  100. package/dist/internal/runtime/rsc-runtime.d.ts +37 -0
  101. package/dist/internal/runtime/rsc-runtime.js +1 -0
  102. package/dist/internal/runtime/rsc-runtime.js.map +1 -0
  103. package/dist/internal/runtime/rsc.cjs +23 -12
  104. package/dist/internal/runtime/rsc.cjs.map +1 -1
  105. package/dist/internal/runtime/rsc.d.ts +19 -2
  106. package/dist/internal/runtime/rsc.js +20 -11
  107. package/dist/internal/runtime/rsc.js.map +1 -1
  108. package/dist/internal/runtime/turbopack/chunk-loader.cjs +53 -35
  109. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  110. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +1 -1
  111. package/dist/internal/runtime/turbopack/chunk-loader.js +53 -35
  112. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  113. package/dist/internal/runtime/turbopack/module.cjs +17 -4
  114. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  115. package/dist/internal/runtime/turbopack/module.d.ts +23 -1
  116. package/dist/internal/runtime/turbopack/module.js +16 -4
  117. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  118. package/dist/internal/runtime/turbopack/patterns.cjs +26 -10
  119. package/dist/internal/runtime/turbopack/patterns.cjs.map +1 -1
  120. package/dist/internal/runtime/turbopack/patterns.d.ts +44 -49
  121. package/dist/internal/runtime/turbopack/patterns.js +23 -7
  122. package/dist/internal/runtime/turbopack/patterns.js.map +1 -1
  123. package/dist/internal/runtime/turbopack/{webpack-runtime.cjs → remote-scope-setup.cjs} +35 -32
  124. package/dist/internal/runtime/turbopack/remote-scope-setup.cjs.map +1 -0
  125. package/dist/internal/runtime/turbopack/remote-scope-setup.d.ts +25 -0
  126. package/dist/internal/runtime/turbopack/{webpack-runtime.js → remote-scope-setup.js} +36 -19
  127. package/dist/internal/runtime/turbopack/remote-scope-setup.js.map +1 -0
  128. package/dist/internal/runtime/turbopack/remote-scope.cjs +4 -6
  129. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -1
  130. package/dist/internal/runtime/turbopack/remote-scope.d.ts +20 -1
  131. package/dist/internal/runtime/turbopack/remote-scope.js +4 -6
  132. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -1
  133. package/dist/internal/runtime/turbopack/shared-modules.cjs +21 -15
  134. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  135. package/dist/internal/runtime/turbopack/shared-modules.d.ts +9 -2
  136. package/dist/internal/runtime/turbopack/shared-modules.js +24 -18
  137. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  138. package/dist/internal/runtime/types.cjs.map +1 -1
  139. package/dist/internal/runtime/types.d.ts +5 -41
  140. package/dist/internal/utils/logger.cjs +1 -1
  141. package/dist/internal/utils/logger.cjs.map +1 -1
  142. package/dist/internal/utils/logger.d.ts +2 -2
  143. package/dist/internal/utils/logger.js +1 -1
  144. package/dist/internal/utils/logger.js.map +1 -1
  145. package/dist/remote/html.cjs +78 -22
  146. package/dist/remote/html.cjs.map +1 -1
  147. package/dist/remote/html.js +78 -22
  148. package/dist/remote/html.js.map +1 -1
  149. package/dist/remote/nextjs/app.cjs +14 -55
  150. package/dist/remote/nextjs/app.cjs.map +1 -1
  151. package/dist/remote/nextjs/app.js +24 -45
  152. package/dist/remote/nextjs/app.js.map +1 -1
  153. package/dist/types-59251814.d.ts +94 -0
  154. package/package.json +1 -1
  155. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +0 -1
  156. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +0 -23
  157. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +0 -1
@@ -51,7 +51,15 @@ var RemoteComponentsError = class extends Error {
51
51
 
52
52
  // src/utils/logger.ts
53
53
  var PREFIX = "remote-components";
54
- var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
54
+ var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
55
+ function logDebug(location2, message) {
56
+ if (DEBUG) {
57
+ console.debug(`[${PREFIX}:${location2}]: ${message}`);
58
+ }
59
+ }
60
+ function logWarn(location2, message) {
61
+ console.warn(`[${PREFIX}:${location2}]: ${message}`);
62
+ }
55
63
  function logError(location2, message, cause) {
56
64
  console.error(
57
65
  new RemoteComponentsError(`[${PREFIX}:${location2}]: ${message}`, {
@@ -60,6 +68,28 @@ function logError(location2, message, cause) {
60
68
  );
61
69
  }
62
70
 
71
+ // src/host/shared/polyfill.tsx
72
+ var import_jsx_runtime = require("react/jsx-runtime");
73
+
74
+ // src/host/shared/shared-module-resolver.ts
75
+ var CORE_REACT_SHARED_KEYS = [
76
+ "react",
77
+ "react/jsx-dev-runtime",
78
+ "react/jsx-runtime",
79
+ "react-dom",
80
+ "react-dom/client"
81
+ ];
82
+ var CORE_REACT_PATH_MAP = {
83
+ react: "/react/index.js",
84
+ "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
85
+ "react/jsx-runtime": "/react/jsx-runtime.js",
86
+ "react-dom": "/react-dom/index.js",
87
+ "react-dom/client": "/react-dom/client.js"
88
+ };
89
+ var VENDOR_SHARED = Object.fromEntries(
90
+ Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
91
+ );
92
+
63
93
  // src/utils/project-id.ts
64
94
  var import_node_fs = require("fs");
65
95
  var import_find_up = require("find-up");
@@ -224,7 +254,11 @@ __webpack_require__.l = function __remote_webpack_require_l__(url, done, key, ch
224
254
  const bundle = match?.groups?.bundle;
225
255
  const id = match?.groups?.id;
226
256
  if (!(id && bundle)) {
227
- return __webpack_require_l__(new URL(url, globalThis.__remote_bundle_url__?.["${this.appName}"] ?? location.origin).href, done, key, chunkId);
257
+ // __remote_bundle_url__[appName] is the *host app's own* asset base URL
258
+ // (set by the HTML host or setupWebpackRuntime). It is NOT a remote
259
+ // bundle URL \u2014 it just ensures the host's own chunks resolve correctly
260
+ // when the page is served from a CDN or different origin.
261
+ return __webpack_require_l__(new URL(url, globalThis.__remote_bundle_url__?.["${this.appName}"] ?? location.origin).href, done, key, chunkId);
228
262
  }
229
263
  return done();
230
264
  };
@@ -331,6 +365,23 @@ function transform(nextConfig, {
331
365
  }
332
366
 
333
367
  // src/config/nextjs/index.ts
368
+ function getNextMajorVersion() {
369
+ try {
370
+ const nextPkgPath = (0, import_find_up2.findUpSync)("node_modules/next/package.json", {
371
+ cwd: process.cwd()
372
+ });
373
+ if (!nextPkgPath)
374
+ return void 0;
375
+ const { version } = JSON.parse((0, import_node_fs2.readFileSync)(nextPkgPath, "utf8"));
376
+ const major = version.split(".")[0];
377
+ return major ? Number.parseInt(major, 10) : void 0;
378
+ } catch {
379
+ return void 0;
380
+ }
381
+ }
382
+ function hasPagesDirectory() {
383
+ return (0, import_node_fs2.existsSync)((0, import_node_path3.join)(process.cwd(), "pages")) || (0, import_node_fs2.existsSync)((0, import_node_path3.join)(process.cwd(), "src/pages"));
384
+ }
334
385
  function readProjectPackageJson() {
335
386
  const defaults = { name: (0, import_node_path3.basename)(process.cwd()), type: "module" };
336
387
  try {
@@ -365,46 +416,29 @@ function withRemoteComponentsConfig(nextConfig, options) {
365
416
  ".remote-components/shared/pages-host.tsx"
366
417
  );
367
418
  const appShared = /* @__PURE__ */ new Set([
368
- ...[
369
- "react",
370
- "react/jsx-dev-runtime",
371
- "react/jsx-runtime",
372
- "react-dom",
373
- "react-dom/client",
374
- "next/navigation",
375
- "next/dist/client/components/navigation",
376
- "next/link",
377
- "next/dist/client/app-dir/link",
378
- "next/form",
379
- "next/dist/client/app-dir/form",
380
- "next/dist/shared/lib/image-loader",
381
- "next/script",
382
- "next/dist/client/script",
383
- "next/dist/build/polyfills/process"
384
- ],
419
+ ...CORE_REACT_SHARED_KEYS,
420
+ "next/navigation",
421
+ "next/dist/client/components/navigation",
422
+ "next/link",
423
+ "next/dist/client/app-dir/link",
424
+ "next/form",
425
+ "next/dist/client/app-dir/form",
426
+ "next/dist/shared/lib/image-loader",
427
+ "next/script",
428
+ "next/dist/client/script",
429
+ "next/dist/build/polyfills/process",
385
430
  ...options?.shared ?? []
386
431
  ]);
387
432
  const pagesShared = /* @__PURE__ */ new Set([
388
- ...[
389
- "react",
390
- "react/jsx-dev-runtime",
391
- "react/jsx-runtime",
392
- "react-dom",
393
- "react-dom/client",
394
- "next/router",
395
- "next/link",
396
- "next/dist/shared/lib/image-loader",
397
- "next/script",
398
- "next/form"
399
- ],
433
+ ...CORE_REACT_SHARED_KEYS,
434
+ "next/router",
435
+ "next/link",
436
+ "next/dist/shared/lib/image-loader",
437
+ "next/script",
438
+ "next/form",
400
439
  ...options?.shared ?? []
401
440
  ]);
402
- const vendorShared = {
403
- react: `'/react/index.js'`,
404
- "react/jsx-dev-runtime": `'/react/jsx-dev-runtime.js'`,
405
- "react/jsx-runtime": `'/react/jsx-runtime.js'`,
406
- "react-dom": `'/react-dom/index.js'`
407
- };
441
+ const vendorShared = { ...VENDOR_SHARED };
408
442
  const resolve = import_enhanced_resolve.default.create.sync({
409
443
  conditionNames: ["browser", "import", "module", "require"],
410
444
  ...(0, import_node_fs2.existsSync)((0, import_node_path3.join)(process.cwd(), "tsconfig.json")) ? {
@@ -500,6 +534,21 @@ ${exportPre}${Array.from(sharedHost).reduce((acc, curr) => {
500
534
  };
501
535
  const projectId = resolveProjectId(packageJson.name);
502
536
  process.env.REMOTE_COMPONENTS_PROJECT_ID = projectId;
537
+ if (hasPagesDirectory()) {
538
+ if (process.env.TURBOPACK) {
539
+ throw new RemoteComponentsError(
540
+ "Remote Components does not support Next.js Pages Router with Turbopack. Use webpack instead (`next dev` / `next build` without `--turbo`)."
541
+ );
542
+ }
543
+ const nextMajor = getNextMajorVersion();
544
+ if (nextMajor !== void 0 && nextMajor < 16) {
545
+ const log = process.env.NODE_ENV !== "production" || process.env.VERCEL_ENV === "preview" ? logWarn : logDebug;
546
+ log(
547
+ "Config",
548
+ `Remote Components does not support Pages Router hosts on Next.js ${nextMajor}. Pages Router remotes are unaffected. Upgrade to Next.js 16+ for host support.`
549
+ );
550
+ }
551
+ }
503
552
  if (process.env.TURBOPACK) {
504
553
  if (!import_config_schema.configSchema.safeParse({
505
554
  turbopack: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/nextjs/index.ts","../../src/utils/error.ts","../../src/utils/logger.ts","../../src/utils/project-id.ts","../../src/utils/project-id-env.ts","../../src/config/webpack/nextjs.ts","../../src/config/webpack/plugins/conditional-exec.ts","../../src/config/webpack/plugins/module-id-embed.ts","../../src/config/webpack/plugins/module-id-embed-runtime-module.ts","../../src/config/webpack/plugins/patch-require.ts","../../src/config/webpack/plugins/remote-webpack-require-runtime-module.ts","../../src/config/webpack/plugins/remote-webpack-require.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, dirname, join, relative } from 'node:path';\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 { logError } from '#internal/utils/logger';\nimport { resolveProjectId } from '#internal/utils/project-id';\nimport { transform as webpackTransform } from '../webpack/nextjs';\n\ninterface ZodSchema {\n safeParse: (data: unknown) => { success: boolean };\n}\n\nfunction readProjectPackageJson(): { name: string; type: string } {\n const defaults = { name: basename(process.cwd()), type: 'module' };\n try {\n const packageJsonPath = findUpSync('package.json', {\n cwd: process.cwd(),\n });\n if (packageJsonPath) {\n return {\n ...defaults,\n ...(JSON.parse(readFileSync(packageJsonPath, 'utf8')) as {\n name: string;\n type: string;\n }),\n };\n }\n } catch {\n // noop\n }\n return defaults;\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` (loader only), 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 { withRemoteComponentsConfig } from 'remote-components/config/nextjs';\n *\n * const nextConfig = {\n * // your Next.js configuration\n * };\n *\n * export default withRemoteComponentsConfig(\n * withMicrofrontends(nextConfig),\n * {\n * shared: ['some-package', 'another-package'],\n * },\n * );\n * ```\n */\nexport function withRemoteComponentsConfig(\n nextConfig: NextConfig,\n options?: WithRemoteComponentsOptions,\n) {\n const virtualRemoteComponentAppSharedRemote = join(\n process.cwd(),\n '.remote-components/shared/app-remote.tsx',\n );\n const virtualRemoteComponentPagesSharedRemote = join(\n process.cwd(),\n '.remote-components/shared/pages-remote.tsx',\n );\n const virtualRemoteComponentAppSharedHost = join(\n process.cwd(),\n '.remote-components/shared/app-host.tsx',\n );\n const virtualRemoteComponentPagesSharedHost = join(\n process.cwd(),\n '.remote-components/shared/pages-host.tsx',\n );\n\n const appShared = 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/dist/client/components/navigation',\n 'next/link',\n 'next/dist/client/app-dir/link',\n 'next/form',\n 'next/dist/client/app-dir/form',\n 'next/dist/shared/lib/image-loader',\n 'next/script',\n 'next/dist/client/script',\n 'next/dist/build/polyfills/process',\n ],\n ...(options?.shared ?? []),\n ]);\n const pagesShared = new Set([\n ...[\n 'react',\n 'react/jsx-dev-runtime',\n 'react/jsx-runtime',\n 'react-dom',\n 'react-dom/client',\n 'next/router',\n 'next/link',\n 'next/dist/shared/lib/image-loader',\n 'next/script',\n 'next/form',\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\n const packageJson = readProjectPackageJson();\n\n const exportPre =\n packageJson.type !== 'module'\n ? 'module.exports = { shared: { '\n : 'export const shared = { ';\n const exportPost = packageJson.type !== 'module' ? '} };\\n' : '};\\n';\n\n const resolveSharedPath = (moduleName: string): string | undefined => {\n try {\n const resolved = resolve(process.cwd(), moduleName);\n if (resolved) {\n return relative(process.cwd(), resolved).replace(\n /^(?<relative>\\.\\.\\/)+/,\n '',\n );\n }\n } catch {\n // if module resolution using enhanced-resolve fails, fallback to require.resolve called in the shared/remote file\n }\n };\n\n const generateSharedRemote = (sharedRemote: Set<string>) =>\n `'use client';\\n${exportPre}${Array.from(sharedRemote)\n .reduce<string[]>((acc, curr) => {\n const path = resolveSharedPath(curr);\n acc.push(\n `[${\n vendorShared[curr] ??\n (path ? `'${path}'` : `require.resolve('${curr}')`)\n }]: '${curr}',`,\n );\n acc.push(\n `['__remote_shared_module_${curr}']: () => import('${curr}'),`,\n );\n return acc;\n }, [])\n .join('\\n')}${exportPost}`;\n const generateSharedHost = (sharedHost: Set<string>) =>\n `'use client';\\n${exportPre}${Array.from(sharedHost)\n .reduce<string[]>((acc, curr) => {\n acc.push(`['${curr}']: () => import('${curr}'),`);\n return acc;\n }, [])\n .join('\\n')}${exportPost}`;\n\n const appSharedRemote = generateSharedRemote(appShared);\n const pagesSharedRemote = generateSharedRemote(pagesShared);\n\n const appSharedHost = generateSharedHost(appShared);\n const pagesSharedHost = generateSharedHost(pagesShared);\n\n const emitSharedFiles = () => {\n mkdirSync(dirname(virtualRemoteComponentAppSharedRemote), {\n recursive: true,\n });\n\n writeFileSync(\n virtualRemoteComponentAppSharedRemote,\n appSharedRemote,\n 'utf-8',\n );\n writeFileSync(\n virtualRemoteComponentPagesSharedRemote,\n pagesSharedRemote,\n 'utf-8',\n );\n writeFileSync(virtualRemoteComponentAppSharedHost, appSharedHost, 'utf-8');\n writeFileSync(\n virtualRemoteComponentPagesSharedHost,\n pagesSharedHost,\n 'utf-8',\n );\n };\n\n nextConfig.transpilePackages = [\n ...(nextConfig.transpilePackages ?? []),\n 'remote-components',\n ];\n\n nextConfig.env = {\n ...nextConfig.env,\n REMOTE_COMPONENTS_CONFIGURED: '1',\n };\n\n const alias = {\n '#remote-components/remote/defaults/app': `./${relative(\n process.cwd(),\n virtualRemoteComponentAppSharedRemote,\n )}`,\n '#remote-components/remote/defaults/pages': `./${relative(\n process.cwd(),\n virtualRemoteComponentPagesSharedRemote,\n )}`,\n '#remote-components/host/defaults/app': `./${relative(\n process.cwd(),\n virtualRemoteComponentAppSharedHost,\n )}`,\n '#remote-components/host/defaults/pages': `./${relative(\n process.cwd(),\n virtualRemoteComponentPagesSharedHost,\n )}`,\n };\n\n const projectId = resolveProjectId(packageJson.name);\n process.env.REMOTE_COMPONENTS_PROJECT_ID = projectId;\n\n if (process.env.TURBOPACK) {\n if (\n !(configSchema as ZodSchema).safeParse({\n turbopack: {\n resolveAlias: {\n ...alias,\n },\n },\n compiler: {\n defineServer: {\n REMOTE_COMPONENTS_PROJECT_ID: projectId,\n },\n },\n }).success\n ) {\n logError(\n 'Config',\n 'Turbopack support requires a Next.js version that includes `compiler.defineServer`. ' +\n 'Upgrade Next.js to continue using Remote Components with Turbopack.',\n );\n process.exit(1);\n }\n nextConfig.turbopack = {\n ...nextConfig.turbopack,\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 { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport { isAbortError } from '#internal/utils/abort';\nimport {\n CORS_DOCS_URL,\n RC_PROTECTED_REMOTE_FETCH_PATHNAME,\n} from '#internal/utils/constants';\n\nexport class RemoteComponentsError extends Error {\n code = 'REMOTE_COMPONENTS_ERROR';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'RemoteComponentsError';\n }\n}\n\nexport function multipleRemoteComponentsError(url: string | undefined) {\n return new RemoteComponentsError(\n `Multiple Remote Components found at \"${url}\". When a page exposes multiple Remote Components you must specify the \"name\" prop to select which one to load.`,\n );\n}\n\nexport function failedToFetchRemoteComponentError(\n url: string,\n { status, statusText }: { status: number; statusText: string },\n help: string = 'Is the URL correct and accessible?',\n) {\n return new RemoteComponentsError(\n `Failed to fetch Remote Component from \"${url}\". ${help}`,\n { cause: new Error(`${status} ${statusText}`) },\n );\n}\n\nexport async function errorFromFailedFetch(\n originalUrl: string,\n resolvedUrl: URL,\n res: Response | null | undefined,\n): Promise<RemoteComponentsError> {\n const isProxied = isProxiedUrl(resolvedUrl.href);\n\n if (isProxied && res) {\n const body = await res.text().catch(() => '');\n return failedProxyFetchError(\n originalUrl,\n resolvedUrl.href,\n res.status,\n body,\n );\n }\n\n const fallback = failedToFetchRemoteComponentError(\n originalUrl,\n res ?? { status: 0, statusText: 'No Response' },\n );\n\n if (!res) return fallback;\n\n try {\n const body = await res.text();\n const parser = new DOMParser();\n const doc = parser.parseFromString(body, 'text/html');\n const errorTemplate = doc.querySelector(\n 'template[data-next-error-message]',\n );\n const errorMessage = errorTemplate?.getAttribute('data-next-error-message');\n if (errorMessage) {\n const error = new RemoteComponentsError(errorMessage);\n const errorStack = errorTemplate?.getAttribute('data-next-error-stack');\n if (errorStack) {\n error.stack = errorStack;\n }\n return error;\n }\n } catch (parseError) {\n // Re-throw abort errors, ignore parse errors\n if (isAbortError(parseError)) throw parseError;\n }\n\n return fallback;\n}\n\nexport function failedProxiedAssetError(\n kind: 'chunk' | 'script',\n url: string,\n resolvedUrl: string,\n): RemoteComponentsError {\n return new RemoteComponentsError(\n `Failed to load ${kind} \"${url}\" via proxy \"${resolvedUrl}\". ` +\n `Ensure withRemoteComponentsHostProxy middleware is configured, \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" is in the matcher, ` +\n `and the remote URL is included in allowedProxyUrls. ` +\n `See: ${CORS_DOCS_URL}`,\n );\n}\n\nexport function failedProxyFetchError(\n originalUrl: string,\n proxyUrl: string,\n status: number,\n responseBody?: string,\n): RemoteComponentsError {\n if (status === 404) {\n return new RemoteComponentsError(\n `Could not proxy the request to \"${originalUrl}\" — the proxy endpoint \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" returned 404.\\n\\n` +\n `The host server needs middleware or a route that handles \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\".\\n\\n` +\n `Proxying requires two pieces:\\n` +\n ` 1. resolveClientUrl={routeThroughHostProxy} on <RemoteComponent>\\n` +\n ` 2. Middleware or a route for \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" on the host server\\n\\n` +\n `Docs: ${CORS_DOCS_URL}`,\n );\n }\n if (status === 403) {\n const detail = responseBody ? ` ${responseBody}` : '';\n return new RemoteComponentsError(\n `Proxied request to \"${proxyUrl}\" was forbidden.${detail} ` +\n `See: ${CORS_DOCS_URL}`,\n );\n }\n return new RemoteComponentsError(\n `Proxied request for \"${originalUrl}\" via \"${proxyUrl}\" failed with status ${status}. ` +\n `See: ${CORS_DOCS_URL}`,\n );\n}\n","import { CORS_DOCS_URL } from '#internal/utils/constants';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\ntype LogLocation =\n | 'ChunkLoader'\n | 'ChunkDispatcher'\n | 'ComponentLoader'\n | 'ModuleDispatcher'\n | 'RemoteScope'\n | 'SharedModules'\n | 'WebpackRuntime'\n | 'TurbopackModule'\n | 'StaticLoader'\n | 'ScriptLoader'\n | 'Polyfill'\n | 'HtmlRemote'\n | 'HtmlHost'\n | 'Config'\n | 'NextAppRouter'\n | 'NextAppRouterCompat'\n | 'FetchRemoteComponent';\n\nconst PREFIX = 'remote-components';\nconst DEBUG =\n typeof window !== 'undefined' && localStorage.getItem('RC_DEBUG') === 'true';\n\nexport function logDebug(location: LogLocation, message: string) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.debug(`[${PREFIX}:${location}]: ${message}`);\n }\n}\n\nexport function logInfo(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.info(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logWarn(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.warn(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logError(\n location: LogLocation,\n message: string,\n cause?: unknown,\n) {\n // eslint-disable-next-line no-console\n console.error(\n new RemoteComponentsError(`[${PREFIX}:${location}]: ${message}`, {\n cause,\n }),\n );\n}\n\n/**\n * Logs a warning when a cross-origin asset request fails, guiding users\n * to configure the proxy middleware and resolveClientUrl on their host.\n */\nexport function warnCrossOriginFetchError(\n logLocation: LogLocation,\n url: string | URL,\n): void {\n try {\n const parsed = typeof url === 'string' ? new URL(url) : url;\n if (typeof location === 'undefined' || parsed.origin === location.origin) {\n return;\n }\n logWarn(\n logLocation,\n `Failed to fetch cross-origin resource \"${parsed.href}\". ` +\n 'To load assets from a protected deployment, two steps are required: ' +\n '(1) configure withRemoteComponentsHostProxy middleware in your host with the remote URL in allowedProxyUrls, ' +\n 'and (2) provide a resolveClientUrl prop that rewrites cross-origin asset URLs to go through the proxy. ' +\n `See: ${CORS_DOCS_URL}`,\n );\n } catch {\n // URL parsing failed — skip the warning\n }\n}\n","import { readFileSync } from 'node:fs';\nimport { findUpSync } from 'find-up';\nimport { resolveProjectIdFromEnv } from './project-id-env';\n\n/**\n * Resolves the project ID using environment variables first, then\n * falling back to `.vercel/project.json` and finally the package name.\n * Node-only — requires file system access.\n */\nexport function resolveProjectId(packageName: string): string {\n const fromEnv = resolveProjectIdFromEnv();\n if (fromEnv) return fromEnv;\n\n try {\n const projectPath = findUpSync('.vercel/project.json', {\n cwd: process.cwd(),\n });\n if (projectPath) {\n return (\n JSON.parse(readFileSync(projectPath, 'utf8')) as { projectId: string }\n ).projectId;\n }\n } catch {\n // fallback below\n }\n\n return packageName;\n}\n","/**\n * Resolves the project ID from environment variables only.\n * Safe for edge/browser contexts where file system access is unavailable.\n */\nexport function resolveProjectIdFromEnv(): string | undefined {\n return (\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID ||\n undefined\n );\n}\n","import { join } from 'node:path';\nimport type { NextConfig } from 'next';\nimport type { WebpackOptionsNormalized } from 'webpack';\nimport { ConditionalExecPlugin } from './plugins/conditional-exec';\nimport { ModuleIdEmbedPlugin } from './plugins/module-id-embed';\nimport { PatchRequirePlugin } from './plugins/patch-require';\nimport { RemoteWebpackRequirePlugin } from './plugins/remote-webpack-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, { isServer: webpackContext.isServer }),\n new ConditionalExecPlugin(app.name),\n new PatchRequirePlugin(app.name),\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","import type { Compiler } from 'webpack';\n\nexport class ConditionalExecPlugin {\n appName: string;\n\n constructor(appName: string) {\n this.appName = appName;\n }\n\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__ && globalThis.__DISABLE_WEBPACK_EXEC__[\"${this.appName}\"]) 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 { relative } from 'node:path';\nimport type { Compiler, NormalModule, RuntimeModule } from 'webpack';\nimport { createModuleIdEmbedRuntimeModule } from './module-id-embed-runtime-module';\n\nconst cwd = process.cwd();\n\nexport class ModuleIdEmbedPlugin {\n appName: string;\n includeAllModules: boolean;\n isServer: boolean;\n\n constructor(\n appName: string,\n options?: { includeAllModules?: boolean; isServer?: boolean },\n ) {\n this.appName = appName;\n this.includeAllModules = options?.includeAllModules ?? false;\n this.isServer = options?.isServer ?? false;\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 mod of compilation.modules) {\n const id = compilation.chunkGraph.getModuleId(mod);\n if (\n id &&\n (this.includeAllModules ||\n mod.layer?.endsWith('browser') ||\n (!this.isServer && mod.layer === null))\n ) {\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\n// This plugin patches the webpack require function to support loading remote components in Next.js\nexport class PatchRequirePlugin {\n appName: string;\n\n constructor(appName: string) {\n this.appName = appName;\n }\n\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>[^\\\\]]+)\\\\] (?<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 const error = new Error(\\`Remote Components are not available in \"\\${bundle}\". Did you forget to wrap the Next.js config with \\\\\\`withRemoteComponentsConfig\\\\\\` on both host and remote?\\`);\n error.name = 'RemoteComponentsError';\n error.code = 'REMOTE_COMPONENTS_ERROR';\n throw error;\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__(new URL(url, globalThis.__remote_bundle_url__?.[\"${this.appName}\"] ?? location.origin).href, 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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AA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A,wCAAwC,SAAK;AAAA,MAC3C,QAAQ,IAAI;AAAA,MACZ;AAAA,IACF;AAAA,IACA,0CAA0C,SAAK;AAAA,MAC7C,QAAQ,IAAI;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AAEA,QAAM,YAAY,iBAAiB,YAAY,IAAI;AACnD,UAAQ,IAAI,+BAA+B;AAE3C,MAAI,QAAQ,IAAI,WAAW;AACzB,QACE,CAAE,kCAA2B,UAAU;AAAA,MACrC,WAAW;AAAA,QACT,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;AACA;AAAA,QACE;AAAA,QACA;AAAA,MAEF;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,eAAW,YAAY;AAAA,MACrB,GAAG,WAAW;AAAA,MACd,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_fs","import_node_path","import_find_up","location","import_node_path","enhancedResolve","TsConfigPathsWebpackPlugin"]}
1
+ {"version":3,"sources":["../../src/config/nextjs/index.ts","../../src/utils/error.ts","../../src/utils/logger.ts","../../src/host/shared/polyfill.tsx","../../src/host/shared/shared-module-resolver.ts","../../src/utils/project-id.ts","../../src/utils/project-id-env.ts","../../src/config/webpack/nextjs.ts","../../src/config/webpack/plugins/conditional-exec.ts","../../src/config/webpack/plugins/module-id-embed.ts","../../src/config/webpack/plugins/module-id-embed-runtime-module.ts","../../src/config/webpack/plugins/patch-require.ts","../../src/config/webpack/plugins/remote-webpack-require-runtime-module.ts","../../src/config/webpack/plugins/remote-webpack-require.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, dirname, join, relative } from 'node:path';\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 {\n CORE_REACT_SHARED_KEYS,\n VENDOR_SHARED,\n} from '#internal/host/shared/shared-module-resolver';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { logDebug, logError, logWarn } from '#internal/utils/logger';\nimport { resolveProjectId } from '#internal/utils/project-id';\nimport { transform as webpackTransform } from '../webpack/nextjs';\n\nfunction getNextMajorVersion(): number | undefined {\n try {\n const nextPkgPath = findUpSync('node_modules/next/package.json', {\n cwd: process.cwd(),\n });\n if (!nextPkgPath) return undefined;\n const { version } = JSON.parse(readFileSync(nextPkgPath, 'utf8')) as {\n version: string;\n };\n const major = version.split('.')[0];\n return major ? Number.parseInt(major, 10) : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction hasPagesDirectory(): boolean {\n return (\n existsSync(join(process.cwd(), 'pages')) ||\n existsSync(join(process.cwd(), 'src/pages'))\n );\n}\n\ninterface ZodSchema {\n safeParse: (data: unknown) => { success: boolean };\n}\n\nfunction readProjectPackageJson(): { name: string; type: string } {\n const defaults = { name: basename(process.cwd()), type: 'module' };\n try {\n const packageJsonPath = findUpSync('package.json', {\n cwd: process.cwd(),\n });\n if (packageJsonPath) {\n return {\n ...defaults,\n ...(JSON.parse(readFileSync(packageJsonPath, 'utf8')) as {\n name: string;\n type: string;\n }),\n };\n }\n } catch {\n // noop\n }\n return defaults;\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` (loader only), 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 { withRemoteComponentsConfig } from 'remote-components/config/nextjs';\n *\n * const nextConfig = {\n * // your Next.js configuration\n * };\n *\n * export default withRemoteComponentsConfig(\n * withMicrofrontends(nextConfig),\n * {\n * shared: ['some-package', 'another-package'],\n * },\n * );\n * ```\n */\nexport function withRemoteComponentsConfig(\n nextConfig: NextConfig,\n options?: WithRemoteComponentsOptions,\n) {\n const virtualRemoteComponentAppSharedRemote = join(\n process.cwd(),\n '.remote-components/shared/app-remote.tsx',\n );\n const virtualRemoteComponentPagesSharedRemote = join(\n process.cwd(),\n '.remote-components/shared/pages-remote.tsx',\n );\n const virtualRemoteComponentAppSharedHost = join(\n process.cwd(),\n '.remote-components/shared/app-host.tsx',\n );\n const virtualRemoteComponentPagesSharedHost = join(\n process.cwd(),\n '.remote-components/shared/pages-host.tsx',\n );\n\n const appShared = new Set([\n ...CORE_REACT_SHARED_KEYS,\n 'next/navigation',\n 'next/dist/client/components/navigation',\n 'next/link',\n 'next/dist/client/app-dir/link',\n 'next/form',\n 'next/dist/client/app-dir/form',\n 'next/dist/shared/lib/image-loader',\n 'next/script',\n 'next/dist/client/script',\n 'next/dist/build/polyfills/process',\n ...(options?.shared ?? []),\n ]);\n const pagesShared = new Set([\n ...CORE_REACT_SHARED_KEYS,\n 'next/router',\n 'next/link',\n 'next/dist/shared/lib/image-loader',\n 'next/script',\n 'next/form',\n ...(options?.shared ?? []),\n ]);\n\n const vendorShared = { ...VENDOR_SHARED };\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\n const packageJson = readProjectPackageJson();\n\n const exportPre =\n packageJson.type !== 'module'\n ? 'module.exports = { shared: { '\n : 'export const shared = { ';\n const exportPost = packageJson.type !== 'module' ? '} };\\n' : '};\\n';\n\n const resolveSharedPath = (moduleName: string): string | undefined => {\n try {\n const resolved = resolve(process.cwd(), moduleName);\n if (resolved) {\n return relative(process.cwd(), resolved).replace(\n /^(?<relative>\\.\\.\\/)+/,\n '',\n );\n }\n } catch {\n // if module resolution using enhanced-resolve fails, fallback to require.resolve called in the shared/remote file\n }\n };\n\n const generateSharedRemote = (sharedRemote: Set<string>) =>\n `'use client';\\n${exportPre}${Array.from(sharedRemote)\n .reduce<string[]>((acc, curr) => {\n const path = resolveSharedPath(curr);\n acc.push(\n `[${\n vendorShared[curr] ??\n (path ? `'${path}'` : `require.resolve('${curr}')`)\n }]: '${curr}',`,\n );\n acc.push(\n `['__remote_shared_module_${curr}']: () => import('${curr}'),`,\n );\n return acc;\n }, [])\n .join('\\n')}${exportPost}`;\n const generateSharedHost = (sharedHost: Set<string>) =>\n `'use client';\\n${exportPre}${Array.from(sharedHost)\n .reduce<string[]>((acc, curr) => {\n acc.push(`['${curr}']: () => import('${curr}'),`);\n return acc;\n }, [])\n .join('\\n')}${exportPost}`;\n\n const appSharedRemote = generateSharedRemote(appShared);\n const pagesSharedRemote = generateSharedRemote(pagesShared);\n\n const appSharedHost = generateSharedHost(appShared);\n const pagesSharedHost = generateSharedHost(pagesShared);\n\n const emitSharedFiles = () => {\n mkdirSync(dirname(virtualRemoteComponentAppSharedRemote), {\n recursive: true,\n });\n\n writeFileSync(\n virtualRemoteComponentAppSharedRemote,\n appSharedRemote,\n 'utf-8',\n );\n writeFileSync(\n virtualRemoteComponentPagesSharedRemote,\n pagesSharedRemote,\n 'utf-8',\n );\n writeFileSync(virtualRemoteComponentAppSharedHost, appSharedHost, 'utf-8');\n writeFileSync(\n virtualRemoteComponentPagesSharedHost,\n pagesSharedHost,\n 'utf-8',\n );\n };\n\n nextConfig.transpilePackages = [\n ...(nextConfig.transpilePackages ?? []),\n 'remote-components',\n ];\n\n nextConfig.env = {\n ...nextConfig.env,\n REMOTE_COMPONENTS_CONFIGURED: '1',\n };\n\n const alias = {\n '#remote-components/remote/defaults/app': `./${relative(\n process.cwd(),\n virtualRemoteComponentAppSharedRemote,\n )}`,\n '#remote-components/remote/defaults/pages': `./${relative(\n process.cwd(),\n virtualRemoteComponentPagesSharedRemote,\n )}`,\n '#remote-components/host/defaults/app': `./${relative(\n process.cwd(),\n virtualRemoteComponentAppSharedHost,\n )}`,\n '#remote-components/host/defaults/pages': `./${relative(\n process.cwd(),\n virtualRemoteComponentPagesSharedHost,\n )}`,\n };\n\n const projectId = resolveProjectId(packageJson.name);\n process.env.REMOTE_COMPONENTS_PROJECT_ID = projectId;\n\n if (hasPagesDirectory()) {\n if (process.env.TURBOPACK) {\n throw new RemoteComponentsError(\n 'Remote Components does not support Next.js Pages Router with Turbopack. ' +\n 'Use webpack instead (`next dev` / `next build` without `--turbo`).',\n );\n }\n // Log instead of throwing for the version check because\n // withRemoteComponentsConfig is shared by both hosts and remotes.\n // Only Pages Router hosts are broken on Next.js < 16 — remotes\n // work fine and must not have their builds blocked.\n const nextMajor = getNextMajorVersion();\n if (nextMajor !== undefined && nextMajor < 16) {\n const log =\n process.env.NODE_ENV !== 'production' ||\n process.env.VERCEL_ENV === 'preview'\n ? logWarn\n : logDebug;\n log(\n 'Config',\n `Remote Components does not support Pages Router hosts on Next.js ${nextMajor}. ` +\n 'Pages Router remotes are unaffected. Upgrade to Next.js 16+ for host support.',\n );\n }\n }\n\n if (process.env.TURBOPACK) {\n if (\n !(configSchema as ZodSchema).safeParse({\n turbopack: {\n resolveAlias: {\n ...alias,\n },\n },\n compiler: {\n defineServer: {\n REMOTE_COMPONENTS_PROJECT_ID: projectId,\n },\n },\n }).success\n ) {\n logError(\n 'Config',\n 'Turbopack support requires a Next.js version that includes `compiler.defineServer`. ' +\n 'Upgrade Next.js to continue using Remote Components with Turbopack.',\n );\n process.exit(1);\n }\n nextConfig.turbopack = {\n ...nextConfig.turbopack,\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 { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport { isAbortError } from '#internal/utils/abort';\nimport {\n CORS_DOCS_URL,\n RC_PROTECTED_REMOTE_FETCH_PATHNAME,\n} from '#internal/utils/constants';\n\nexport class RemoteComponentsError extends Error {\n code = 'REMOTE_COMPONENTS_ERROR';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'RemoteComponentsError';\n }\n}\n\nexport function multipleRemoteComponentsError(url: string | undefined) {\n return new RemoteComponentsError(\n `Multiple Remote Components found at \"${url}\". When a page exposes multiple Remote Components you must specify the \"name\" prop to select which one to load.`,\n );\n}\n\nexport function failedToFetchRemoteComponentError(\n url: string,\n { status, statusText }: { status: number; statusText: string },\n help: string = 'Is the URL correct and accessible?',\n) {\n return new RemoteComponentsError(\n `Failed to fetch Remote Component from \"${url}\". ${help}`,\n { cause: new Error(`${status} ${statusText}`) },\n );\n}\n\nexport async function errorFromFailedFetch(\n originalUrl: string,\n resolvedUrl: URL,\n res: Response | null | undefined,\n): Promise<RemoteComponentsError> {\n const isProxied = isProxiedUrl(resolvedUrl.href);\n\n if (isProxied && res) {\n const body = await res.text().catch(() => '');\n return failedProxyFetchError(\n originalUrl,\n resolvedUrl.href,\n res.status,\n body,\n );\n }\n\n const fallback = failedToFetchRemoteComponentError(\n originalUrl,\n res ?? { status: 0, statusText: 'No Response' },\n );\n\n if (!res) return fallback;\n\n try {\n const body = await res.text();\n const parser = new DOMParser();\n const doc = parser.parseFromString(body, 'text/html');\n const errorTemplate = doc.querySelector(\n 'template[data-next-error-message]',\n );\n const errorMessage = errorTemplate?.getAttribute('data-next-error-message');\n if (errorMessage) {\n const error = new RemoteComponentsError(errorMessage);\n const errorStack = errorTemplate?.getAttribute('data-next-error-stack');\n if (errorStack) {\n error.stack = errorStack;\n }\n return error;\n }\n } catch (parseError) {\n // Re-throw abort errors, ignore parse errors\n if (isAbortError(parseError)) throw parseError;\n }\n\n return fallback;\n}\n\nexport function failedProxiedAssetError(\n kind: 'chunk' | 'script',\n url: string,\n resolvedUrl: string,\n): RemoteComponentsError {\n return new RemoteComponentsError(\n `Failed to load ${kind} \"${url}\" via proxy \"${resolvedUrl}\". ` +\n `Ensure withRemoteComponentsHostProxy middleware is configured, \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" is in the matcher, ` +\n `and the remote URL is included in allowedProxyUrls. ` +\n `See: ${CORS_DOCS_URL}`,\n );\n}\n\nexport function failedProxyFetchError(\n originalUrl: string,\n proxyUrl: string,\n status: number,\n responseBody?: string,\n): RemoteComponentsError {\n if (status === 404) {\n return new RemoteComponentsError(\n `Could not proxy the request to \"${originalUrl}\" — the proxy endpoint \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" returned 404.\\n\\n` +\n `The host server needs middleware or a route that handles \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\".\\n\\n` +\n `Proxying requires two pieces:\\n` +\n ` 1. resolveClientUrl={routeThroughHostProxy} on <RemoteComponent>\\n` +\n ` 2. Middleware or a route for \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" on the host server\\n\\n` +\n `Docs: ${CORS_DOCS_URL}`,\n );\n }\n if (status === 403) {\n const detail = responseBody ? ` ${responseBody}` : '';\n return new RemoteComponentsError(\n `Proxied request to \"${proxyUrl}\" was forbidden.${detail} ` +\n `See: ${CORS_DOCS_URL}`,\n );\n }\n return new RemoteComponentsError(\n `Proxied request for \"${originalUrl}\" via \"${proxyUrl}\" failed with status ${status}. ` +\n `See: ${CORS_DOCS_URL}`,\n );\n}\n","import { CORS_DOCS_URL } from '#internal/utils/constants';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\nexport type LogLocation =\n | 'ChunkLoader'\n | 'ChunkDispatcher'\n | 'ComponentLoader'\n | 'ModuleDispatcher'\n | 'RemoteScope'\n | 'SharedModules'\n | 'WebpackRuntime'\n | 'TurbopackModule'\n | 'StaticLoader'\n | 'ScriptLoader'\n | 'Polyfill'\n | 'HtmlRemote'\n | 'HtmlHost'\n | 'Config'\n | 'NextAppRouter'\n | 'NextAppRouterCompat'\n | 'FetchRemoteComponent'\n | 'SharedModuleResolver';\n\nconst PREFIX = 'remote-components';\nconst DEBUG =\n (typeof window !== 'undefined' &&\n localStorage.getItem('RC_DEBUG') === 'true') ||\n (typeof process !== 'undefined' && process.env.RC_DEBUG === 'true');\n\nexport function logDebug(location: LogLocation, message: string) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.debug(`[${PREFIX}:${location}]: ${message}`);\n }\n}\n\nexport function logInfo(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.info(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logWarn(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.warn(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logError(\n location: LogLocation,\n message: string,\n cause?: unknown,\n) {\n // eslint-disable-next-line no-console\n console.error(\n new RemoteComponentsError(`[${PREFIX}:${location}]: ${message}`, {\n cause,\n }),\n );\n}\n\n/**\n * Logs a warning when a cross-origin asset request fails, guiding users\n * to configure the proxy middleware and resolveClientUrl on their host.\n */\nexport function warnCrossOriginFetchError(\n logLocation: LogLocation,\n url: string | URL,\n): void {\n try {\n const parsed = typeof url === 'string' ? new URL(url) : url;\n if (typeof location === 'undefined' || parsed.origin === location.origin) {\n return;\n }\n logWarn(\n logLocation,\n `Failed to fetch cross-origin resource \"${parsed.href}\". ` +\n 'To load assets from a protected deployment, two steps are required: ' +\n '(1) configure withRemoteComponentsHostProxy middleware in your host with the remote URL in allowedProxyUrls, ' +\n 'and (2) provide a resolveClientUrl prop that rewrites cross-origin asset URLs to go through the proxy. ' +\n `See: ${CORS_DOCS_URL}`,\n );\n } catch {\n // URL parsing failed — skip the warning\n }\n}\n","import type { LinkProps } from 'next/link';\nimport { createRemoteImageLoader } from '#internal/host/shared/remote-image-loader';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport type { InternalResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\nimport { logWarn } from '#internal/utils/logger';\n\n// polyfill Next.js App Router client API (minimal)\n// implementations are minimal and do not cover all use cases\n// developer can override these shared modules from configuration\nexport function sharedPolyfills(\n shared?: Record<string, () => Promise<unknown>>,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n const hostShared = getNamespace().hostSharedModules;\n const polyfill = {\n 'next/dist/client/components/navigation':\n hostShared['next/navigation'] ??\n shared?.['next/navigation'] ??\n (() =>\n Promise.resolve({\n useRouter() {\n return {\n push: (routerUrl: string) => {\n history.pushState({}, '', routerUrl);\n },\n replace: (routerUrl: string) => {\n history.replaceState({}, '', routerUrl);\n },\n back: () => {\n history.back();\n },\n };\n },\n usePathname() {\n return location.pathname;\n },\n useParams() {\n return {};\n },\n useSearchParams() {\n return new URLSearchParams(location.search);\n },\n useSelectedLayoutSegment() {\n return null;\n },\n useSelectedLayoutSegments() {\n return [];\n },\n __esModule: true,\n })),\n 'next/dist/client/app-dir/link':\n hostShared['next/link'] ??\n shared?.['next/link'] ??\n (() =>\n Promise.resolve({\n default: ({\n scroll: _,\n replace,\n prefetch,\n onNavigate,\n children,\n ...props\n }: React.PropsWithChildren<LinkProps>) => {\n if (prefetch) {\n logWarn(\n 'Polyfill',\n 'Next.js Link prefetch is not supported in remote components',\n );\n }\n return (\n <a\n {...props}\n href={props.href as string}\n onClick={(e) => {\n e.preventDefault();\n let preventDefaulted = false;\n e.preventDefault = () => {\n preventDefaulted = true;\n e.defaultPrevented = true;\n };\n if (typeof props.onClick === 'function') {\n props.onClick(e);\n }\n onNavigate?.(e);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (preventDefaulted) {\n return;\n }\n if (replace) {\n history.replaceState({}, '', props.href as string);\n } else {\n history.pushState({}, '', props.href as string);\n }\n }}\n suppressHydrationWarning\n >\n {children ?? null}\n </a>\n );\n },\n useLinkStatus() {\n return { pending: false };\n },\n __esModule: true,\n })),\n 'next/dist/client/app-dir/form':\n hostShared['next/form'] ??\n shared?.['next/form'] ??\n (() =>\n Promise.resolve({\n default: () => {\n // TODO: implement <Form> component for non-Next.js host applications\n throw new Error('Next.js <Form> component not implemented');\n },\n __esModule: true,\n })),\n // Instead of replacing next/image entirely, we let the real Next.js Image\n // component load from the remote bundle and only replace its default loader.\n // This gives us full next/image fidelity (fill, priority, srcSet, blur\n // placeholders, error handling) while routing image optimization through the\n // remote app's /_next/image endpoint.\n 'next/dist/shared/lib/image-loader':\n hostShared['next/dist/shared/lib/image-loader'] ??\n shared?.['next/dist/shared/lib/image-loader'] ??\n ((bundle: string) =>\n Promise.resolve({\n default: createRemoteImageLoader(bundle, resolveClientUrl),\n __esModule: true,\n })),\n 'next/dist/client/script':\n hostShared['next/script'] ??\n shared?.['next/script'] ??\n (() =>\n Promise.resolve({\n // TODO: implement <Script> component for non-Next.js host applications\n // do not throw an error for now\n default: () => null,\n __esModule: true,\n })),\n 'next/router':\n hostShared['next/router'] ??\n shared?.['next/router'] ??\n (() =>\n // TODO: incomplete implementation\n Promise.resolve({\n useRouter() {\n return {\n push: (routerUrl: string) => {\n history.pushState({}, '', routerUrl);\n },\n replace: (routerUrl: string) => {\n history.replaceState({}, '', routerUrl);\n },\n back: () => {\n history.back();\n },\n };\n },\n __esModule: true,\n })),\n 'next/dist/build/polyfills/process': () =>\n Promise.resolve({\n default: {\n env: {\n NODE_ENV: 'production',\n },\n },\n __esModule: true,\n }),\n } as Record<string, () => Promise<unknown>>;\n\n polyfill['next/navigation'] = polyfill[\n 'next/dist/client/components/navigation'\n ] as () => Promise<unknown>;\n polyfill['next/link'] = polyfill[\n 'next/dist/client/app-dir/link'\n ] as () => Promise<unknown>;\n polyfill['next/form'] = polyfill[\n 'next/dist/client/app-dir/form'\n ] as () => Promise<unknown>;\n polyfill['next/dist/esm/shared/lib/image-loader'] = polyfill[\n 'next/dist/shared/lib/image-loader'\n ] as () => Promise<unknown>;\n polyfill['next/script'] = polyfill[\n 'next/dist/client/script'\n ] as () => Promise<unknown>;\n\n return polyfill;\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { sharedPolyfills } from '#internal/host/shared/polyfill';\nimport type { LogLocation } from '#internal/utils/logger';\nimport { logDebug } from '#internal/utils/logger';\n\n/**\n * The core React packages that are always shared between host and remote.\n * These correspond to the `/react/*.js` and `/react-dom/*.js` path keys\n * used in the webpack module resolution map.\n */\nexport const CORE_REACT_SHARED_KEYS = [\n 'react',\n 'react/jsx-dev-runtime',\n 'react/jsx-runtime',\n 'react-dom',\n 'react-dom/client',\n] as const;\n\n/**\n * Maps each core React package to its webpack-style path key.\n * For example, `react` maps to `/react/index.js`.\n */\nexport const CORE_REACT_PATH_MAP: 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 'react-dom/client': '/react-dom/client.js',\n};\n\n/**\n * The vendorShared record used by the Next.js config to map React packages\n * to their webpack path-key string literals. Derived from CORE_REACT_PATH_MAP\n * but excludes `react-dom/client` to match the existing config behavior.\n */\nexport const VENDOR_SHARED: Record<string, string> = Object.fromEntries(\n Object.entries(CORE_REACT_PATH_MAP)\n .filter(([key]) => key !== 'react-dom/client')\n .map(([key, path]) => [key, `'${path}'`]),\n);\n\ntype SharedModuleFactory = (bundle?: string) => Promise<unknown>;\n\n/**\n * Builds the `coreShared` map for the Turbopack runtime's\n * `initializeSharedModules`. Each entry is an async factory that dynamically\n * imports the corresponding React package. User-provided shared modules\n * override core entries (e.g. to supply a pinned React version).\n */\nexport function buildCoreShared(\n userShared?: Record<string, SharedModuleFactory>,\n): Record<string, SharedModuleFactory> {\n return {\n react: async () => (await import('react')).default,\n 'react-dom': async () => (await import('react-dom')).default,\n 'react/jsx-dev-runtime': async () =>\n (await import('react/jsx-dev-runtime')).default,\n 'react/jsx-runtime': async () =>\n (await import('react/jsx-runtime')).default,\n 'react-dom/client': async () => (await import('react-dom/client')).default,\n ...userShared,\n };\n}\n\ninterface HostSharedGlobals {\n __remote_component_host_shared_modules__?: Record<\n string,\n SharedModuleFactory\n >;\n __remote_component_shared__?: Record<string, SharedModuleFactory>;\n}\n\n/**\n * Builds the merged host shared modules map with a consistent merge priority:\n * 1. Polyfills (lowest priority — fallback implementations)\n * 2. Global host shared modules (`__remote_component_host_shared_modules__`)\n * 3. User-provided shared modules (highest priority — explicit overrides)\n *\n * Some callers also include `__remote_component_shared__` (the pages router\n * global). Pass `includeRemoteComponentShared: true` to include it at the end.\n */\nexport function buildHostShared(\n userShared?: Record<string, SharedModuleFactory>,\n resolveClientUrl?: InternalResolveClientUrl,\n options?: { includeRemoteComponentShared?: boolean },\n): Record<string, SharedModuleFactory> {\n const self = globalThis as typeof globalThis & HostSharedGlobals;\n const result: Record<string, SharedModuleFactory> = {\n ...sharedPolyfills(userShared, resolveClientUrl),\n ...self.__remote_component_host_shared_modules__,\n ...userShared,\n };\n if (options?.includeRemoteComponentShared) {\n Object.assign(result, self.__remote_component_shared__);\n }\n return result;\n}\n\n/**\n * React module instances keyed by their webpack path, e.g.\n * `{ '/react/index.js': React }`. Passed into `buildWebpackResolve` so it\n * can populate the resolve map without importing React itself.\n */\nexport interface ReactModules {\n '/react/index.js': unknown;\n '/react/jsx-dev-runtime.js': unknown;\n '/react/jsx-runtime.js': unknown;\n '/react-dom/index.js': unknown;\n '/react-dom/client.js': unknown;\n}\n\n/**\n * Builds the `resolve` map passed to `applySharedModules` for the webpack\n * runtime. Combines:\n * - Static React module path keys (`/react/index.js`, etc.)\n * - Remote shared modules matched against host shared, with `(ssr)/` prefix stripped\n *\n * After building the map, resolves any factory functions by awaiting them\n * with the given bundle name.\n */\nexport async function buildWebpackResolve(\n hostShared: Record<string, SharedModuleFactory | unknown>,\n remoteShared: Record<string, string | number>,\n bundle: string,\n reactModules: ReactModules,\n callerTag: LogLocation = 'SharedModuleResolver',\n): Promise<Record<string, unknown>> {\n const resolve: Record<string, unknown> = {\n ...reactModules,\n ...Object.entries(remoteShared).reduce<Record<string, unknown>>(\n (acc, [key, value]) => {\n if (typeof hostShared[value] !== 'undefined') {\n acc[key.replace(/^\\(ssr\\)\\/(?<relative>\\.\\/)?/, '')] =\n hostShared[value];\n } else {\n logDebug(\n callerTag,\n `Remote requests \"${value}\" but host doesn't provide it`,\n );\n }\n return acc;\n },\n {},\n ),\n };\n await Promise.all(\n Object.entries(resolve).map(async ([key, value]) => {\n if (typeof value === 'function') {\n resolve[key] = await value(bundle);\n }\n return Promise.resolve(value);\n }),\n );\n return resolve;\n}\n","import { readFileSync } from 'node:fs';\nimport { findUpSync } from 'find-up';\nimport { resolveProjectIdFromEnv } from './project-id-env';\n\n/**\n * Resolves the project ID using environment variables first, then\n * falling back to `.vercel/project.json` and finally the package name.\n * Node-only — requires file system access.\n */\nexport function resolveProjectId(packageName: string): string {\n const fromEnv = resolveProjectIdFromEnv();\n if (fromEnv) return fromEnv;\n\n try {\n const projectPath = findUpSync('.vercel/project.json', {\n cwd: process.cwd(),\n });\n if (projectPath) {\n return (\n JSON.parse(readFileSync(projectPath, 'utf8')) as { projectId: string }\n ).projectId;\n }\n } catch {\n // fallback below\n }\n\n return packageName;\n}\n","/**\n * Resolves the project ID from environment variables only.\n * Safe for edge/browser contexts where file system access is unavailable.\n */\nexport function resolveProjectIdFromEnv(): string | undefined {\n return (\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID ||\n undefined\n );\n}\n","import { join } from 'node:path';\nimport type { NextConfig } from 'next';\nimport type { WebpackOptionsNormalized } from 'webpack';\nimport { ConditionalExecPlugin } from './plugins/conditional-exec';\nimport { ModuleIdEmbedPlugin } from './plugins/module-id-embed';\nimport { PatchRequirePlugin } from './plugins/patch-require';\nimport { RemoteWebpackRequirePlugin } from './plugins/remote-webpack-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, { isServer: webpackContext.isServer }),\n new ConditionalExecPlugin(app.name),\n new PatchRequirePlugin(app.name),\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","import type { Compiler } from 'webpack';\n\nexport class ConditionalExecPlugin {\n appName: string;\n\n constructor(appName: string) {\n this.appName = appName;\n }\n\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__ && globalThis.__DISABLE_WEBPACK_EXEC__[\"${this.appName}\"]) 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 { relative } from 'node:path';\nimport type { Compiler, NormalModule, RuntimeModule } from 'webpack';\nimport { createModuleIdEmbedRuntimeModule } from './module-id-embed-runtime-module';\n\nconst cwd = process.cwd();\n\nexport class ModuleIdEmbedPlugin {\n appName: string;\n includeAllModules: boolean;\n isServer: boolean;\n\n constructor(\n appName: string,\n options?: { includeAllModules?: boolean; isServer?: boolean },\n ) {\n this.appName = appName;\n this.includeAllModules = options?.includeAllModules ?? false;\n this.isServer = options?.isServer ?? false;\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 mod of compilation.modules) {\n const id = compilation.chunkGraph.getModuleId(mod);\n if (\n id &&\n (this.includeAllModules ||\n mod.layer?.endsWith('browser') ||\n (!this.isServer && mod.layer === null))\n ) {\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\n// This plugin patches the webpack require function to support loading remote components in Next.js\nexport class PatchRequirePlugin {\n appName: string;\n\n constructor(appName: string) {\n this.appName = appName;\n }\n\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>[^\\\\]]+)\\\\] (?<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 const error = new Error(\\`Remote Components are not available in \"\\${bundle}\". Did you forget to wrap the Next.js config with \\\\\\`withRemoteComponentsConfig\\\\\\` on both host and remote?\\`);\n error.name = 'RemoteComponentsError';\n error.code = 'REMOTE_COMPONENTS_ERROR';\n throw error;\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 // __remote_bundle_url__[appName] is the *host app's own* asset base URL\n // (set by the HTML host or setupWebpackRuntime). It is NOT a remote\n // bundle URL — it just ensures the host's own chunks resolve correctly\n // when the page is served from a CDN or different origin.\n return __webpack_require_l__(new URL(url, globalThis.__remote_bundle_url__?.[\"${this.appName}\"] ?? location.origin).href, 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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,kBAAmE;AACnE,IAAAC,oBAAkD;AAClD,8BAA4B;AAC5B,IAAAC,kBAA2B;AAE3B,2BAA6B;AAC7B,2CAAuC;;;ACChC,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAC/C,OAAO;AAAA,EAEP,YAAY,SAAiB,SAA+B;AAC1D,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AAAA,EACd;AACF;;;ACSA,I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MAAI,QAAQ,IAAI,WAAW;AACzB,QACE,CAAE,kCAA2B,UAAU;AAAA,MACrC,WAAW;AAAA,QACT,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;AACA;AAAA,QACE;AAAA,QACA;AAAA,MAEF;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,eAAW,YAAY;AAAA,MACrB,GAAG,WAAW;AAAA,MACd,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_fs","import_node_path","import_find_up","location","location","import_node_path","enhancedResolve","TsConfigPathsWebpackPlugin"]}
@@ -17,7 +17,15 @@ var RemoteComponentsError = class extends Error {
17
17
 
18
18
  // src/utils/logger.ts
19
19
  var PREFIX = "remote-components";
20
- var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
20
+ var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
21
+ function logDebug(location2, message) {
22
+ if (DEBUG) {
23
+ console.debug(`[${PREFIX}:${location2}]: ${message}`);
24
+ }
25
+ }
26
+ function logWarn(location2, message) {
27
+ console.warn(`[${PREFIX}:${location2}]: ${message}`);
28
+ }
21
29
  function logError(location2, message, cause) {
22
30
  console.error(
23
31
  new RemoteComponentsError(`[${PREFIX}:${location2}]: ${message}`, {
@@ -26,6 +34,28 @@ function logError(location2, message, cause) {
26
34
  );
27
35
  }
28
36
 
37
+ // src/host/shared/polyfill.tsx
38
+ import { jsx } from "react/jsx-runtime";
39
+
40
+ // src/host/shared/shared-module-resolver.ts
41
+ var CORE_REACT_SHARED_KEYS = [
42
+ "react",
43
+ "react/jsx-dev-runtime",
44
+ "react/jsx-runtime",
45
+ "react-dom",
46
+ "react-dom/client"
47
+ ];
48
+ var CORE_REACT_PATH_MAP = {
49
+ react: "/react/index.js",
50
+ "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
51
+ "react/jsx-runtime": "/react/jsx-runtime.js",
52
+ "react-dom": "/react-dom/index.js",
53
+ "react-dom/client": "/react-dom/client.js"
54
+ };
55
+ var VENDOR_SHARED = Object.fromEntries(
56
+ Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
57
+ );
58
+
29
59
  // src/utils/project-id.ts
30
60
  import { readFileSync } from "node:fs";
31
61
  import { findUpSync } from "find-up";
@@ -190,7 +220,11 @@ __webpack_require__.l = function __remote_webpack_require_l__(url, done, key, ch
190
220
  const bundle = match?.groups?.bundle;
191
221
  const id = match?.groups?.id;
192
222
  if (!(id && bundle)) {
193
- return __webpack_require_l__(new URL(url, globalThis.__remote_bundle_url__?.["${this.appName}"] ?? location.origin).href, done, key, chunkId);
223
+ // __remote_bundle_url__[appName] is the *host app's own* asset base URL
224
+ // (set by the HTML host or setupWebpackRuntime). It is NOT a remote
225
+ // bundle URL \u2014 it just ensures the host's own chunks resolve correctly
226
+ // when the page is served from a CDN or different origin.
227
+ return __webpack_require_l__(new URL(url, globalThis.__remote_bundle_url__?.["${this.appName}"] ?? location.origin).href, done, key, chunkId);
194
228
  }
195
229
  return done();
196
230
  };
@@ -297,6 +331,23 @@ function transform(nextConfig, {
297
331
  }
298
332
 
299
333
  // src/config/nextjs/index.ts
334
+ function getNextMajorVersion() {
335
+ try {
336
+ const nextPkgPath = findUpSync2("node_modules/next/package.json", {
337
+ cwd: process.cwd()
338
+ });
339
+ if (!nextPkgPath)
340
+ return void 0;
341
+ const { version } = JSON.parse(readFileSync2(nextPkgPath, "utf8"));
342
+ const major = version.split(".")[0];
343
+ return major ? Number.parseInt(major, 10) : void 0;
344
+ } catch {
345
+ return void 0;
346
+ }
347
+ }
348
+ function hasPagesDirectory() {
349
+ return existsSync(join2(process.cwd(), "pages")) || existsSync(join2(process.cwd(), "src/pages"));
350
+ }
300
351
  function readProjectPackageJson() {
301
352
  const defaults = { name: basename(process.cwd()), type: "module" };
302
353
  try {
@@ -331,46 +382,29 @@ function withRemoteComponentsConfig(nextConfig, options) {
331
382
  ".remote-components/shared/pages-host.tsx"
332
383
  );
333
384
  const appShared = /* @__PURE__ */ new Set([
334
- ...[
335
- "react",
336
- "react/jsx-dev-runtime",
337
- "react/jsx-runtime",
338
- "react-dom",
339
- "react-dom/client",
340
- "next/navigation",
341
- "next/dist/client/components/navigation",
342
- "next/link",
343
- "next/dist/client/app-dir/link",
344
- "next/form",
345
- "next/dist/client/app-dir/form",
346
- "next/dist/shared/lib/image-loader",
347
- "next/script",
348
- "next/dist/client/script",
349
- "next/dist/build/polyfills/process"
350
- ],
385
+ ...CORE_REACT_SHARED_KEYS,
386
+ "next/navigation",
387
+ "next/dist/client/components/navigation",
388
+ "next/link",
389
+ "next/dist/client/app-dir/link",
390
+ "next/form",
391
+ "next/dist/client/app-dir/form",
392
+ "next/dist/shared/lib/image-loader",
393
+ "next/script",
394
+ "next/dist/client/script",
395
+ "next/dist/build/polyfills/process",
351
396
  ...options?.shared ?? []
352
397
  ]);
353
398
  const pagesShared = /* @__PURE__ */ new Set([
354
- ...[
355
- "react",
356
- "react/jsx-dev-runtime",
357
- "react/jsx-runtime",
358
- "react-dom",
359
- "react-dom/client",
360
- "next/router",
361
- "next/link",
362
- "next/dist/shared/lib/image-loader",
363
- "next/script",
364
- "next/form"
365
- ],
399
+ ...CORE_REACT_SHARED_KEYS,
400
+ "next/router",
401
+ "next/link",
402
+ "next/dist/shared/lib/image-loader",
403
+ "next/script",
404
+ "next/form",
366
405
  ...options?.shared ?? []
367
406
  ]);
368
- const vendorShared = {
369
- react: `'/react/index.js'`,
370
- "react/jsx-dev-runtime": `'/react/jsx-dev-runtime.js'`,
371
- "react/jsx-runtime": `'/react/jsx-runtime.js'`,
372
- "react-dom": `'/react-dom/index.js'`
373
- };
407
+ const vendorShared = { ...VENDOR_SHARED };
374
408
  const resolve = enhancedResolve.create.sync({
375
409
  conditionNames: ["browser", "import", "module", "require"],
376
410
  ...existsSync(join2(process.cwd(), "tsconfig.json")) ? {
@@ -466,6 +500,21 @@ ${exportPre}${Array.from(sharedHost).reduce((acc, curr) => {
466
500
  };
467
501
  const projectId = resolveProjectId(packageJson.name);
468
502
  process.env.REMOTE_COMPONENTS_PROJECT_ID = projectId;
503
+ if (hasPagesDirectory()) {
504
+ if (process.env.TURBOPACK) {
505
+ throw new RemoteComponentsError(
506
+ "Remote Components does not support Next.js Pages Router with Turbopack. Use webpack instead (`next dev` / `next build` without `--turbo`)."
507
+ );
508
+ }
509
+ const nextMajor = getNextMajorVersion();
510
+ if (nextMajor !== void 0 && nextMajor < 16) {
511
+ const log = process.env.NODE_ENV !== "production" || process.env.VERCEL_ENV === "preview" ? logWarn : logDebug;
512
+ log(
513
+ "Config",
514
+ `Remote Components does not support Pages Router hosts on Next.js ${nextMajor}. Pages Router remotes are unaffected. Upgrade to Next.js 16+ for host support.`
515
+ );
516
+ }
517
+ }
469
518
  if (process.env.TURBOPACK) {
470
519
  if (!configSchema.safeParse({
471
520
  turbopack: {