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
@@ -213,6 +213,9 @@ var init_logger = __esm({
213
213
  function escapeString(str) {
214
214
  return str.replace(/[^a-z0-9]/g, "_");
215
215
  }
216
+ function computeScopedName(name, options) {
217
+ return options.isCrossOrigin ? `${name}_${escapeString(options.remoteHost.toLowerCase())}` : name;
218
+ }
216
219
  var init_utils = __esm({
217
220
  "src/utils/index.ts"() {
218
221
  "use strict";
@@ -424,11 +427,93 @@ var init_next_client_pages_loader = __esm({
424
427
  }
425
428
  });
426
429
 
427
- // src/host/shared/remote-image-loader.ts
428
- function getRemoteBundleOrigin(bundle) {
430
+ // src/runtime/patterns.ts
431
+ function collapseDoubleSlashes(path) {
432
+ return path.replace(DOUBLE_SLASH_RE, "/");
433
+ }
434
+ var REMOTE_COMPONENT_REGEX, NEXT_BUNDLE_PATH_RE, DOUBLE_SLASH_RE;
435
+ var init_patterns = __esm({
436
+ "src/runtime/patterns.ts"() {
437
+ "use strict";
438
+ REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
439
+ NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
440
+ DOUBLE_SLASH_RE = /(?<!:)\/\//g;
441
+ }
442
+ });
443
+
444
+ // src/runtime/turbopack/remote-scope.ts
445
+ function getRegistry() {
429
446
  const self = globalThis;
430
- return self.__remote_bundle_url__?.[bundle]?.origin ?? "";
447
+ if (!self.__remote_component_scopes__) {
448
+ self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
449
+ }
450
+ return self.__remote_component_scopes__;
451
+ }
452
+ function createScope(name, url, runtime, resolveClientUrl) {
453
+ const isCrossOrigin = url.origin !== location.origin;
454
+ const scopedName = computeScopedName(name, {
455
+ remoteHost: url.host,
456
+ isCrossOrigin
457
+ });
458
+ const globalKey = getBundleKey(scopedName);
459
+ return {
460
+ name,
461
+ scopedName,
462
+ globalKey,
463
+ url,
464
+ runtime,
465
+ resolveClientUrl,
466
+ moduleCache: {},
467
+ sharedModules: {},
468
+ moduleGlobal: {}
469
+ };
470
+ }
471
+ function registerScope(scope) {
472
+ const registry = getRegistry();
473
+ registry.set(scope.scopedName, scope);
474
+ if (scope.scopedName !== scope.name) {
475
+ const existing = registry.get(scope.name);
476
+ if (existing && existing.scopedName !== scope.scopedName) {
477
+ logWarn(
478
+ "RemoteScope",
479
+ `Plain name "${scope.name}" already registered by scope "${existing.scopedName}" \u2014 overwriting with "${scope.scopedName}". Static hosts will only resolve the latest one.`
480
+ );
481
+ }
482
+ registry.set(scope.name, scope);
483
+ }
484
+ logDebug(
485
+ "RemoteScope",
486
+ `Registered scope "${scope.scopedName}" (${registry.size} total)`
487
+ );
488
+ }
489
+ function getScope(name) {
490
+ return getRegistry().get(name);
491
+ }
492
+ function formatRemoteId(scope, path) {
493
+ return `[${scope.scopedName}] ${path}`;
494
+ }
495
+ function parseRemoteId(id) {
496
+ const groups = REMOTE_COMPONENT_REGEX.exec(id)?.groups;
497
+ if (groups?.bundle && groups.id) {
498
+ return {
499
+ bundle: groups.bundle,
500
+ path: groups.id,
501
+ prefix: groups.prefix ?? ""
502
+ };
503
+ }
504
+ return { bundle: "default", path: id, prefix: "" };
431
505
  }
506
+ var init_remote_scope = __esm({
507
+ "src/runtime/turbopack/remote-scope.ts"() {
508
+ "use strict";
509
+ init_constants2();
510
+ init_patterns();
511
+ init_utils();
512
+ init_logger();
513
+ }
514
+ });
515
+
516
+ // src/host/shared/remote-image-loader.ts
432
517
  function createRemoteImageLoader(bundle, resolveClientUrl) {
433
518
  const loader = Object.assign(
434
519
  ({
@@ -438,7 +523,7 @@ function createRemoteImageLoader(bundle, resolveClientUrl) {
438
523
  quality
439
524
  }) => {
440
525
  const q = quality ?? 75;
441
- const remoteOrigin = getRemoteBundleOrigin(bundle);
526
+ const remoteOrigin = getScope(bundle)?.url.origin ?? "";
442
527
  const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;
443
528
  const basePath = isCrossOrigin ? `${remoteOrigin}${config.path ?? "/_next/image"}` : config.path ?? `${remoteOrigin}/_next/image`;
444
529
  const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;
@@ -453,6 +538,7 @@ function createRemoteImageLoader(bundle, resolveClientUrl) {
453
538
  var init_remote_image_loader = __esm({
454
539
  "src/host/shared/remote-image-loader.ts"() {
455
540
  "use strict";
541
+ init_remote_scope();
456
542
  }
457
543
  });
458
544
 
@@ -607,16 +693,6 @@ var init_polyfill = __esm({
607
693
  }
608
694
  });
609
695
 
610
- // src/runtime/patterns.ts
611
- var REMOTE_COMPONENT_REGEX, NEXT_BUNDLE_PATH_RE;
612
- var init_patterns = __esm({
613
- "src/runtime/patterns.ts"() {
614
- "use strict";
615
- REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
616
- NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
617
- }
618
- });
619
-
620
696
  // src/runtime/loaders/script-loader.ts
621
697
  async function loadScripts(scripts, resolveClientUrl) {
622
698
  await Promise.all(
@@ -775,62 +851,39 @@ var init_patterns2 = __esm({
775
851
  });
776
852
 
777
853
  // src/runtime/turbopack/chunk-loader.ts
778
- function createChunkLoader(runtime, resolveClientUrl) {
779
- return function __turbopack_chunk_load__(chunkId, scriptBundle) {
780
- logDebug("ChunkLoader", `Loading chunk: "${chunkId}"`);
781
- const self = globalThis;
782
- const {
783
- bundle,
784
- id: path,
785
- prefix
786
- } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
787
- bundle: scriptBundle ?? "",
788
- id: chunkId
789
- };
790
- logDebug(
791
- "ChunkLoader",
792
- `Parsed chunk - bundle: "${bundle}", path: "${path}", prefix: "${prefix}"`
793
- );
794
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
795
- logDebug("ChunkLoader", `Remote runtime: "${remoteRuntime}"`);
796
- if (remoteRuntime === RUNTIME_WEBPACK) {
797
- logDebug("ChunkLoader", "Skipping chunk load - webpack runtime detected");
798
- return Promise.resolve(void 0);
799
- }
800
- const url = new URL(
801
- path ? `${prefix ?? ""}${path}`.replace(
802
- /(?<char>[^:])(?<double>\/\/)/g,
803
- "$1/"
804
- ) : "/",
805
- self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
806
- ).href;
807
- if (url.endsWith(".css")) {
808
- logDebug("ChunkLoader", `Skipping CSS file: "${url}"`);
809
- return;
810
- }
811
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
812
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
813
- }
814
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
815
- logDebug("ChunkLoader", `Returning cached promise for: "${url}"`);
816
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
817
- }
818
- const resolvedUrl = resolveClientUrl?.(url) ?? url;
819
- logDebug("ChunkLoader", `Fetching chunk from: "${resolvedUrl}"`);
820
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise((resolve, reject) => {
854
+ function loadChunkWithScope(scope, chunkId) {
855
+ logDebug(
856
+ "ChunkLoader",
857
+ `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
858
+ );
859
+ const self = globalThis;
860
+ const { bundle, path, prefix } = parseRemoteId(chunkId);
861
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
862
+ if (remoteRuntime === RUNTIME_WEBPACK) {
863
+ return Promise.resolve(void 0);
864
+ }
865
+ const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : "/";
866
+ const url = new URL(rawPath, scope.url).href;
867
+ if (url.endsWith(".css")) {
868
+ return;
869
+ }
870
+ if (!self.__remote_components_turbopack_chunk_loader_promise__) {
871
+ self.__remote_components_turbopack_chunk_loader_promise__ = {};
872
+ }
873
+ if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
874
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
875
+ }
876
+ const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
877
+ if (resolvedUrl !== url) {
878
+ logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
879
+ }
880
+ self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
881
+ (resolve, reject) => {
821
882
  fetch(resolvedUrl).then((res) => res.text()).then((code) => {
822
883
  const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
823
884
  if (hasTurbopack) {
824
- return handleTurbopackChunk(code, bundle ?? "", url);
885
+ return handleTurbopackChunk(code, scope, url);
825
886
  }
826
- logDebug(
827
- "ChunkLoader",
828
- `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: "${url}"`
829
- );
830
- logDebug(
831
- "ChunkLoader",
832
- `First 500 chars of chunk: ${code.slice(0, 500)}`
833
- );
834
887
  }).then(resolve).catch((error) => {
835
888
  const isProxied = isProxiedUrl(resolvedUrl);
836
889
  if (isProxied) {
@@ -840,17 +893,29 @@ function createChunkLoader(runtime, resolveClientUrl) {
840
893
  reject(error);
841
894
  }
842
895
  });
843
- });
844
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
896
+ }
897
+ );
898
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
899
+ }
900
+ function createChunkDispatcher() {
901
+ return function __chunk_dispatcher__(chunkId, scriptBundle) {
902
+ logDebug("ChunkDispatcher", `Dispatching chunk: "${chunkId}"`);
903
+ const { bundle } = parseRemoteId(chunkId);
904
+ const bundleName = bundle || scriptBundle || "default";
905
+ const scope = getScope(bundleName);
906
+ logDebug(
907
+ "ChunkDispatcher",
908
+ `Scope resolution: bundle="${bundleName}", scope=${scope?.scopedName ?? "null"}`
909
+ );
910
+ if (!scope) {
911
+ logWarn("ChunkDispatcher", `No scope found for bundle "${bundleName}"`);
912
+ return Promise.resolve(void 0);
913
+ }
914
+ return loadChunkWithScope(scope, chunkId);
845
915
  };
846
916
  }
847
- async function handleTurbopackChunk(code, bundle, url) {
848
- logDebug(
849
- "ChunkLoader",
850
- `Handling Turbopack chunk - bundle: "${bundle}", url: "${url}"`
851
- );
917
+ async function handleTurbopackChunk(code, scope, url) {
852
918
  if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
853
- logDebug("ChunkLoader", `Skipping worker chunk: "${url}"`);
854
919
  const preloadLinks = document.querySelectorAll(
855
920
  `link[rel="preload"][href="${new URL(url).pathname}"]`
856
921
  );
@@ -858,58 +923,41 @@ async function handleTurbopackChunk(code, bundle, url) {
858
923
  return;
859
924
  }
860
925
  const self = globalThis;
861
- const bundleKey = getBundleKey(bundle);
862
- logDebug("ChunkLoader", `Bundle key: "${bundleKey}"`);
926
+ const { globalKey } = scope;
863
927
  const transformedCode = code.replace(
864
928
  /globalThis\[\s*["']TURBOPACK["']\s*\]/g,
865
- `globalThis["TURBOPACK_${bundleKey}"]`
929
+ `globalThis["TURBOPACK_${globalKey}"]`
866
930
  ).replace(
867
931
  /self\[\s*["']TURBOPACK["']\s*\]/g,
868
- `self["TURBOPACK_${bundleKey}"]`
869
- ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`).replace(
932
+ `self["TURBOPACK_${globalKey}"]`
933
+ ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`).replace(
870
934
  /TURBOPACK_WORKER_LOCATION/g,
871
- `TURBOPACK_WORKER_LOCATION_${bundleKey}`
935
+ `TURBOPACK_WORKER_LOCATION_${globalKey}`
872
936
  ).replace(
873
937
  /TURBOPACK_NEXT_CHUNK_URLS/g,
874
- `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
938
+ `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`
875
939
  ).replace(
876
940
  /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
877
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
878
- ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
941
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`
942
+ ).replace(/__next_require__/g, `__${globalKey}_next_require__`).replace(
879
943
  /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
880
- `//# sourceMappingURL=${new URL(
881
- ".",
882
- new URL(
883
- url,
884
- self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
885
- )
886
- ).href}$1$2.js.map`
944
+ `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
887
945
  );
888
- if (!self[`TURBOPACK_${bundleKey}`]) {
946
+ if (!self[`TURBOPACK_${globalKey}`]) {
889
947
  const chunkData = [];
890
948
  const turbopackObject = {
891
949
  push: (item) => {
892
- logDebug(
893
- "ChunkLoader",
894
- `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? "array" : typeof item}`
895
- );
896
950
  if (Array.isArray(item)) {
897
951
  chunkData.push(item);
898
- logDebug(
899
- "ChunkLoader",
900
- `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`
901
- );
902
952
  } else {
903
953
  chunkData.push([item]);
904
954
  }
905
955
  return chunkData.length;
906
956
  },
907
- // Store chunks for later access
908
957
  __chunks__: chunkData
909
958
  };
910
- self[`TURBOPACK_${bundleKey}`] = turbopackObject;
959
+ self[`TURBOPACK_${globalKey}`] = turbopackObject;
911
960
  }
912
- logDebug("ChunkLoader", `Creating blob script for: "${url}"`);
913
961
  await new Promise((scriptResolve, scriptReject) => {
914
962
  const blob = new Blob([transformedCode], {
915
963
  type: "application/javascript; charset=UTF-8"
@@ -921,21 +969,6 @@ async function handleTurbopackChunk(code, bundle, url) {
921
969
  script.async = true;
922
970
  script.onload = () => {
923
971
  URL.revokeObjectURL(scriptUrl);
924
- logDebug(
925
- "ChunkLoader",
926
- `Script loaded successfully for bundle "${bundle}"`
927
- );
928
- const turbopackBundle = self[`TURBOPACK_${bundleKey}`];
929
- logDebug(
930
- "ChunkLoader",
931
- `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${turbopackBundle ? Object.keys(turbopackBundle).slice(0, 10).join(", ") : "none"}`
932
- );
933
- if (turbopackBundle && typeof turbopackBundle === "object") {
934
- logDebug(
935
- "ChunkLoader",
936
- `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle).length}`
937
- );
938
- }
939
972
  scriptResolve(void 0);
940
973
  script.remove();
941
974
  };
@@ -950,35 +983,25 @@ async function handleTurbopackChunk(code, bundle, url) {
950
983
  };
951
984
  document.head.appendChild(script);
952
985
  });
953
- const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
954
- logDebug(
955
- "ChunkLoader",
956
- `Processing chunk lists for bundle "${bundle}": ${chunkLists?.length ?? 0} lists`
957
- );
958
- const loadChunkLists = [];
986
+ const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`];
987
+ const loadChunkPromises = [];
959
988
  while (chunkLists?.length) {
960
989
  const { chunks } = chunkLists.shift() ?? { chunks: [] };
961
990
  if (chunks.length > 0) {
962
- logDebug(
963
- "ChunkLoader",
964
- `Loading ${chunks.length} additional chunks for bundle "${bundle}": [${chunks.join(", ")}]`
965
- );
966
- chunks.forEach((id) => {
967
- const chunkLoadResult = self.__webpack_chunk_load__?.(
968
- `[${bundle}] ${url.slice(0, url.indexOf("/_next"))}/_next/${id}`
991
+ for (const id of chunks) {
992
+ const baseUrl = url.slice(0, url.indexOf("/_next"));
993
+ const chunkLoadResult = loadChunkWithScope(
994
+ scope,
995
+ formatRemoteId(scope, `${baseUrl}/_next/${id}`)
969
996
  );
970
997
  if (chunkLoadResult) {
971
- loadChunkLists.push(chunkLoadResult);
998
+ loadChunkPromises.push(chunkLoadResult);
972
999
  }
973
- });
1000
+ }
974
1001
  }
975
1002
  }
976
- if (loadChunkLists.length > 0) {
977
- logDebug(
978
- "ChunkLoader",
979
- `Waiting for ${loadChunkLists.length} additional chunks to load`
980
- );
981
- await Promise.all(loadChunkLists);
1003
+ if (loadChunkPromises.length > 0) {
1004
+ await Promise.all(loadChunkPromises);
982
1005
  }
983
1006
  }
984
1007
  var init_chunk_loader = __esm({
@@ -990,14 +1013,169 @@ var init_chunk_loader = __esm({
990
1013
  init_error();
991
1014
  init_logger();
992
1015
  init_patterns2();
1016
+ init_remote_scope();
1017
+ }
1018
+ });
1019
+
1020
+ // src/runtime/turbopack/shared-modules.ts
1021
+ function getTurbopackModules(scope) {
1022
+ const self = globalThis;
1023
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1024
+ if (!raw)
1025
+ return void 0;
1026
+ if (typeof raw === "object" && "__chunks__" in raw) {
1027
+ return raw.__chunks__.flat();
1028
+ }
1029
+ if (Array.isArray(raw)) {
1030
+ return raw.flat();
1031
+ }
1032
+ return Object.entries(raw).flat();
1033
+ }
1034
+ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}) {
1035
+ const allModules = getTurbopackModules(scope);
1036
+ logDebug(
1037
+ "SharedModules",
1038
+ `initializeSharedModules: scope="${scope.scopedName}", allModules=${allModules ? allModules.length : "null"}, hostShared=[${Object.keys(hostShared).join(", ")}], remoteShared=${JSON.stringify(remoteShared)}`
1039
+ );
1040
+ let sharedModuleInitializer = null;
1041
+ if (allModules) {
1042
+ const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1043
+ if (typeof idOrFunc !== "function") {
1044
+ return false;
1045
+ }
1046
+ const funcCode = idOrFunc.toString();
1047
+ return REMOTE_SHARED_MARKER_RE.test(funcCode);
1048
+ });
1049
+ if (sharedModuleInitializerIndex > 0) {
1050
+ const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1051
+ const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1052
+ const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1053
+ if (sharedModuleId) {
1054
+ const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1055
+ scope,
1056
+ sharedModuleId,
1057
+ formatRemoteId(scope, String(sharedModuleInitializerId))
1058
+ );
1059
+ sharedModuleInitializer = sharedModuleInitializerInstance;
1060
+ }
1061
+ }
1062
+ if (sharedModuleInitializer) {
1063
+ const { shared } = await sharedModuleInitializer;
1064
+ const sharedModuleIds = extractSharedModuleIds(shared, scope);
1065
+ logDebug(
1066
+ "SharedModules",
1067
+ `Resolved shared modules for scope="${scope.scopedName}": ${JSON.stringify(sharedModuleIds)}`
1068
+ );
1069
+ return Promise.all(
1070
+ Object.entries(sharedModuleIds).map(async ([id, module2]) => {
1071
+ if (hostShared[module2]) {
1072
+ scope.sharedModules[id] = await hostShared[module2](scope.name);
1073
+ } else {
1074
+ logError(
1075
+ "SharedModules",
1076
+ `Host shared module "${module2}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1077
+ );
1078
+ }
1079
+ })
1080
+ );
1081
+ }
1082
+ logWarn(
1083
+ "SharedModules",
1084
+ `No shared module initializer found in bundle for scope="${scope.scopedName}" \u2014 falling back to remoteShared mapping`
1085
+ );
1086
+ } else {
1087
+ logWarn(
1088
+ "SharedModules",
1089
+ `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
1090
+ );
1091
+ }
1092
+ return Promise.all(
1093
+ Object.entries(remoteShared).map(async ([id, module2]) => {
1094
+ if (hostShared[module2]) {
1095
+ const normalizedId = id.replace("[app-ssr]", "[app-client]");
1096
+ scope.sharedModules[normalizedId] = await hostShared[module2](
1097
+ scope.name
1098
+ );
1099
+ } else {
1100
+ logError(
1101
+ "SharedModules",
1102
+ `Shared module "${module2}" not found for "${scope.name}". ${DEDUPLICATION_WARNING}`
1103
+ );
1104
+ }
1105
+ })
1106
+ );
1107
+ }
1108
+ function extractSharedModuleIds(shared, scope) {
1109
+ return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1110
+ const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1111
+ if (asyncSharedModuleId) {
1112
+ const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1113
+ let asyncSharedModule;
1114
+ const turbopackModules = getTurbopackModules(scope) ?? [];
1115
+ const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1116
+ asyncSharedModuleIdNumber
1117
+ );
1118
+ if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1119
+ asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1120
+ }
1121
+ if (asyncSharedModule) {
1122
+ const asyncSharedModuleCode = asyncSharedModule.toString();
1123
+ const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1124
+ acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1125
+ "__remote_shared_module_",
1126
+ ""
1127
+ );
1128
+ }
1129
+ }
1130
+ return acc;
1131
+ }, {});
1132
+ }
1133
+ function getSharedModule(scope, id) {
1134
+ const idStr = String(id);
1135
+ if (scope.sharedModules[idStr] !== void 0) {
1136
+ return scope.sharedModules[idStr];
1137
+ }
1138
+ for (const [key, value] of Object.entries(scope.sharedModules)) {
1139
+ if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
1140
+ return value;
1141
+ }
1142
+ }
1143
+ return null;
1144
+ }
1145
+ var DEDUPLICATION_WARNING;
1146
+ var init_shared_modules = __esm({
1147
+ "src/runtime/turbopack/shared-modules.ts"() {
1148
+ "use strict";
1149
+ init_logger();
1150
+ init_module();
1151
+ init_patterns2();
1152
+ init_remote_scope();
1153
+ 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).";
993
1154
  }
994
1155
  });
995
1156
 
996
1157
  // src/runtime/turbopack/module.ts
997
- function handleTurbopackModule(bundle, moduleId, id) {
1158
+ function requireModule(scope, moduleId, fullId) {
1159
+ const idStr = String(moduleId);
1160
+ if (scope.moduleCache[idStr])
1161
+ return scope.moduleCache[idStr];
1162
+ const sharedModule = getSharedModule(scope, moduleId);
1163
+ if (sharedModule) {
1164
+ scope.moduleCache[idStr] = sharedModule;
1165
+ return sharedModule;
1166
+ }
1167
+ return handleTurbopackModule(
1168
+ scope,
1169
+ idStr,
1170
+ fullId ?? formatRemoteId(scope, idStr)
1171
+ );
1172
+ }
1173
+ function handleTurbopackModule(scope, moduleId, id) {
998
1174
  const self = globalThis;
999
- const bundleKey = getBundleKey(bundle);
1000
- const raw = self[`TURBOPACK_${bundleKey}`];
1175
+ if (scope.moduleCache[moduleId]) {
1176
+ return scope.moduleCache[moduleId];
1177
+ }
1178
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1001
1179
  let modules;
1002
1180
  if (raw && typeof raw === "object" && "__chunks__" in raw) {
1003
1181
  modules = raw.__chunks__.flat();
@@ -1006,48 +1184,35 @@ function handleTurbopackModule(bundle, moduleId, id) {
1006
1184
  } else {
1007
1185
  modules = raw;
1008
1186
  }
1009
- if (!self.__remote_components_turbopack_modules__) {
1010
- self.__remote_components_turbopack_modules__ = {};
1011
- }
1012
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1013
- self.__remote_components_turbopack_modules__[bundle] = {};
1014
- }
1015
- if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
1016
- return self.__remote_components_turbopack_modules__[bundle][moduleId];
1017
- }
1018
1187
  if (!modules) {
1019
- logError("TurbopackModule", `TURBOPACK_${bundleKey} is undefined`);
1188
+ logError(
1189
+ "TurbopackModule",
1190
+ `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1191
+ );
1020
1192
  }
1021
1193
  const moduleInit = findModuleInit(modules, moduleId);
1022
1194
  const exports = {};
1023
1195
  const moduleExports = { exports };
1024
1196
  if (typeof moduleInit !== "function") {
1025
1197
  throw new Error(
1026
- `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
1198
+ `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1027
1199
  );
1028
1200
  }
1029
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1030
- if (!self.__remote_components_turbopack_global__) {
1031
- self.__remote_components_turbopack_global__ = {};
1032
- }
1033
- if (!self.__remote_components_turbopack_global__[bundle]) {
1034
- self.__remote_components_turbopack_global__[bundle] = {};
1035
- }
1201
+ scope.moduleCache[moduleId] = moduleExports.exports;
1036
1202
  moduleInit(
1037
1203
  createTurbopackContext(
1038
- bundle,
1204
+ scope,
1039
1205
  exports,
1040
1206
  moduleExports,
1041
1207
  modules,
1042
1208
  moduleInit,
1043
- id,
1044
- self
1209
+ id
1045
1210
  ),
1046
1211
  moduleExports,
1047
1212
  exports
1048
1213
  );
1049
- if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
1050
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1214
+ if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1215
+ scope.moduleCache[moduleId] = moduleExports.exports;
1051
1216
  }
1052
1217
  return moduleExports.exports;
1053
1218
  }
@@ -1072,7 +1237,8 @@ function findModuleInit(modules, moduleId) {
1072
1237
  (e) => Boolean(e && typeof e === "object" && moduleId in e)
1073
1238
  )?.[moduleId];
1074
1239
  }
1075
- function createTurbopackContext(bundle, exports, moduleExports, modules, moduleInit, id, self) {
1240
+ function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1241
+ const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
1076
1242
  return {
1077
1243
  // HMR not implemented for Remote Components
1078
1244
  k: {
@@ -1088,16 +1254,10 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1088
1254
  s(bindings, esmId) {
1089
1255
  let mod = exports;
1090
1256
  if (typeof esmId === "string" || typeof esmId === "number") {
1091
- if (!self.__remote_components_turbopack_modules__) {
1092
- self.__remote_components_turbopack_modules__ = {};
1093
- }
1094
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1095
- self.__remote_components_turbopack_modules__[bundle] = {};
1257
+ if (!scope.moduleCache[esmId]) {
1258
+ scope.moduleCache[esmId] = {};
1096
1259
  }
1097
- if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
1098
- self.__remote_components_turbopack_modules__[bundle][esmId] = {};
1099
- }
1100
- mod = self.__remote_components_turbopack_modules__[bundle][esmId];
1260
+ mod = scope.moduleCache[esmId];
1101
1261
  }
1102
1262
  Object.defineProperty(mod, "__esModule", { value: true });
1103
1263
  if (Array.isArray(bindings)) {
@@ -1130,7 +1290,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1130
1290
  }
1131
1291
  }
1132
1292
  },
1133
- // import
1293
+ // import — resolves directly via scope, no global dispatch
1134
1294
  i(importId) {
1135
1295
  let mod;
1136
1296
  if (typeof importId === "string") {
@@ -1141,7 +1301,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1141
1301
  /\s+<export(?<specifier>.*)>$/,
1142
1302
  ""
1143
1303
  );
1144
- mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`);
1304
+ mod = scopedRequire(normalizedId);
1145
1305
  if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1146
1306
  if (exportSource === "*") {
1147
1307
  mod[exportName] = mod;
@@ -1150,7 +1310,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1150
1310
  }
1151
1311
  }
1152
1312
  } else {
1153
- mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
1313
+ mod = scopedRequire(importId);
1154
1314
  }
1155
1315
  if (typeof mod !== "object" || mod === null) {
1156
1316
  mod = { default: mod };
@@ -1162,16 +1322,14 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1162
1322
  }
1163
1323
  return mod;
1164
1324
  },
1165
- // require
1325
+ // require — resolves directly via scope
1166
1326
  r(requireId) {
1167
- return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
1327
+ return scopedRequire(requireId);
1168
1328
  },
1169
1329
  // value exports
1170
1330
  v(value) {
1171
1331
  if (typeof value === "function") {
1172
- exports.default = value((vid) => {
1173
- return self.__webpack_require__?.(`[${bundle}] ${vid}`);
1174
- });
1332
+ exports.default = value((vid) => scopedRequire(vid));
1175
1333
  } else {
1176
1334
  moduleExports.exports = value;
1177
1335
  }
@@ -1186,17 +1344,15 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1186
1344
  );
1187
1345
  exports.default = result;
1188
1346
  },
1189
- // async module loader
1347
+ // async module loader — resolves directly via scope
1190
1348
  async A(Aid) {
1191
- const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
1192
- return mod.default(
1193
- (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
1194
- );
1349
+ const mod = scopedRequire(Aid);
1350
+ return mod.default((parentId) => scopedRequire(parentId));
1195
1351
  },
1196
1352
  // dynamic import tracking — no-op for remote components
1197
1353
  j() {
1198
1354
  },
1199
- // chunk loader
1355
+ // chunk loader — loads directly via scope, no global dispatch
1200
1356
  l(url) {
1201
1357
  const flatModules = Array.isArray(modules) ? modules : [];
1202
1358
  const moduleInitIndex = flatModules.indexOf(moduleInit);
@@ -1207,16 +1363,16 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1207
1363
  const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1208
1364
  const nextIndex = scriptSrc.indexOf("/_next");
1209
1365
  const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1210
- const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
1211
- return self.__webpack_chunk_load__?.(bundleUrl, bundle);
1366
+ const chunkUrl = `${baseUrl}/_next/${url}`;
1367
+ return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1212
1368
  }
1213
1369
  }
1214
1370
  throw new Error(
1215
1371
  `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1216
1372
  );
1217
1373
  },
1218
- // global object for this bundle
1219
- g: self.__remote_components_turbopack_global__?.[bundle],
1374
+ // globalThis substitute shared across all modules in this scope
1375
+ g: scope.moduleGlobal,
1220
1376
  m: moduleExports,
1221
1377
  e: exports
1222
1378
  };
@@ -1224,169 +1380,49 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1224
1380
  var init_module = __esm({
1225
1381
  "src/runtime/turbopack/module.ts"() {
1226
1382
  "use strict";
1227
- init_constants2();
1228
1383
  init_logger();
1229
- }
1230
- });
1231
-
1232
- // src/runtime/turbopack/shared-modules.ts
1233
- async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {}) {
1234
- const self = globalThis;
1235
- self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
1236
- if (!self.__remote_shared_modules__[bundle]) {
1237
- self.__remote_shared_modules__[bundle] = {};
1238
- }
1239
- const bundleKey = getBundleKey(bundle);
1240
- let modules = self[`TURBOPACK_${bundleKey}`];
1241
- if (modules && typeof modules === "object" && "__chunks__" in modules) {
1242
- const chunks = modules.__chunks__;
1243
- modules = chunks.flat();
1244
- }
1245
- let sharedModuleInitializer = null;
1246
- if (modules) {
1247
- const allModules = Array.isArray(modules) ? modules.flat() : Object.entries(modules).flat();
1248
- const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1249
- if (typeof idOrFunc !== "function") {
1250
- return false;
1251
- }
1252
- const funcCode = idOrFunc.toString();
1253
- return REMOTE_SHARED_MARKER_RE.test(funcCode);
1254
- });
1255
- if (sharedModuleInitializerIndex > 0) {
1256
- const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1257
- const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1258
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1259
- if (sharedModuleId) {
1260
- const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1261
- bundle,
1262
- sharedModuleId,
1263
- `[${bundle}] ${sharedModuleInitializerId}`
1264
- );
1265
- sharedModuleInitializer = sharedModuleInitializerInstance;
1266
- }
1267
- }
1268
- if (sharedModuleInitializer) {
1269
- const { shared } = await sharedModuleInitializer;
1270
- const sharedModuleIds = extractSharedModuleIds(
1271
- shared,
1272
- bundleKey,
1273
- self
1274
- );
1275
- return Promise.all(
1276
- Object.entries(sharedModuleIds).map(async ([id, module2]) => {
1277
- if (self.__remote_shared_modules__?.[bundle]) {
1278
- if (hostShared[module2]) {
1279
- self.__remote_shared_modules__[bundle][id] = await hostShared[module2](bundle);
1280
- } else {
1281
- logError(
1282
- "SharedModules",
1283
- `Host shared module "${module2}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1284
- );
1285
- }
1286
- }
1287
- })
1288
- );
1289
- }
1290
- }
1291
- return Promise.all(
1292
- Object.entries(remoteShared).map(async ([id, module2]) => {
1293
- if (self.__remote_shared_modules__?.[bundle]) {
1294
- if (hostShared[module2]) {
1295
- const normalizedId = id.replace("[app-ssr]", "[app-client]");
1296
- self.__remote_shared_modules__[bundle][normalizedId] = await hostShared[module2](bundle);
1297
- } else {
1298
- logError(
1299
- "SharedModules",
1300
- `Shared module "${module2}" not found for "${bundle}". ${DEDUPLICATION_WARNING}`
1301
- );
1302
- }
1303
- }
1304
- })
1305
- );
1306
- }
1307
- function extractSharedModuleIds(shared, bundleKey, self) {
1308
- return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1309
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1310
- if (asyncSharedModuleId) {
1311
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1312
- let asyncSharedModule;
1313
- let turbopackModules = self[`TURBOPACK_${bundleKey}`];
1314
- if (turbopackModules && typeof turbopackModules === "object" && "__chunks__" in turbopackModules) {
1315
- const chunks = turbopackModules.__chunks__;
1316
- turbopackModules = chunks.flat();
1317
- }
1318
- const newAllModules = Array.isArray(turbopackModules) ? turbopackModules.flat() : turbopackModules ? Object.entries(turbopackModules).flatMap(([key2, value2]) => [
1319
- key2,
1320
- value2
1321
- ]) : [];
1322
- const asyncSharedModuleIdIndex = newAllModules.indexOf(
1323
- asyncSharedModuleIdNumber
1324
- );
1325
- if (asyncSharedModuleIdIndex !== -1 && typeof newAllModules[asyncSharedModuleIdIndex + 1] === "function") {
1326
- asyncSharedModule = newAllModules[asyncSharedModuleIdIndex + 1];
1327
- }
1328
- if (asyncSharedModule) {
1329
- const asyncSharedModuleCode = asyncSharedModule.toString();
1330
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1331
- acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1332
- "__remote_shared_module_",
1333
- ""
1334
- );
1335
- }
1336
- }
1337
- return acc;
1338
- }, {});
1339
- }
1340
- function getSharedModule(bundle, id) {
1341
- const self = globalThis;
1342
- for (const [key, value] of Object.entries(
1343
- self.__remote_shared_modules__?.[bundle] ?? {}
1344
- )) {
1345
- if (typeof value !== "undefined" && (typeof id === "string" && id.includes(key) || id === key)) {
1346
- return value;
1347
- }
1348
- }
1349
- return null;
1350
- }
1351
- var DEDUPLICATION_WARNING;
1352
- var init_shared_modules = __esm({
1353
- "src/runtime/turbopack/shared-modules.ts"() {
1354
- "use strict";
1355
- init_constants2();
1356
- init_logger();
1357
- init_module();
1358
- init_patterns2();
1359
- 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).";
1384
+ init_chunk_loader();
1385
+ init_remote_scope();
1386
+ init_shared_modules();
1360
1387
  }
1361
1388
  });
1362
1389
 
1363
1390
  // src/runtime/turbopack/webpack-runtime.ts
1364
1391
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1365
1392
  const self = globalThis;
1393
+ const bundleName = bundle ?? "default";
1394
+ const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1395
+ registerScope(scope);
1366
1396
  if (!self.__remote_bundle_url__) {
1367
1397
  self.__remote_bundle_url__ = {};
1368
1398
  }
1369
- self.__remote_bundle_url__[bundle ?? "default"] = url;
1399
+ self.__remote_bundle_url__[bundleName] = url;
1400
+ if (scope.scopedName !== bundleName) {
1401
+ self.__remote_bundle_url__[scope.scopedName] = url;
1402
+ }
1370
1403
  self.__webpack_get_script_filename__ = () => null;
1371
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
1404
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1405
+ if (willCreateDispatchers) {
1372
1406
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1373
1407
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1374
1408
  self.__original_webpack_require__ = self.__webpack_require__;
1375
1409
  }
1376
- self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
1377
- self.__webpack_require__ = createModuleRequire(runtime);
1410
+ self.__webpack_chunk_load__ = createChunkDispatcher();
1411
+ self.__webpack_require__ = createModuleDispatcher(runtime);
1378
1412
  self.__webpack_require_type__ = runtime;
1379
1413
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1380
- const remoteBundle = bundle ?? "default";
1381
- self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
1382
- self.__remote_webpack_require__[remoteBundle].type = "turbopack";
1414
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1415
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
1383
1416
  }
1384
1417
  }
1418
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1419
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1420
+ }
1385
1421
  if (runtime === RUNTIME_TURBOPACK) {
1386
1422
  const results = await Promise.allSettled(
1387
1423
  scripts.map((script) => {
1388
1424
  if (script.src) {
1389
- return self.__webpack_chunk_load__?.(script.src, bundle);
1425
+ return loadChunkWithScope(scope, script.src);
1390
1426
  }
1391
1427
  return Promise.resolve(void 0);
1392
1428
  })
@@ -1408,54 +1444,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1408
1444
  "react-dom/client": async () => (await import("react-dom/client")).default,
1409
1445
  ...shared
1410
1446
  };
1411
- await initializeSharedModules(
1412
- bundle ?? "default",
1413
- // include all core modules as shared
1414
- coreShared,
1415
- remoteShared
1416
- );
1447
+ await initializeSharedModules(scope, coreShared, remoteShared);
1417
1448
  }
1418
- function createModuleRequire(runtime) {
1449
+ function createModuleDispatcher(runtime) {
1419
1450
  return (id) => {
1420
1451
  const self = globalThis;
1421
1452
  const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1422
1453
  bundle: "default",
1423
1454
  id
1424
1455
  };
1425
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1426
- logDebug("WebpackRuntime", `remoteRuntime: "${remoteRuntime}"`);
1456
+ const bundleName = bundle ?? "default";
1457
+ const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
1458
+ logDebug(
1459
+ "ModuleDispatcher",
1460
+ `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
1461
+ );
1427
1462
  try {
1428
1463
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1429
1464
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1430
1465
  }
1431
- const sharedModuleId = moduleId ?? id;
1432
- const sharedModule = getSharedModule(bundle ?? "default", sharedModuleId);
1433
- if (sharedModule) {
1434
- return sharedModule;
1435
- }
1436
- if (bundle && moduleId) {
1437
- return handleTurbopackModule(bundle, moduleId, id);
1466
+ const scope = getScope(bundleName);
1467
+ if (scope) {
1468
+ return requireModule(scope, moduleId ?? id, id);
1438
1469
  }
1439
- throw new Error(`Module "${id}" not found.`);
1470
+ throw new Error(
1471
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1472
+ );
1440
1473
  } catch (requireError) {
1441
1474
  logWarn(
1442
- "WebpackRuntime",
1475
+ "ModuleDispatcher",
1443
1476
  `Module require failed: ${String(requireError)}`
1444
1477
  );
1445
1478
  if (typeof self.__original_webpack_require__ !== "function") {
1446
1479
  throw new RemoteComponentsError(
1447
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1480
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1448
1481
  {
1449
1482
  cause: requireError instanceof Error ? requireError : void 0
1450
1483
  }
1451
1484
  );
1452
1485
  }
1453
1486
  try {
1454
- logDebug("WebpackRuntime", "Falling back to original webpack require");
1487
+ logDebug(
1488
+ "ModuleDispatcher",
1489
+ "Falling back to original webpack require"
1490
+ );
1455
1491
  return self.__original_webpack_require__(id);
1456
1492
  } catch (originalError) {
1457
1493
  throw new RemoteComponentsError(
1458
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1494
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1459
1495
  { cause: originalError instanceof Error ? originalError : void 0 }
1460
1496
  );
1461
1497
  }
@@ -1471,6 +1507,7 @@ var init_webpack_runtime = __esm({
1471
1507
  init_logger();
1472
1508
  init_chunk_loader();
1473
1509
  init_module();
1510
+ init_remote_scope();
1474
1511
  init_shared_modules();
1475
1512
  }
1476
1513
  });