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
@@ -39,98 +39,40 @@ var init_app = __esm({
39
39
  // src/host/nextjs/app-client-only.tsx
40
40
  import { useMemo as useMemo3 } from "react";
41
41
 
42
- // src/host/shared/remote-image-loader.ts
43
- function getRemoteBundleOrigin(bundle) {
44
- const self = globalThis;
45
- return self.__remote_bundle_url__?.[bundle]?.origin ?? "";
46
- }
47
- function createRemoteImageLoader(bundle, resolveClientUrl) {
48
- const loader = Object.assign(
49
- ({
50
- config,
51
- src,
52
- width,
53
- quality
54
- }) => {
55
- const q = quality ?? 75;
56
- const remoteOrigin = getRemoteBundleOrigin(bundle);
57
- const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;
58
- const basePath = isCrossOrigin ? `${remoteOrigin}${config.path ?? "/_next/image"}` : config.path ?? `${remoteOrigin}/_next/image`;
59
- const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;
60
- return resolveClientUrl?.(url) ?? url;
61
- },
62
- // Signals to getImgProps that this is a default loader (not a user-defined
63
- // one), enabling srcSet generation with device/image sizes from the config.
64
- { __next_img_default: true }
65
- );
66
- return loader;
67
- }
68
-
69
- // src/runtime/url/resolve-client-url.ts
70
- function withRemoteSrc(resolveClientUrl, remoteSrc) {
71
- const remoteOrigin = parseOrigin(remoteSrc);
72
- return (url) => {
73
- const urlOrigin = parseOrigin(url);
74
- if (remoteOrigin && urlOrigin && urlOrigin !== remoteOrigin) {
75
- return void 0;
76
- }
77
- return resolveClientUrl(remoteSrc, url);
78
- };
42
+ // src/utils/index.ts
43
+ function escapeString(str) {
44
+ return str.replace(/[^a-z0-9]/g, "_");
79
45
  }
80
- function parseOrigin(url) {
81
- try {
82
- return new URL(url).origin;
83
- } catch {
84
- return void 0;
85
- }
46
+ function computeScopedName(name, options) {
47
+ return options.isCrossOrigin ? `${name}_${escapeString(options.remoteHost.toLowerCase())}` : name;
86
48
  }
49
+ var attrToProp = {
50
+ fetchpriority: "fetchPriority",
51
+ crossorigin: "crossOrigin",
52
+ imagesrcset: "imageSrcSet",
53
+ imagesizes: "imageSizes",
54
+ srcset: "srcSet"
55
+ };
87
56
 
88
- // src/runtime/url/default-resolve-client-url.ts
89
- function bindResolveClientUrl(prop, remoteSrc) {
90
- return prop ? withRemoteSrc(prop, remoteSrc) : void 0;
57
+ // src/runtime/constants.ts
58
+ var DEFAULT_BUNDLE_NAME = "__vercel_remote_bundle";
59
+ var DEFAULT_COMPONENT_NAME = "__vercel_remote_component";
60
+ var DEFAULT_ROUTE = "/";
61
+ var RUNTIME_WEBPACK = "webpack";
62
+ var RUNTIME_TURBOPACK = "turbopack";
63
+ var RUNTIME_SCRIPT = "script";
64
+ function getBundleKey(bundle) {
65
+ return escapeString(bundle);
91
66
  }
92
67
 
93
- // src/host/nextjs/image-shared.ts
94
- function resolveForBundle(unbound, bundle) {
95
- if (!unbound)
96
- return void 0;
97
- const self = globalThis;
98
- const remoteSrc = self.__remote_bundle_url__?.[bundle]?.href ?? "";
99
- return bindResolveClientUrl(unbound, remoteSrc);
100
- }
101
- function createImageLoaderSharedEntries({
102
- bound,
103
- unbound
104
- } = {}) {
105
- const entry = (bundle) => {
106
- const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
107
- return Promise.resolve({
108
- default: createRemoteImageLoader(bundle, resolveClientUrl),
109
- __esModule: true
110
- });
111
- };
112
- return {
113
- "next/dist/shared/lib/image-loader": entry,
114
- "next/dist/esm/shared/lib/image-loader": entry
115
- };
68
+ // src/runtime/patterns.ts
69
+ var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
70
+ var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
71
+ var DOUBLE_SLASH_RE = /(?<!:)\/\//g;
72
+ function collapseDoubleSlashes(path) {
73
+ return path.replace(DOUBLE_SLASH_RE, "/");
116
74
  }
117
75
 
118
- // src/host/nextjs/app-client-only.tsx
119
- import { RemoteComponentsContext } from "#internal/host/react/context";
120
-
121
- // src/host/react/index.tsx
122
- import {
123
- startTransition,
124
- useEffect,
125
- useId,
126
- useLayoutEffect as useLayoutEffect2,
127
- useMemo as useMemo2,
128
- useRef as useRef2,
129
- useState as useState2
130
- } from "react";
131
- import { createPortal } from "react-dom";
132
- import { useRemoteComponentsContext as useRemoteComponentsContext2 } from "#internal/host/react/context";
133
-
134
76
  // src/utils/logger.ts
135
77
  init_constants();
136
78
 
@@ -277,6 +219,156 @@ function warnCrossOriginFetchError(logLocation, url) {
277
219
  }
278
220
  }
279
221
 
222
+ // src/runtime/turbopack/remote-scope.ts
223
+ function getRegistry() {
224
+ const self = globalThis;
225
+ if (!self.__remote_component_scopes__) {
226
+ self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
227
+ }
228
+ return self.__remote_component_scopes__;
229
+ }
230
+ function createScope(name, url, runtime, resolveClientUrl) {
231
+ const isCrossOrigin = url.origin !== location.origin;
232
+ const scopedName = computeScopedName(name, {
233
+ remoteHost: url.host,
234
+ isCrossOrigin
235
+ });
236
+ const globalKey = getBundleKey(scopedName);
237
+ return {
238
+ name,
239
+ scopedName,
240
+ globalKey,
241
+ url,
242
+ runtime,
243
+ resolveClientUrl,
244
+ moduleCache: {},
245
+ sharedModules: {},
246
+ moduleGlobal: {}
247
+ };
248
+ }
249
+ function registerScope(scope) {
250
+ const registry = getRegistry();
251
+ registry.set(scope.scopedName, scope);
252
+ if (scope.scopedName !== scope.name) {
253
+ const existing = registry.get(scope.name);
254
+ if (existing && existing.scopedName !== scope.scopedName) {
255
+ logWarn(
256
+ "RemoteScope",
257
+ `Plain name "${scope.name}" already registered by scope "${existing.scopedName}" \u2014 overwriting with "${scope.scopedName}". Static hosts will only resolve the latest one.`
258
+ );
259
+ }
260
+ registry.set(scope.name, scope);
261
+ }
262
+ logDebug(
263
+ "RemoteScope",
264
+ `Registered scope "${scope.scopedName}" (${registry.size} total)`
265
+ );
266
+ }
267
+ function getScope(name) {
268
+ return getRegistry().get(name);
269
+ }
270
+ function formatRemoteId(scope, path) {
271
+ return `[${scope.scopedName}] ${path}`;
272
+ }
273
+ function parseRemoteId(id) {
274
+ const groups = REMOTE_COMPONENT_REGEX.exec(id)?.groups;
275
+ if (groups?.bundle && groups.id) {
276
+ return {
277
+ bundle: groups.bundle,
278
+ path: groups.id,
279
+ prefix: groups.prefix ?? ""
280
+ };
281
+ }
282
+ return { bundle: "default", path: id, prefix: "" };
283
+ }
284
+
285
+ // src/host/shared/remote-image-loader.ts
286
+ function createRemoteImageLoader(bundle, resolveClientUrl) {
287
+ const loader = Object.assign(
288
+ ({
289
+ config,
290
+ src,
291
+ width,
292
+ quality
293
+ }) => {
294
+ const q = quality ?? 75;
295
+ const remoteOrigin = getScope(bundle)?.url.origin ?? "";
296
+ const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;
297
+ const basePath = isCrossOrigin ? `${remoteOrigin}${config.path ?? "/_next/image"}` : config.path ?? `${remoteOrigin}/_next/image`;
298
+ const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;
299
+ return resolveClientUrl?.(url) ?? url;
300
+ },
301
+ // Signals to getImgProps that this is a default loader (not a user-defined
302
+ // one), enabling srcSet generation with device/image sizes from the config.
303
+ { __next_img_default: true }
304
+ );
305
+ return loader;
306
+ }
307
+
308
+ // src/runtime/url/resolve-client-url.ts
309
+ function withRemoteSrc(resolveClientUrl, remoteSrc) {
310
+ const remoteOrigin = parseOrigin(remoteSrc);
311
+ return (url) => {
312
+ const urlOrigin = parseOrigin(url);
313
+ if (remoteOrigin && urlOrigin && urlOrigin !== remoteOrigin) {
314
+ return void 0;
315
+ }
316
+ return resolveClientUrl(remoteSrc, url);
317
+ };
318
+ }
319
+ function parseOrigin(url) {
320
+ try {
321
+ return new URL(url).origin;
322
+ } catch {
323
+ return void 0;
324
+ }
325
+ }
326
+
327
+ // src/runtime/url/default-resolve-client-url.ts
328
+ function bindResolveClientUrl(prop, remoteSrc) {
329
+ return prop ? withRemoteSrc(prop, remoteSrc) : void 0;
330
+ }
331
+
332
+ // src/host/nextjs/image-shared.ts
333
+ function resolveForBundle(unbound, bundle) {
334
+ if (!unbound)
335
+ return void 0;
336
+ const remoteSrc = getScope(bundle)?.url.href ?? "";
337
+ return bindResolveClientUrl(unbound, remoteSrc);
338
+ }
339
+ function createImageLoaderSharedEntries({
340
+ bound,
341
+ unbound
342
+ } = {}) {
343
+ const entry = (bundle) => {
344
+ const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
345
+ return Promise.resolve({
346
+ default: createRemoteImageLoader(bundle, resolveClientUrl),
347
+ __esModule: true
348
+ });
349
+ };
350
+ return {
351
+ "next/dist/shared/lib/image-loader": entry,
352
+ "next/dist/esm/shared/lib/image-loader": entry
353
+ };
354
+ }
355
+
356
+ // src/host/nextjs/app-client-only.tsx
357
+ import { RemoteComponentsContext } from "#internal/host/react/context";
358
+
359
+ // src/host/react/index.tsx
360
+ import {
361
+ startTransition,
362
+ useEffect,
363
+ useId,
364
+ useLayoutEffect as useLayoutEffect2,
365
+ useMemo as useMemo2,
366
+ useRef as useRef2,
367
+ useState as useState2
368
+ } from "react";
369
+ import { createPortal } from "react-dom";
370
+ import { useRemoteComponentsContext as useRemoteComponentsContext2 } from "#internal/host/react/context";
371
+
280
372
  // src/host/server/fetch-headers.ts
281
373
  function remoteFetchHeaders() {
282
374
  return {
@@ -501,29 +593,6 @@ function resolveNameFromSrc(src, defaultName) {
501
593
  return name || defaultName;
502
594
  }
503
595
 
504
- // src/utils/index.ts
505
- function escapeString(str) {
506
- return str.replace(/[^a-z0-9]/g, "_");
507
- }
508
- var attrToProp = {
509
- fetchpriority: "fetchPriority",
510
- crossorigin: "crossOrigin",
511
- imagesrcset: "imageSrcSet",
512
- imagesizes: "imageSizes",
513
- srcset: "srcSet"
514
- };
515
-
516
- // src/runtime/constants.ts
517
- var DEFAULT_BUNDLE_NAME = "__vercel_remote_bundle";
518
- var DEFAULT_COMPONENT_NAME = "__vercel_remote_component";
519
- var DEFAULT_ROUTE = "/";
520
- var RUNTIME_WEBPACK = "webpack";
521
- var RUNTIME_TURBOPACK = "turbopack";
522
- var RUNTIME_SCRIPT = "script";
523
- function getBundleKey(bundle) {
524
- return escapeString(bundle);
525
- }
526
-
527
596
  // src/runtime/html/apply-origin.ts
528
597
  var tagNames = [
529
598
  "img",
@@ -998,14 +1067,6 @@ function createRSCStream(rscName, data) {
998
1067
  });
999
1068
  }
1000
1069
 
1001
- // src/runtime/patterns.ts
1002
- var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
1003
- var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
1004
- var DOUBLE_SLASH_RE = /(?<!:)\/\//g;
1005
- function collapseDoubleSlashes(path) {
1006
- return path.replace(DOUBLE_SLASH_RE, "/");
1007
- }
1008
-
1009
1070
  // src/runtime/turbopack/patterns.ts
1010
1071
  var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
1011
1072
  var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
@@ -1015,62 +1076,39 @@ var ASYNC_MODULE_ALL_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<vCb
1015
1076
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
1016
1077
 
1017
1078
  // src/runtime/turbopack/chunk-loader.ts
1018
- function createChunkLoader(runtime, resolveClientUrl) {
1019
- return function __turbopack_chunk_load__(chunkId, scriptBundle) {
1020
- logDebug("ChunkLoader", `Loading chunk: "${chunkId}"`);
1021
- const self = globalThis;
1022
- const {
1023
- bundle,
1024
- id: path,
1025
- prefix
1026
- } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
1027
- bundle: scriptBundle ?? "",
1028
- id: chunkId
1029
- };
1030
- logDebug(
1031
- "ChunkLoader",
1032
- `Parsed chunk - bundle: "${bundle}", path: "${path}", prefix: "${prefix}"`
1033
- );
1034
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1035
- logDebug("ChunkLoader", `Remote runtime: "${remoteRuntime}"`);
1036
- if (remoteRuntime === RUNTIME_WEBPACK) {
1037
- logDebug("ChunkLoader", "Skipping chunk load - webpack runtime detected");
1038
- return Promise.resolve(void 0);
1039
- }
1040
- const url = new URL(
1041
- path ? `${prefix ?? ""}${path}`.replace(
1042
- /(?<char>[^:])(?<double>\/\/)/g,
1043
- "$1/"
1044
- ) : "/",
1045
- self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
1046
- ).href;
1047
- if (url.endsWith(".css")) {
1048
- logDebug("ChunkLoader", `Skipping CSS file: "${url}"`);
1049
- return;
1050
- }
1051
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1052
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
1053
- }
1054
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1055
- logDebug("ChunkLoader", `Returning cached promise for: "${url}"`);
1056
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1057
- }
1058
- const resolvedUrl = resolveClientUrl?.(url) ?? url;
1059
- logDebug("ChunkLoader", `Fetching chunk from: "${resolvedUrl}"`);
1060
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise((resolve, reject) => {
1079
+ function loadChunkWithScope(scope, chunkId) {
1080
+ logDebug(
1081
+ "ChunkLoader",
1082
+ `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
1083
+ );
1084
+ const self = globalThis;
1085
+ const { bundle, path, prefix } = parseRemoteId(chunkId);
1086
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
1087
+ if (remoteRuntime === RUNTIME_WEBPACK) {
1088
+ return Promise.resolve(void 0);
1089
+ }
1090
+ const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : "/";
1091
+ const url = new URL(rawPath, scope.url).href;
1092
+ if (url.endsWith(".css")) {
1093
+ return;
1094
+ }
1095
+ if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1096
+ self.__remote_components_turbopack_chunk_loader_promise__ = {};
1097
+ }
1098
+ if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1099
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
1100
+ }
1101
+ const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1102
+ if (resolvedUrl !== url) {
1103
+ logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1104
+ }
1105
+ self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1106
+ (resolve, reject) => {
1061
1107
  fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1062
1108
  const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1063
1109
  if (hasTurbopack) {
1064
- return handleTurbopackChunk(code, bundle ?? "", url);
1110
+ return handleTurbopackChunk(code, scope, url);
1065
1111
  }
1066
- logDebug(
1067
- "ChunkLoader",
1068
- `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: "${url}"`
1069
- );
1070
- logDebug(
1071
- "ChunkLoader",
1072
- `First 500 chars of chunk: ${code.slice(0, 500)}`
1073
- );
1074
1112
  }).then(resolve).catch((error) => {
1075
1113
  const isProxied = isProxiedUrl(resolvedUrl);
1076
1114
  if (isProxied) {
@@ -1080,17 +1118,29 @@ function createChunkLoader(runtime, resolveClientUrl) {
1080
1118
  reject(error);
1081
1119
  }
1082
1120
  });
1083
- });
1084
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1121
+ }
1122
+ );
1123
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
1124
+ }
1125
+ function createChunkDispatcher() {
1126
+ return function __chunk_dispatcher__(chunkId, scriptBundle) {
1127
+ logDebug("ChunkDispatcher", `Dispatching chunk: "${chunkId}"`);
1128
+ const { bundle } = parseRemoteId(chunkId);
1129
+ const bundleName = bundle || scriptBundle || "default";
1130
+ const scope = getScope(bundleName);
1131
+ logDebug(
1132
+ "ChunkDispatcher",
1133
+ `Scope resolution: bundle="${bundleName}", scope=${scope?.scopedName ?? "null"}`
1134
+ );
1135
+ if (!scope) {
1136
+ logWarn("ChunkDispatcher", `No scope found for bundle "${bundleName}"`);
1137
+ return Promise.resolve(void 0);
1138
+ }
1139
+ return loadChunkWithScope(scope, chunkId);
1085
1140
  };
1086
1141
  }
1087
- async function handleTurbopackChunk(code, bundle, url) {
1088
- logDebug(
1089
- "ChunkLoader",
1090
- `Handling Turbopack chunk - bundle: "${bundle}", url: "${url}"`
1091
- );
1142
+ async function handleTurbopackChunk(code, scope, url) {
1092
1143
  if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
1093
- logDebug("ChunkLoader", `Skipping worker chunk: "${url}"`);
1094
1144
  const preloadLinks = document.querySelectorAll(
1095
1145
  `link[rel="preload"][href="${new URL(url).pathname}"]`
1096
1146
  );
@@ -1098,58 +1148,41 @@ async function handleTurbopackChunk(code, bundle, url) {
1098
1148
  return;
1099
1149
  }
1100
1150
  const self = globalThis;
1101
- const bundleKey = getBundleKey(bundle);
1102
- logDebug("ChunkLoader", `Bundle key: "${bundleKey}"`);
1151
+ const { globalKey } = scope;
1103
1152
  const transformedCode = code.replace(
1104
1153
  /globalThis\[\s*["']TURBOPACK["']\s*\]/g,
1105
- `globalThis["TURBOPACK_${bundleKey}"]`
1154
+ `globalThis["TURBOPACK_${globalKey}"]`
1106
1155
  ).replace(
1107
1156
  /self\[\s*["']TURBOPACK["']\s*\]/g,
1108
- `self["TURBOPACK_${bundleKey}"]`
1109
- ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`).replace(
1157
+ `self["TURBOPACK_${globalKey}"]`
1158
+ ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`).replace(
1110
1159
  /TURBOPACK_WORKER_LOCATION/g,
1111
- `TURBOPACK_WORKER_LOCATION_${bundleKey}`
1160
+ `TURBOPACK_WORKER_LOCATION_${globalKey}`
1112
1161
  ).replace(
1113
1162
  /TURBOPACK_NEXT_CHUNK_URLS/g,
1114
- `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
1163
+ `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`
1115
1164
  ).replace(
1116
1165
  /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
1117
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
1118
- ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
1166
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`
1167
+ ).replace(/__next_require__/g, `__${globalKey}_next_require__`).replace(
1119
1168
  /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
1120
- `//# sourceMappingURL=${new URL(
1121
- ".",
1122
- new URL(
1123
- url,
1124
- self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
1125
- )
1126
- ).href}$1$2.js.map`
1169
+ `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1127
1170
  );
1128
- if (!self[`TURBOPACK_${bundleKey}`]) {
1171
+ if (!self[`TURBOPACK_${globalKey}`]) {
1129
1172
  const chunkData = [];
1130
1173
  const turbopackObject = {
1131
1174
  push: (item) => {
1132
- logDebug(
1133
- "ChunkLoader",
1134
- `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? "array" : typeof item}`
1135
- );
1136
1175
  if (Array.isArray(item)) {
1137
1176
  chunkData.push(item);
1138
- logDebug(
1139
- "ChunkLoader",
1140
- `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`
1141
- );
1142
1177
  } else {
1143
1178
  chunkData.push([item]);
1144
1179
  }
1145
1180
  return chunkData.length;
1146
1181
  },
1147
- // Store chunks for later access
1148
1182
  __chunks__: chunkData
1149
1183
  };
1150
- self[`TURBOPACK_${bundleKey}`] = turbopackObject;
1184
+ self[`TURBOPACK_${globalKey}`] = turbopackObject;
1151
1185
  }
1152
- logDebug("ChunkLoader", `Creating blob script for: "${url}"`);
1153
1186
  await new Promise((scriptResolve, scriptReject) => {
1154
1187
  const blob = new Blob([transformedCode], {
1155
1188
  type: "application/javascript; charset=UTF-8"
@@ -1161,21 +1194,6 @@ async function handleTurbopackChunk(code, bundle, url) {
1161
1194
  script.async = true;
1162
1195
  script.onload = () => {
1163
1196
  URL.revokeObjectURL(scriptUrl);
1164
- logDebug(
1165
- "ChunkLoader",
1166
- `Script loaded successfully for bundle "${bundle}"`
1167
- );
1168
- const turbopackBundle = self[`TURBOPACK_${bundleKey}`];
1169
- logDebug(
1170
- "ChunkLoader",
1171
- `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${turbopackBundle ? Object.keys(turbopackBundle).slice(0, 10).join(", ") : "none"}`
1172
- );
1173
- if (turbopackBundle && typeof turbopackBundle === "object") {
1174
- logDebug(
1175
- "ChunkLoader",
1176
- `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle).length}`
1177
- );
1178
- }
1179
1197
  scriptResolve(void 0);
1180
1198
  script.remove();
1181
1199
  };
@@ -1190,43 +1208,177 @@ async function handleTurbopackChunk(code, bundle, url) {
1190
1208
  };
1191
1209
  document.head.appendChild(script);
1192
1210
  });
1193
- const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
1194
- logDebug(
1195
- "ChunkLoader",
1196
- `Processing chunk lists for bundle "${bundle}": ${chunkLists?.length ?? 0} lists`
1197
- );
1198
- const loadChunkLists = [];
1211
+ const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`];
1212
+ const loadChunkPromises = [];
1199
1213
  while (chunkLists?.length) {
1200
1214
  const { chunks } = chunkLists.shift() ?? { chunks: [] };
1201
1215
  if (chunks.length > 0) {
1202
- logDebug(
1203
- "ChunkLoader",
1204
- `Loading ${chunks.length} additional chunks for bundle "${bundle}": [${chunks.join(", ")}]`
1205
- );
1206
- chunks.forEach((id) => {
1207
- const chunkLoadResult = self.__webpack_chunk_load__?.(
1208
- `[${bundle}] ${url.slice(0, url.indexOf("/_next"))}/_next/${id}`
1216
+ for (const id of chunks) {
1217
+ const baseUrl = url.slice(0, url.indexOf("/_next"));
1218
+ const chunkLoadResult = loadChunkWithScope(
1219
+ scope,
1220
+ formatRemoteId(scope, `${baseUrl}/_next/${id}`)
1209
1221
  );
1210
1222
  if (chunkLoadResult) {
1211
- loadChunkLists.push(chunkLoadResult);
1223
+ loadChunkPromises.push(chunkLoadResult);
1212
1224
  }
1213
- });
1225
+ }
1214
1226
  }
1215
1227
  }
1216
- if (loadChunkLists.length > 0) {
1217
- logDebug(
1218
- "ChunkLoader",
1219
- `Waiting for ${loadChunkLists.length} additional chunks to load`
1228
+ if (loadChunkPromises.length > 0) {
1229
+ await Promise.all(loadChunkPromises);
1230
+ }
1231
+ }
1232
+
1233
+ // src/runtime/turbopack/shared-modules.ts
1234
+ var DEDUPLICATION_WARNING = "This module will not be deduplicated \u2014 the remote may load its own copy, which can cause duplicate instance errors (e.g. invalid hook calls if React is loaded twice).";
1235
+ function getTurbopackModules(scope) {
1236
+ const self = globalThis;
1237
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1238
+ if (!raw)
1239
+ return void 0;
1240
+ if (typeof raw === "object" && "__chunks__" in raw) {
1241
+ return raw.__chunks__.flat();
1242
+ }
1243
+ if (Array.isArray(raw)) {
1244
+ return raw.flat();
1245
+ }
1246
+ return Object.entries(raw).flat();
1247
+ }
1248
+ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}) {
1249
+ const allModules = getTurbopackModules(scope);
1250
+ logDebug(
1251
+ "SharedModules",
1252
+ `initializeSharedModules: scope="${scope.scopedName}", allModules=${allModules ? allModules.length : "null"}, hostShared=[${Object.keys(hostShared).join(", ")}], remoteShared=${JSON.stringify(remoteShared)}`
1253
+ );
1254
+ let sharedModuleInitializer = null;
1255
+ if (allModules) {
1256
+ const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1257
+ if (typeof idOrFunc !== "function") {
1258
+ return false;
1259
+ }
1260
+ const funcCode = idOrFunc.toString();
1261
+ return REMOTE_SHARED_MARKER_RE.test(funcCode);
1262
+ });
1263
+ if (sharedModuleInitializerIndex > 0) {
1264
+ const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1265
+ const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1266
+ const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1267
+ if (sharedModuleId) {
1268
+ const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1269
+ scope,
1270
+ sharedModuleId,
1271
+ formatRemoteId(scope, String(sharedModuleInitializerId))
1272
+ );
1273
+ sharedModuleInitializer = sharedModuleInitializerInstance;
1274
+ }
1275
+ }
1276
+ if (sharedModuleInitializer) {
1277
+ const { shared: shared2 } = await sharedModuleInitializer;
1278
+ const sharedModuleIds = extractSharedModuleIds(shared2, scope);
1279
+ logDebug(
1280
+ "SharedModules",
1281
+ `Resolved shared modules for scope="${scope.scopedName}": ${JSON.stringify(sharedModuleIds)}`
1282
+ );
1283
+ return Promise.all(
1284
+ Object.entries(sharedModuleIds).map(async ([id, module]) => {
1285
+ if (hostShared[module]) {
1286
+ scope.sharedModules[id] = await hostShared[module](scope.name);
1287
+ } else {
1288
+ logError(
1289
+ "SharedModules",
1290
+ `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1291
+ );
1292
+ }
1293
+ })
1294
+ );
1295
+ }
1296
+ logWarn(
1297
+ "SharedModules",
1298
+ `No shared module initializer found in bundle for scope="${scope.scopedName}" \u2014 falling back to remoteShared mapping`
1299
+ );
1300
+ } else {
1301
+ logWarn(
1302
+ "SharedModules",
1303
+ `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
1220
1304
  );
1221
- await Promise.all(loadChunkLists);
1222
1305
  }
1306
+ return Promise.all(
1307
+ Object.entries(remoteShared).map(async ([id, module]) => {
1308
+ if (hostShared[module]) {
1309
+ const normalizedId = id.replace("[app-ssr]", "[app-client]");
1310
+ scope.sharedModules[normalizedId] = await hostShared[module](
1311
+ scope.name
1312
+ );
1313
+ } else {
1314
+ logError(
1315
+ "SharedModules",
1316
+ `Shared module "${module}" not found for "${scope.name}". ${DEDUPLICATION_WARNING}`
1317
+ );
1318
+ }
1319
+ })
1320
+ );
1321
+ }
1322
+ function extractSharedModuleIds(shared2, scope) {
1323
+ return Object.entries(shared2).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1324
+ const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1325
+ if (asyncSharedModuleId) {
1326
+ const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1327
+ let asyncSharedModule;
1328
+ const turbopackModules = getTurbopackModules(scope) ?? [];
1329
+ const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1330
+ asyncSharedModuleIdNumber
1331
+ );
1332
+ if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1333
+ asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1334
+ }
1335
+ if (asyncSharedModule) {
1336
+ const asyncSharedModuleCode = asyncSharedModule.toString();
1337
+ const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1338
+ acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1339
+ "__remote_shared_module_",
1340
+ ""
1341
+ );
1342
+ }
1343
+ }
1344
+ return acc;
1345
+ }, {});
1346
+ }
1347
+ function getSharedModule(scope, id) {
1348
+ const idStr = String(id);
1349
+ if (scope.sharedModules[idStr] !== void 0) {
1350
+ return scope.sharedModules[idStr];
1351
+ }
1352
+ for (const [key, value] of Object.entries(scope.sharedModules)) {
1353
+ if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
1354
+ return value;
1355
+ }
1356
+ }
1357
+ return null;
1223
1358
  }
1224
1359
 
1225
1360
  // src/runtime/turbopack/module.ts
1226
- function handleTurbopackModule(bundle, moduleId, id) {
1361
+ function requireModule(scope, moduleId, fullId) {
1362
+ const idStr = String(moduleId);
1363
+ if (scope.moduleCache[idStr])
1364
+ return scope.moduleCache[idStr];
1365
+ const sharedModule = getSharedModule(scope, moduleId);
1366
+ if (sharedModule) {
1367
+ scope.moduleCache[idStr] = sharedModule;
1368
+ return sharedModule;
1369
+ }
1370
+ return handleTurbopackModule(
1371
+ scope,
1372
+ idStr,
1373
+ fullId ?? formatRemoteId(scope, idStr)
1374
+ );
1375
+ }
1376
+ function handleTurbopackModule(scope, moduleId, id) {
1227
1377
  const self = globalThis;
1228
- const bundleKey = getBundleKey(bundle);
1229
- const raw = self[`TURBOPACK_${bundleKey}`];
1378
+ if (scope.moduleCache[moduleId]) {
1379
+ return scope.moduleCache[moduleId];
1380
+ }
1381
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1230
1382
  let modules;
1231
1383
  if (raw && typeof raw === "object" && "__chunks__" in raw) {
1232
1384
  modules = raw.__chunks__.flat();
@@ -1235,48 +1387,35 @@ function handleTurbopackModule(bundle, moduleId, id) {
1235
1387
  } else {
1236
1388
  modules = raw;
1237
1389
  }
1238
- if (!self.__remote_components_turbopack_modules__) {
1239
- self.__remote_components_turbopack_modules__ = {};
1240
- }
1241
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1242
- self.__remote_components_turbopack_modules__[bundle] = {};
1243
- }
1244
- if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
1245
- return self.__remote_components_turbopack_modules__[bundle][moduleId];
1246
- }
1247
1390
  if (!modules) {
1248
- logError("TurbopackModule", `TURBOPACK_${bundleKey} is undefined`);
1391
+ logError(
1392
+ "TurbopackModule",
1393
+ `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1394
+ );
1249
1395
  }
1250
1396
  const moduleInit = findModuleInit(modules, moduleId);
1251
1397
  const exports = {};
1252
1398
  const moduleExports = { exports };
1253
1399
  if (typeof moduleInit !== "function") {
1254
1400
  throw new Error(
1255
- `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
1401
+ `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1256
1402
  );
1257
1403
  }
1258
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1259
- if (!self.__remote_components_turbopack_global__) {
1260
- self.__remote_components_turbopack_global__ = {};
1261
- }
1262
- if (!self.__remote_components_turbopack_global__[bundle]) {
1263
- self.__remote_components_turbopack_global__[bundle] = {};
1264
- }
1404
+ scope.moduleCache[moduleId] = moduleExports.exports;
1265
1405
  moduleInit(
1266
1406
  createTurbopackContext(
1267
- bundle,
1407
+ scope,
1268
1408
  exports,
1269
1409
  moduleExports,
1270
1410
  modules,
1271
1411
  moduleInit,
1272
- id,
1273
- self
1412
+ id
1274
1413
  ),
1275
1414
  moduleExports,
1276
1415
  exports
1277
1416
  );
1278
- if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
1279
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1417
+ if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1418
+ scope.moduleCache[moduleId] = moduleExports.exports;
1280
1419
  }
1281
1420
  return moduleExports.exports;
1282
1421
  }
@@ -1301,7 +1440,8 @@ function findModuleInit(modules, moduleId) {
1301
1440
  (e) => Boolean(e && typeof e === "object" && moduleId in e)
1302
1441
  )?.[moduleId];
1303
1442
  }
1304
- function createTurbopackContext(bundle, exports, moduleExports, modules, moduleInit, id, self) {
1443
+ function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1444
+ const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
1305
1445
  return {
1306
1446
  // HMR not implemented for Remote Components
1307
1447
  k: {
@@ -1317,16 +1457,10 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1317
1457
  s(bindings, esmId) {
1318
1458
  let mod = exports;
1319
1459
  if (typeof esmId === "string" || typeof esmId === "number") {
1320
- if (!self.__remote_components_turbopack_modules__) {
1321
- self.__remote_components_turbopack_modules__ = {};
1322
- }
1323
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1324
- self.__remote_components_turbopack_modules__[bundle] = {};
1325
- }
1326
- if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
1327
- self.__remote_components_turbopack_modules__[bundle][esmId] = {};
1460
+ if (!scope.moduleCache[esmId]) {
1461
+ scope.moduleCache[esmId] = {};
1328
1462
  }
1329
- mod = self.__remote_components_turbopack_modules__[bundle][esmId];
1463
+ mod = scope.moduleCache[esmId];
1330
1464
  }
1331
1465
  Object.defineProperty(mod, "__esModule", { value: true });
1332
1466
  if (Array.isArray(bindings)) {
@@ -1359,7 +1493,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1359
1493
  }
1360
1494
  }
1361
1495
  },
1362
- // import
1496
+ // import — resolves directly via scope, no global dispatch
1363
1497
  i(importId) {
1364
1498
  let mod;
1365
1499
  if (typeof importId === "string") {
@@ -1370,7 +1504,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1370
1504
  /\s+<export(?<specifier>.*)>$/,
1371
1505
  ""
1372
1506
  );
1373
- mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`);
1507
+ mod = scopedRequire(normalizedId);
1374
1508
  if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1375
1509
  if (exportSource === "*") {
1376
1510
  mod[exportName] = mod;
@@ -1379,7 +1513,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1379
1513
  }
1380
1514
  }
1381
1515
  } else {
1382
- mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
1516
+ mod = scopedRequire(importId);
1383
1517
  }
1384
1518
  if (typeof mod !== "object" || mod === null) {
1385
1519
  mod = { default: mod };
@@ -1391,16 +1525,14 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1391
1525
  }
1392
1526
  return mod;
1393
1527
  },
1394
- // require
1528
+ // require — resolves directly via scope
1395
1529
  r(requireId) {
1396
- return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
1530
+ return scopedRequire(requireId);
1397
1531
  },
1398
1532
  // value exports
1399
1533
  v(value) {
1400
1534
  if (typeof value === "function") {
1401
- exports.default = value((vid) => {
1402
- return self.__webpack_require__?.(`[${bundle}] ${vid}`);
1403
- });
1535
+ exports.default = value((vid) => scopedRequire(vid));
1404
1536
  } else {
1405
1537
  moduleExports.exports = value;
1406
1538
  }
@@ -1415,17 +1547,15 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1415
1547
  );
1416
1548
  exports.default = result;
1417
1549
  },
1418
- // async module loader
1550
+ // async module loader — resolves directly via scope
1419
1551
  async A(Aid) {
1420
- const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
1421
- return mod.default(
1422
- (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
1423
- );
1552
+ const mod = scopedRequire(Aid);
1553
+ return mod.default((parentId) => scopedRequire(parentId));
1424
1554
  },
1425
1555
  // dynamic import tracking — no-op for remote components
1426
1556
  j() {
1427
1557
  },
1428
- // chunk loader
1558
+ // chunk loader — loads directly via scope, no global dispatch
1429
1559
  l(url) {
1430
1560
  const flatModules = Array.isArray(modules) ? modules : [];
1431
1561
  const moduleInitIndex = flatModules.indexOf(moduleInit);
@@ -1436,169 +1566,57 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1436
1566
  const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1437
1567
  const nextIndex = scriptSrc.indexOf("/_next");
1438
1568
  const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1439
- const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
1440
- return self.__webpack_chunk_load__?.(bundleUrl, bundle);
1569
+ const chunkUrl = `${baseUrl}/_next/${url}`;
1570
+ return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1441
1571
  }
1442
1572
  }
1443
1573
  throw new Error(
1444
1574
  `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1445
1575
  );
1446
1576
  },
1447
- // global object for this bundle
1448
- g: self.__remote_components_turbopack_global__?.[bundle],
1577
+ // globalThis substitute shared across all modules in this scope
1578
+ g: scope.moduleGlobal,
1449
1579
  m: moduleExports,
1450
1580
  e: exports
1451
1581
  };
1452
1582
  }
1453
1583
 
1454
- // src/runtime/turbopack/shared-modules.ts
1455
- var DEDUPLICATION_WARNING = "This module will not be deduplicated \u2014 the remote may load its own copy, which can cause duplicate instance errors (e.g. invalid hook calls if React is loaded twice).";
1456
- async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {}) {
1457
- const self = globalThis;
1458
- self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
1459
- if (!self.__remote_shared_modules__[bundle]) {
1460
- self.__remote_shared_modules__[bundle] = {};
1461
- }
1462
- const bundleKey = getBundleKey(bundle);
1463
- let modules = self[`TURBOPACK_${bundleKey}`];
1464
- if (modules && typeof modules === "object" && "__chunks__" in modules) {
1465
- const chunks = modules.__chunks__;
1466
- modules = chunks.flat();
1467
- }
1468
- let sharedModuleInitializer = null;
1469
- if (modules) {
1470
- const allModules = Array.isArray(modules) ? modules.flat() : Object.entries(modules).flat();
1471
- const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1472
- if (typeof idOrFunc !== "function") {
1473
- return false;
1474
- }
1475
- const funcCode = idOrFunc.toString();
1476
- return REMOTE_SHARED_MARKER_RE.test(funcCode);
1477
- });
1478
- if (sharedModuleInitializerIndex > 0) {
1479
- const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1480
- const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1481
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1482
- if (sharedModuleId) {
1483
- const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1484
- bundle,
1485
- sharedModuleId,
1486
- `[${bundle}] ${sharedModuleInitializerId}`
1487
- );
1488
- sharedModuleInitializer = sharedModuleInitializerInstance;
1489
- }
1490
- }
1491
- if (sharedModuleInitializer) {
1492
- const { shared: shared2 } = await sharedModuleInitializer;
1493
- const sharedModuleIds = extractSharedModuleIds(
1494
- shared2,
1495
- bundleKey,
1496
- self
1497
- );
1498
- return Promise.all(
1499
- Object.entries(sharedModuleIds).map(async ([id, module]) => {
1500
- if (self.__remote_shared_modules__?.[bundle]) {
1501
- if (hostShared[module]) {
1502
- self.__remote_shared_modules__[bundle][id] = await hostShared[module](bundle);
1503
- } else {
1504
- logError(
1505
- "SharedModules",
1506
- `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1507
- );
1508
- }
1509
- }
1510
- })
1511
- );
1512
- }
1513
- }
1514
- return Promise.all(
1515
- Object.entries(remoteShared).map(async ([id, module]) => {
1516
- if (self.__remote_shared_modules__?.[bundle]) {
1517
- if (hostShared[module]) {
1518
- const normalizedId = id.replace("[app-ssr]", "[app-client]");
1519
- self.__remote_shared_modules__[bundle][normalizedId] = await hostShared[module](bundle);
1520
- } else {
1521
- logError(
1522
- "SharedModules",
1523
- `Shared module "${module}" not found for "${bundle}". ${DEDUPLICATION_WARNING}`
1524
- );
1525
- }
1526
- }
1527
- })
1528
- );
1529
- }
1530
- function extractSharedModuleIds(shared2, bundleKey, self) {
1531
- return Object.entries(shared2).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1532
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1533
- if (asyncSharedModuleId) {
1534
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1535
- let asyncSharedModule;
1536
- let turbopackModules = self[`TURBOPACK_${bundleKey}`];
1537
- if (turbopackModules && typeof turbopackModules === "object" && "__chunks__" in turbopackModules) {
1538
- const chunks = turbopackModules.__chunks__;
1539
- turbopackModules = chunks.flat();
1540
- }
1541
- const newAllModules = Array.isArray(turbopackModules) ? turbopackModules.flat() : turbopackModules ? Object.entries(turbopackModules).flatMap(([key2, value2]) => [
1542
- key2,
1543
- value2
1544
- ]) : [];
1545
- const asyncSharedModuleIdIndex = newAllModules.indexOf(
1546
- asyncSharedModuleIdNumber
1547
- );
1548
- if (asyncSharedModuleIdIndex !== -1 && typeof newAllModules[asyncSharedModuleIdIndex + 1] === "function") {
1549
- asyncSharedModule = newAllModules[asyncSharedModuleIdIndex + 1];
1550
- }
1551
- if (asyncSharedModule) {
1552
- const asyncSharedModuleCode = asyncSharedModule.toString();
1553
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1554
- acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1555
- "__remote_shared_module_",
1556
- ""
1557
- );
1558
- }
1559
- }
1560
- return acc;
1561
- }, {});
1562
- }
1563
- function getSharedModule(bundle, id) {
1564
- const self = globalThis;
1565
- for (const [key, value] of Object.entries(
1566
- self.__remote_shared_modules__?.[bundle] ?? {}
1567
- )) {
1568
- if (typeof value !== "undefined" && (typeof id === "string" && id.includes(key) || id === key)) {
1569
- return value;
1570
- }
1571
- }
1572
- return null;
1573
- }
1574
-
1575
1584
  // src/runtime/turbopack/webpack-runtime.ts
1576
1585
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared2 = {}, remoteShared = {}, resolveClientUrl) {
1577
1586
  const self = globalThis;
1587
+ const bundleName = bundle ?? "default";
1588
+ const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1589
+ registerScope(scope);
1578
1590
  if (!self.__remote_bundle_url__) {
1579
1591
  self.__remote_bundle_url__ = {};
1580
1592
  }
1581
- self.__remote_bundle_url__[bundle ?? "default"] = url;
1593
+ self.__remote_bundle_url__[bundleName] = url;
1594
+ if (scope.scopedName !== bundleName) {
1595
+ self.__remote_bundle_url__[scope.scopedName] = url;
1596
+ }
1582
1597
  self.__webpack_get_script_filename__ = () => null;
1583
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
1598
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1599
+ if (willCreateDispatchers) {
1584
1600
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1585
1601
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1586
1602
  self.__original_webpack_require__ = self.__webpack_require__;
1587
1603
  }
1588
- self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
1589
- self.__webpack_require__ = createModuleRequire(runtime);
1604
+ self.__webpack_chunk_load__ = createChunkDispatcher();
1605
+ self.__webpack_require__ = createModuleDispatcher(runtime);
1590
1606
  self.__webpack_require_type__ = runtime;
1591
1607
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1592
- const remoteBundle = bundle ?? "default";
1593
- self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
1594
- self.__remote_webpack_require__[remoteBundle].type = "turbopack";
1608
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1609
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
1595
1610
  }
1596
1611
  }
1612
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1613
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1614
+ }
1597
1615
  if (runtime === RUNTIME_TURBOPACK) {
1598
1616
  const results = await Promise.allSettled(
1599
1617
  scripts.map((script) => {
1600
1618
  if (script.src) {
1601
- return self.__webpack_chunk_load__?.(script.src, bundle);
1619
+ return loadChunkWithScope(scope, script.src);
1602
1620
  }
1603
1621
  return Promise.resolve(void 0);
1604
1622
  })
@@ -1620,54 +1638,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1620
1638
  "react-dom/client": async () => (await import("react-dom/client")).default,
1621
1639
  ...shared2
1622
1640
  };
1623
- await initializeSharedModules(
1624
- bundle ?? "default",
1625
- // include all core modules as shared
1626
- coreShared,
1627
- remoteShared
1628
- );
1641
+ await initializeSharedModules(scope, coreShared, remoteShared);
1629
1642
  }
1630
- function createModuleRequire(runtime) {
1643
+ function createModuleDispatcher(runtime) {
1631
1644
  return (id) => {
1632
1645
  const self = globalThis;
1633
1646
  const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1634
1647
  bundle: "default",
1635
1648
  id
1636
1649
  };
1637
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1638
- logDebug("WebpackRuntime", `remoteRuntime: "${remoteRuntime}"`);
1650
+ const bundleName = bundle ?? "default";
1651
+ const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
1652
+ logDebug(
1653
+ "ModuleDispatcher",
1654
+ `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
1655
+ );
1639
1656
  try {
1640
1657
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1641
1658
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1642
1659
  }
1643
- const sharedModuleId = moduleId ?? id;
1644
- const sharedModule = getSharedModule(bundle ?? "default", sharedModuleId);
1645
- if (sharedModule) {
1646
- return sharedModule;
1660
+ const scope = getScope(bundleName);
1661
+ if (scope) {
1662
+ return requireModule(scope, moduleId ?? id, id);
1647
1663
  }
1648
- if (bundle && moduleId) {
1649
- return handleTurbopackModule(bundle, moduleId, id);
1650
- }
1651
- throw new Error(`Module "${id}" not found.`);
1664
+ throw new Error(
1665
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1666
+ );
1652
1667
  } catch (requireError) {
1653
1668
  logWarn(
1654
- "WebpackRuntime",
1669
+ "ModuleDispatcher",
1655
1670
  `Module require failed: ${String(requireError)}`
1656
1671
  );
1657
1672
  if (typeof self.__original_webpack_require__ !== "function") {
1658
1673
  throw new RemoteComponentsError(
1659
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1674
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1660
1675
  {
1661
1676
  cause: requireError instanceof Error ? requireError : void 0
1662
1677
  }
1663
1678
  );
1664
1679
  }
1665
1680
  try {
1666
- logDebug("WebpackRuntime", "Falling back to original webpack require");
1681
+ logDebug(
1682
+ "ModuleDispatcher",
1683
+ "Falling back to original webpack require"
1684
+ );
1667
1685
  return self.__original_webpack_require__(id);
1668
1686
  } catch (originalError) {
1669
1687
  throw new RemoteComponentsError(
1670
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1688
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1671
1689
  { cause: originalError instanceof Error ? originalError : void 0 }
1672
1690
  );
1673
1691
  }