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
@@ -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
+ };
431
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: "" };
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(
@@ -628,6 +704,13 @@ async function loadScripts(scripts, resolveClientUrl) {
628
704
  location.origin
629
705
  ).href;
630
706
  const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;
707
+ const alreadyLoaded = Array.from(
708
+ document.querySelectorAll("script[src]")
709
+ ).some((s) => s.src === resolvedSrc);
710
+ if (alreadyLoaded) {
711
+ resolve();
712
+ return;
713
+ }
631
714
  const newScript = document.createElement("script");
632
715
  newScript.onload = () => resolve();
633
716
  newScript.onerror = () => {
@@ -775,62 +858,39 @@ var init_patterns2 = __esm({
775
858
  });
776
859
 
777
860
  // 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) => {
861
+ function loadChunkWithScope(scope, chunkId) {
862
+ logDebug(
863
+ "ChunkLoader",
864
+ `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
865
+ );
866
+ const self = globalThis;
867
+ const { bundle, path, prefix } = parseRemoteId(chunkId);
868
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
869
+ if (remoteRuntime === RUNTIME_WEBPACK) {
870
+ return Promise.resolve(void 0);
871
+ }
872
+ const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : "/";
873
+ const url = new URL(rawPath, scope.url).href;
874
+ if (url.endsWith(".css")) {
875
+ return;
876
+ }
877
+ if (!self.__remote_components_turbopack_chunk_loader_promise__) {
878
+ self.__remote_components_turbopack_chunk_loader_promise__ = {};
879
+ }
880
+ if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
881
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
882
+ }
883
+ const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
884
+ if (resolvedUrl !== url) {
885
+ logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
886
+ }
887
+ self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
888
+ (resolve, reject) => {
821
889
  fetch(resolvedUrl).then((res) => res.text()).then((code) => {
822
890
  const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
823
891
  if (hasTurbopack) {
824
- return handleTurbopackChunk(code, bundle ?? "", url);
892
+ return handleTurbopackChunk(code, scope, url);
825
893
  }
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
894
  }).then(resolve).catch((error) => {
835
895
  const isProxied = isProxiedUrl(resolvedUrl);
836
896
  if (isProxied) {
@@ -840,17 +900,29 @@ function createChunkLoader(runtime, resolveClientUrl) {
840
900
  reject(error);
841
901
  }
842
902
  });
843
- });
844
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
903
+ }
904
+ );
905
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
906
+ }
907
+ function createChunkDispatcher() {
908
+ return function __chunk_dispatcher__(chunkId, scriptBundle) {
909
+ logDebug("ChunkDispatcher", `Dispatching chunk: "${chunkId}"`);
910
+ const { bundle } = parseRemoteId(chunkId);
911
+ const bundleName = bundle || scriptBundle || "default";
912
+ const scope = getScope(bundleName);
913
+ logDebug(
914
+ "ChunkDispatcher",
915
+ `Scope resolution: bundle="${bundleName}", scope=${scope?.scopedName ?? "null"}`
916
+ );
917
+ if (!scope) {
918
+ logWarn("ChunkDispatcher", `No scope found for bundle "${bundleName}"`);
919
+ return Promise.resolve(void 0);
920
+ }
921
+ return loadChunkWithScope(scope, chunkId);
845
922
  };
846
923
  }
847
- async function handleTurbopackChunk(code, bundle, url) {
848
- logDebug(
849
- "ChunkLoader",
850
- `Handling Turbopack chunk - bundle: "${bundle}", url: "${url}"`
851
- );
924
+ async function handleTurbopackChunk(code, scope, url) {
852
925
  if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
853
- logDebug("ChunkLoader", `Skipping worker chunk: "${url}"`);
854
926
  const preloadLinks = document.querySelectorAll(
855
927
  `link[rel="preload"][href="${new URL(url).pathname}"]`
856
928
  );
@@ -858,58 +930,41 @@ async function handleTurbopackChunk(code, bundle, url) {
858
930
  return;
859
931
  }
860
932
  const self = globalThis;
861
- const bundleKey = getBundleKey(bundle);
862
- logDebug("ChunkLoader", `Bundle key: "${bundleKey}"`);
933
+ const { globalKey } = scope;
863
934
  const transformedCode = code.replace(
864
935
  /globalThis\[\s*["']TURBOPACK["']\s*\]/g,
865
- `globalThis["TURBOPACK_${bundleKey}"]`
936
+ `globalThis["TURBOPACK_${globalKey}"]`
866
937
  ).replace(
867
938
  /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(
939
+ `self["TURBOPACK_${globalKey}"]`
940
+ ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`).replace(
870
941
  /TURBOPACK_WORKER_LOCATION/g,
871
- `TURBOPACK_WORKER_LOCATION_${bundleKey}`
942
+ `TURBOPACK_WORKER_LOCATION_${globalKey}`
872
943
  ).replace(
873
944
  /TURBOPACK_NEXT_CHUNK_URLS/g,
874
- `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
945
+ `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`
875
946
  ).replace(
876
947
  /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
877
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
878
- ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
948
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`
949
+ ).replace(/__next_require__/g, `__${globalKey}_next_require__`).replace(
879
950
  /\/\/# 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`
951
+ `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
887
952
  );
888
- if (!self[`TURBOPACK_${bundleKey}`]) {
953
+ if (!self[`TURBOPACK_${globalKey}`]) {
889
954
  const chunkData = [];
890
955
  const turbopackObject = {
891
956
  push: (item) => {
892
- logDebug(
893
- "ChunkLoader",
894
- `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? "array" : typeof item}`
895
- );
896
957
  if (Array.isArray(item)) {
897
958
  chunkData.push(item);
898
- logDebug(
899
- "ChunkLoader",
900
- `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`
901
- );
902
959
  } else {
903
960
  chunkData.push([item]);
904
961
  }
905
962
  return chunkData.length;
906
963
  },
907
- // Store chunks for later access
908
964
  __chunks__: chunkData
909
965
  };
910
- self[`TURBOPACK_${bundleKey}`] = turbopackObject;
966
+ self[`TURBOPACK_${globalKey}`] = turbopackObject;
911
967
  }
912
- logDebug("ChunkLoader", `Creating blob script for: "${url}"`);
913
968
  await new Promise((scriptResolve, scriptReject) => {
914
969
  const blob = new Blob([transformedCode], {
915
970
  type: "application/javascript; charset=UTF-8"
@@ -921,21 +976,6 @@ async function handleTurbopackChunk(code, bundle, url) {
921
976
  script.async = true;
922
977
  script.onload = () => {
923
978
  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
979
  scriptResolve(void 0);
940
980
  script.remove();
941
981
  };
@@ -950,35 +990,25 @@ async function handleTurbopackChunk(code, bundle, url) {
950
990
  };
951
991
  document.head.appendChild(script);
952
992
  });
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 = [];
993
+ const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`];
994
+ const loadChunkPromises = [];
959
995
  while (chunkLists?.length) {
960
996
  const { chunks } = chunkLists.shift() ?? { chunks: [] };
961
997
  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}`
998
+ for (const id of chunks) {
999
+ const baseUrl = url.slice(0, url.indexOf("/_next"));
1000
+ const chunkLoadResult = loadChunkWithScope(
1001
+ scope,
1002
+ formatRemoteId(scope, `${baseUrl}/_next/${id}`)
969
1003
  );
970
1004
  if (chunkLoadResult) {
971
- loadChunkLists.push(chunkLoadResult);
1005
+ loadChunkPromises.push(chunkLoadResult);
972
1006
  }
973
- });
1007
+ }
974
1008
  }
975
1009
  }
976
- if (loadChunkLists.length > 0) {
977
- logDebug(
978
- "ChunkLoader",
979
- `Waiting for ${loadChunkLists.length} additional chunks to load`
980
- );
981
- await Promise.all(loadChunkLists);
1010
+ if (loadChunkPromises.length > 0) {
1011
+ await Promise.all(loadChunkPromises);
982
1012
  }
983
1013
  }
984
1014
  var init_chunk_loader = __esm({
@@ -990,64 +1020,195 @@ var init_chunk_loader = __esm({
990
1020
  init_error();
991
1021
  init_logger();
992
1022
  init_patterns2();
1023
+ init_remote_scope();
993
1024
  }
994
1025
  });
995
1026
 
996
- // src/runtime/turbopack/module.ts
997
- function handleTurbopackModule(bundle, moduleId, id) {
1027
+ // src/runtime/turbopack/shared-modules.ts
1028
+ function getTurbopackModules(scope) {
998
1029
  const self = globalThis;
999
- const bundleKey = getBundleKey(bundle);
1000
- const raw = self[`TURBOPACK_${bundleKey}`];
1001
- let modules;
1002
- if (raw && typeof raw === "object" && "__chunks__" in raw) {
1003
- modules = raw.__chunks__.flat();
1004
- } else if (Array.isArray(raw)) {
1005
- modules = raw.flat();
1030
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1031
+ if (!raw)
1032
+ return void 0;
1033
+ if (typeof raw === "object" && "__chunks__" in raw) {
1034
+ return raw.__chunks__.flat();
1035
+ }
1036
+ if (Array.isArray(raw)) {
1037
+ return raw.flat();
1038
+ }
1039
+ return Object.entries(raw).flat();
1040
+ }
1041
+ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}) {
1042
+ const allModules = getTurbopackModules(scope);
1043
+ logDebug(
1044
+ "SharedModules",
1045
+ `initializeSharedModules: scope="${scope.scopedName}", allModules=${allModules ? allModules.length : "null"}, hostShared=[${Object.keys(hostShared).join(", ")}], remoteShared=${JSON.stringify(remoteShared)}`
1046
+ );
1047
+ let sharedModuleInitializer = null;
1048
+ if (allModules) {
1049
+ const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1050
+ if (typeof idOrFunc !== "function") {
1051
+ return false;
1052
+ }
1053
+ const funcCode = idOrFunc.toString();
1054
+ return REMOTE_SHARED_MARKER_RE.test(funcCode);
1055
+ });
1056
+ if (sharedModuleInitializerIndex > 0) {
1057
+ const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1058
+ const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1059
+ const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1060
+ if (sharedModuleId) {
1061
+ const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1062
+ scope,
1063
+ sharedModuleId,
1064
+ formatRemoteId(scope, String(sharedModuleInitializerId))
1065
+ );
1066
+ sharedModuleInitializer = sharedModuleInitializerInstance;
1067
+ }
1068
+ }
1069
+ if (sharedModuleInitializer) {
1070
+ const { shared } = await sharedModuleInitializer;
1071
+ const sharedModuleIds = extractSharedModuleIds(shared, scope);
1072
+ logDebug(
1073
+ "SharedModules",
1074
+ `Resolved shared modules for scope="${scope.scopedName}": ${JSON.stringify(sharedModuleIds)}`
1075
+ );
1076
+ return Promise.all(
1077
+ Object.entries(sharedModuleIds).map(async ([id, module2]) => {
1078
+ if (hostShared[module2]) {
1079
+ scope.sharedModules[id] = await hostShared[module2](scope.name);
1080
+ } else {
1081
+ logError(
1082
+ "SharedModules",
1083
+ `Host shared module "${module2}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1084
+ );
1085
+ }
1086
+ })
1087
+ );
1088
+ }
1089
+ logWarn(
1090
+ "SharedModules",
1091
+ `No shared module initializer found in bundle for scope="${scope.scopedName}" \u2014 falling back to remoteShared mapping`
1092
+ );
1006
1093
  } else {
1007
- modules = raw;
1094
+ logWarn(
1095
+ "SharedModules",
1096
+ `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
1097
+ );
1098
+ }
1099
+ return Promise.all(
1100
+ Object.entries(remoteShared).map(async ([id, module2]) => {
1101
+ if (hostShared[module2]) {
1102
+ const normalizedId = id.replace("[app-ssr]", "[app-client]");
1103
+ scope.sharedModules[normalizedId] = await hostShared[module2](
1104
+ scope.name
1105
+ );
1106
+ } else {
1107
+ logError(
1108
+ "SharedModules",
1109
+ `Shared module "${module2}" not found for "${scope.name}". ${DEDUPLICATION_WARNING}`
1110
+ );
1111
+ }
1112
+ })
1113
+ );
1114
+ }
1115
+ function extractSharedModuleIds(shared, scope) {
1116
+ return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1117
+ const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1118
+ if (asyncSharedModuleId) {
1119
+ const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1120
+ let asyncSharedModule;
1121
+ const turbopackModules = getTurbopackModules(scope) ?? [];
1122
+ const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1123
+ asyncSharedModuleIdNumber
1124
+ );
1125
+ if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1126
+ asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1127
+ }
1128
+ if (asyncSharedModule) {
1129
+ const asyncSharedModuleCode = asyncSharedModule.toString();
1130
+ const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1131
+ acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1132
+ "__remote_shared_module_",
1133
+ ""
1134
+ );
1135
+ }
1136
+ }
1137
+ return acc;
1138
+ }, {});
1139
+ }
1140
+ function getSharedModule(scope, id) {
1141
+ const idStr = String(id);
1142
+ if (scope.sharedModules[idStr] !== void 0) {
1143
+ return scope.sharedModules[idStr];
1008
1144
  }
1009
- if (!self.__remote_components_turbopack_modules__) {
1010
- self.__remote_components_turbopack_modules__ = {};
1145
+ for (const [key, value] of Object.entries(scope.sharedModules)) {
1146
+ if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
1147
+ return value;
1148
+ }
1011
1149
  }
1012
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1013
- self.__remote_components_turbopack_modules__[bundle] = {};
1150
+ return null;
1151
+ }
1152
+ var DEDUPLICATION_WARNING;
1153
+ var init_shared_modules = __esm({
1154
+ "src/runtime/turbopack/shared-modules.ts"() {
1155
+ "use strict";
1156
+ init_logger();
1157
+ init_module();
1158
+ init_patterns2();
1159
+ init_remote_scope();
1160
+ 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).";
1014
1161
  }
1015
- if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
1016
- return self.__remote_components_turbopack_modules__[bundle][moduleId];
1162
+ });
1163
+
1164
+ // src/runtime/turbopack/module.ts
1165
+ function requireModule(scope, moduleId, fullId) {
1166
+ const idStr = String(moduleId);
1167
+ if (scope.moduleCache[idStr])
1168
+ return scope.moduleCache[idStr];
1169
+ const sharedModule = getSharedModule(scope, moduleId);
1170
+ if (sharedModule)
1171
+ return sharedModule;
1172
+ return handleTurbopackModule(
1173
+ scope,
1174
+ idStr,
1175
+ fullId ?? formatRemoteId(scope, idStr)
1176
+ );
1177
+ }
1178
+ function handleTurbopackModule(scope, moduleId, id) {
1179
+ if (scope.moduleCache[moduleId]) {
1180
+ return scope.moduleCache[moduleId];
1017
1181
  }
1182
+ const modules = getTurbopackModules(scope);
1018
1183
  if (!modules) {
1019
- logError("TurbopackModule", `TURBOPACK_${bundleKey} is undefined`);
1184
+ logError(
1185
+ "TurbopackModule",
1186
+ `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1187
+ );
1020
1188
  }
1021
1189
  const moduleInit = findModuleInit(modules, moduleId);
1022
1190
  const exports = {};
1023
1191
  const moduleExports = { exports };
1024
1192
  if (typeof moduleInit !== "function") {
1025
1193
  throw new Error(
1026
- `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
1194
+ `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1027
1195
  );
1028
1196
  }
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
- }
1197
+ scope.moduleCache[moduleId] = moduleExports.exports;
1036
1198
  moduleInit(
1037
1199
  createTurbopackContext(
1038
- bundle,
1200
+ scope,
1039
1201
  exports,
1040
1202
  moduleExports,
1041
1203
  modules,
1042
1204
  moduleInit,
1043
- id,
1044
- self
1205
+ id
1045
1206
  ),
1046
1207
  moduleExports,
1047
1208
  exports
1048
1209
  );
1049
- if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
1050
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1210
+ if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1211
+ scope.moduleCache[moduleId] = moduleExports.exports;
1051
1212
  }
1052
1213
  return moduleExports.exports;
1053
1214
  }
@@ -1072,7 +1233,8 @@ function findModuleInit(modules, moduleId) {
1072
1233
  (e) => Boolean(e && typeof e === "object" && moduleId in e)
1073
1234
  )?.[moduleId];
1074
1235
  }
1075
- function createTurbopackContext(bundle, exports, moduleExports, modules, moduleInit, id, self) {
1236
+ function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1237
+ const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
1076
1238
  return {
1077
1239
  // HMR not implemented for Remote Components
1078
1240
  k: {
@@ -1088,16 +1250,10 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1088
1250
  s(bindings, esmId) {
1089
1251
  let mod = exports;
1090
1252
  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] = {};
1096
- }
1097
- if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
1098
- self.__remote_components_turbopack_modules__[bundle][esmId] = {};
1253
+ if (!scope.moduleCache[esmId]) {
1254
+ scope.moduleCache[esmId] = {};
1099
1255
  }
1100
- mod = self.__remote_components_turbopack_modules__[bundle][esmId];
1256
+ mod = scope.moduleCache[esmId];
1101
1257
  }
1102
1258
  Object.defineProperty(mod, "__esModule", { value: true });
1103
1259
  if (Array.isArray(bindings)) {
@@ -1130,7 +1286,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1130
1286
  }
1131
1287
  }
1132
1288
  },
1133
- // import
1289
+ // import — resolves directly via scope, no global dispatch
1134
1290
  i(importId) {
1135
1291
  let mod;
1136
1292
  if (typeof importId === "string") {
@@ -1141,7 +1297,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1141
1297
  /\s+<export(?<specifier>.*)>$/,
1142
1298
  ""
1143
1299
  );
1144
- mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`);
1300
+ mod = scopedRequire(normalizedId);
1145
1301
  if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1146
1302
  if (exportSource === "*") {
1147
1303
  mod[exportName] = mod;
@@ -1150,7 +1306,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1150
1306
  }
1151
1307
  }
1152
1308
  } else {
1153
- mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
1309
+ mod = scopedRequire(importId);
1154
1310
  }
1155
1311
  if (typeof mod !== "object" || mod === null) {
1156
1312
  mod = { default: mod };
@@ -1162,16 +1318,14 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1162
1318
  }
1163
1319
  return mod;
1164
1320
  },
1165
- // require
1321
+ // require — resolves directly via scope
1166
1322
  r(requireId) {
1167
- return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
1323
+ return scopedRequire(requireId);
1168
1324
  },
1169
1325
  // value exports
1170
1326
  v(value) {
1171
1327
  if (typeof value === "function") {
1172
- exports.default = value((vid) => {
1173
- return self.__webpack_require__?.(`[${bundle}] ${vid}`);
1174
- });
1328
+ exports.default = value((vid) => scopedRequire(vid));
1175
1329
  } else {
1176
1330
  moduleExports.exports = value;
1177
1331
  }
@@ -1186,17 +1340,15 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1186
1340
  );
1187
1341
  exports.default = result;
1188
1342
  },
1189
- // async module loader
1343
+ // async module loader — resolves directly via scope
1190
1344
  async A(Aid) {
1191
- const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
1192
- return mod.default(
1193
- (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
1194
- );
1345
+ const mod = scopedRequire(Aid);
1346
+ return mod.default((parentId) => scopedRequire(parentId));
1195
1347
  },
1196
1348
  // dynamic import tracking — no-op for remote components
1197
1349
  j() {
1198
1350
  },
1199
- // chunk loader
1351
+ // chunk loader — loads directly via scope, no global dispatch
1200
1352
  l(url) {
1201
1353
  const flatModules = Array.isArray(modules) ? modules : [];
1202
1354
  const moduleInitIndex = flatModules.indexOf(moduleInit);
@@ -1207,16 +1359,16 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1207
1359
  const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1208
1360
  const nextIndex = scriptSrc.indexOf("/_next");
1209
1361
  const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1210
- const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
1211
- return self.__webpack_chunk_load__?.(bundleUrl, bundle);
1362
+ const chunkUrl = `${baseUrl}/_next/${url}`;
1363
+ return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1212
1364
  }
1213
1365
  }
1214
1366
  throw new Error(
1215
1367
  `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1216
1368
  );
1217
1369
  },
1218
- // global object for this bundle
1219
- g: self.__remote_components_turbopack_global__?.[bundle],
1370
+ // globalThis substitute shared across all modules in this scope
1371
+ g: scope.moduleGlobal,
1220
1372
  m: moduleExports,
1221
1373
  e: exports
1222
1374
  };
@@ -1224,169 +1376,49 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1224
1376
  var init_module = __esm({
1225
1377
  "src/runtime/turbopack/module.ts"() {
1226
1378
  "use strict";
1227
- init_constants2();
1228
1379
  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).";
1380
+ init_chunk_loader();
1381
+ init_remote_scope();
1382
+ init_shared_modules();
1360
1383
  }
1361
1384
  });
1362
1385
 
1363
1386
  // src/runtime/turbopack/webpack-runtime.ts
1364
1387
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1365
1388
  const self = globalThis;
1389
+ const bundleName = bundle ?? "default";
1390
+ const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1391
+ registerScope(scope);
1366
1392
  if (!self.__remote_bundle_url__) {
1367
1393
  self.__remote_bundle_url__ = {};
1368
1394
  }
1369
- self.__remote_bundle_url__[bundle ?? "default"] = url;
1395
+ self.__remote_bundle_url__[bundleName] = url;
1396
+ if (scope.scopedName !== bundleName) {
1397
+ self.__remote_bundle_url__[scope.scopedName] = url;
1398
+ }
1370
1399
  self.__webpack_get_script_filename__ = () => null;
1371
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
1400
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1401
+ if (willCreateDispatchers) {
1372
1402
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1373
1403
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1374
1404
  self.__original_webpack_require__ = self.__webpack_require__;
1375
1405
  }
1376
- self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
1377
- self.__webpack_require__ = createModuleRequire(runtime);
1406
+ self.__webpack_chunk_load__ = createChunkDispatcher();
1407
+ self.__webpack_require__ = createModuleDispatcher(runtime);
1378
1408
  self.__webpack_require_type__ = runtime;
1379
1409
  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";
1410
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1411
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
1383
1412
  }
1384
1413
  }
1414
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1415
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1416
+ }
1385
1417
  if (runtime === RUNTIME_TURBOPACK) {
1386
1418
  const results = await Promise.allSettled(
1387
1419
  scripts.map((script) => {
1388
1420
  if (script.src) {
1389
- return self.__webpack_chunk_load__?.(script.src, bundle);
1421
+ return loadChunkWithScope(scope, script.src);
1390
1422
  }
1391
1423
  return Promise.resolve(void 0);
1392
1424
  })
@@ -1408,54 +1440,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1408
1440
  "react-dom/client": async () => (await import("react-dom/client")).default,
1409
1441
  ...shared
1410
1442
  };
1411
- await initializeSharedModules(
1412
- bundle ?? "default",
1413
- // include all core modules as shared
1414
- coreShared,
1415
- remoteShared
1416
- );
1443
+ await initializeSharedModules(scope, coreShared, remoteShared);
1417
1444
  }
1418
- function createModuleRequire(runtime) {
1445
+ function createModuleDispatcher(runtime) {
1419
1446
  return (id) => {
1420
1447
  const self = globalThis;
1421
1448
  const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1422
1449
  bundle: "default",
1423
1450
  id
1424
1451
  };
1425
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1426
- logDebug("WebpackRuntime", `remoteRuntime: "${remoteRuntime}"`);
1452
+ const bundleName = bundle ?? "default";
1453
+ const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
1454
+ logDebug(
1455
+ "ModuleDispatcher",
1456
+ `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
1457
+ );
1427
1458
  try {
1428
1459
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1429
1460
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1430
1461
  }
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);
1462
+ const scope = getScope(bundleName);
1463
+ if (scope) {
1464
+ return requireModule(scope, moduleId ?? id, id);
1438
1465
  }
1439
- throw new Error(`Module "${id}" not found.`);
1466
+ throw new Error(
1467
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1468
+ );
1440
1469
  } catch (requireError) {
1441
1470
  logWarn(
1442
- "WebpackRuntime",
1471
+ "ModuleDispatcher",
1443
1472
  `Module require failed: ${String(requireError)}`
1444
1473
  );
1445
1474
  if (typeof self.__original_webpack_require__ !== "function") {
1446
1475
  throw new RemoteComponentsError(
1447
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1476
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1448
1477
  {
1449
1478
  cause: requireError instanceof Error ? requireError : void 0
1450
1479
  }
1451
1480
  );
1452
1481
  }
1453
1482
  try {
1454
- logDebug("WebpackRuntime", "Falling back to original webpack require");
1483
+ logDebug(
1484
+ "ModuleDispatcher",
1485
+ "Falling back to original webpack require"
1486
+ );
1455
1487
  return self.__original_webpack_require__(id);
1456
1488
  } catch (originalError) {
1457
1489
  throw new RemoteComponentsError(
1458
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1490
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1459
1491
  { cause: originalError instanceof Error ? originalError : void 0 }
1460
1492
  );
1461
1493
  }
@@ -1471,6 +1503,7 @@ var init_webpack_runtime = __esm({
1471
1503
  init_logger();
1472
1504
  init_chunk_loader();
1473
1505
  init_module();
1506
+ init_remote_scope();
1474
1507
  init_shared_modules();
1475
1508
  }
1476
1509
  });