remote-components 0.3.1 → 0.3.2

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 (64) hide show
  1. package/dist/config/nextjs.cjs.map +1 -1
  2. package/dist/config/nextjs.js.map +1 -1
  3. package/dist/host/html.cjs +390 -353
  4. package/dist/host/html.cjs.map +1 -1
  5. package/dist/host/html.js +390 -353
  6. package/dist/host/html.js.map +1 -1
  7. package/dist/host/nextjs/app/client-only.cjs +453 -435
  8. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  9. package/dist/host/nextjs/app/client-only.js +461 -443
  10. package/dist/host/nextjs/app/client-only.js.map +1 -1
  11. package/dist/host/react.cjs +381 -362
  12. package/dist/host/react.cjs.map +1 -1
  13. package/dist/host/react.js +381 -362
  14. package/dist/host/react.js.map +1 -1
  15. package/dist/internal/host/nextjs/image-shared.cjs +2 -2
  16. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  17. package/dist/internal/host/nextjs/image-shared.js +2 -2
  18. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  19. package/dist/internal/host/server/fetch-remote-component.cjs +20 -1
  20. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  21. package/dist/internal/host/server/fetch-remote-component.js +20 -1
  22. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  23. package/dist/internal/host/shared/remote-image-loader.cjs +2 -5
  24. package/dist/internal/host/shared/remote-image-loader.cjs.map +1 -1
  25. package/dist/internal/host/shared/remote-image-loader.js +2 -5
  26. package/dist/internal/host/shared/remote-image-loader.js.map +1 -1
  27. package/dist/internal/runtime/turbopack/chunk-loader.cjs +76 -126
  28. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  29. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +22 -7
  30. package/dist/internal/runtime/turbopack/chunk-loader.js +85 -131
  31. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  32. package/dist/internal/runtime/turbopack/module.cjs +56 -57
  33. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  34. package/dist/internal/runtime/turbopack/module.d.ts +14 -11
  35. package/dist/internal/runtime/turbopack/module.js +54 -56
  36. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  37. package/dist/internal/runtime/turbopack/remote-scope.cjs +101 -0
  38. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -0
  39. package/dist/internal/runtime/turbopack/remote-scope.d.ts +55 -0
  40. package/dist/internal/runtime/turbopack/remote-scope.js +73 -0
  41. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -0
  42. package/dist/internal/runtime/turbopack/shared-modules.cjs +62 -56
  43. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  44. package/dist/internal/runtime/turbopack/shared-modules.d.ts +7 -3
  45. package/dist/internal/runtime/turbopack/shared-modules.js +63 -57
  46. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  47. package/dist/internal/runtime/turbopack/webpack-runtime.cjs +39 -29
  48. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +1 -1
  49. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +5 -2
  50. package/dist/internal/runtime/turbopack/webpack-runtime.js +42 -32
  51. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +1 -1
  52. package/dist/internal/runtime/types.cjs.map +1 -1
  53. package/dist/internal/runtime/types.d.ts +4 -3
  54. package/dist/internal/utils/logger.cjs.map +1 -1
  55. package/dist/internal/utils/logger.d.ts +1 -1
  56. package/dist/internal/utils/logger.js.map +1 -1
  57. package/dist/internal/utils.cjs +5 -0
  58. package/dist/internal/utils.cjs.map +1 -1
  59. package/dist/internal/utils.d.ts +15 -1
  60. package/dist/internal/utils.js +4 -0
  61. package/dist/internal/utils.js.map +1 -1
  62. package/dist/remote/html.cjs.map +1 -1
  63. package/dist/remote/html.js.map +1 -1
  64. package/package.json +1 -1
@@ -211,11 +211,104 @@ function getClientOrServerUrl(src, serverFallback) {
211
211
  return typeof src === "string" ? new URL(src, fallback) : src;
212
212
  }
213
213
 
214
- // src/host/shared/remote-image-loader.ts
215
- function getRemoteBundleOrigin(bundle) {
214
+ // src/utils/index.ts
215
+ function escapeString(str) {
216
+ return str.replace(/[^a-z0-9]/g, "_");
217
+ }
218
+ function computeScopedName(name, options) {
219
+ return options.isCrossOrigin ? `${name}_${escapeString(options.remoteHost.toLowerCase())}` : name;
220
+ }
221
+ var attrToProp = {
222
+ fetchpriority: "fetchPriority",
223
+ crossorigin: "crossOrigin",
224
+ imagesrcset: "imageSrcSet",
225
+ imagesizes: "imageSizes",
226
+ srcset: "srcSet"
227
+ };
228
+
229
+ // src/runtime/constants.ts
230
+ var DEFAULT_BUNDLE_NAME = "__vercel_remote_bundle";
231
+ var DEFAULT_COMPONENT_NAME = "__vercel_remote_component";
232
+ var DEFAULT_ROUTE = "/";
233
+ var RUNTIME_WEBPACK = "webpack";
234
+ var RUNTIME_TURBOPACK = "turbopack";
235
+ var RUNTIME_SCRIPT = "script";
236
+ function getBundleKey(bundle) {
237
+ return escapeString(bundle);
238
+ }
239
+
240
+ // src/runtime/patterns.ts
241
+ var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
242
+ var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
243
+ var DOUBLE_SLASH_RE = /(?<!:)\/\//g;
244
+ function collapseDoubleSlashes(path) {
245
+ return path.replace(DOUBLE_SLASH_RE, "/");
246
+ }
247
+
248
+ // src/runtime/turbopack/remote-scope.ts
249
+ function getRegistry() {
216
250
  const self = globalThis;
217
- return self.__remote_bundle_url__?.[bundle]?.origin ?? "";
251
+ if (!self.__remote_component_scopes__) {
252
+ self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
253
+ }
254
+ return self.__remote_component_scopes__;
255
+ }
256
+ function createScope(name, url, runtime, resolveClientUrl) {
257
+ const isCrossOrigin = url.origin !== location.origin;
258
+ const scopedName = computeScopedName(name, {
259
+ remoteHost: url.host,
260
+ isCrossOrigin
261
+ });
262
+ const globalKey = getBundleKey(scopedName);
263
+ return {
264
+ name,
265
+ scopedName,
266
+ globalKey,
267
+ url,
268
+ runtime,
269
+ resolveClientUrl,
270
+ moduleCache: {},
271
+ sharedModules: {},
272
+ moduleGlobal: {}
273
+ };
218
274
  }
275
+ function registerScope(scope) {
276
+ const registry = getRegistry();
277
+ registry.set(scope.scopedName, scope);
278
+ if (scope.scopedName !== scope.name) {
279
+ const existing = registry.get(scope.name);
280
+ if (existing && existing.scopedName !== scope.scopedName) {
281
+ logWarn(
282
+ "RemoteScope",
283
+ `Plain name "${scope.name}" already registered by scope "${existing.scopedName}" \u2014 overwriting with "${scope.scopedName}". Static hosts will only resolve the latest one.`
284
+ );
285
+ }
286
+ registry.set(scope.name, scope);
287
+ }
288
+ logDebug(
289
+ "RemoteScope",
290
+ `Registered scope "${scope.scopedName}" (${registry.size} total)`
291
+ );
292
+ }
293
+ function getScope(name) {
294
+ return getRegistry().get(name);
295
+ }
296
+ function formatRemoteId(scope, path) {
297
+ return `[${scope.scopedName}] ${path}`;
298
+ }
299
+ function parseRemoteId(id) {
300
+ const groups = REMOTE_COMPONENT_REGEX.exec(id)?.groups;
301
+ if (groups?.bundle && groups.id) {
302
+ return {
303
+ bundle: groups.bundle,
304
+ path: groups.id,
305
+ prefix: groups.prefix ?? ""
306
+ };
307
+ }
308
+ return { bundle: "default", path: id, prefix: "" };
309
+ }
310
+
311
+ // src/host/shared/remote-image-loader.ts
219
312
  function createRemoteImageLoader(bundle, resolveClientUrl) {
220
313
  const loader = Object.assign(
221
314
  ({
@@ -225,7 +318,7 @@ function createRemoteImageLoader(bundle, resolveClientUrl) {
225
318
  quality
226
319
  }) => {
227
320
  const q = quality ?? 75;
228
- const remoteOrigin = getRemoteBundleOrigin(bundle);
321
+ const remoteOrigin = getScope(bundle)?.url.origin ?? "";
229
322
  const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;
230
323
  const basePath = isCrossOrigin ? `${remoteOrigin}${config.path ?? "/_next/image"}` : config.path ?? `${remoteOrigin}/_next/image`;
231
324
  const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;
@@ -407,29 +500,6 @@ function resolveNameFromSrc(src, defaultName) {
407
500
  return name || defaultName;
408
501
  }
409
502
 
410
- // src/utils/index.ts
411
- function escapeString(str) {
412
- return str.replace(/[^a-z0-9]/g, "_");
413
- }
414
- var attrToProp = {
415
- fetchpriority: "fetchPriority",
416
- crossorigin: "crossOrigin",
417
- imagesrcset: "imageSrcSet",
418
- imagesizes: "imageSizes",
419
- srcset: "srcSet"
420
- };
421
-
422
- // src/runtime/constants.ts
423
- var DEFAULT_BUNDLE_NAME = "__vercel_remote_bundle";
424
- var DEFAULT_COMPONENT_NAME = "__vercel_remote_component";
425
- var DEFAULT_ROUTE = "/";
426
- var RUNTIME_WEBPACK = "webpack";
427
- var RUNTIME_TURBOPACK = "turbopack";
428
- var RUNTIME_SCRIPT = "script";
429
- function getBundleKey(bundle) {
430
- return escapeString(bundle);
431
- }
432
-
433
503
  // src/runtime/html/apply-origin.ts
434
504
  var tagNames = [
435
505
  "img",
@@ -904,14 +974,6 @@ function createRSCStream(rscName, data) {
904
974
  });
905
975
  }
906
976
 
907
- // src/runtime/patterns.ts
908
- var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
909
- var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
910
- var DOUBLE_SLASH_RE = /(?<!:)\/\//g;
911
- function collapseDoubleSlashes(path) {
912
- return path.replace(DOUBLE_SLASH_RE, "/");
913
- }
914
-
915
977
  // src/runtime/turbopack/patterns.ts
916
978
  var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
917
979
  var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
@@ -921,62 +983,39 @@ var ASYNC_MODULE_ALL_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<vCb
921
983
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
922
984
 
923
985
  // src/runtime/turbopack/chunk-loader.ts
924
- function createChunkLoader(runtime, resolveClientUrl) {
925
- return function __turbopack_chunk_load__(chunkId, scriptBundle) {
926
- logDebug("ChunkLoader", `Loading chunk: "${chunkId}"`);
927
- const self = globalThis;
928
- const {
929
- bundle,
930
- id: path,
931
- prefix
932
- } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
933
- bundle: scriptBundle ?? "",
934
- id: chunkId
935
- };
936
- logDebug(
937
- "ChunkLoader",
938
- `Parsed chunk - bundle: "${bundle}", path: "${path}", prefix: "${prefix}"`
939
- );
940
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
941
- logDebug("ChunkLoader", `Remote runtime: "${remoteRuntime}"`);
942
- if (remoteRuntime === RUNTIME_WEBPACK) {
943
- logDebug("ChunkLoader", "Skipping chunk load - webpack runtime detected");
944
- return Promise.resolve(void 0);
945
- }
946
- const url = new URL(
947
- path ? `${prefix ?? ""}${path}`.replace(
948
- /(?<char>[^:])(?<double>\/\/)/g,
949
- "$1/"
950
- ) : "/",
951
- self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
952
- ).href;
953
- if (url.endsWith(".css")) {
954
- logDebug("ChunkLoader", `Skipping CSS file: "${url}"`);
955
- return;
956
- }
957
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
958
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
959
- }
960
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
961
- logDebug("ChunkLoader", `Returning cached promise for: "${url}"`);
962
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
963
- }
964
- const resolvedUrl = resolveClientUrl?.(url) ?? url;
965
- logDebug("ChunkLoader", `Fetching chunk from: "${resolvedUrl}"`);
966
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise((resolve, reject) => {
986
+ function loadChunkWithScope(scope, chunkId) {
987
+ logDebug(
988
+ "ChunkLoader",
989
+ `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
990
+ );
991
+ const self = globalThis;
992
+ const { bundle, path, prefix } = parseRemoteId(chunkId);
993
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
994
+ if (remoteRuntime === RUNTIME_WEBPACK) {
995
+ return Promise.resolve(void 0);
996
+ }
997
+ const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : "/";
998
+ const url = new URL(rawPath, scope.url).href;
999
+ if (url.endsWith(".css")) {
1000
+ return;
1001
+ }
1002
+ if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1003
+ self.__remote_components_turbopack_chunk_loader_promise__ = {};
1004
+ }
1005
+ if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1006
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
1007
+ }
1008
+ const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1009
+ if (resolvedUrl !== url) {
1010
+ logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1011
+ }
1012
+ self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1013
+ (resolve, reject) => {
967
1014
  fetch(resolvedUrl).then((res) => res.text()).then((code) => {
968
1015
  const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
969
1016
  if (hasTurbopack) {
970
- return handleTurbopackChunk(code, bundle ?? "", url);
1017
+ return handleTurbopackChunk(code, scope, url);
971
1018
  }
972
- logDebug(
973
- "ChunkLoader",
974
- `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: "${url}"`
975
- );
976
- logDebug(
977
- "ChunkLoader",
978
- `First 500 chars of chunk: ${code.slice(0, 500)}`
979
- );
980
1019
  }).then(resolve).catch((error) => {
981
1020
  const isProxied = isProxiedUrl(resolvedUrl);
982
1021
  if (isProxied) {
@@ -986,17 +1025,29 @@ function createChunkLoader(runtime, resolveClientUrl) {
986
1025
  reject(error);
987
1026
  }
988
1027
  });
989
- });
990
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1028
+ }
1029
+ );
1030
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
1031
+ }
1032
+ function createChunkDispatcher() {
1033
+ return function __chunk_dispatcher__(chunkId, scriptBundle) {
1034
+ logDebug("ChunkDispatcher", `Dispatching chunk: "${chunkId}"`);
1035
+ const { bundle } = parseRemoteId(chunkId);
1036
+ const bundleName = bundle || scriptBundle || "default";
1037
+ const scope = getScope(bundleName);
1038
+ logDebug(
1039
+ "ChunkDispatcher",
1040
+ `Scope resolution: bundle="${bundleName}", scope=${scope?.scopedName ?? "null"}`
1041
+ );
1042
+ if (!scope) {
1043
+ logWarn("ChunkDispatcher", `No scope found for bundle "${bundleName}"`);
1044
+ return Promise.resolve(void 0);
1045
+ }
1046
+ return loadChunkWithScope(scope, chunkId);
991
1047
  };
992
1048
  }
993
- async function handleTurbopackChunk(code, bundle, url) {
994
- logDebug(
995
- "ChunkLoader",
996
- `Handling Turbopack chunk - bundle: "${bundle}", url: "${url}"`
997
- );
1049
+ async function handleTurbopackChunk(code, scope, url) {
998
1050
  if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
999
- logDebug("ChunkLoader", `Skipping worker chunk: "${url}"`);
1000
1051
  const preloadLinks = document.querySelectorAll(
1001
1052
  `link[rel="preload"][href="${new URL(url).pathname}"]`
1002
1053
  );
@@ -1004,58 +1055,41 @@ async function handleTurbopackChunk(code, bundle, url) {
1004
1055
  return;
1005
1056
  }
1006
1057
  const self = globalThis;
1007
- const bundleKey = getBundleKey(bundle);
1008
- logDebug("ChunkLoader", `Bundle key: "${bundleKey}"`);
1058
+ const { globalKey } = scope;
1009
1059
  const transformedCode = code.replace(
1010
1060
  /globalThis\[\s*["']TURBOPACK["']\s*\]/g,
1011
- `globalThis["TURBOPACK_${bundleKey}"]`
1061
+ `globalThis["TURBOPACK_${globalKey}"]`
1012
1062
  ).replace(
1013
1063
  /self\[\s*["']TURBOPACK["']\s*\]/g,
1014
- `self["TURBOPACK_${bundleKey}"]`
1015
- ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`).replace(
1064
+ `self["TURBOPACK_${globalKey}"]`
1065
+ ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`).replace(
1016
1066
  /TURBOPACK_WORKER_LOCATION/g,
1017
- `TURBOPACK_WORKER_LOCATION_${bundleKey}`
1067
+ `TURBOPACK_WORKER_LOCATION_${globalKey}`
1018
1068
  ).replace(
1019
1069
  /TURBOPACK_NEXT_CHUNK_URLS/g,
1020
- `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
1070
+ `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`
1021
1071
  ).replace(
1022
1072
  /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
1023
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
1024
- ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
1073
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`
1074
+ ).replace(/__next_require__/g, `__${globalKey}_next_require__`).replace(
1025
1075
  /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
1026
- `//# sourceMappingURL=${new URL(
1027
- ".",
1028
- new URL(
1029
- url,
1030
- self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
1031
- )
1032
- ).href}$1$2.js.map`
1076
+ `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1033
1077
  );
1034
- if (!self[`TURBOPACK_${bundleKey}`]) {
1078
+ if (!self[`TURBOPACK_${globalKey}`]) {
1035
1079
  const chunkData = [];
1036
1080
  const turbopackObject = {
1037
1081
  push: (item) => {
1038
- logDebug(
1039
- "ChunkLoader",
1040
- `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? "array" : typeof item}`
1041
- );
1042
1082
  if (Array.isArray(item)) {
1043
1083
  chunkData.push(item);
1044
- logDebug(
1045
- "ChunkLoader",
1046
- `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`
1047
- );
1048
1084
  } else {
1049
1085
  chunkData.push([item]);
1050
1086
  }
1051
1087
  return chunkData.length;
1052
1088
  },
1053
- // Store chunks for later access
1054
1089
  __chunks__: chunkData
1055
1090
  };
1056
- self[`TURBOPACK_${bundleKey}`] = turbopackObject;
1091
+ self[`TURBOPACK_${globalKey}`] = turbopackObject;
1057
1092
  }
1058
- logDebug("ChunkLoader", `Creating blob script for: "${url}"`);
1059
1093
  await new Promise((scriptResolve, scriptReject) => {
1060
1094
  const blob = new Blob([transformedCode], {
1061
1095
  type: "application/javascript; charset=UTF-8"
@@ -1067,21 +1101,6 @@ async function handleTurbopackChunk(code, bundle, url) {
1067
1101
  script.async = true;
1068
1102
  script.onload = () => {
1069
1103
  URL.revokeObjectURL(scriptUrl);
1070
- logDebug(
1071
- "ChunkLoader",
1072
- `Script loaded successfully for bundle "${bundle}"`
1073
- );
1074
- const turbopackBundle = self[`TURBOPACK_${bundleKey}`];
1075
- logDebug(
1076
- "ChunkLoader",
1077
- `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${turbopackBundle ? Object.keys(turbopackBundle).slice(0, 10).join(", ") : "none"}`
1078
- );
1079
- if (turbopackBundle && typeof turbopackBundle === "object") {
1080
- logDebug(
1081
- "ChunkLoader",
1082
- `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle).length}`
1083
- );
1084
- }
1085
1104
  scriptResolve(void 0);
1086
1105
  script.remove();
1087
1106
  };
@@ -1096,43 +1115,177 @@ async function handleTurbopackChunk(code, bundle, url) {
1096
1115
  };
1097
1116
  document.head.appendChild(script);
1098
1117
  });
1099
- const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
1100
- logDebug(
1101
- "ChunkLoader",
1102
- `Processing chunk lists for bundle "${bundle}": ${chunkLists?.length ?? 0} lists`
1103
- );
1104
- const loadChunkLists = [];
1118
+ const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`];
1119
+ const loadChunkPromises = [];
1105
1120
  while (chunkLists?.length) {
1106
1121
  const { chunks } = chunkLists.shift() ?? { chunks: [] };
1107
1122
  if (chunks.length > 0) {
1108
- logDebug(
1109
- "ChunkLoader",
1110
- `Loading ${chunks.length} additional chunks for bundle "${bundle}": [${chunks.join(", ")}]`
1111
- );
1112
- chunks.forEach((id) => {
1113
- const chunkLoadResult = self.__webpack_chunk_load__?.(
1114
- `[${bundle}] ${url.slice(0, url.indexOf("/_next"))}/_next/${id}`
1123
+ for (const id of chunks) {
1124
+ const baseUrl = url.slice(0, url.indexOf("/_next"));
1125
+ const chunkLoadResult = loadChunkWithScope(
1126
+ scope,
1127
+ formatRemoteId(scope, `${baseUrl}/_next/${id}`)
1115
1128
  );
1116
1129
  if (chunkLoadResult) {
1117
- loadChunkLists.push(chunkLoadResult);
1130
+ loadChunkPromises.push(chunkLoadResult);
1118
1131
  }
1119
- });
1132
+ }
1120
1133
  }
1121
1134
  }
1122
- if (loadChunkLists.length > 0) {
1123
- logDebug(
1124
- "ChunkLoader",
1125
- `Waiting for ${loadChunkLists.length} additional chunks to load`
1135
+ if (loadChunkPromises.length > 0) {
1136
+ await Promise.all(loadChunkPromises);
1137
+ }
1138
+ }
1139
+
1140
+ // src/runtime/turbopack/shared-modules.ts
1141
+ var 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).";
1142
+ function getTurbopackModules(scope) {
1143
+ const self = globalThis;
1144
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1145
+ if (!raw)
1146
+ return void 0;
1147
+ if (typeof raw === "object" && "__chunks__" in raw) {
1148
+ return raw.__chunks__.flat();
1149
+ }
1150
+ if (Array.isArray(raw)) {
1151
+ return raw.flat();
1152
+ }
1153
+ return Object.entries(raw).flat();
1154
+ }
1155
+ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}) {
1156
+ const allModules = getTurbopackModules(scope);
1157
+ logDebug(
1158
+ "SharedModules",
1159
+ `initializeSharedModules: scope="${scope.scopedName}", allModules=${allModules ? allModules.length : "null"}, hostShared=[${Object.keys(hostShared).join(", ")}], remoteShared=${JSON.stringify(remoteShared)}`
1160
+ );
1161
+ let sharedModuleInitializer = null;
1162
+ if (allModules) {
1163
+ const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1164
+ if (typeof idOrFunc !== "function") {
1165
+ return false;
1166
+ }
1167
+ const funcCode = idOrFunc.toString();
1168
+ return REMOTE_SHARED_MARKER_RE.test(funcCode);
1169
+ });
1170
+ if (sharedModuleInitializerIndex > 0) {
1171
+ const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1172
+ const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1173
+ const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1174
+ if (sharedModuleId) {
1175
+ const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1176
+ scope,
1177
+ sharedModuleId,
1178
+ formatRemoteId(scope, String(sharedModuleInitializerId))
1179
+ );
1180
+ sharedModuleInitializer = sharedModuleInitializerInstance;
1181
+ }
1182
+ }
1183
+ if (sharedModuleInitializer) {
1184
+ const { shared } = await sharedModuleInitializer;
1185
+ const sharedModuleIds = extractSharedModuleIds(shared, scope);
1186
+ logDebug(
1187
+ "SharedModules",
1188
+ `Resolved shared modules for scope="${scope.scopedName}": ${JSON.stringify(sharedModuleIds)}`
1189
+ );
1190
+ return Promise.all(
1191
+ Object.entries(sharedModuleIds).map(async ([id, module]) => {
1192
+ if (hostShared[module]) {
1193
+ scope.sharedModules[id] = await hostShared[module](scope.name);
1194
+ } else {
1195
+ logError(
1196
+ "SharedModules",
1197
+ `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1198
+ );
1199
+ }
1200
+ })
1201
+ );
1202
+ }
1203
+ logWarn(
1204
+ "SharedModules",
1205
+ `No shared module initializer found in bundle for scope="${scope.scopedName}" \u2014 falling back to remoteShared mapping`
1206
+ );
1207
+ } else {
1208
+ logWarn(
1209
+ "SharedModules",
1210
+ `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
1126
1211
  );
1127
- await Promise.all(loadChunkLists);
1128
1212
  }
1213
+ return Promise.all(
1214
+ Object.entries(remoteShared).map(async ([id, module]) => {
1215
+ if (hostShared[module]) {
1216
+ const normalizedId = id.replace("[app-ssr]", "[app-client]");
1217
+ scope.sharedModules[normalizedId] = await hostShared[module](
1218
+ scope.name
1219
+ );
1220
+ } else {
1221
+ logError(
1222
+ "SharedModules",
1223
+ `Shared module "${module}" not found for "${scope.name}". ${DEDUPLICATION_WARNING}`
1224
+ );
1225
+ }
1226
+ })
1227
+ );
1228
+ }
1229
+ function extractSharedModuleIds(shared, scope) {
1230
+ return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1231
+ const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1232
+ if (asyncSharedModuleId) {
1233
+ const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1234
+ let asyncSharedModule;
1235
+ const turbopackModules = getTurbopackModules(scope) ?? [];
1236
+ const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1237
+ asyncSharedModuleIdNumber
1238
+ );
1239
+ if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1240
+ asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1241
+ }
1242
+ if (asyncSharedModule) {
1243
+ const asyncSharedModuleCode = asyncSharedModule.toString();
1244
+ const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1245
+ acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1246
+ "__remote_shared_module_",
1247
+ ""
1248
+ );
1249
+ }
1250
+ }
1251
+ return acc;
1252
+ }, {});
1253
+ }
1254
+ function getSharedModule(scope, id) {
1255
+ const idStr = String(id);
1256
+ if (scope.sharedModules[idStr] !== void 0) {
1257
+ return scope.sharedModules[idStr];
1258
+ }
1259
+ for (const [key, value] of Object.entries(scope.sharedModules)) {
1260
+ if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
1261
+ return value;
1262
+ }
1263
+ }
1264
+ return null;
1129
1265
  }
1130
1266
 
1131
1267
  // src/runtime/turbopack/module.ts
1132
- function handleTurbopackModule(bundle, moduleId, id) {
1268
+ function requireModule(scope, moduleId, fullId) {
1269
+ const idStr = String(moduleId);
1270
+ if (scope.moduleCache[idStr])
1271
+ return scope.moduleCache[idStr];
1272
+ const sharedModule = getSharedModule(scope, moduleId);
1273
+ if (sharedModule) {
1274
+ scope.moduleCache[idStr] = sharedModule;
1275
+ return sharedModule;
1276
+ }
1277
+ return handleTurbopackModule(
1278
+ scope,
1279
+ idStr,
1280
+ fullId ?? formatRemoteId(scope, idStr)
1281
+ );
1282
+ }
1283
+ function handleTurbopackModule(scope, moduleId, id) {
1133
1284
  const self = globalThis;
1134
- const bundleKey = getBundleKey(bundle);
1135
- const raw = self[`TURBOPACK_${bundleKey}`];
1285
+ if (scope.moduleCache[moduleId]) {
1286
+ return scope.moduleCache[moduleId];
1287
+ }
1288
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1136
1289
  let modules;
1137
1290
  if (raw && typeof raw === "object" && "__chunks__" in raw) {
1138
1291
  modules = raw.__chunks__.flat();
@@ -1141,48 +1294,35 @@ function handleTurbopackModule(bundle, moduleId, id) {
1141
1294
  } else {
1142
1295
  modules = raw;
1143
1296
  }
1144
- if (!self.__remote_components_turbopack_modules__) {
1145
- self.__remote_components_turbopack_modules__ = {};
1146
- }
1147
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1148
- self.__remote_components_turbopack_modules__[bundle] = {};
1149
- }
1150
- if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
1151
- return self.__remote_components_turbopack_modules__[bundle][moduleId];
1152
- }
1153
1297
  if (!modules) {
1154
- logError("TurbopackModule", `TURBOPACK_${bundleKey} is undefined`);
1298
+ logError(
1299
+ "TurbopackModule",
1300
+ `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1301
+ );
1155
1302
  }
1156
1303
  const moduleInit = findModuleInit(modules, moduleId);
1157
1304
  const exports = {};
1158
1305
  const moduleExports = { exports };
1159
1306
  if (typeof moduleInit !== "function") {
1160
1307
  throw new Error(
1161
- `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
1308
+ `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1162
1309
  );
1163
1310
  }
1164
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1165
- if (!self.__remote_components_turbopack_global__) {
1166
- self.__remote_components_turbopack_global__ = {};
1167
- }
1168
- if (!self.__remote_components_turbopack_global__[bundle]) {
1169
- self.__remote_components_turbopack_global__[bundle] = {};
1170
- }
1311
+ scope.moduleCache[moduleId] = moduleExports.exports;
1171
1312
  moduleInit(
1172
1313
  createTurbopackContext(
1173
- bundle,
1314
+ scope,
1174
1315
  exports,
1175
1316
  moduleExports,
1176
1317
  modules,
1177
1318
  moduleInit,
1178
- id,
1179
- self
1319
+ id
1180
1320
  ),
1181
1321
  moduleExports,
1182
1322
  exports
1183
1323
  );
1184
- if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
1185
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1324
+ if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1325
+ scope.moduleCache[moduleId] = moduleExports.exports;
1186
1326
  }
1187
1327
  return moduleExports.exports;
1188
1328
  }
@@ -1207,7 +1347,8 @@ function findModuleInit(modules, moduleId) {
1207
1347
  (e) => Boolean(e && typeof e === "object" && moduleId in e)
1208
1348
  )?.[moduleId];
1209
1349
  }
1210
- function createTurbopackContext(bundle, exports, moduleExports, modules, moduleInit, id, self) {
1350
+ function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1351
+ const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
1211
1352
  return {
1212
1353
  // HMR not implemented for Remote Components
1213
1354
  k: {
@@ -1223,16 +1364,10 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1223
1364
  s(bindings, esmId) {
1224
1365
  let mod = exports;
1225
1366
  if (typeof esmId === "string" || typeof esmId === "number") {
1226
- if (!self.__remote_components_turbopack_modules__) {
1227
- self.__remote_components_turbopack_modules__ = {};
1228
- }
1229
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1230
- self.__remote_components_turbopack_modules__[bundle] = {};
1367
+ if (!scope.moduleCache[esmId]) {
1368
+ scope.moduleCache[esmId] = {};
1231
1369
  }
1232
- if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
1233
- self.__remote_components_turbopack_modules__[bundle][esmId] = {};
1234
- }
1235
- mod = self.__remote_components_turbopack_modules__[bundle][esmId];
1370
+ mod = scope.moduleCache[esmId];
1236
1371
  }
1237
1372
  Object.defineProperty(mod, "__esModule", { value: true });
1238
1373
  if (Array.isArray(bindings)) {
@@ -1265,7 +1400,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1265
1400
  }
1266
1401
  }
1267
1402
  },
1268
- // import
1403
+ // import — resolves directly via scope, no global dispatch
1269
1404
  i(importId) {
1270
1405
  let mod;
1271
1406
  if (typeof importId === "string") {
@@ -1276,7 +1411,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1276
1411
  /\s+<export(?<specifier>.*)>$/,
1277
1412
  ""
1278
1413
  );
1279
- mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`);
1414
+ mod = scopedRequire(normalizedId);
1280
1415
  if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1281
1416
  if (exportSource === "*") {
1282
1417
  mod[exportName] = mod;
@@ -1285,7 +1420,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1285
1420
  }
1286
1421
  }
1287
1422
  } else {
1288
- mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
1423
+ mod = scopedRequire(importId);
1289
1424
  }
1290
1425
  if (typeof mod !== "object" || mod === null) {
1291
1426
  mod = { default: mod };
@@ -1297,16 +1432,14 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1297
1432
  }
1298
1433
  return mod;
1299
1434
  },
1300
- // require
1435
+ // require — resolves directly via scope
1301
1436
  r(requireId) {
1302
- return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
1437
+ return scopedRequire(requireId);
1303
1438
  },
1304
1439
  // value exports
1305
1440
  v(value) {
1306
1441
  if (typeof value === "function") {
1307
- exports.default = value((vid) => {
1308
- return self.__webpack_require__?.(`[${bundle}] ${vid}`);
1309
- });
1442
+ exports.default = value((vid) => scopedRequire(vid));
1310
1443
  } else {
1311
1444
  moduleExports.exports = value;
1312
1445
  }
@@ -1321,17 +1454,15 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1321
1454
  );
1322
1455
  exports.default = result;
1323
1456
  },
1324
- // async module loader
1457
+ // async module loader — resolves directly via scope
1325
1458
  async A(Aid) {
1326
- const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
1327
- return mod.default(
1328
- (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
1329
- );
1459
+ const mod = scopedRequire(Aid);
1460
+ return mod.default((parentId) => scopedRequire(parentId));
1330
1461
  },
1331
1462
  // dynamic import tracking — no-op for remote components
1332
1463
  j() {
1333
1464
  },
1334
- // chunk loader
1465
+ // chunk loader — loads directly via scope, no global dispatch
1335
1466
  l(url) {
1336
1467
  const flatModules = Array.isArray(modules) ? modules : [];
1337
1468
  const moduleInitIndex = flatModules.indexOf(moduleInit);
@@ -1342,169 +1473,57 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1342
1473
  const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1343
1474
  const nextIndex = scriptSrc.indexOf("/_next");
1344
1475
  const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1345
- const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
1346
- return self.__webpack_chunk_load__?.(bundleUrl, bundle);
1476
+ const chunkUrl = `${baseUrl}/_next/${url}`;
1477
+ return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1347
1478
  }
1348
1479
  }
1349
1480
  throw new Error(
1350
1481
  `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1351
1482
  );
1352
1483
  },
1353
- // global object for this bundle
1354
- g: self.__remote_components_turbopack_global__?.[bundle],
1484
+ // globalThis substitute shared across all modules in this scope
1485
+ g: scope.moduleGlobal,
1355
1486
  m: moduleExports,
1356
1487
  e: exports
1357
1488
  };
1358
1489
  }
1359
1490
 
1360
- // src/runtime/turbopack/shared-modules.ts
1361
- var 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).";
1362
- async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {}) {
1363
- const self = globalThis;
1364
- self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
1365
- if (!self.__remote_shared_modules__[bundle]) {
1366
- self.__remote_shared_modules__[bundle] = {};
1367
- }
1368
- const bundleKey = getBundleKey(bundle);
1369
- let modules = self[`TURBOPACK_${bundleKey}`];
1370
- if (modules && typeof modules === "object" && "__chunks__" in modules) {
1371
- const chunks = modules.__chunks__;
1372
- modules = chunks.flat();
1373
- }
1374
- let sharedModuleInitializer = null;
1375
- if (modules) {
1376
- const allModules = Array.isArray(modules) ? modules.flat() : Object.entries(modules).flat();
1377
- const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1378
- if (typeof idOrFunc !== "function") {
1379
- return false;
1380
- }
1381
- const funcCode = idOrFunc.toString();
1382
- return REMOTE_SHARED_MARKER_RE.test(funcCode);
1383
- });
1384
- if (sharedModuleInitializerIndex > 0) {
1385
- const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1386
- const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1387
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1388
- if (sharedModuleId) {
1389
- const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1390
- bundle,
1391
- sharedModuleId,
1392
- `[${bundle}] ${sharedModuleInitializerId}`
1393
- );
1394
- sharedModuleInitializer = sharedModuleInitializerInstance;
1395
- }
1396
- }
1397
- if (sharedModuleInitializer) {
1398
- const { shared } = await sharedModuleInitializer;
1399
- const sharedModuleIds = extractSharedModuleIds(
1400
- shared,
1401
- bundleKey,
1402
- self
1403
- );
1404
- return Promise.all(
1405
- Object.entries(sharedModuleIds).map(async ([id, module]) => {
1406
- if (self.__remote_shared_modules__?.[bundle]) {
1407
- if (hostShared[module]) {
1408
- self.__remote_shared_modules__[bundle][id] = await hostShared[module](bundle);
1409
- } else {
1410
- logError(
1411
- "SharedModules",
1412
- `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1413
- );
1414
- }
1415
- }
1416
- })
1417
- );
1418
- }
1419
- }
1420
- return Promise.all(
1421
- Object.entries(remoteShared).map(async ([id, module]) => {
1422
- if (self.__remote_shared_modules__?.[bundle]) {
1423
- if (hostShared[module]) {
1424
- const normalizedId = id.replace("[app-ssr]", "[app-client]");
1425
- self.__remote_shared_modules__[bundle][normalizedId] = await hostShared[module](bundle);
1426
- } else {
1427
- logError(
1428
- "SharedModules",
1429
- `Shared module "${module}" not found for "${bundle}". ${DEDUPLICATION_WARNING}`
1430
- );
1431
- }
1432
- }
1433
- })
1434
- );
1435
- }
1436
- function extractSharedModuleIds(shared, bundleKey, self) {
1437
- return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1438
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1439
- if (asyncSharedModuleId) {
1440
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1441
- let asyncSharedModule;
1442
- let turbopackModules = self[`TURBOPACK_${bundleKey}`];
1443
- if (turbopackModules && typeof turbopackModules === "object" && "__chunks__" in turbopackModules) {
1444
- const chunks = turbopackModules.__chunks__;
1445
- turbopackModules = chunks.flat();
1446
- }
1447
- const newAllModules = Array.isArray(turbopackModules) ? turbopackModules.flat() : turbopackModules ? Object.entries(turbopackModules).flatMap(([key2, value2]) => [
1448
- key2,
1449
- value2
1450
- ]) : [];
1451
- const asyncSharedModuleIdIndex = newAllModules.indexOf(
1452
- asyncSharedModuleIdNumber
1453
- );
1454
- if (asyncSharedModuleIdIndex !== -1 && typeof newAllModules[asyncSharedModuleIdIndex + 1] === "function") {
1455
- asyncSharedModule = newAllModules[asyncSharedModuleIdIndex + 1];
1456
- }
1457
- if (asyncSharedModule) {
1458
- const asyncSharedModuleCode = asyncSharedModule.toString();
1459
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1460
- acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1461
- "__remote_shared_module_",
1462
- ""
1463
- );
1464
- }
1465
- }
1466
- return acc;
1467
- }, {});
1468
- }
1469
- function getSharedModule(bundle, id) {
1470
- const self = globalThis;
1471
- for (const [key, value] of Object.entries(
1472
- self.__remote_shared_modules__?.[bundle] ?? {}
1473
- )) {
1474
- if (typeof value !== "undefined" && (typeof id === "string" && id.includes(key) || id === key)) {
1475
- return value;
1476
- }
1477
- }
1478
- return null;
1479
- }
1480
-
1481
1491
  // src/runtime/turbopack/webpack-runtime.ts
1482
1492
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1483
1493
  const self = globalThis;
1494
+ const bundleName = bundle ?? "default";
1495
+ const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1496
+ registerScope(scope);
1484
1497
  if (!self.__remote_bundle_url__) {
1485
1498
  self.__remote_bundle_url__ = {};
1486
1499
  }
1487
- self.__remote_bundle_url__[bundle ?? "default"] = url;
1500
+ self.__remote_bundle_url__[bundleName] = url;
1501
+ if (scope.scopedName !== bundleName) {
1502
+ self.__remote_bundle_url__[scope.scopedName] = url;
1503
+ }
1488
1504
  self.__webpack_get_script_filename__ = () => null;
1489
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
1505
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1506
+ if (willCreateDispatchers) {
1490
1507
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1491
1508
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1492
1509
  self.__original_webpack_require__ = self.__webpack_require__;
1493
1510
  }
1494
- self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
1495
- self.__webpack_require__ = createModuleRequire(runtime);
1511
+ self.__webpack_chunk_load__ = createChunkDispatcher();
1512
+ self.__webpack_require__ = createModuleDispatcher(runtime);
1496
1513
  self.__webpack_require_type__ = runtime;
1497
1514
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1498
- const remoteBundle = bundle ?? "default";
1499
- self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
1500
- self.__remote_webpack_require__[remoteBundle].type = "turbopack";
1515
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1516
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
1501
1517
  }
1502
1518
  }
1519
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1520
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1521
+ }
1503
1522
  if (runtime === RUNTIME_TURBOPACK) {
1504
1523
  const results = await Promise.allSettled(
1505
1524
  scripts.map((script) => {
1506
1525
  if (script.src) {
1507
- return self.__webpack_chunk_load__?.(script.src, bundle);
1526
+ return loadChunkWithScope(scope, script.src);
1508
1527
  }
1509
1528
  return Promise.resolve(void 0);
1510
1529
  })
@@ -1526,54 +1545,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1526
1545
  "react-dom/client": async () => (await import("react-dom/client")).default,
1527
1546
  ...shared
1528
1547
  };
1529
- await initializeSharedModules(
1530
- bundle ?? "default",
1531
- // include all core modules as shared
1532
- coreShared,
1533
- remoteShared
1534
- );
1548
+ await initializeSharedModules(scope, coreShared, remoteShared);
1535
1549
  }
1536
- function createModuleRequire(runtime) {
1550
+ function createModuleDispatcher(runtime) {
1537
1551
  return (id) => {
1538
1552
  const self = globalThis;
1539
1553
  const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1540
1554
  bundle: "default",
1541
1555
  id
1542
1556
  };
1543
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1544
- logDebug("WebpackRuntime", `remoteRuntime: "${remoteRuntime}"`);
1557
+ const bundleName = bundle ?? "default";
1558
+ const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
1559
+ logDebug(
1560
+ "ModuleDispatcher",
1561
+ `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
1562
+ );
1545
1563
  try {
1546
1564
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1547
1565
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1548
1566
  }
1549
- const sharedModuleId = moduleId ?? id;
1550
- const sharedModule = getSharedModule(bundle ?? "default", sharedModuleId);
1551
- if (sharedModule) {
1552
- return sharedModule;
1567
+ const scope = getScope(bundleName);
1568
+ if (scope) {
1569
+ return requireModule(scope, moduleId ?? id, id);
1553
1570
  }
1554
- if (bundle && moduleId) {
1555
- return handleTurbopackModule(bundle, moduleId, id);
1556
- }
1557
- throw new Error(`Module "${id}" not found.`);
1571
+ throw new Error(
1572
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1573
+ );
1558
1574
  } catch (requireError) {
1559
1575
  logWarn(
1560
- "WebpackRuntime",
1576
+ "ModuleDispatcher",
1561
1577
  `Module require failed: ${String(requireError)}`
1562
1578
  );
1563
1579
  if (typeof self.__original_webpack_require__ !== "function") {
1564
1580
  throw new RemoteComponentsError(
1565
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1581
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1566
1582
  {
1567
1583
  cause: requireError instanceof Error ? requireError : void 0
1568
1584
  }
1569
1585
  );
1570
1586
  }
1571
1587
  try {
1572
- logDebug("WebpackRuntime", "Falling back to original webpack require");
1588
+ logDebug(
1589
+ "ModuleDispatcher",
1590
+ "Falling back to original webpack require"
1591
+ );
1573
1592
  return self.__original_webpack_require__(id);
1574
1593
  } catch (originalError) {
1575
1594
  throw new RemoteComponentsError(
1576
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1595
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1577
1596
  { cause: originalError instanceof Error ? originalError : void 0 }
1578
1597
  );
1579
1598
  }