remote-components 0.3.1 → 0.3.3

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 (131) hide show
  1. package/dist/config/nextjs.cjs +36 -25
  2. package/dist/config/nextjs.cjs.map +1 -1
  3. package/dist/config/nextjs.js +30 -19
  4. package/dist/config/nextjs.js.map +1 -1
  5. package/dist/host/defaults/app.cjs +2 -5
  6. package/dist/host/defaults/app.cjs.map +1 -1
  7. package/dist/host/defaults/app.d.ts +1 -3
  8. package/dist/host/defaults/app.js +1 -4
  9. package/dist/host/defaults/app.js.map +1 -1
  10. package/dist/host/defaults/pages.cjs +2 -5
  11. package/dist/host/defaults/pages.cjs.map +1 -1
  12. package/dist/host/defaults/pages.d.ts +1 -3
  13. package/dist/host/defaults/pages.js +1 -4
  14. package/dist/host/defaults/pages.js.map +1 -1
  15. package/dist/host/defaults/shared.cjs +32 -0
  16. package/dist/host/defaults/shared.cjs.map +1 -0
  17. package/dist/host/defaults/shared.d.ts +3 -0
  18. package/dist/host/defaults/shared.js +8 -0
  19. package/dist/host/defaults/shared.js.map +1 -0
  20. package/dist/host/html.cjs +390 -357
  21. package/dist/host/html.cjs.map +1 -1
  22. package/dist/host/html.js +390 -357
  23. package/dist/host/html.js.map +1 -1
  24. package/dist/host/nextjs/app/client-only.cjs +477 -453
  25. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  26. package/dist/host/nextjs/app/client-only.js +485 -461
  27. package/dist/host/nextjs/app/client-only.js.map +1 -1
  28. package/dist/host/react.cjs +382 -367
  29. package/dist/host/react.cjs.map +1 -1
  30. package/dist/host/react.js +382 -367
  31. package/dist/host/react.js.map +1 -1
  32. package/dist/internal/host/nextjs/app-client.cjs +2 -19
  33. package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
  34. package/dist/internal/host/nextjs/app-client.js +1 -8
  35. package/dist/internal/host/nextjs/app-client.js.map +1 -1
  36. package/dist/internal/host/nextjs/image-shared.cjs +2 -2
  37. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  38. package/dist/internal/host/nextjs/image-shared.js +2 -2
  39. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  40. package/dist/internal/host/nextjs/shared-import.cjs +46 -0
  41. package/dist/internal/host/nextjs/shared-import.cjs.map +1 -0
  42. package/dist/internal/host/nextjs/shared-import.d.ts +3 -0
  43. package/dist/internal/host/nextjs/shared-import.js +12 -0
  44. package/dist/internal/host/nextjs/shared-import.js.map +1 -0
  45. package/dist/internal/host/server/fetch-remote-component.cjs +20 -1
  46. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  47. package/dist/internal/host/server/fetch-remote-component.js +20 -1
  48. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  49. package/dist/internal/host/shared/remote-image-loader.cjs +2 -5
  50. package/dist/internal/host/shared/remote-image-loader.cjs.map +1 -1
  51. package/dist/internal/host/shared/remote-image-loader.js +2 -5
  52. package/dist/internal/host/shared/remote-image-loader.js.map +1 -1
  53. package/dist/internal/runtime/loaders/script-loader.cjs +7 -0
  54. package/dist/internal/runtime/loaders/script-loader.cjs.map +1 -1
  55. package/dist/internal/runtime/loaders/script-loader.js +7 -0
  56. package/dist/internal/runtime/loaders/script-loader.js.map +1 -1
  57. package/dist/internal/runtime/turbopack/chunk-loader.cjs +76 -126
  58. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  59. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +22 -7
  60. package/dist/internal/runtime/turbopack/chunk-loader.js +85 -131
  61. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  62. package/dist/internal/runtime/turbopack/module.cjs +53 -65
  63. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  64. package/dist/internal/runtime/turbopack/module.d.ts +14 -11
  65. package/dist/internal/runtime/turbopack/module.js +51 -64
  66. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  67. package/dist/internal/runtime/turbopack/remote-scope.cjs +101 -0
  68. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -0
  69. package/dist/internal/runtime/turbopack/remote-scope.d.ts +55 -0
  70. package/dist/internal/runtime/turbopack/remote-scope.js +73 -0
  71. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -0
  72. package/dist/internal/runtime/turbopack/shared-modules.cjs +64 -56
  73. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  74. package/dist/internal/runtime/turbopack/shared-modules.d.ts +13 -4
  75. package/dist/internal/runtime/turbopack/shared-modules.js +64 -57
  76. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  77. package/dist/internal/runtime/turbopack/webpack-runtime.cjs +39 -29
  78. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +1 -1
  79. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +5 -2
  80. package/dist/internal/runtime/turbopack/webpack-runtime.js +42 -32
  81. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +1 -1
  82. package/dist/internal/runtime/types.cjs.map +1 -1
  83. package/dist/internal/runtime/types.d.ts +4 -3
  84. package/dist/internal/utils/logger.cjs.map +1 -1
  85. package/dist/internal/utils/logger.d.ts +1 -1
  86. package/dist/internal/utils/logger.js.map +1 -1
  87. package/dist/internal/utils/project-id-env.cjs +31 -0
  88. package/dist/internal/utils/project-id-env.cjs.map +1 -0
  89. package/dist/internal/utils/project-id-env.d.ts +7 -0
  90. package/dist/internal/utils/project-id-env.js +7 -0
  91. package/dist/internal/utils/project-id-env.js.map +1 -0
  92. package/dist/internal/utils/project-id.cjs +46 -0
  93. package/dist/internal/utils/project-id.cjs.map +1 -0
  94. package/dist/internal/utils/project-id.d.ts +8 -0
  95. package/dist/internal/utils/project-id.js +22 -0
  96. package/dist/internal/utils/project-id.js.map +1 -0
  97. package/dist/internal/utils.cjs +5 -0
  98. package/dist/internal/utils.cjs.map +1 -1
  99. package/dist/internal/utils.d.ts +15 -1
  100. package/dist/internal/utils.js +4 -0
  101. package/dist/internal/utils.js.map +1 -1
  102. package/dist/remote/defaults/app.cjs +2 -5
  103. package/dist/remote/defaults/app.cjs.map +1 -1
  104. package/dist/remote/defaults/app.d.ts +1 -3
  105. package/dist/remote/defaults/app.js +1 -4
  106. package/dist/remote/defaults/app.js.map +1 -1
  107. package/dist/remote/defaults/pages.cjs +2 -5
  108. package/dist/remote/defaults/pages.cjs.map +1 -1
  109. package/dist/remote/defaults/pages.d.ts +1 -3
  110. package/dist/remote/defaults/pages.js +1 -4
  111. package/dist/remote/defaults/pages.js.map +1 -1
  112. package/dist/{internal/host/shared/resolved-data.cjs → remote/defaults/shared.cjs} +18 -3
  113. package/dist/remote/defaults/shared.cjs.map +1 -0
  114. package/dist/remote/defaults/shared.d.ts +3 -0
  115. package/dist/remote/defaults/shared.js +8 -0
  116. package/dist/remote/defaults/shared.js.map +1 -0
  117. package/dist/remote/html.cjs.map +1 -1
  118. package/dist/remote/html.js.map +1 -1
  119. package/dist/remote/nextjs/app.cjs +2 -1
  120. package/dist/remote/nextjs/app.cjs.map +1 -1
  121. package/dist/remote/nextjs/app.js +2 -1
  122. package/dist/remote/nextjs/app.js.map +1 -1
  123. package/dist/remote/nextjs/pages.cjs +2 -1
  124. package/dist/remote/nextjs/pages.cjs.map +1 -1
  125. package/dist/remote/nextjs/pages.js +2 -1
  126. package/dist/remote/nextjs/pages.js.map +1 -1
  127. package/package.json +1 -1
  128. package/dist/internal/host/shared/resolved-data.cjs.map +0 -1
  129. package/dist/internal/host/shared/resolved-data.d.ts +0 -48
  130. package/dist/internal/host/shared/resolved-data.js +0 -1
  131. package/dist/internal/host/shared/resolved-data.js.map +0 -1
@@ -1,5 +1,4 @@
1
- import { getBundleKey } from "#internal/runtime/constants";
2
- import { logError } from "#internal/utils/logger";
1
+ import { logDebug, logError, logWarn } from "#internal/utils/logger";
3
2
  import { handleTurbopackModule } from "./module";
4
3
  import {
5
4
  ASYNC_MODULE_ALL_RE,
@@ -8,22 +7,29 @@ import {
8
7
  REMOTE_SHARED_ASSIGNMENT_RE,
9
8
  REMOTE_SHARED_MARKER_RE
10
9
  } from "./patterns";
10
+ import { formatRemoteId } from "./remote-scope";
11
11
  const DEDUPLICATION_WARNING = "This module will not be deduplicated \u2014 the remote may load its own copy, which can cause duplicate instance errors (e.g. invalid hook calls if React is loaded twice).";
12
- async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {}) {
12
+ function getTurbopackModules(scope) {
13
13
  const self = globalThis;
14
- self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
15
- if (!self.__remote_shared_modules__[bundle]) {
16
- self.__remote_shared_modules__[bundle] = {};
14
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
15
+ if (!raw)
16
+ return void 0;
17
+ if (typeof raw === "object" && "__chunks__" in raw) {
18
+ return raw.__chunks__.flat();
17
19
  }
18
- const bundleKey = getBundleKey(bundle);
19
- let modules = self[`TURBOPACK_${bundleKey}`];
20
- if (modules && typeof modules === "object" && "__chunks__" in modules) {
21
- const chunks = modules.__chunks__;
22
- modules = chunks.flat();
20
+ if (Array.isArray(raw)) {
21
+ return raw.flat();
23
22
  }
23
+ return Object.entries(raw).flat();
24
+ }
25
+ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}) {
26
+ const allModules = getTurbopackModules(scope);
27
+ logDebug(
28
+ "SharedModules",
29
+ `initializeSharedModules: scope="${scope.scopedName}", allModules=${allModules ? allModules.length : "null"}, hostShared=[${Object.keys(hostShared).join(", ")}], remoteShared=${JSON.stringify(remoteShared)}`
30
+ );
24
31
  let sharedModuleInitializer = null;
25
- if (modules) {
26
- const allModules = Array.isArray(modules) ? modules.flat() : Object.entries(modules).flat();
32
+ if (allModules) {
27
33
  const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
28
34
  if (typeof idOrFunc !== "function") {
29
35
  return false;
@@ -37,72 +43,71 @@ async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {
37
43
  const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
38
44
  if (sharedModuleId) {
39
45
  const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
40
- bundle,
46
+ scope,
41
47
  sharedModuleId,
42
- `[${bundle}] ${sharedModuleInitializerId}`
48
+ formatRemoteId(scope, String(sharedModuleInitializerId))
43
49
  );
44
50
  sharedModuleInitializer = sharedModuleInitializerInstance;
45
51
  }
46
52
  }
47
53
  if (sharedModuleInitializer) {
48
54
  const { shared } = await sharedModuleInitializer;
49
- const sharedModuleIds = extractSharedModuleIds(
50
- shared,
51
- bundleKey,
52
- self
55
+ const sharedModuleIds = extractSharedModuleIds(shared, scope);
56
+ logDebug(
57
+ "SharedModules",
58
+ `Resolved shared modules for scope="${scope.scopedName}": ${JSON.stringify(sharedModuleIds)}`
53
59
  );
54
60
  return Promise.all(
55
61
  Object.entries(sharedModuleIds).map(async ([id, module]) => {
56
- if (self.__remote_shared_modules__?.[bundle]) {
57
- if (hostShared[module]) {
58
- self.__remote_shared_modules__[bundle][id] = await hostShared[module](bundle);
59
- } else {
60
- logError(
61
- "SharedModules",
62
- `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
63
- );
64
- }
62
+ if (hostShared[module]) {
63
+ scope.sharedModules[id] = await hostShared[module](scope.name);
64
+ } else {
65
+ logError(
66
+ "SharedModules",
67
+ `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
68
+ );
65
69
  }
66
70
  })
67
71
  );
68
72
  }
73
+ logWarn(
74
+ "SharedModules",
75
+ `No shared module initializer found in bundle for scope="${scope.scopedName}" \u2014 falling back to remoteShared mapping`
76
+ );
77
+ } else {
78
+ logWarn(
79
+ "SharedModules",
80
+ `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
81
+ );
69
82
  }
70
83
  return Promise.all(
71
84
  Object.entries(remoteShared).map(async ([id, module]) => {
72
- if (self.__remote_shared_modules__?.[bundle]) {
73
- if (hostShared[module]) {
74
- const normalizedId = id.replace("[app-ssr]", "[app-client]");
75
- self.__remote_shared_modules__[bundle][normalizedId] = await hostShared[module](bundle);
76
- } else {
77
- logError(
78
- "SharedModules",
79
- `Shared module "${module}" not found for "${bundle}". ${DEDUPLICATION_WARNING}`
80
- );
81
- }
85
+ if (hostShared[module]) {
86
+ const normalizedId = id.replace("[app-ssr]", "[app-client]");
87
+ scope.sharedModules[normalizedId] = await hostShared[module](
88
+ scope.name
89
+ );
90
+ } else {
91
+ logError(
92
+ "SharedModules",
93
+ `Shared module "${module}" not found for "${scope.name}". ${DEDUPLICATION_WARNING}`
94
+ );
82
95
  }
83
96
  })
84
97
  );
85
98
  }
86
- function extractSharedModuleIds(shared, bundleKey, self) {
99
+ function extractSharedModuleIds(shared, scope) {
87
100
  return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
88
101
  const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
89
102
  if (asyncSharedModuleId) {
90
103
  const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
91
104
  let asyncSharedModule;
92
- let turbopackModules = self[`TURBOPACK_${bundleKey}`];
93
- if (turbopackModules && typeof turbopackModules === "object" && "__chunks__" in turbopackModules) {
94
- const chunks = turbopackModules.__chunks__;
95
- turbopackModules = chunks.flat();
96
- }
97
- const newAllModules = Array.isArray(turbopackModules) ? turbopackModules.flat() : turbopackModules ? Object.entries(turbopackModules).flatMap(([key2, value2]) => [
98
- key2,
99
- value2
100
- ]) : [];
101
- const asyncSharedModuleIdIndex = newAllModules.indexOf(
105
+ const turbopackModules = getTurbopackModules(scope) ?? [];
106
+ const asyncSharedModuleIdIndex = turbopackModules.indexOf(
102
107
  asyncSharedModuleIdNumber
103
108
  );
104
- if (asyncSharedModuleIdIndex !== -1 && typeof newAllModules[asyncSharedModuleIdIndex + 1] === "function") {
105
- asyncSharedModule = newAllModules[asyncSharedModuleIdIndex + 1];
109
+ if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
110
+ asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
106
111
  }
107
112
  if (asyncSharedModule) {
108
113
  const asyncSharedModuleCode = asyncSharedModule.toString();
@@ -116,12 +121,13 @@ function extractSharedModuleIds(shared, bundleKey, self) {
116
121
  return acc;
117
122
  }, {});
118
123
  }
119
- function getSharedModule(bundle, id) {
120
- const self = globalThis;
121
- for (const [key, value] of Object.entries(
122
- self.__remote_shared_modules__?.[bundle] ?? {}
123
- )) {
124
- if (typeof value !== "undefined" && (typeof id === "string" && id.includes(key) || id === key)) {
124
+ function getSharedModule(scope, id) {
125
+ const idStr = String(id);
126
+ if (scope.sharedModules[idStr] !== void 0) {
127
+ return scope.sharedModules[idStr];
128
+ }
129
+ for (const [key, value] of Object.entries(scope.sharedModules)) {
130
+ if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
125
131
  return value;
126
132
  }
127
133
  }
@@ -129,6 +135,7 @@ function getSharedModule(bundle, id) {
129
135
  }
130
136
  export {
131
137
  getSharedModule,
138
+ getTurbopackModules,
132
139
  initializeSharedModules
133
140
  };
134
141
  //# sourceMappingURL=shared-modules.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/runtime/turbopack/shared-modules.ts"],"sourcesContent":["import { getBundleKey } from '#internal/runtime/constants';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { logError } from '#internal/utils/logger';\nimport { handleTurbopackModule } from './module';\nimport {\n ASYNC_MODULE_ALL_RE,\n ASYNC_MODULE_LOADER_RE,\n ASYNC_MODULE_RESOLVE_RE,\n REMOTE_SHARED_ASSIGNMENT_RE,\n REMOTE_SHARED_MARKER_RE,\n} from './patterns';\n\nconst DEDUPLICATION_WARNING =\n 'This module will not be deduplicated — the remote may load its own copy, ' +\n 'which can cause duplicate instance errors (e.g. invalid hook calls if React is loaded twice).';\n\n/**\n * Initializes shared modules between the host application and remote components.\n * This enables sharing of common dependencies like React to avoid duplicate instances.\n *\n * The function works by:\n * 1. Looking for a shared module initializer in the Turbopack bundle\n * 2. Extracting module IDs from the initializer\n * 3. Loading the corresponding host modules and mapping them to the remote's expected IDs\n */\nexport async function initializeSharedModules(\n bundle: string,\n hostShared: Record<string, (bundle?: string) => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n // biome-ignore lint/suspicious/noConfusingVoidType: Runtime is undefined but in TS land service it is void\n): Promise<void[]> {\n const self = globalThis as GlobalScope & {\n __next_f?: unknown[];\n };\n self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};\n\n if (!self.__remote_shared_modules__[bundle]) {\n self.__remote_shared_modules__[bundle] = {};\n }\n\n // prepare to load shared module initializers from the Turbopack bundle\n const bundleKey = getBundleKey(bundle);\n let modules = self[`TURBOPACK_${bundleKey}`] as\n | [unknown, Record<string, unknown>][]\n | Record<string, unknown>\n | undefined;\n\n // Check for new push-based format with __chunks__\n if (modules && typeof modules === 'object' && '__chunks__' in modules) {\n const chunks = (modules as { __chunks__: unknown[][] }).__chunks__;\n // Flatten chunks into module array format\n modules = chunks.flat() as [unknown, Record<string, unknown>][];\n }\n let sharedModuleInitializer: Promise<{\n shared: Record<string, string | (() => Promise<unknown>)>;\n }> | null = null;\n\n // find the shared module initializer in the Turbopack bundle\n if (modules) {\n // Handle both array and object formats for modules\n const allModules = Array.isArray(modules)\n ? modules.flat()\n : Object.entries(modules).flat();\n // find the shared module initializer module id by looking for\n // a function that contains the TURBOPACK_REMOTE_SHARED pattern\n const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {\n if (typeof idOrFunc !== 'function') {\n return false;\n }\n const funcCode = idOrFunc.toString();\n return REMOTE_SHARED_MARKER_RE.test(funcCode);\n });\n\n // if found, extract the shared module initializer\n // first element in the array is always the source script element\n if (sharedModuleInitializerIndex > 0) {\n const sharedModuleInitializerCode = (\n allModules[sharedModuleInitializerIndex] as () => unknown\n ).toString();\n const sharedModuleInitializerId = allModules[\n sharedModuleInitializerIndex - 1\n ] as string | number;\n // extract the shared module id from the function code\n const { sharedModuleId } =\n REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ??\n {};\n // load the shared module initializer using the extracted module id\n if (sharedModuleId) {\n const { default: sharedModuleInitializerInstance } =\n handleTurbopackModule(\n bundle,\n sharedModuleId,\n `[${bundle}] ${sharedModuleInitializerId}`,\n ) as {\n default: Promise<{\n shared: Record<string, string | (() => Promise<unknown>)>;\n }>;\n };\n sharedModuleInitializer = sharedModuleInitializerInstance;\n }\n }\n\n // if we have a shared module initializer, load the shared modules from the host application\n if (sharedModuleInitializer) {\n const { shared } = await sharedModuleInitializer;\n // map shared module ids to their initializer functions\n const sharedModuleIds = extractSharedModuleIds(\n shared,\n bundleKey,\n self as GlobalScope,\n );\n\n // load shared modules from the host application\n return Promise.all(\n Object.entries(sharedModuleIds).map(async ([id, module]) => {\n if (self.__remote_shared_modules__?.[bundle]) {\n if (hostShared[module]) {\n self.__remote_shared_modules__[bundle][id] =\n await hostShared[module](bundle);\n } else {\n logError(\n 'SharedModules',\n `Host shared module \"${module}\" not found for ID ${id}. ${DEDUPLICATION_WARNING}`,\n );\n }\n }\n }),\n );\n }\n }\n\n // fallback: ensure that the shared modules are initialized using remoteShared mapping\n return Promise.all(\n Object.entries(remoteShared).map(async ([id, module]) => {\n if (self.__remote_shared_modules__?.[bundle]) {\n if (hostShared[module]) {\n const normalizedId = id.replace('[app-ssr]', '[app-client]');\n self.__remote_shared_modules__[bundle][normalizedId] =\n await hostShared[module](bundle);\n } else {\n logError(\n 'SharedModules',\n `Shared module \"${module}\" not found for \"${bundle}\". ${DEDUPLICATION_WARNING}`,\n );\n }\n }\n }),\n );\n}\n\n/**\n * Extracts shared module IDs from the shared module initializer functions.\n * This parses the minified Turbopack code to find the module ID mappings.\n */\nfunction extractSharedModuleIds(\n shared: Record<string, string | (() => Promise<unknown>)>,\n bundleKey: string,\n self: GlobalScope,\n): Record<string, string> {\n return Object.entries(shared)\n .filter(([, value]) => typeof value === 'function')\n .reduce<Record<string, string>>((acc, [key, value]) => {\n const { asyncSharedModuleId } =\n ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};\n\n if (asyncSharedModuleId) {\n const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);\n\n let asyncSharedModule;\n let turbopackModules = self[`TURBOPACK_${bundleKey}`] as\n | unknown[]\n | Record<string, unknown>\n | undefined;\n\n // Check for new push-based format with __chunks__\n if (\n turbopackModules &&\n typeof turbopackModules === 'object' &&\n '__chunks__' in turbopackModules\n ) {\n const chunks = (turbopackModules as { __chunks__: unknown[][] })\n .__chunks__;\n turbopackModules = chunks.flat() as unknown[];\n }\n\n const newAllModules = Array.isArray(turbopackModules)\n ? turbopackModules.flat()\n : turbopackModules\n ? Object.entries(turbopackModules).flatMap(([key, value]) => [\n key,\n value,\n ])\n : [];\n const asyncSharedModuleIdIndex = newAllModules.indexOf(\n asyncSharedModuleIdNumber,\n );\n if (\n asyncSharedModuleIdIndex !== -1 &&\n typeof newAllModules[asyncSharedModuleIdIndex + 1] === 'function'\n ) {\n asyncSharedModule = newAllModules[\n asyncSharedModuleIdIndex + 1\n ] as () => unknown;\n }\n if (asyncSharedModule) {\n const asyncSharedModuleCode = asyncSharedModule.toString();\n // Try both Promise.resolve and Promise.all patterns\n const { sharedModuleId } =\n ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ??\n ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ??\n {};\n // map the shared module id to the actual module name\n acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(\n '__remote_shared_module_',\n '',\n );\n }\n }\n return acc;\n }, {});\n}\n\n/**\n * Returns a shared module for the given bundle and module ID.\n * Shared modules are common dependencies like React that are provided by the host.\n */\nexport function getSharedModule(bundle: string, id: string | number): unknown {\n const self = globalThis as {\n __remote_shared_modules__?: Record<string, Record<string, unknown>>;\n };\n\n for (const [key, value] of Object.entries(\n self.__remote_shared_modules__?.[bundle] ?? {},\n )) {\n if (\n typeof value !== 'undefined' &&\n ((typeof id === 'string' && id.includes(key)) || id === key)\n ) {\n return value;\n }\n }\n return null;\n}\n"],"mappings":"AAAA,SAAS,oBAAoB;AAE7B,SAAS,gBAAgB;AACzB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,wBACJ;AAYF,eAAsB,wBACpB,QACA,aAAoE,CAAC,GACrE,eAAuC,CAAC,GAEvB;AACjB,QAAM,OAAO;AAGb,OAAK,4BAA4B,KAAK,6BAA6B,CAAC;AAEpE,MAAI,CAAC,KAAK,0BAA0B,MAAM,GAAG;AAC3C,SAAK,0BAA0B,MAAM,IAAI,CAAC;AAAA,EAC5C;AAGA,QAAM,YAAY,aAAa,MAAM;AACrC,MAAI,UAAU,KAAK,aAAa,WAAW;AAM3C,MAAI,WAAW,OAAO,YAAY,YAAY,gBAAgB,SAAS;AACrE,UAAM,SAAU,QAAwC;AAExD,cAAU,OAAO,KAAK;AAAA,EACxB;AACA,MAAI,0BAEQ;AAGZ,MAAI,SAAS;AAEX,UAAM,aAAa,MAAM,QAAQ,OAAO,IACpC,QAAQ,KAAK,IACb,OAAO,QAAQ,OAAO,EAAE,KAAK;AAGjC,UAAM,+BAA+B,WAAW,UAAU,CAAC,aAAa;AACtE,UAAI,OAAO,aAAa,YAAY;AAClC,eAAO;AAAA,MACT;AACA,YAAM,WAAW,SAAS,SAAS;AACnC,aAAO,wBAAwB,KAAK,QAAQ;AAAA,IAC9C,CAAC;AAID,QAAI,+BAA+B,GAAG;AACpC,YAAM,8BACJ,WAAW,4BAA4B,EACvC,SAAS;AACX,YAAM,4BAA4B,WAChC,+BAA+B,CACjC;AAEA,YAAM,EAAE,eAAe,IACrB,4BAA4B,KAAK,2BAA2B,GAAG,UAC/D,CAAC;AAEH,UAAI,gBAAgB;AAClB,cAAM,E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ACF;AACA,SAAO;AACT;","names":["key","value"]}
1
+ {"version":3,"sources":["../../../../src/runtime/turbopack/shared-modules.ts"],"sourcesContent":["import type { GlobalScope } from '#internal/runtime/types';\nimport { logDebug, logError, logWarn } from '#internal/utils/logger';\nimport { handleTurbopackModule } from './module';\nimport {\n ASYNC_MODULE_ALL_RE,\n ASYNC_MODULE_LOADER_RE,\n ASYNC_MODULE_RESOLVE_RE,\n REMOTE_SHARED_ASSIGNMENT_RE,\n REMOTE_SHARED_MARKER_RE,\n} from './patterns';\nimport { formatRemoteId, type RemoteScope } from './remote-scope';\n\nconst DEDUPLICATION_WARNING =\n 'This module will not be deduplicated — the remote may load its own copy, ' +\n 'which can cause duplicate instance errors (e.g. invalid hook calls if React is loaded twice).';\n\n/**\n * Reads the TURBOPACK global for a scope, normalizing the push-based\n * `__chunks__` format into a flat module list when needed.\n */\nexport function getTurbopackModules(scope: RemoteScope): unknown[] | undefined {\n const self = globalThis as GlobalScope;\n const raw = self[`TURBOPACK_${scope.globalKey}`];\n if (!raw) return undefined;\n\n if (typeof raw === 'object' && '__chunks__' in (raw as object)) {\n return (raw as { __chunks__: unknown[][] }).__chunks__.flat();\n }\n if (Array.isArray(raw)) {\n return (raw as unknown[]).flat();\n }\n return Object.entries(raw as Record<string, unknown>).flat();\n}\n\n/**\n * Initializes shared modules between the host application and remote components.\n * This enables sharing of common dependencies like React to avoid duplicate instances.\n *\n * The function works by:\n * 1. Looking for a shared module initializer in the Turbopack bundle\n * 2. Extracting module IDs from the initializer\n * 3. Loading the corresponding host modules and mapping them to the remote's expected IDs\n */\nexport async function initializeSharedModules(\n scope: RemoteScope,\n hostShared: Record<string, (bundle?: string) => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n // biome-ignore lint/suspicious/noConfusingVoidType: Runtime is undefined but in TS land service it is void\n): Promise<void[]> {\n const allModules = getTurbopackModules(scope);\n\n logDebug(\n 'SharedModules',\n `initializeSharedModules: scope=\"${scope.scopedName}\", ` +\n `allModules=${allModules ? allModules.length : 'null'}, ` +\n `hostShared=[${Object.keys(hostShared).join(', ')}], ` +\n `remoteShared=${JSON.stringify(remoteShared)}`,\n );\n\n let sharedModuleInitializer: Promise<{\n shared: Record<string, string | (() => Promise<unknown>)>;\n }> | null = null;\n\n // find the shared module initializer in the Turbopack bundle\n if (allModules) {\n // find the shared module initializer module id by looking for\n // a function that contains the TURBOPACK_REMOTE_SHARED pattern\n const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {\n if (typeof idOrFunc !== 'function') {\n return false;\n }\n const funcCode = idOrFunc.toString();\n return REMOTE_SHARED_MARKER_RE.test(funcCode);\n });\n\n // if found, extract the shared module initializer\n // first element in the array is always the source script element\n if (sharedModuleInitializerIndex > 0) {\n const sharedModuleInitializerCode = (\n allModules[sharedModuleInitializerIndex] as () => unknown\n ).toString();\n const sharedModuleInitializerId = allModules[\n sharedModuleInitializerIndex - 1\n ] as string | number;\n // extract the shared module id from the function code\n const { sharedModuleId } =\n REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ??\n {};\n // load the shared module initializer using the extracted module id\n if (sharedModuleId) {\n const { default: sharedModuleInitializerInstance } =\n handleTurbopackModule(\n scope,\n sharedModuleId,\n formatRemoteId(scope, String(sharedModuleInitializerId)),\n ) as {\n default: Promise<{\n shared: Record<string, string | (() => Promise<unknown>)>;\n }>;\n };\n sharedModuleInitializer = sharedModuleInitializerInstance;\n }\n }\n\n // if we have a shared module initializer, load the shared modules from the host application\n if (sharedModuleInitializer) {\n const { shared } = await sharedModuleInitializer;\n // map shared module ids to their initializer functions\n const sharedModuleIds = extractSharedModuleIds(shared, scope);\n logDebug(\n 'SharedModules',\n `Resolved shared modules for scope=\"${scope.scopedName}\": ${JSON.stringify(sharedModuleIds)}`,\n );\n\n // load shared modules from the host application\n return Promise.all(\n Object.entries(sharedModuleIds).map(async ([id, module]) => {\n if (hostShared[module]) {\n scope.sharedModules[id] = await hostShared[module](scope.name);\n } else {\n logError(\n 'SharedModules',\n `Host shared module \"${module}\" not found for ID ${id}. ${DEDUPLICATION_WARNING}`,\n );\n }\n }),\n );\n }\n\n logWarn(\n 'SharedModules',\n `No shared module initializer found in bundle for scope=\"${scope.scopedName}\" — falling back to remoteShared mapping`,\n );\n } else {\n logWarn(\n 'SharedModules',\n `No TURBOPACK modules found for scope=\"${scope.scopedName}\" (TURBOPACK_${scope.globalKey} is empty)`,\n );\n }\n\n // fallback: ensure that the shared modules are initialized using remoteShared mapping\n return Promise.all(\n Object.entries(remoteShared).map(async ([id, module]) => {\n if (hostShared[module]) {\n const normalizedId = id.replace('[app-ssr]', '[app-client]');\n scope.sharedModules[normalizedId] = await hostShared[module](\n scope.name,\n );\n } else {\n logError(\n 'SharedModules',\n `Shared module \"${module}\" not found for \"${scope.name}\". ${DEDUPLICATION_WARNING}`,\n );\n }\n }),\n );\n}\n\n/**\n * Extracts shared module IDs from the shared module initializer functions.\n * This parses the minified Turbopack code to find the module ID mappings.\n */\nfunction extractSharedModuleIds(\n shared: Record<string, string | (() => Promise<unknown>)>,\n scope: RemoteScope,\n): Record<string, string> {\n return Object.entries(shared)\n .filter(([, value]) => typeof value === 'function')\n .reduce<Record<string, string>>((acc, [key, value]) => {\n const { asyncSharedModuleId } =\n ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};\n\n if (asyncSharedModuleId) {\n const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);\n\n let asyncSharedModule: (() => unknown) | undefined;\n const turbopackModules = getTurbopackModules(scope) ?? [];\n const asyncSharedModuleIdIndex = turbopackModules.indexOf(\n asyncSharedModuleIdNumber,\n );\n if (\n asyncSharedModuleIdIndex !== -1 &&\n typeof turbopackModules[asyncSharedModuleIdIndex + 1] === 'function'\n ) {\n asyncSharedModule = turbopackModules[\n asyncSharedModuleIdIndex + 1\n ] as () => unknown;\n }\n if (asyncSharedModule) {\n const asyncSharedModuleCode = asyncSharedModule.toString();\n // Try both Promise.resolve and Promise.all patterns\n const { sharedModuleId } =\n ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ??\n ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ??\n {};\n // map the shared module id to the actual module name\n acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(\n '__remote_shared_module_',\n '',\n );\n }\n }\n return acc;\n }, {});\n}\n\n/**\n * Returns a shared module for the given scope and module ID.\n * Shared modules are common dependencies like React that are provided by the host.\n */\nexport function getSharedModule(\n scope: RemoteScope,\n id: string | number,\n): unknown {\n const idStr = String(id);\n\n // Exact match first (covers both string and numeric IDs)\n if (scope.sharedModules[idStr] !== undefined) {\n return scope.sharedModules[idStr];\n }\n\n // Fallback: the id may be a bundle-prefixed string like \"[bundle] /react/index.js\"\n // that contains the shared module key as a suffix. Only match when the key\n // appears as a complete suffix segment to avoid \"react\" matching \"react-dom\".\n for (const [key, value] of Object.entries(scope.sharedModules)) {\n if (typeof value !== 'undefined' && idStr !== key && idStr.endsWith(key)) {\n return value;\n }\n }\n\n return null;\n}\n"],"mappings":"AACA,SAAS,UAAU,UAAU,eAAe;AAC5C,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAwC;AAEjD,MAAM,wBACJ;AAOK,SAAS,oBAAoB,OAA2C;AAC7E,QAAM,OAAO;AACb,QAAM,MAAM,KAAK,aAAa,MAAM,WAAW;AAC/C,MAAI,CAAC;AAAK,WAAO;AAEjB,MAAI,OAAO,QAAQ,YAAY,gBAAiB,KAAgB;AAC9D,WAAQ,IAAoC,WAAW,KAAK;AAAA,EAC9D;AACA,MAAI,MAAM,QAAQ,GAAG,GAAG;AACtB,WAAQ,IAAkB,KAAK;AAAA,EACjC;AACA,SAAO,OAAO,QAAQ,GAA8B,EAAE,KAAK;AAC7D;AAWA,eAAsB,wBACpB,OACA,aAAoE,CAAC,GACrE,eAAuC,CAAC,GAEvB;AACjB,Q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,UACjD,CAAC;AAEH,YAAI,kBAAkB,mBAAmB,IAAI,IAAI;AAAA,UAC/C;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AACT;AAMO,SAAS,gBACd,OACA,IACS;AACT,QAAM,QAAQ,OAAO,EAAE;AAGvB,MAAI,MAAM,cAAc,KAAK,MAAM,QAAW;AAC5C,WAAO,MAAM,cAAc,KAAK;AAAA,EAClC;AAKA,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,aAAa,GAAG;AAC9D,QAAI,OAAO,UAAU,eAAe,UAAU,OAAO,MAAM,SAAS,GAAG,GAAG;AACxE,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -37,33 +37,43 @@ var import_error = require("#internal/utils/error");
37
37
  var import_logger = require("#internal/utils/logger");
38
38
  var import_chunk_loader = require("./chunk-loader");
39
39
  var import_module = require("./module");
40
+ var import_remote_scope = require("./remote-scope");
40
41
  var import_shared_modules = require("./shared-modules");
41
42
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
42
43
  const self = globalThis;
44
+ const bundleName = bundle ?? "default";
45
+ const scope = (0, import_remote_scope.createScope)(bundleName, url, runtime, resolveClientUrl);
46
+ (0, import_remote_scope.registerScope)(scope);
43
47
  if (!self.__remote_bundle_url__) {
44
48
  self.__remote_bundle_url__ = {};
45
49
  }
46
- self.__remote_bundle_url__[bundle ?? "default"] = url;
50
+ self.__remote_bundle_url__[bundleName] = url;
51
+ if (scope.scopedName !== bundleName) {
52
+ self.__remote_bundle_url__[scope.scopedName] = url;
53
+ }
47
54
  self.__webpack_get_script_filename__ = () => null;
48
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
55
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
56
+ if (willCreateDispatchers) {
49
57
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
50
58
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
51
59
  self.__original_webpack_require__ = self.__webpack_require__;
52
60
  }
53
- self.__webpack_chunk_load__ = (0, import_chunk_loader.createChunkLoader)(runtime, resolveClientUrl);
54
- self.__webpack_require__ = createModuleRequire(runtime);
61
+ self.__webpack_chunk_load__ = (0, import_chunk_loader.createChunkDispatcher)();
62
+ self.__webpack_require__ = createModuleDispatcher(runtime);
55
63
  self.__webpack_require_type__ = runtime;
56
64
  if (self.__remote_webpack_require__ && runtime === import_constants.RUNTIME_TURBOPACK) {
57
- const remoteBundle = bundle ?? "default";
58
- self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
59
- self.__remote_webpack_require__[remoteBundle].type = "turbopack";
65
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
66
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
60
67
  }
61
68
  }
69
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
70
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
71
+ }
62
72
  if (runtime === import_constants.RUNTIME_TURBOPACK) {
63
73
  const results = await Promise.allSettled(
64
74
  scripts.map((script) => {
65
75
  if (script.src) {
66
- return self.__webpack_chunk_load__?.(script.src, bundle);
76
+ return (0, import_chunk_loader.loadChunkWithScope)(scope, script.src);
67
77
  }
68
78
  return Promise.resolve(void 0);
69
79
  })
@@ -85,54 +95,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
85
95
  "react-dom/client": async () => (await import("react-dom/client")).default,
86
96
  ...shared
87
97
  };
88
- await (0, import_shared_modules.initializeSharedModules)(
89
- bundle ?? "default",
90
- // include all core modules as shared
91
- coreShared,
92
- remoteShared
93
- );
98
+ await (0, import_shared_modules.initializeSharedModules)(scope, coreShared, remoteShared);
94
99
  }
95
- function createModuleRequire(runtime) {
100
+ function createModuleDispatcher(runtime) {
96
101
  return (id) => {
97
102
  const self = globalThis;
98
103
  const { bundle, id: moduleId } = id.match(import_patterns.REMOTE_COMPONENT_REGEX)?.groups ?? {
99
104
  bundle: "default",
100
105
  id
101
106
  };
102
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
103
- (0, import_logger.logDebug)("WebpackRuntime", `remoteRuntime: "${remoteRuntime}"`);
107
+ const bundleName = bundle ?? "default";
108
+ const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
109
+ (0, import_logger.logDebug)(
110
+ "ModuleDispatcher",
111
+ `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
112
+ );
104
113
  try {
105
114
  if (remoteRuntime === import_constants.RUNTIME_WEBPACK && bundle && moduleId) {
106
115
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
107
116
  }
108
- const sharedModuleId = moduleId ?? id;
109
- const sharedModule = (0, import_shared_modules.getSharedModule)(bundle ?? "default", sharedModuleId);
110
- if (sharedModule) {
111
- return sharedModule;
117
+ const scope = (0, import_remote_scope.getScope)(bundleName);
118
+ if (scope) {
119
+ return (0, import_module.requireModule)(scope, moduleId ?? id, id);
112
120
  }
113
- if (bundle && moduleId) {
114
- return (0, import_module.handleTurbopackModule)(bundle, moduleId, id);
115
- }
116
- throw new Error(`Module "${id}" not found.`);
121
+ throw new Error(
122
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
123
+ );
117
124
  } catch (requireError) {
118
125
  (0, import_logger.logWarn)(
119
- "WebpackRuntime",
126
+ "ModuleDispatcher",
120
127
  `Module require failed: ${String(requireError)}`
121
128
  );
122
129
  if (typeof self.__original_webpack_require__ !== "function") {
123
130
  throw new import_error.RemoteComponentsError(
124
- `Module "${id}" not found in remote component bundle "${bundle}".`,
131
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
125
132
  {
126
133
  cause: requireError instanceof Error ? requireError : void 0
127
134
  }
128
135
  );
129
136
  }
130
137
  try {
131
- (0, import_logger.logDebug)("WebpackRuntime", "Falling back to original webpack require");
138
+ (0, import_logger.logDebug)(
139
+ "ModuleDispatcher",
140
+ "Falling back to original webpack require"
141
+ );
132
142
  return self.__original_webpack_require__(id);
133
143
  } catch (originalError) {
134
144
  throw new import_error.RemoteComponentsError(
135
- `Module "${id}" not found in remote component bundle "${bundle}".`,
145
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
136
146
  { cause: originalError instanceof Error ? originalError : void 0 }
137
147
  );
138
148
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/runtime/turbopack/webpack-runtime.ts"],"sourcesContent":["import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n RUNTIME_TURBOPACK,\n RUNTIME_WEBPACK,\n type Runtime,\n} from '#internal/runtime/constants';\nimport { REMOTE_COMPONENT_REGEX } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { logDebug, logWarn } from '#internal/utils/logger';\nimport { createChunkLoader } from './chunk-loader';\nimport { handleTurbopackModule } from './module';\nimport { getSharedModule, initializeSharedModules } from './shared-modules';\n\n/**\n * Sets up webpack runtime environment for remote components.\n * This function initializes the global webpack require and chunk loading functions\n * to support loading and executing remote component bundles.\n *\n * @param runtime - The bundler runtime type ('webpack' or 'turbopack')\n * @param scripts - Initial script chunks to load for Turbopack runtime\n * @param url - Base URL for the remote component bundle\n * @param bundle - Bundle identifier (defaults to 'default')\n * @param shared - Host-provided shared modules (e.g., React)\n * @param remoteShared - Mapping of remote module IDs to shared module names\n */\nexport async function setupWebpackRuntime(\n runtime: Runtime,\n scripts: { src: string | null }[] = [],\n url: URL = new URL(location.href),\n bundle?: string,\n shared: Record<string, () => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n resolveClientUrl?: InternalResolveClientUrl,\n): Promise<void> {\n const self = globalThis as GlobalScope;\n\n if (!self.__remote_bundle_url__) {\n self.__remote_bundle_url__ = {};\n }\n self.__remote_bundle_url__[bundle ?? 'default'] = url;\n self.__webpack_get_script_filename__ = () => null;\n\n if (\n typeof self.__webpack_require__ !== 'function' ||\n self.__webpack_require_type__ !== 'turbopack'\n ) {\n // preserve original webpack functions for fallback\n if (\n !self.__original_webpack_require__ &&\n !self.__original_webpack_chunk_load__\n ) {\n self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;\n self.__original_webpack_require__ = self.__webpack_require__;\n }\n\n self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);\n self.__webpack_require__ = createModuleRequire(runtime);\n self.__webpack_require_type__ = runtime;\n\n if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {\n const remoteBundle = bundle ?? 'default';\n self.__remote_webpack_require__[remoteBundle] =\n self.__webpack_require__ as (remoteId: string | number) => unknown;\n self.__remote_webpack_require__[remoteBundle].type = 'turbopack';\n }\n }\n\n // load all initial chunks when using Turbopack runtime\n if (runtime === RUNTIME_TURBOPACK) {\n const results = await Promise.allSettled(\n scripts.map((script) => {\n if (script.src) {\n return self.__webpack_chunk_load__?.(script.src, bundle);\n }\n return Promise.resolve(undefined);\n }),\n );\n\n for (const result of results) {\n if (result.status === 'rejected') {\n logWarn(\n 'WebpackRuntime',\n `Initial chunk load failed: ${String(result.reason)}`,\n );\n }\n }\n }\n\n // initialize shared modules with core React dependencies\n const coreShared = {\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 ...shared,\n };\n await initializeSharedModules(\n bundle ?? 'default',\n // include all core modules as shared\n coreShared,\n remoteShared,\n );\n}\n\n/**\n * Creates module require function for webpack runtime.\n * This function resolves module IDs to their exports, handling:\n * - Webpack remotes (pre-loaded bundles)\n * - Shared modules (React, etc.)\n * - Turbopack modules (dynamically loaded)\n */\nfunction createModuleRequire(runtime: Runtime): (id: string) => unknown {\n return (id: string) => {\n const self = globalThis as GlobalScope;\n const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)\n ?.groups ?? {\n bundle: 'default',\n id,\n };\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : runtime;\n\n logDebug('WebpackRuntime', `remoteRuntime: \"${remoteRuntime}\"`);\n\n try {\n // for webpack remotes, use the pre-loaded require function\n if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {\n return self.__remote_webpack_require__?.[bundle]?.(moduleId);\n }\n const sharedModuleId = moduleId ?? id;\n const sharedModule = getSharedModule(bundle ?? 'default', sharedModuleId);\n if (sharedModule) {\n return sharedModule;\n }\n if (bundle && moduleId) {\n return handleTurbopackModule(bundle, moduleId, id);\n }\n throw new Error(`Module \"${id}\" not found.`);\n } catch (requireError) {\n logWarn(\n 'WebpackRuntime',\n `Module require failed: ${String(requireError)}`,\n );\n if (typeof self.__original_webpack_require__ !== 'function') {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundle}\".`,\n {\n cause: requireError instanceof Error ? requireError : undefined,\n },\n );\n }\n try {\n logDebug('WebpackRuntime', 'Falling back to original webpack require');\n return self.__original_webpack_require__(id);\n } catch (originalError) {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundle}\".`,\n { cause: originalError instanceof Error ? originalError : undefined },\n );\n }\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAIO;AACP,sBAAuC;AAEvC,mBAAsC;AACtC,oBAAkC;AAClC,0BAAkC;AAClC,oBAAsC;AACtC,4BAAyD;AAcz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B,EAAE;AAAA,MAC7C,SAAS,eAAP;AACA,cAAM,IAAI;AAAA,UACR,WAAW,6CAA6C;AAAA,UACxD,EAAE,OAAO,yBAAyB,QAAQ,gBAAgB,OAAU;AAAA,QACtE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../../src/runtime/turbopack/webpack-runtime.ts"],"sourcesContent":["import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n RUNTIME_TURBOPACK,\n RUNTIME_WEBPACK,\n type Runtime,\n} from '#internal/runtime/constants';\nimport { REMOTE_COMPONENT_REGEX } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { logDebug, logWarn } from '#internal/utils/logger';\nimport { createChunkDispatcher, loadChunkWithScope } from './chunk-loader';\nimport { requireModule } from './module';\nimport { createScope, getScope, registerScope } from './remote-scope';\nimport { initializeSharedModules } from './shared-modules';\n\n/**\n * Sets up webpack runtime environment for remote components.\n *\n * Creates a RemoteScope that encapsulates all per-remote state (base URL,\n * proxy callback, module cache, shared modules) and registers it in the\n * global scope registry. Global dispatchers (__webpack_require__,\n * __webpack_chunk_load__) are set once and route to the correct scope.\n *\n * @param runtime - The bundler runtime type ('webpack' or 'turbopack')\n * @param scripts - Initial script chunks to load for Turbopack runtime\n * @param url - Base URL for the remote component bundle\n * @param bundle - Bundle identifier (defaults to 'default')\n * @param shared - Host-provided shared modules (e.g., React)\n * @param remoteShared - Mapping of remote module IDs to shared module names\n */\nexport async function setupWebpackRuntime(\n runtime: Runtime,\n scripts: { src: string | null }[] = [],\n url: URL = new URL(location.href),\n bundle?: string,\n shared: Record<string, () => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n resolveClientUrl?: InternalResolveClientUrl,\n): Promise<void> {\n const self = globalThis as GlobalScope;\n const bundleName = bundle ?? 'default';\n\n // Create and register a scope for this remote\n const scope = createScope(bundleName, url, runtime, resolveClientUrl);\n registerScope(scope);\n\n // Still needed by patch-require.ts (webpack plugin that generates runtime\n // code as a string template — can't call getScope at build time) and the\n // HTML host (html/index.tsx writes this before setupWebpackRuntime runs).\n if (!self.__remote_bundle_url__) {\n self.__remote_bundle_url__ = {};\n }\n self.__remote_bundle_url__[bundleName] = url;\n // Also register under scopedName so webpack hosts (patch-require.ts) can\n // resolve cross-origin remotes whose bundle identifiers were rewritten.\n if (scope.scopedName !== bundleName) {\n self.__remote_bundle_url__[scope.scopedName] = url;\n }\n self.__webpack_get_script_filename__ = () => null;\n\n const willCreateDispatchers =\n typeof self.__webpack_require__ !== 'function' ||\n self.__webpack_require_type__ !== 'turbopack';\n\n if (willCreateDispatchers) {\n // preserve original webpack functions for fallback\n if (\n !self.__original_webpack_require__ &&\n !self.__original_webpack_chunk_load__\n ) {\n self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;\n self.__original_webpack_require__ = self.__webpack_require__;\n }\n\n self.__webpack_chunk_load__ = createChunkDispatcher();\n self.__webpack_require__ = createModuleDispatcher(runtime);\n self.__webpack_require_type__ = runtime;\n\n if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {\n self.__remote_webpack_require__[bundleName] =\n self.__webpack_require__ as (remoteId: string | number) => unknown;\n self.__remote_webpack_require__[bundleName].type = 'turbopack';\n }\n }\n\n // Alias __remote_webpack_require__ under the scoped name so the module\n // dispatcher can find it when RSC data uses the rewritten bundle identifier.\n // For turbopack remotes the entry was just created above; for webpack remotes\n // it was populated by the remote's own scripts under the plain name.\n if (\n self.__remote_webpack_require__?.[bundleName] &&\n scope.scopedName !== bundleName\n ) {\n self.__remote_webpack_require__[scope.scopedName] =\n self.__remote_webpack_require__[bundleName];\n }\n\n // load all initial chunks directly via scope — no global dispatch needed\n if (runtime === RUNTIME_TURBOPACK) {\n const results = await Promise.allSettled(\n scripts.map((script) => {\n if (script.src) {\n return loadChunkWithScope(scope, script.src);\n }\n return Promise.resolve(undefined);\n }),\n );\n\n for (const result of results) {\n if (result.status === 'rejected') {\n logWarn(\n 'WebpackRuntime',\n `Initial chunk load failed: ${String(result.reason)}`,\n );\n }\n }\n }\n\n // initialize shared modules with core React dependencies\n const coreShared = {\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 ...shared,\n };\n await initializeSharedModules(scope, coreShared, remoteShared);\n}\n\n/**\n * Creates the global module dispatcher for __webpack_require__.\n * Called by external code (React's RSC runtime) that doesn't have access to\n * a scope. Parses the module ID to find the correct scope and delegates\n * to scope-local module resolution.\n */\nfunction createModuleDispatcher(runtime: Runtime): (id: string) => unknown {\n return (id: string) => {\n const self = globalThis as GlobalScope;\n const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)\n ?.groups ?? {\n bundle: 'default',\n id,\n };\n const bundleName = bundle ?? 'default';\n const remoteRuntime = self.__remote_webpack_require__?.[bundleName]\n ? self.__remote_webpack_require__[bundleName]?.type || 'webpack'\n : runtime;\n\n logDebug(\n 'ModuleDispatcher',\n `Resolving \"${id}\" (bundle: \"${bundleName}\", runtime: \"${remoteRuntime}\")`,\n );\n\n try {\n // for webpack remotes, use the pre-loaded require function\n if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {\n return self.__remote_webpack_require__?.[bundle]?.(moduleId);\n }\n\n // Look up scope by parsed bundle name. Works with both the scoped\n // name (Next.js hosts with server-side rewriting) and the plain\n // bundle name (static/HTML hosts with unrewritten chunks).\n const scope = getScope(bundleName);\n if (scope) {\n return requireModule(scope, moduleId ?? id, id);\n }\n\n throw new Error(\n `Module \"${id}\" not found — no scope for bundle \"${bundleName}\".`,\n );\n } catch (requireError) {\n logWarn(\n 'ModuleDispatcher',\n `Module require failed: ${String(requireError)}`,\n );\n if (typeof self.__original_webpack_require__ !== 'function') {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundleName}\".`,\n {\n cause: requireError instanceof Error ? requireError : undefined,\n },\n );\n }\n try {\n logDebug(\n 'ModuleDispatcher',\n 'Falling back to original webpack require',\n );\n return self.__original_webpack_require__(id);\n } catch (originalError) {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundleName}\".`,\n { cause: originalError instanceof Error ? originalError : undefined },\n );\n }\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAIO;AACP,sBAAuC;AAEvC,mBAAsC;AACtC,oBAAkC;AAClC,0BAA0D;AAC1D,oBAA8B;AAC9B,0BAAqD;AACrD,4BAAwC;AAiBxC,eAAsB,oBACpB,SACA,UAAoC,CAAC,GACrC,MAAW,IAAI,IAAI,SAAS,IAAI,GAChC,QACA,SAAiD,CAAC,GAClD,eAAuC,CAAC,GACxC,kBACe;AACf,QAAM,OAAO;AACb,QAAM,aAAa,UAAU;AAG7B,QAAM,YAAQ,iCAAY,YAAY,KAAK,SAAS,gBAAgB;AACpE,yCAAc,KAAK;AAKnB,MAAI,CAAC,KAAK,uBAAuB;AAC/B,SAAK,wBAAwB,CAAC;AAAA,EAChC;AACA,OAAK,sBAAsB,UAAU,IAAI;AAGzC,MAAI,MAAM,eAAe,YAAY;AACnC,SAAK,sBAAsB,MAAM,UAAU,IAAI;AAAA,EACjD;AACA,OAAK,kCAAkC,MAAM;AAE7C,QAAM,wBACJ,OAAO,KAAK,wBAAwB,cACpC,KAAK,6BAA6B;AAEpC,MAAI,uBAAuB;AAEzB,QACE,CAAC,KAAK,gCACN,CAAC,KAAK,iCACN;AACA,WAAK,kCAAkC,KAAK;AAC5C,WAAK,+BAA+B,KAAK;AAAA,IAC3C;AAEA,SAAK,6BAAyB,2CAAsB;AACpD,SAAK,sBAAsB,uBAAuB,OAAO;AACzD,SAAK,2BAA2B;AAEhC,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K,6BAA6B,UAAU,IAC9D,KAAK,2BAA2B,UAAU,GAAG,QAAQ,YACrD;AAEJ;AAAA,MACE;AAAA,MACA,cAAc,iBAAiB,0BAA0B;AAAA,IAC3D;AAEA,QAAI;AAEF,UAAI,kBAAkB,oCAAmB,UAAU,UAAU;AAC3D,eAAO,KAAK,6BAA6B,MAAM,IAAI,QAAQ;AAAA,MAC7D;AAKA,YAAM,YAAQ,8BAAS,UAAU;AACjC,UAAI,OAAO;AACT,mBAAO,6BAAc,OAAO,YAAY,IAAI,EAAE;AAAA,MAChD;AAEA,YAAM,IAAI;AAAA,QACR,WAAW,6CAAwC;AAAA,MACrD;AAAA,IACF,SAAS,cAAP;AACA;AAAA,QACE;AAAA,QACA,0BAA0B,OAAO,YAAY;AAAA,MAC/C;AACA,UAAI,OAAO,KAAK,iCAAiC,YAAY;AAC3D,cAAM,IAAI;AAAA,UACR,WAAW,6CAA6C;AAAA,UACxD;AAAA,YACE,OAAO,wBAAwB,QAAQ,eAAe;AAAA,UACxD;AAAA,QACF;AAAA,MACF;AACA,UAAI;AACF;AAAA,UACE;AAAA,UACA;AAAA,QACF;AACA,eAAO,KAAK,6BAA6B,EAAE;AAAA,MAC7C,SAAS,eAAP;AACA,cAAM,IAAI;AAAA,UACR,WAAW,6CAA6C;AAAA,UACxD,EAAE,OAAO,yBAAyB,QAAQ,gBAAgB,OAAU;AAAA,QACtE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -3,8 +3,11 @@ import { Runtime } from '../constants.js';
3
3
 
4
4
  /**
5
5
  * Sets up webpack runtime environment for remote components.
6
- * This function initializes the global webpack require and chunk loading functions
7
- * to support loading and executing remote component bundles.
6
+ *
7
+ * Creates a RemoteScope that encapsulates all per-remote state (base URL,
8
+ * proxy callback, module cache, shared modules) and registers it in the
9
+ * global scope registry. Global dispatchers (__webpack_require__,
10
+ * __webpack_chunk_load__) are set once and route to the correct scope.
8
11
  *
9
12
  * @param runtime - The bundler runtime type ('webpack' or 'turbopack')
10
13
  * @param scripts - Initial script chunks to load for Turbopack runtime
@@ -5,35 +5,45 @@ import {
5
5
  import { REMOTE_COMPONENT_REGEX } from "#internal/runtime/patterns";
6
6
  import { RemoteComponentsError } from "#internal/utils/error";
7
7
  import { logDebug, logWarn } from "#internal/utils/logger";
8
- import { createChunkLoader } from "./chunk-loader";
9
- import { handleTurbopackModule } from "./module";
10
- import { getSharedModule, initializeSharedModules } from "./shared-modules";
8
+ import { createChunkDispatcher, loadChunkWithScope } from "./chunk-loader";
9
+ import { requireModule } from "./module";
10
+ import { createScope, getScope, registerScope } from "./remote-scope";
11
+ import { initializeSharedModules } from "./shared-modules";
11
12
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
12
13
  const self = globalThis;
14
+ const bundleName = bundle ?? "default";
15
+ const scope = createScope(bundleName, url, runtime, resolveClientUrl);
16
+ registerScope(scope);
13
17
  if (!self.__remote_bundle_url__) {
14
18
  self.__remote_bundle_url__ = {};
15
19
  }
16
- self.__remote_bundle_url__[bundle ?? "default"] = url;
20
+ self.__remote_bundle_url__[bundleName] = url;
21
+ if (scope.scopedName !== bundleName) {
22
+ self.__remote_bundle_url__[scope.scopedName] = url;
23
+ }
17
24
  self.__webpack_get_script_filename__ = () => null;
18
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
25
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
26
+ if (willCreateDispatchers) {
19
27
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
20
28
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
21
29
  self.__original_webpack_require__ = self.__webpack_require__;
22
30
  }
23
- self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
24
- self.__webpack_require__ = createModuleRequire(runtime);
31
+ self.__webpack_chunk_load__ = createChunkDispatcher();
32
+ self.__webpack_require__ = createModuleDispatcher(runtime);
25
33
  self.__webpack_require_type__ = runtime;
26
34
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
27
- const remoteBundle = bundle ?? "default";
28
- self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
29
- self.__remote_webpack_require__[remoteBundle].type = "turbopack";
35
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
36
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
30
37
  }
31
38
  }
39
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
40
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
41
+ }
32
42
  if (runtime === RUNTIME_TURBOPACK) {
33
43
  const results = await Promise.allSettled(
34
44
  scripts.map((script) => {
35
45
  if (script.src) {
36
- return self.__webpack_chunk_load__?.(script.src, bundle);
46
+ return loadChunkWithScope(scope, script.src);
37
47
  }
38
48
  return Promise.resolve(void 0);
39
49
  })
@@ -55,54 +65,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
55
65
  "react-dom/client": async () => (await import("react-dom/client")).default,
56
66
  ...shared
57
67
  };
58
- await initializeSharedModules(
59
- bundle ?? "default",
60
- // include all core modules as shared
61
- coreShared,
62
- remoteShared
63
- );
68
+ await initializeSharedModules(scope, coreShared, remoteShared);
64
69
  }
65
- function createModuleRequire(runtime) {
70
+ function createModuleDispatcher(runtime) {
66
71
  return (id) => {
67
72
  const self = globalThis;
68
73
  const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
69
74
  bundle: "default",
70
75
  id
71
76
  };
72
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
73
- logDebug("WebpackRuntime", `remoteRuntime: "${remoteRuntime}"`);
77
+ const bundleName = bundle ?? "default";
78
+ const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
79
+ logDebug(
80
+ "ModuleDispatcher",
81
+ `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
82
+ );
74
83
  try {
75
84
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
76
85
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
77
86
  }
78
- const sharedModuleId = moduleId ?? id;
79
- const sharedModule = getSharedModule(bundle ?? "default", sharedModuleId);
80
- if (sharedModule) {
81
- return sharedModule;
87
+ const scope = getScope(bundleName);
88
+ if (scope) {
89
+ return requireModule(scope, moduleId ?? id, id);
82
90
  }
83
- if (bundle && moduleId) {
84
- return handleTurbopackModule(bundle, moduleId, id);
85
- }
86
- throw new Error(`Module "${id}" not found.`);
91
+ throw new Error(
92
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
93
+ );
87
94
  } catch (requireError) {
88
95
  logWarn(
89
- "WebpackRuntime",
96
+ "ModuleDispatcher",
90
97
  `Module require failed: ${String(requireError)}`
91
98
  );
92
99
  if (typeof self.__original_webpack_require__ !== "function") {
93
100
  throw new RemoteComponentsError(
94
- `Module "${id}" not found in remote component bundle "${bundle}".`,
101
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
95
102
  {
96
103
  cause: requireError instanceof Error ? requireError : void 0
97
104
  }
98
105
  );
99
106
  }
100
107
  try {
101
- logDebug("WebpackRuntime", "Falling back to original webpack require");
108
+ logDebug(
109
+ "ModuleDispatcher",
110
+ "Falling back to original webpack require"
111
+ );
102
112
  return self.__original_webpack_require__(id);
103
113
  } catch (originalError) {
104
114
  throw new RemoteComponentsError(
105
- `Module "${id}" not found in remote component bundle "${bundle}".`,
115
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
106
116
  { cause: originalError instanceof Error ? originalError : void 0 }
107
117
  );
108
118
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/runtime/turbopack/webpack-runtime.ts"],"sourcesContent":["import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n RUNTIME_TURBOPACK,\n RUNTIME_WEBPACK,\n type Runtime,\n} from '#internal/runtime/constants';\nimport { REMOTE_COMPONENT_REGEX } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { logDebug, logWarn } from '#internal/utils/logger';\nimport { createChunkLoader } from './chunk-loader';\nimport { handleTurbopackModule } from './module';\nimport { getSharedModule, initializeSharedModules } from './shared-modules';\n\n/**\n * Sets up webpack runtime environment for remote components.\n * This function initializes the global webpack require and chunk loading functions\n * to support loading and executing remote component bundles.\n *\n * @param runtime - The bundler runtime type ('webpack' or 'turbopack')\n * @param scripts - Initial script chunks to load for Turbopack runtime\n * @param url - Base URL for the remote component bundle\n * @param bundle - Bundle identifier (defaults to 'default')\n * @param shared - Host-provided shared modules (e.g., React)\n * @param remoteShared - Mapping of remote module IDs to shared module names\n */\nexport async function setupWebpackRuntime(\n runtime: Runtime,\n scripts: { src: string | null }[] = [],\n url: URL = new URL(location.href),\n bundle?: string,\n shared: Record<string, () => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n resolveClientUrl?: InternalResolveClientUrl,\n): Promise<void> {\n const self = globalThis as GlobalScope;\n\n if (!self.__remote_bundle_url__) {\n self.__remote_bundle_url__ = {};\n }\n self.__remote_bundle_url__[bundle ?? 'default'] = url;\n self.__webpack_get_script_filename__ = () => null;\n\n if (\n typeof self.__webpack_require__ !== 'function' ||\n self.__webpack_require_type__ !== 'turbopack'\n ) {\n // preserve original webpack functions for fallback\n if (\n !self.__original_webpack_require__ &&\n !self.__original_webpack_chunk_load__\n ) {\n self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;\n self.__original_webpack_require__ = self.__webpack_require__;\n }\n\n self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);\n self.__webpack_require__ = createModuleRequire(runtime);\n self.__webpack_require_type__ = runtime;\n\n if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {\n const remoteBundle = bundle ?? 'default';\n self.__remote_webpack_require__[remoteBundle] =\n self.__webpack_require__ as (remoteId: string | number) => unknown;\n self.__remote_webpack_require__[remoteBundle].type = 'turbopack';\n }\n }\n\n // load all initial chunks when using Turbopack runtime\n if (runtime === RUNTIME_TURBOPACK) {\n const results = await Promise.allSettled(\n scripts.map((script) => {\n if (script.src) {\n return self.__webpack_chunk_load__?.(script.src, bundle);\n }\n return Promise.resolve(undefined);\n }),\n );\n\n for (const result of results) {\n if (result.status === 'rejected') {\n logWarn(\n 'WebpackRuntime',\n `Initial chunk load failed: ${String(result.reason)}`,\n );\n }\n }\n }\n\n // initialize shared modules with core React dependencies\n const coreShared = {\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 ...shared,\n };\n await initializeSharedModules(\n bundle ?? 'default',\n // include all core modules as shared\n coreShared,\n remoteShared,\n );\n}\n\n/**\n * Creates module require function for webpack runtime.\n * This function resolves module IDs to their exports, handling:\n * - Webpack remotes (pre-loaded bundles)\n * - Shared modules (React, etc.)\n * - Turbopack modules (dynamically loaded)\n */\nfunction createModuleRequire(runtime: Runtime): (id: string) => unknown {\n return (id: string) => {\n const self = globalThis as GlobalScope;\n const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)\n ?.groups ?? {\n bundle: 'default',\n id,\n };\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : runtime;\n\n logDebug('WebpackRuntime', `remoteRuntime: \"${remoteRuntime}\"`);\n\n try {\n // for webpack remotes, use the pre-loaded require function\n if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {\n return self.__remote_webpack_require__?.[bundle]?.(moduleId);\n }\n const sharedModuleId = moduleId ?? id;\n const sharedModule = getSharedModule(bundle ?? 'default', sharedModuleId);\n if (sharedModule) {\n return sharedModule;\n }\n if (bundle && moduleId) {\n return handleTurbopackModule(bundle, moduleId, id);\n }\n throw new Error(`Module \"${id}\" not found.`);\n } catch (requireError) {\n logWarn(\n 'WebpackRuntime',\n `Module require failed: ${String(requireError)}`,\n );\n if (typeof self.__original_webpack_require__ !== 'function') {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundle}\".`,\n {\n cause: requireError instanceof Error ? requireError : undefined,\n },\n );\n }\n try {\n logDebug('WebpackRuntime', 'Falling back to original webpack require');\n return self.__original_webpack_require__(id);\n } catch (originalError) {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundle}\".`,\n { cause: originalError instanceof Error ? originalError : undefined },\n );\n }\n }\n };\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,8BAA8B;AAEvC,SAAS,6BAA6B;AACtC,SAAS,UAAU,eAAe;AAClC,SAAS,yBAAyB;AAClC,SAAS,6BAA6B;AACtC,SAAS,iBAAiB,+BAA+B;AAczD,eAAsB,oBACpB,SACA,UAAoC,CAAC,GACrC,MAAW,IAAI,IAAI,SAAS,IAAI,GAChC,QACA,SAAiD,CAAC,GAClD,eAAuC,CAAC,GACxC,kBACe;AACf,QAAM,OAAO;AAEb,MAAI,CAAC,KAAK,uBAAuB;AAC/B,SAAK,wBAAwB,CAAC;AAAA,EAChC;AACA,OAAK,sBAAsB,UAAU,SAAS,IAAI;AAClD,OAAK,kCAAkC,MAAM;AAE7C,MACE,OAAO,KAAK,wBAAwB,cACpC,KAAK,6BAA6B,aAClC;AAEA,QACE,CAAC,KAAK,gCACN,CAAC,KAAK,iCACN;AACA,WAAK,kCAAkC,KAAK;AAC5C,WAAK,+BAA+B,KAAK;AAAA,IAC3C;AAEA,SAAK,yBAAyB,kBAAkB,SAA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,IACvE,KAAK,2BAA2B,UAAU,SAAS,GAAG,QAAQ,YAC9D;AAEJ,aAAS,kBAAkB,mBAAmB,gBAAgB;AAE9D,QAAI;AAEF,UAAI,kBAAkB,mBAAmB,UAAU,UAAU;AAC3D,eAAO,KAAK,6BAA6B,MAAM,IAAI,QAAQ;AAAA,MAC7D;AACA,YAAM,iBAAiB,YAAY;AACnC,YAAM,eAAe,gBAAgB,UAAU,WAAW,cAAc;AACxE,UAAI,cAAc;AAChB,eAAO;AAAA,MACT;AACA,UAAI,UAAU,UAAU;AACtB,eAAO,sBAAsB,QAAQ,UAAU,EAAE;AAAA,MACnD;AACA,YAAM,IAAI,MAAM,WAAW,gBAAgB;AAAA,IAC7C,SAAS,cAAP;AACA;AAAA,QACE;AAAA,QACA,0BAA0B,OAAO,YAAY;AAAA,MAC/C;AACA,UAAI,OAAO,KAAK,iCAAiC,YAAY;AAC3D,cAAM,IAAI;AAAA,UACR,WAAW,6CAA6C;AAAA,UACxD;AAAA,YACE,OAAO,wBAAwB,QAAQ,eAAe;AAAA,UACxD;AAAA,QACF;AAAA,MACF;AACA,UAAI;AACF,iBAAS,kBAAkB,0CAA0C;AACrE,eAAO,KAAK,6BAA6B,EAAE;AAAA,MAC7C,SAAS,eAAP;AACA,cAAM,IAAI;AAAA,UACR,WAAW,6CAA6C;AAAA,UACxD,EAAE,OAAO,yBAAyB,QAAQ,gBAAgB,OAAU;AAAA,QACtE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../../src/runtime/turbopack/webpack-runtime.ts"],"sourcesContent":["import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n RUNTIME_TURBOPACK,\n RUNTIME_WEBPACK,\n type Runtime,\n} from '#internal/runtime/constants';\nimport { REMOTE_COMPONENT_REGEX } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { logDebug, logWarn } from '#internal/utils/logger';\nimport { createChunkDispatcher, loadChunkWithScope } from './chunk-loader';\nimport { requireModule } from './module';\nimport { createScope, getScope, registerScope } from './remote-scope';\nimport { initializeSharedModules } from './shared-modules';\n\n/**\n * Sets up webpack runtime environment for remote components.\n *\n * Creates a RemoteScope that encapsulates all per-remote state (base URL,\n * proxy callback, module cache, shared modules) and registers it in the\n * global scope registry. Global dispatchers (__webpack_require__,\n * __webpack_chunk_load__) are set once and route to the correct scope.\n *\n * @param runtime - The bundler runtime type ('webpack' or 'turbopack')\n * @param scripts - Initial script chunks to load for Turbopack runtime\n * @param url - Base URL for the remote component bundle\n * @param bundle - Bundle identifier (defaults to 'default')\n * @param shared - Host-provided shared modules (e.g., React)\n * @param remoteShared - Mapping of remote module IDs to shared module names\n */\nexport async function setupWebpackRuntime(\n runtime: Runtime,\n scripts: { src: string | null }[] = [],\n url: URL = new URL(location.href),\n bundle?: string,\n shared: Record<string, () => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n resolveClientUrl?: InternalResolveClientUrl,\n): Promise<void> {\n const self = globalThis as GlobalScope;\n const bundleName = bundle ?? 'default';\n\n // Create and register a scope for this remote\n const scope = createScope(bundleName, url, runtime, resolveClientUrl);\n registerScope(scope);\n\n // Still needed by patch-require.ts (webpack plugin that generates runtime\n // code as a string template — can't call getScope at build time) and the\n // HTML host (html/index.tsx writes this before setupWebpackRuntime runs).\n if (!self.__remote_bundle_url__) {\n self.__remote_bundle_url__ = {};\n }\n self.__remote_bundle_url__[bundleName] = url;\n // Also register under scopedName so webpack hosts (patch-require.ts) can\n // resolve cross-origin remotes whose bundle identifiers were rewritten.\n if (scope.scopedName !== bundleName) {\n self.__remote_bundle_url__[scope.scopedName] = url;\n }\n self.__webpack_get_script_filename__ = () => null;\n\n const willCreateDispatchers =\n typeof self.__webpack_require__ !== 'function' ||\n self.__webpack_require_type__ !== 'turbopack';\n\n if (willCreateDispatchers) {\n // preserve original webpack functions for fallback\n if (\n !self.__original_webpack_require__ &&\n !self.__original_webpack_chunk_load__\n ) {\n self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;\n self.__original_webpack_require__ = self.__webpack_require__;\n }\n\n self.__webpack_chunk_load__ = createChunkDispatcher();\n self.__webpack_require__ = createModuleDispatcher(runtime);\n self.__webpack_require_type__ = runtime;\n\n if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {\n self.__remote_webpack_require__[bundleName] =\n self.__webpack_require__ as (remoteId: string | number) => unknown;\n self.__remote_webpack_require__[bundleName].type = 'turbopack';\n }\n }\n\n // Alias __remote_webpack_require__ under the scoped name so the module\n // dispatcher can find it when RSC data uses the rewritten bundle identifier.\n // For turbopack remotes the entry was just created above; for webpack remotes\n // it was populated by the remote's own scripts under the plain name.\n if (\n self.__remote_webpack_require__?.[bundleName] &&\n scope.scopedName !== bundleName\n ) {\n self.__remote_webpack_require__[scope.scopedName] =\n self.__remote_webpack_require__[bundleName];\n }\n\n // load all initial chunks directly via scope — no global dispatch needed\n if (runtime === RUNTIME_TURBOPACK) {\n const results = await Promise.allSettled(\n scripts.map((script) => {\n if (script.src) {\n return loadChunkWithScope(scope, script.src);\n }\n return Promise.resolve(undefined);\n }),\n );\n\n for (const result of results) {\n if (result.status === 'rejected') {\n logWarn(\n 'WebpackRuntime',\n `Initial chunk load failed: ${String(result.reason)}`,\n );\n }\n }\n }\n\n // initialize shared modules with core React dependencies\n const coreShared = {\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 ...shared,\n };\n await initializeSharedModules(scope, coreShared, remoteShared);\n}\n\n/**\n * Creates the global module dispatcher for __webpack_require__.\n * Called by external code (React's RSC runtime) that doesn't have access to\n * a scope. Parses the module ID to find the correct scope and delegates\n * to scope-local module resolution.\n */\nfunction createModuleDispatcher(runtime: Runtime): (id: string) => unknown {\n return (id: string) => {\n const self = globalThis as GlobalScope;\n const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)\n ?.groups ?? {\n bundle: 'default',\n id,\n };\n const bundleName = bundle ?? 'default';\n const remoteRuntime = self.__remote_webpack_require__?.[bundleName]\n ? self.__remote_webpack_require__[bundleName]?.type || 'webpack'\n : runtime;\n\n logDebug(\n 'ModuleDispatcher',\n `Resolving \"${id}\" (bundle: \"${bundleName}\", runtime: \"${remoteRuntime}\")`,\n );\n\n try {\n // for webpack remotes, use the pre-loaded require function\n if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {\n return self.__remote_webpack_require__?.[bundle]?.(moduleId);\n }\n\n // Look up scope by parsed bundle name. Works with both the scoped\n // name (Next.js hosts with server-side rewriting) and the plain\n // bundle name (static/HTML hosts with unrewritten chunks).\n const scope = getScope(bundleName);\n if (scope) {\n return requireModule(scope, moduleId ?? id, id);\n }\n\n throw new Error(\n `Module \"${id}\" not found — no scope for bundle \"${bundleName}\".`,\n );\n } catch (requireError) {\n logWarn(\n 'ModuleDispatcher',\n `Module require failed: ${String(requireError)}`,\n );\n if (typeof self.__original_webpack_require__ !== 'function') {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundleName}\".`,\n {\n cause: requireError instanceof Error ? requireError : undefined,\n },\n );\n }\n try {\n logDebug(\n 'ModuleDispatcher',\n 'Falling back to original webpack require',\n );\n return self.__original_webpack_require__(id);\n } catch (originalError) {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundleName}\".`,\n { cause: originalError instanceof Error ? originalError : undefined },\n );\n }\n }\n };\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,8BAA8B;AAEvC,SAAS,6BAA6B;AACtC,SAAS,UAAU,eAAe;AAClC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,qBAAqB;AAC9B,SAAS,aAAa,UAAU,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