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
@@ -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
+ };
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
+ );
218
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,93 +1115,203 @@ 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`
1126
- );
1127
- await Promise.all(loadChunkLists);
1135
+ if (loadChunkPromises.length > 0) {
1136
+ await Promise.all(loadChunkPromises);
1128
1137
  }
1129
1138
  }
1130
1139
 
1131
- // src/runtime/turbopack/module.ts
1132
- function handleTurbopackModule(bundle, moduleId, id) {
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) {
1133
1143
  const self = globalThis;
1134
- const bundleKey = getBundleKey(bundle);
1135
- const raw = self[`TURBOPACK_${bundleKey}`];
1136
- let modules;
1137
- if (raw && typeof raw === "object" && "__chunks__" in raw) {
1138
- modules = raw.__chunks__.flat();
1139
- } else if (Array.isArray(raw)) {
1140
- modules = raw.flat();
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
+ );
1141
1207
  } else {
1142
- modules = raw;
1208
+ logWarn(
1209
+ "SharedModules",
1210
+ `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
1211
+ );
1143
1212
  }
1144
- if (!self.__remote_components_turbopack_modules__) {
1145
- self.__remote_components_turbopack_modules__ = {};
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];
1146
1258
  }
1147
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1148
- self.__remote_components_turbopack_modules__[bundle] = {};
1259
+ for (const [key, value] of Object.entries(scope.sharedModules)) {
1260
+ if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
1261
+ return value;
1262
+ }
1149
1263
  }
1150
- if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
1151
- return self.__remote_components_turbopack_modules__[bundle][moduleId];
1264
+ return null;
1265
+ }
1266
+
1267
+ // src/runtime/turbopack/module.ts
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
+ return sharedModule;
1275
+ return handleTurbopackModule(
1276
+ scope,
1277
+ idStr,
1278
+ fullId ?? formatRemoteId(scope, idStr)
1279
+ );
1280
+ }
1281
+ function handleTurbopackModule(scope, moduleId, id) {
1282
+ if (scope.moduleCache[moduleId]) {
1283
+ return scope.moduleCache[moduleId];
1152
1284
  }
1285
+ const modules = getTurbopackModules(scope);
1153
1286
  if (!modules) {
1154
- logError("TurbopackModule", `TURBOPACK_${bundleKey} is undefined`);
1287
+ logError(
1288
+ "TurbopackModule",
1289
+ `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1290
+ );
1155
1291
  }
1156
1292
  const moduleInit = findModuleInit(modules, moduleId);
1157
1293
  const exports = {};
1158
1294
  const moduleExports = { exports };
1159
1295
  if (typeof moduleInit !== "function") {
1160
1296
  throw new Error(
1161
- `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
1297
+ `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1162
1298
  );
1163
1299
  }
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
- }
1300
+ scope.moduleCache[moduleId] = moduleExports.exports;
1171
1301
  moduleInit(
1172
1302
  createTurbopackContext(
1173
- bundle,
1303
+ scope,
1174
1304
  exports,
1175
1305
  moduleExports,
1176
1306
  modules,
1177
1307
  moduleInit,
1178
- id,
1179
- self
1308
+ id
1180
1309
  ),
1181
1310
  moduleExports,
1182
1311
  exports
1183
1312
  );
1184
- if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
1185
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1313
+ if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1314
+ scope.moduleCache[moduleId] = moduleExports.exports;
1186
1315
  }
1187
1316
  return moduleExports.exports;
1188
1317
  }
@@ -1207,7 +1336,8 @@ function findModuleInit(modules, moduleId) {
1207
1336
  (e) => Boolean(e && typeof e === "object" && moduleId in e)
1208
1337
  )?.[moduleId];
1209
1338
  }
1210
- function createTurbopackContext(bundle, exports, moduleExports, modules, moduleInit, id, self) {
1339
+ function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1340
+ const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
1211
1341
  return {
1212
1342
  // HMR not implemented for Remote Components
1213
1343
  k: {
@@ -1223,16 +1353,10 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1223
1353
  s(bindings, esmId) {
1224
1354
  let mod = exports;
1225
1355
  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] = {};
1231
- }
1232
- if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
1233
- self.__remote_components_turbopack_modules__[bundle][esmId] = {};
1356
+ if (!scope.moduleCache[esmId]) {
1357
+ scope.moduleCache[esmId] = {};
1234
1358
  }
1235
- mod = self.__remote_components_turbopack_modules__[bundle][esmId];
1359
+ mod = scope.moduleCache[esmId];
1236
1360
  }
1237
1361
  Object.defineProperty(mod, "__esModule", { value: true });
1238
1362
  if (Array.isArray(bindings)) {
@@ -1265,7 +1389,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1265
1389
  }
1266
1390
  }
1267
1391
  },
1268
- // import
1392
+ // import — resolves directly via scope, no global dispatch
1269
1393
  i(importId) {
1270
1394
  let mod;
1271
1395
  if (typeof importId === "string") {
@@ -1276,7 +1400,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1276
1400
  /\s+<export(?<specifier>.*)>$/,
1277
1401
  ""
1278
1402
  );
1279
- mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`);
1403
+ mod = scopedRequire(normalizedId);
1280
1404
  if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1281
1405
  if (exportSource === "*") {
1282
1406
  mod[exportName] = mod;
@@ -1285,7 +1409,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1285
1409
  }
1286
1410
  }
1287
1411
  } else {
1288
- mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
1412
+ mod = scopedRequire(importId);
1289
1413
  }
1290
1414
  if (typeof mod !== "object" || mod === null) {
1291
1415
  mod = { default: mod };
@@ -1297,16 +1421,14 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1297
1421
  }
1298
1422
  return mod;
1299
1423
  },
1300
- // require
1424
+ // require — resolves directly via scope
1301
1425
  r(requireId) {
1302
- return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
1426
+ return scopedRequire(requireId);
1303
1427
  },
1304
1428
  // value exports
1305
1429
  v(value) {
1306
1430
  if (typeof value === "function") {
1307
- exports.default = value((vid) => {
1308
- return self.__webpack_require__?.(`[${bundle}] ${vid}`);
1309
- });
1431
+ exports.default = value((vid) => scopedRequire(vid));
1310
1432
  } else {
1311
1433
  moduleExports.exports = value;
1312
1434
  }
@@ -1321,17 +1443,15 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1321
1443
  );
1322
1444
  exports.default = result;
1323
1445
  },
1324
- // async module loader
1446
+ // async module loader — resolves directly via scope
1325
1447
  async A(Aid) {
1326
- const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
1327
- return mod.default(
1328
- (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
1329
- );
1448
+ const mod = scopedRequire(Aid);
1449
+ return mod.default((parentId) => scopedRequire(parentId));
1330
1450
  },
1331
1451
  // dynamic import tracking — no-op for remote components
1332
1452
  j() {
1333
1453
  },
1334
- // chunk loader
1454
+ // chunk loader — loads directly via scope, no global dispatch
1335
1455
  l(url) {
1336
1456
  const flatModules = Array.isArray(modules) ? modules : [];
1337
1457
  const moduleInitIndex = flatModules.indexOf(moduleInit);
@@ -1342,169 +1462,57 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1342
1462
  const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1343
1463
  const nextIndex = scriptSrc.indexOf("/_next");
1344
1464
  const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1345
- const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
1346
- return self.__webpack_chunk_load__?.(bundleUrl, bundle);
1465
+ const chunkUrl = `${baseUrl}/_next/${url}`;
1466
+ return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1347
1467
  }
1348
1468
  }
1349
1469
  throw new Error(
1350
1470
  `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1351
1471
  );
1352
1472
  },
1353
- // global object for this bundle
1354
- g: self.__remote_components_turbopack_global__?.[bundle],
1473
+ // globalThis substitute shared across all modules in this scope
1474
+ g: scope.moduleGlobal,
1355
1475
  m: moduleExports,
1356
1476
  e: exports
1357
1477
  };
1358
1478
  }
1359
1479
 
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
1480
  // src/runtime/turbopack/webpack-runtime.ts
1482
1481
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1483
1482
  const self = globalThis;
1483
+ const bundleName = bundle ?? "default";
1484
+ const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1485
+ registerScope(scope);
1484
1486
  if (!self.__remote_bundle_url__) {
1485
1487
  self.__remote_bundle_url__ = {};
1486
1488
  }
1487
- self.__remote_bundle_url__[bundle ?? "default"] = url;
1489
+ self.__remote_bundle_url__[bundleName] = url;
1490
+ if (scope.scopedName !== bundleName) {
1491
+ self.__remote_bundle_url__[scope.scopedName] = url;
1492
+ }
1488
1493
  self.__webpack_get_script_filename__ = () => null;
1489
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
1494
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1495
+ if (willCreateDispatchers) {
1490
1496
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1491
1497
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1492
1498
  self.__original_webpack_require__ = self.__webpack_require__;
1493
1499
  }
1494
- self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
1495
- self.__webpack_require__ = createModuleRequire(runtime);
1500
+ self.__webpack_chunk_load__ = createChunkDispatcher();
1501
+ self.__webpack_require__ = createModuleDispatcher(runtime);
1496
1502
  self.__webpack_require_type__ = runtime;
1497
1503
  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";
1504
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1505
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
1501
1506
  }
1502
1507
  }
1508
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1509
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1510
+ }
1503
1511
  if (runtime === RUNTIME_TURBOPACK) {
1504
1512
  const results = await Promise.allSettled(
1505
1513
  scripts.map((script) => {
1506
1514
  if (script.src) {
1507
- return self.__webpack_chunk_load__?.(script.src, bundle);
1515
+ return loadChunkWithScope(scope, script.src);
1508
1516
  }
1509
1517
  return Promise.resolve(void 0);
1510
1518
  })
@@ -1526,54 +1534,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1526
1534
  "react-dom/client": async () => (await import("react-dom/client")).default,
1527
1535
  ...shared
1528
1536
  };
1529
- await initializeSharedModules(
1530
- bundle ?? "default",
1531
- // include all core modules as shared
1532
- coreShared,
1533
- remoteShared
1534
- );
1537
+ await initializeSharedModules(scope, coreShared, remoteShared);
1535
1538
  }
1536
- function createModuleRequire(runtime) {
1539
+ function createModuleDispatcher(runtime) {
1537
1540
  return (id) => {
1538
1541
  const self = globalThis;
1539
1542
  const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1540
1543
  bundle: "default",
1541
1544
  id
1542
1545
  };
1543
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1544
- logDebug("WebpackRuntime", `remoteRuntime: "${remoteRuntime}"`);
1546
+ const bundleName = bundle ?? "default";
1547
+ const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
1548
+ logDebug(
1549
+ "ModuleDispatcher",
1550
+ `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
1551
+ );
1545
1552
  try {
1546
1553
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1547
1554
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1548
1555
  }
1549
- const sharedModuleId = moduleId ?? id;
1550
- const sharedModule = getSharedModule(bundle ?? "default", sharedModuleId);
1551
- if (sharedModule) {
1552
- return sharedModule;
1553
- }
1554
- if (bundle && moduleId) {
1555
- return handleTurbopackModule(bundle, moduleId, id);
1556
+ const scope = getScope(bundleName);
1557
+ if (scope) {
1558
+ return requireModule(scope, moduleId ?? id, id);
1556
1559
  }
1557
- throw new Error(`Module "${id}" not found.`);
1560
+ throw new Error(
1561
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1562
+ );
1558
1563
  } catch (requireError) {
1559
1564
  logWarn(
1560
- "WebpackRuntime",
1565
+ "ModuleDispatcher",
1561
1566
  `Module require failed: ${String(requireError)}`
1562
1567
  );
1563
1568
  if (typeof self.__original_webpack_require__ !== "function") {
1564
1569
  throw new RemoteComponentsError(
1565
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1570
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1566
1571
  {
1567
1572
  cause: requireError instanceof Error ? requireError : void 0
1568
1573
  }
1569
1574
  );
1570
1575
  }
1571
1576
  try {
1572
- logDebug("WebpackRuntime", "Falling back to original webpack require");
1577
+ logDebug(
1578
+ "ModuleDispatcher",
1579
+ "Falling back to original webpack require"
1580
+ );
1573
1581
  return self.__original_webpack_require__(id);
1574
1582
  } catch (originalError) {
1575
1583
  throw new RemoteComponentsError(
1576
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1584
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1577
1585
  { cause: originalError instanceof Error ? originalError : void 0 }
1578
1586
  );
1579
1587
  }
@@ -1592,6 +1600,13 @@ async function loadScripts(scripts, resolveClientUrl) {
1592
1600
  location.origin
1593
1601
  ).href;
1594
1602
  const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;
1603
+ const alreadyLoaded = Array.from(
1604
+ document.querySelectorAll("script[src]")
1605
+ ).some((s) => s.src === resolvedSrc);
1606
+ if (alreadyLoaded) {
1607
+ resolve();
1608
+ return;
1609
+ }
1595
1610
  const newScript = document.createElement("script");
1596
1611
  newScript.onload = () => resolve();
1597
1612
  newScript.onerror = () => {