remote-components 0.3.3 → 0.3.4

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 (157) hide show
  1. package/dist/config/nextjs.cjs +86 -37
  2. package/dist/config/nextjs.cjs.map +1 -1
  3. package/dist/config/nextjs.js +86 -37
  4. package/dist/config/nextjs.js.map +1 -1
  5. package/dist/config/webpack.cjs +5 -1
  6. package/dist/config/webpack.cjs.map +1 -1
  7. package/dist/config/webpack.js +5 -1
  8. package/dist/config/webpack.js.map +1 -1
  9. package/dist/host/html.cjs +524 -338
  10. package/dist/host/html.cjs.map +1 -1
  11. package/dist/host/html.js +524 -338
  12. package/dist/host/html.js.map +1 -1
  13. package/dist/host/nextjs/app/client-only.cjs +462 -259
  14. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  15. package/dist/host/nextjs/app/client-only.js +436 -233
  16. package/dist/host/nextjs/app/client-only.js.map +1 -1
  17. package/dist/host/react.cjs +403 -228
  18. package/dist/host/react.cjs.map +1 -1
  19. package/dist/host/react.js +403 -228
  20. package/dist/host/react.js.map +1 -1
  21. package/dist/internal/config/webpack/apply-shared-modules.cjs +6 -4
  22. package/dist/internal/config/webpack/apply-shared-modules.cjs.map +1 -1
  23. package/dist/internal/config/webpack/apply-shared-modules.js +6 -4
  24. package/dist/internal/config/webpack/apply-shared-modules.js.map +1 -1
  25. package/dist/internal/config/webpack/next-client-pages-loader.cjs +6 -7
  26. package/dist/internal/config/webpack/next-client-pages-loader.cjs.map +1 -1
  27. package/dist/internal/config/webpack/next-client-pages-loader.js +6 -7
  28. package/dist/internal/config/webpack/next-client-pages-loader.js.map +1 -1
  29. package/dist/internal/host/nextjs/app-client.cjs +4 -3
  30. package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
  31. package/dist/internal/host/nextjs/app-client.js +4 -3
  32. package/dist/internal/host/nextjs/app-client.js.map +1 -1
  33. package/dist/internal/host/nextjs/dom-flight.cjs +19 -39
  34. package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
  35. package/dist/internal/host/nextjs/dom-flight.js +31 -39
  36. package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
  37. package/dist/internal/host/nextjs/image-shared.cjs +39 -3
  38. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  39. package/dist/internal/host/nextjs/image-shared.d.ts +5 -10
  40. package/dist/internal/host/nextjs/image-shared.js +29 -3
  41. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  42. package/dist/internal/host/server/fetch-remote-component.cjs +2 -1
  43. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  44. package/dist/internal/host/server/fetch-remote-component.js +2 -1
  45. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  46. package/dist/internal/host/shared/polyfill.cjs +8 -7
  47. package/dist/internal/host/shared/polyfill.cjs.map +1 -1
  48. package/dist/internal/host/shared/polyfill.js +8 -7
  49. package/dist/internal/host/shared/polyfill.js.map +1 -1
  50. package/dist/internal/host/shared/shared-module-resolver.cjs +117 -0
  51. package/dist/internal/host/shared/shared-module-resolver.cjs.map +1 -0
  52. package/dist/internal/host/shared/shared-module-resolver.d.ts +64 -0
  53. package/dist/internal/host/shared/shared-module-resolver.js +78 -0
  54. package/dist/internal/host/shared/shared-module-resolver.js.map +1 -0
  55. package/dist/internal/remote/nextjs/next-internals.cjs +53 -0
  56. package/dist/internal/remote/nextjs/next-internals.cjs.map +1 -0
  57. package/dist/internal/remote/nextjs/next-internals.d.ts +42 -0
  58. package/dist/internal/remote/nextjs/next-internals.js +26 -0
  59. package/dist/internal/remote/nextjs/next-internals.js.map +1 -0
  60. package/dist/internal/runtime/html/apply-origin.cjs +11 -32
  61. package/dist/internal/runtime/html/apply-origin.cjs.map +1 -1
  62. package/dist/internal/runtime/html/apply-origin.js +11 -32
  63. package/dist/internal/runtime/html/apply-origin.js.map +1 -1
  64. package/dist/internal/runtime/html/html-spec.cjs +78 -0
  65. package/dist/internal/runtime/html/html-spec.cjs.map +1 -0
  66. package/dist/internal/runtime/html/html-spec.d.ts +23 -0
  67. package/dist/internal/runtime/html/html-spec.js +41 -0
  68. package/dist/internal/runtime/html/html-spec.js.map +1 -0
  69. package/dist/internal/runtime/html/parse-remote-html.cjs +15 -12
  70. package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
  71. package/dist/internal/runtime/html/parse-remote-html.js +29 -12
  72. package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
  73. package/dist/internal/runtime/html/rewrite-srcset.cjs +38 -0
  74. package/dist/internal/runtime/html/rewrite-srcset.cjs.map +1 -0
  75. package/dist/internal/runtime/html/rewrite-srcset.d.ts +12 -0
  76. package/dist/internal/runtime/html/rewrite-srcset.js +14 -0
  77. package/dist/internal/runtime/html/rewrite-srcset.js.map +1 -0
  78. package/dist/internal/runtime/loaders/component-loader.cjs +25 -44
  79. package/dist/internal/runtime/loaders/component-loader.cjs.map +1 -1
  80. package/dist/internal/runtime/loaders/component-loader.d.ts +3 -1
  81. package/dist/internal/runtime/loaders/component-loader.js +28 -44
  82. package/dist/internal/runtime/loaders/component-loader.js.map +1 -1
  83. package/dist/internal/runtime/loaders/static-loader.cjs +15 -21
  84. package/dist/internal/runtime/loaders/static-loader.cjs.map +1 -1
  85. package/dist/internal/runtime/loaders/static-loader.d.ts +3 -1
  86. package/dist/internal/runtime/loaders/static-loader.js +15 -21
  87. package/dist/internal/runtime/loaders/static-loader.js.map +1 -1
  88. package/dist/internal/runtime/namespace.cjs +82 -0
  89. package/dist/internal/runtime/namespace.cjs.map +1 -0
  90. package/dist/internal/runtime/namespace.d.ts +5 -0
  91. package/dist/internal/runtime/namespace.js +58 -0
  92. package/dist/internal/runtime/namespace.js.map +1 -0
  93. package/dist/internal/runtime/rsc-imports.cjs +86 -0
  94. package/dist/internal/runtime/rsc-imports.cjs.map +1 -0
  95. package/dist/internal/runtime/rsc-imports.d.ts +39 -0
  96. package/dist/internal/runtime/rsc-imports.js +50 -0
  97. package/dist/internal/runtime/rsc-imports.js.map +1 -0
  98. package/dist/internal/runtime/rsc-runtime.cjs +17 -0
  99. package/dist/internal/runtime/rsc-runtime.cjs.map +1 -0
  100. package/dist/internal/runtime/rsc-runtime.d.ts +37 -0
  101. package/dist/internal/runtime/rsc-runtime.js +1 -0
  102. package/dist/internal/runtime/rsc-runtime.js.map +1 -0
  103. package/dist/internal/runtime/rsc.cjs +23 -12
  104. package/dist/internal/runtime/rsc.cjs.map +1 -1
  105. package/dist/internal/runtime/rsc.d.ts +19 -2
  106. package/dist/internal/runtime/rsc.js +20 -11
  107. package/dist/internal/runtime/rsc.js.map +1 -1
  108. package/dist/internal/runtime/turbopack/chunk-loader.cjs +53 -35
  109. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  110. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +1 -1
  111. package/dist/internal/runtime/turbopack/chunk-loader.js +53 -35
  112. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  113. package/dist/internal/runtime/turbopack/module.cjs +17 -4
  114. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  115. package/dist/internal/runtime/turbopack/module.d.ts +23 -1
  116. package/dist/internal/runtime/turbopack/module.js +16 -4
  117. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  118. package/dist/internal/runtime/turbopack/patterns.cjs +26 -10
  119. package/dist/internal/runtime/turbopack/patterns.cjs.map +1 -1
  120. package/dist/internal/runtime/turbopack/patterns.d.ts +44 -49
  121. package/dist/internal/runtime/turbopack/patterns.js +23 -7
  122. package/dist/internal/runtime/turbopack/patterns.js.map +1 -1
  123. package/dist/internal/runtime/turbopack/{webpack-runtime.cjs → remote-scope-setup.cjs} +35 -32
  124. package/dist/internal/runtime/turbopack/remote-scope-setup.cjs.map +1 -0
  125. package/dist/internal/runtime/turbopack/remote-scope-setup.d.ts +25 -0
  126. package/dist/internal/runtime/turbopack/{webpack-runtime.js → remote-scope-setup.js} +36 -19
  127. package/dist/internal/runtime/turbopack/remote-scope-setup.js.map +1 -0
  128. package/dist/internal/runtime/turbopack/remote-scope.cjs +4 -6
  129. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -1
  130. package/dist/internal/runtime/turbopack/remote-scope.d.ts +20 -1
  131. package/dist/internal/runtime/turbopack/remote-scope.js +4 -6
  132. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -1
  133. package/dist/internal/runtime/turbopack/shared-modules.cjs +21 -15
  134. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  135. package/dist/internal/runtime/turbopack/shared-modules.d.ts +9 -2
  136. package/dist/internal/runtime/turbopack/shared-modules.js +24 -18
  137. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  138. package/dist/internal/runtime/types.cjs.map +1 -1
  139. package/dist/internal/runtime/types.d.ts +5 -41
  140. package/dist/internal/utils/logger.cjs +1 -1
  141. package/dist/internal/utils/logger.cjs.map +1 -1
  142. package/dist/internal/utils/logger.d.ts +2 -2
  143. package/dist/internal/utils/logger.js +1 -1
  144. package/dist/internal/utils/logger.js.map +1 -1
  145. package/dist/remote/html.cjs +78 -22
  146. package/dist/remote/html.cjs.map +1 -1
  147. package/dist/remote/html.js +78 -22
  148. package/dist/remote/html.js.map +1 -1
  149. package/dist/remote/nextjs/app.cjs +14 -55
  150. package/dist/remote/nextjs/app.cjs.map +1 -1
  151. package/dist/remote/nextjs/app.js +24 -45
  152. package/dist/remote/nextjs/app.js.map +1 -1
  153. package/dist/types-59251814.d.ts +94 -0
  154. package/package.json +1 -1
  155. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +0 -1
  156. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +0 -23
  157. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +0 -1
@@ -126,7 +126,7 @@ Docs: ${CORS_DOCS_URL}`
126
126
 
127
127
  // src/utils/logger.ts
128
128
  var PREFIX = "remote-components";
129
- var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
129
+ var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
130
130
  function logDebug(location2, message) {
131
131
  if (DEBUG) {
132
132
  console.debug(`[${PREFIX}:${location2}]: ${message}`);
@@ -237,6 +237,62 @@ function getBundleKey(bundle) {
237
237
  return escapeString(bundle);
238
238
  }
239
239
 
240
+ // src/runtime/namespace.ts
241
+ var SHADOW_ROOT_PREFIX = "__remote_components_shadowroot_";
242
+ var LEGACY_ALIASES = [
243
+ { global: "__remote_component_scopes__", prop: "scopes" },
244
+ {
245
+ global: "__remote_components_turbopack_chunk_loader_promise__",
246
+ prop: "chunkCache"
247
+ },
248
+ { global: "__remote_script_entrypoint_mount__", prop: "mountFns" },
249
+ { global: "__remote_script_entrypoint_unmount__", prop: "unmountFns" },
250
+ { global: "__remote_bundle_url__", prop: "bundleUrls" },
251
+ { global: "__rc_module_registry__", prop: "moduleRegistry" },
252
+ {
253
+ global: "__remote_component_host_shared_modules__",
254
+ prop: "hostSharedModules"
255
+ },
256
+ { global: "__remote_next_css__", prop: "cssCache" }
257
+ ];
258
+ function getNamespace() {
259
+ const g = globalThis;
260
+ const existing = g.__remote_components__;
261
+ if (existing) {
262
+ return existing;
263
+ }
264
+ const ns = {
265
+ scopes: /* @__PURE__ */ new Map(),
266
+ chunkCache: {},
267
+ mountFns: {},
268
+ unmountFns: {},
269
+ bundleUrls: {},
270
+ moduleRegistry: {},
271
+ dispatcherRuntime: void 0,
272
+ hostSharedModules: {},
273
+ cssCache: {},
274
+ shadowRoots: {}
275
+ };
276
+ const nsRecord = ns;
277
+ for (const { global, prop } of LEGACY_ALIASES) {
278
+ const legacyValue = g[global];
279
+ if (legacyValue != null) {
280
+ nsRecord[prop] = legacyValue;
281
+ }
282
+ g[global] = ns[prop];
283
+ }
284
+ const gRecord = g;
285
+ for (const key of Object.keys(gRecord)) {
286
+ if (key.startsWith(SHADOW_ROOT_PREFIX)) {
287
+ const suffix = key.slice(SHADOW_ROOT_PREFIX.length);
288
+ ns.shadowRoots[suffix] = gRecord[key];
289
+ delete gRecord[key];
290
+ }
291
+ }
292
+ g.__remote_components__ = ns;
293
+ return ns;
294
+ }
295
+
240
296
  // src/runtime/patterns.ts
241
297
  var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
242
298
  var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
@@ -247,11 +303,7 @@ function collapseDoubleSlashes(path) {
247
303
 
248
304
  // src/runtime/turbopack/remote-scope.ts
249
305
  function getRegistry() {
250
- const self = globalThis;
251
- if (!self.__remote_component_scopes__) {
252
- self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
253
- }
254
- return self.__remote_component_scopes__;
306
+ return getNamespace().scopes;
255
307
  }
256
308
  function createScope(name, url, runtime, resolveClientUrl) {
257
309
  const isCrossOrigin = url.origin !== location.origin;
@@ -269,7 +321,8 @@ function createScope(name, url, runtime, resolveClientUrl) {
269
321
  resolveClientUrl,
270
322
  moduleCache: {},
271
323
  sharedModules: {},
272
- moduleGlobal: {}
324
+ moduleGlobal: {},
325
+ turbopackModules: []
273
326
  };
274
327
  }
275
328
  function registerScope(scope) {
@@ -334,9 +387,9 @@ function createRemoteImageLoader(bundle, resolveClientUrl) {
334
387
  // src/host/shared/polyfill.tsx
335
388
  import { jsx } from "react/jsx-runtime";
336
389
  function sharedPolyfills(shared, resolveClientUrl) {
337
- const self = globalThis;
390
+ const hostShared = getNamespace().hostSharedModules;
338
391
  const polyfill = {
339
- "next/dist/client/components/navigation": self.__remote_component_host_shared_modules__?.["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
392
+ "next/dist/client/components/navigation": hostShared["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
340
393
  useRouter() {
341
394
  return {
342
395
  push: (routerUrl) => {
@@ -367,7 +420,7 @@ function sharedPolyfills(shared, resolveClientUrl) {
367
420
  },
368
421
  __esModule: true
369
422
  })),
370
- "next/dist/client/app-dir/link": self.__remote_component_host_shared_modules__?.["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
423
+ "next/dist/client/app-dir/link": hostShared["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
371
424
  default: ({
372
425
  scroll: _,
373
426
  replace,
@@ -417,7 +470,7 @@ function sharedPolyfills(shared, resolveClientUrl) {
417
470
  },
418
471
  __esModule: true
419
472
  })),
420
- "next/dist/client/app-dir/form": self.__remote_component_host_shared_modules__?.["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
473
+ "next/dist/client/app-dir/form": hostShared["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
421
474
  default: () => {
422
475
  throw new Error("Next.js <Form> component not implemented");
423
476
  },
@@ -428,17 +481,17 @@ function sharedPolyfills(shared, resolveClientUrl) {
428
481
  // This gives us full next/image fidelity (fill, priority, srcSet, blur
429
482
  // placeholders, error handling) while routing image optimization through the
430
483
  // remote app's /_next/image endpoint.
431
- "next/dist/shared/lib/image-loader": self.__remote_component_host_shared_modules__?.["next/dist/shared/lib/image-loader"] ?? shared?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
484
+ "next/dist/shared/lib/image-loader": hostShared["next/dist/shared/lib/image-loader"] ?? shared?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
432
485
  default: createRemoteImageLoader(bundle, resolveClientUrl),
433
486
  __esModule: true
434
487
  })),
435
- "next/dist/client/script": self.__remote_component_host_shared_modules__?.["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
488
+ "next/dist/client/script": hostShared["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
436
489
  // TODO: implement <Script> component for non-Next.js host applications
437
490
  // do not throw an error for now
438
491
  default: () => null,
439
492
  __esModule: true
440
493
  })),
441
- "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared?.["next/router"] ?? (() => (
494
+ "next/router": hostShared["next/router"] ?? shared?.["next/router"] ?? (() => (
442
495
  // TODO: incomplete implementation
443
496
  Promise.resolve({
444
497
  useRouter() {
@@ -474,6 +527,68 @@ function sharedPolyfills(shared, resolveClientUrl) {
474
527
  return polyfill;
475
528
  }
476
529
 
530
+ // src/host/shared/shared-module-resolver.ts
531
+ var CORE_REACT_PATH_MAP = {
532
+ react: "/react/index.js",
533
+ "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
534
+ "react/jsx-runtime": "/react/jsx-runtime.js",
535
+ "react-dom": "/react-dom/index.js",
536
+ "react-dom/client": "/react-dom/client.js"
537
+ };
538
+ var VENDOR_SHARED = Object.fromEntries(
539
+ Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
540
+ );
541
+ function buildCoreShared(userShared) {
542
+ return {
543
+ react: async () => (await import("react")).default,
544
+ "react-dom": async () => (await import("react-dom")).default,
545
+ "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
546
+ "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
547
+ "react-dom/client": async () => (await import("react-dom/client")).default,
548
+ ...userShared
549
+ };
550
+ }
551
+ function buildHostShared(userShared, resolveClientUrl, options) {
552
+ const self = globalThis;
553
+ const result = {
554
+ ...sharedPolyfills(userShared, resolveClientUrl),
555
+ ...self.__remote_component_host_shared_modules__,
556
+ ...userShared
557
+ };
558
+ if (options?.includeRemoteComponentShared) {
559
+ Object.assign(result, self.__remote_component_shared__);
560
+ }
561
+ return result;
562
+ }
563
+ async function buildWebpackResolve(hostShared, remoteShared, bundle, reactModules, callerTag = "SharedModuleResolver") {
564
+ const resolve = {
565
+ ...reactModules,
566
+ ...Object.entries(remoteShared).reduce(
567
+ (acc, [key, value]) => {
568
+ if (typeof hostShared[value] !== "undefined") {
569
+ acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
570
+ } else {
571
+ logDebug(
572
+ callerTag,
573
+ `Remote requests "${value}" but host doesn't provide it`
574
+ );
575
+ }
576
+ return acc;
577
+ },
578
+ {}
579
+ )
580
+ };
581
+ await Promise.all(
582
+ Object.entries(resolve).map(async ([key, value]) => {
583
+ if (typeof value === "function") {
584
+ resolve[key] = await value(bundle);
585
+ }
586
+ return Promise.resolve(value);
587
+ })
588
+ );
589
+ return resolve;
590
+ }
591
+
477
592
  // src/host/shared/state.ts
478
593
  function createHostState() {
479
594
  return {
@@ -500,8 +615,8 @@ function resolveNameFromSrc(src, defaultName) {
500
615
  return name || defaultName;
501
616
  }
502
617
 
503
- // src/runtime/html/apply-origin.ts
504
- var tagNames = [
618
+ // src/runtime/html/html-spec.ts
619
+ var ORIGIN_REWRITE_TAGS = [
505
620
  "img",
506
621
  "source",
507
622
  "video",
@@ -512,10 +627,37 @@ var tagNames = [
512
627
  "script",
513
628
  "link"
514
629
  ];
630
+ var ID_SUFFIX_RSC = "_rsc";
631
+ var ID_SUFFIX_SSR = "_ssr";
632
+ var ID_SUFFIX_SHARED = "_shared";
633
+ var DATA_BUNDLE = "data-bundle";
634
+ var DATA_ROUTE = "data-route";
635
+ var DATA_RUNTIME = "data-runtime";
636
+ var DATA_TYPE = "data-type";
637
+ var DATA_SRC = "data-src";
638
+ var DATA_REMOTE_COMPONENTS_SHARED = "data-remote-components-shared";
639
+ var TAG_REMOTE_COMPONENT = "remote-component";
640
+ var NEXT_DATA_ID = "__NEXT_DATA__";
641
+ var REMOTE_NEXT_DATA_ID = "__REMOTE_NEXT_DATA__";
642
+ var NEXT_CONTAINER_ID = "__next";
643
+
644
+ // src/runtime/html/rewrite-srcset.ts
645
+ function rewriteSrcset(srcset, base, resolve) {
646
+ return srcset.split(",").map((entry) => {
647
+ const [url, descriptor] = entry.trim().split(/\s+/);
648
+ if (!url)
649
+ return entry;
650
+ const absoluteUrl = new URL(url, base).href;
651
+ const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;
652
+ return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
653
+ }).join(", ");
654
+ }
655
+
656
+ // src/runtime/html/apply-origin.ts
515
657
  function applyOriginToNodes(doc, url, resolveClientUrl) {
516
658
  if (url.origin !== location.origin) {
517
659
  const nodes = doc.querySelectorAll(
518
- tagNames.map(
660
+ ORIGIN_REWRITE_TAGS.map(
519
661
  (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
520
662
  ).join(",")
521
663
  );
@@ -533,29 +675,17 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
533
675
  );
534
676
  }
535
677
  if (node.hasAttribute("srcset")) {
536
- const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
537
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
538
- if (!urlPart)
539
- return entry;
540
- const absoluteUrl = new URL(urlPart, url).href;
541
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
542
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
543
- }).join(", ");
544
- if (srcSet) {
545
- node.setAttribute("srcset", srcSet);
678
+ const raw = node.getAttribute("srcset");
679
+ if (raw) {
680
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
681
+ node.setAttribute("srcset", rewriteSrcset(raw, url, resolve));
546
682
  }
547
683
  }
548
684
  if (node.hasAttribute("imagesrcset")) {
549
- const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
550
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
551
- if (!urlPart)
552
- return entry;
553
- const absoluteUrl = new URL(urlPart, url).href;
554
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
555
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
556
- }).join(", ");
557
- if (srcSet) {
558
- node.setAttribute("imagesrcset", srcSet);
685
+ const raw = node.getAttribute("imagesrcset");
686
+ if (raw) {
687
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
688
+ node.setAttribute("imagesrcset", rewriteSrcset(raw, url, resolve));
559
689
  }
560
690
  }
561
691
  });
@@ -596,26 +726,28 @@ function buildMetadata(attrs, url) {
596
726
 
597
727
  // src/runtime/html/parse-remote-html.ts
598
728
  function validateSingleComponent(doc, name, url) {
599
- if (doc.querySelectorAll("div[data-bundle][data-route]").length > 1 && !doc.querySelector(`div[data-bundle][data-route][id^="${name}"]`) || doc.querySelectorAll("remote-component:not([src])").length > 1 && !doc.querySelector(`remote-component[name="${name}"]`)) {
729
+ if (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 && !doc.querySelector(
730
+ `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`
731
+ ) || doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 && !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]`)) {
600
732
  throw multipleRemoteComponentsError(url);
601
733
  }
602
734
  }
603
735
  function findComponentElement(doc, name) {
604
- return doc.querySelector(`div[data-bundle][data-route][id^="${name}"]`) ?? doc.querySelector("div[data-bundle][data-route]") ?? doc.querySelector("div#__next") ?? doc.querySelector(`remote-component[name="${name}"]:not([src])`) ?? doc.querySelector("remote-component:not([src])");
736
+ return doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`) ?? doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`) ?? doc.querySelector(`div#${NEXT_CONTAINER_ID}`) ?? doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]:not([src])`) ?? doc.querySelector(`${TAG_REMOTE_COMPONENT}:not([src])`);
605
737
  }
606
738
  function parseNextData(doc) {
607
739
  return JSON.parse(
608
- (doc.querySelector("#__NEXT_DATA__") ?? doc.querySelector("#__REMOTE_NEXT_DATA__"))?.textContent ?? "null"
740
+ (doc.querySelector(`#${NEXT_DATA_ID}`) ?? doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`))?.textContent ?? "null"
609
741
  );
610
742
  }
611
743
  function resolveComponentName(component, nextData, fallbackName) {
612
- const isRemoteComponent = component?.tagName.toLowerCase() === "remote-component";
613
- const name = component?.getAttribute("id")?.replace(/_ssr$/, "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
744
+ const isRemoteComponent = component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;
745
+ const name = component?.getAttribute("id")?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
614
746
  return { name, isRemoteComponent };
615
747
  }
616
748
  function extractRemoteShared(doc, name, nextData) {
617
749
  const remoteSharedEl = doc.querySelector(
618
- `#${name}_shared[data-remote-components-shared]`
750
+ `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`
619
751
  );
620
752
  const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
621
753
  remoteSharedEl?.remove();
@@ -636,7 +768,7 @@ function extractLinks(doc, component) {
636
768
  function extractScripts(doc, component, isRemoteComponent) {
637
769
  return Array.from(
638
770
  (isRemoteComponent ? component : doc).querySelectorAll(
639
- "script[src],script[data-src]"
771
+ `script[src],script[${DATA_SRC}]`
640
772
  )
641
773
  );
642
774
  }
@@ -649,15 +781,15 @@ function parseRemoteComponentDocument(doc, name, url) {
649
781
  nextData,
650
782
  name
651
783
  );
652
- const rsc = doc.querySelector(`#${resolvedName}_rsc`);
784
+ const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);
653
785
  const metadata = buildMetadata(
654
786
  {
655
787
  name: resolvedName,
656
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
657
- route: component?.getAttribute("data-route") ?? nextData?.page,
658
- runtime: component?.getAttribute("data-runtime") ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
788
+ bundle: component?.getAttribute(DATA_BUNDLE) || nextData?.props.__REMOTE_COMPONENT__?.bundle,
789
+ route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,
790
+ runtime: component?.getAttribute(DATA_RUNTIME) ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
659
791
  id: component?.getAttribute("id"),
660
- type: component?.getAttribute("data-type")
792
+ type: component?.getAttribute(DATA_TYPE)
661
793
  },
662
794
  url
663
795
  );
@@ -746,13 +878,15 @@ function applySharedModules(bundle, resolve) {
746
878
  `Shared modules to resolve: ${Object.keys(resolve)}`
747
879
  );
748
880
  const self = globalThis;
749
- if (self.__remote_webpack_require__?.[bundle]) {
881
+ const scope = getScope(bundle);
882
+ const webpackBundle = scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];
883
+ if (webpackBundle) {
750
884
  const modulePaths = Object.keys(
751
- self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
885
+ self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {}
752
886
  );
753
887
  logDebug(
754
888
  "SharedModules",
755
- `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`
889
+ `Available module paths for bundle "${bundle}": ${modulePaths}`
756
890
  );
757
891
  for (const [key, value] of Object.entries(resolve)) {
758
892
  const exactIds = modulePaths.filter((p) => p === key);
@@ -764,7 +898,6 @@ function applySharedModules(bundle, resolve) {
764
898
  );
765
899
  }
766
900
  for (const id of ids) {
767
- const webpackBundle = self.__remote_webpack_require__[bundle];
768
901
  if (webpackBundle.m) {
769
902
  const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
770
903
  if (resolvedId !== id) {
@@ -862,10 +995,8 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
862
995
  ];
863
996
  const { default: Component } = componentLoader();
864
997
  const { default: App } = appLoader();
865
- if (!self.__remote_next_css__) {
866
- self.__remote_next_css__ = {};
867
- }
868
- if (!self.__remote_next_css__[bundle]) {
998
+ const cssCache = getNamespace().cssCache;
999
+ if (!cssCache[bundle]) {
869
1000
  const cssRE = /\.s?css$/;
870
1001
  Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
871
1002
  self.__remote_webpack_require__?.[bundle]?.(id);
@@ -883,15 +1014,15 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
883
1014
  node.remove();
884
1015
  node = nextCss.previousSibling;
885
1016
  }
886
- self.__remote_next_css__[bundle] = elements;
1017
+ cssCache[bundle] = elements;
887
1018
  }
888
1019
  if (styleContainer) {
889
- const elements = self.__remote_next_css__[bundle];
1020
+ const elements = cssCache[bundle];
890
1021
  elements.forEach((el) => {
891
1022
  styleContainer.appendChild(el.cloneNode(true));
892
1023
  });
893
1024
  } else {
894
- const elements = self.__remote_next_css__[bundle];
1025
+ const elements = cssCache[bundle];
895
1026
  elements.forEach((el) => {
896
1027
  document.head.appendChild(el);
897
1028
  });
@@ -928,6 +1059,18 @@ function fixPayload(payload) {
928
1059
  }
929
1060
  }
930
1061
  }
1062
+ function buildRSCChunks(rscName, data) {
1063
+ const chunks = [];
1064
+ for (const chunk of data) {
1065
+ for (const line of chunk.split("\n")) {
1066
+ const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1067
+ if (match?.groups?.rsc) {
1068
+ chunks.push(JSON.parse(`"${match.groups.rsc}"`));
1069
+ }
1070
+ }
1071
+ }
1072
+ return chunks;
1073
+ }
931
1074
  function createRSCStream(rscName, data) {
932
1075
  return new ReadableStream({
933
1076
  type: "bytes",
@@ -935,16 +1078,11 @@ function createRSCStream(rscName, data) {
935
1078
  const encoder = new TextEncoder();
936
1079
  const self = globalThis;
937
1080
  if (data.length > 0) {
938
- data.forEach((chunk) => {
939
- const lines = chunk.split("\n");
940
- for (const line of lines) {
941
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
942
- if (match?.groups?.rsc) {
943
- self[rscName] = self[rscName] ?? [];
944
- self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
945
- }
946
- }
947
- });
1081
+ const parsed = buildRSCChunks(rscName, data);
1082
+ if (parsed.length > 0) {
1083
+ self[rscName] = self[rscName] ?? [];
1084
+ self[rscName].push(...parsed);
1085
+ }
948
1086
  }
949
1087
  const allChunks = (self[rscName] ?? [`0:[null]
950
1088
  `]).join("");
@@ -974,12 +1112,38 @@ function createRSCStream(rscName, data) {
974
1112
  });
975
1113
  }
976
1114
 
1115
+ // src/runtime/rsc-imports.ts
1116
+ async function importRSCClientBrowser() {
1117
+ try {
1118
+ return await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1119
+ } catch {
1120
+ const mod = await import("react-server-dom-webpack/client.browser");
1121
+ return mod.default ?? mod;
1122
+ }
1123
+ }
1124
+
977
1125
  // src/runtime/turbopack/patterns.ts
1126
+ var MODULE_ID_PATTERN = '"[^"]+"|[0-9]+';
1127
+ function stripQuotes(value) {
1128
+ if (value.startsWith('"') && value.endsWith('"')) {
1129
+ return value.slice(1, -1);
1130
+ }
1131
+ return value;
1132
+ }
1133
+ function extractGroup(re, input, group) {
1134
+ const raw = re.exec(input)?.groups?.[group];
1135
+ return raw ? stripQuotes(raw) : void 0;
1136
+ }
978
1137
  var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
979
- var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
980
- var ASYNC_MODULE_LOADER_RE = /(?:__turbopack_context__|e)\.A\((?<asyncSharedModuleId>[0-9]+)\)/;
981
- var ASYNC_MODULE_RESOLVE_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<inner>parentImport|e)=>Promise\.resolve\(\)\.then\(\(\)=>\k<inner>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
982
- var ASYNC_MODULE_ALL_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<vCb>parentImport|t)=>Promise\.all\(\["[^"]+"\]\.map\((?<mapCb>chunk|t)=>\k<ctx>\.l\(\k<mapCb>\)\)\)\.then\(\(\)=>\k<vCb>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
1138
+ var REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(
1139
+ `\\.TURBOPACK_REMOTE_SHARED\\s*=\\s*await (?:__turbopack_context__|[a-z])\\.A\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1140
+ );
1141
+ var ASYNC_MODULE_LOADER_RE = new RegExp(
1142
+ `(?:__turbopack_context__|e)\\.A\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\)`
1143
+ );
1144
+ var ASYNC_MODULE_CALLBACK_RE = new RegExp(
1145
+ `(?:parentImport|[a-z])\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1146
+ );
983
1147
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
984
1148
 
985
1149
  // src/runtime/turbopack/chunk-loader.ts
@@ -989,6 +1153,7 @@ function loadChunkWithScope(scope, chunkId) {
989
1153
  `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
990
1154
  );
991
1155
  const self = globalThis;
1156
+ const ns = getNamespace();
992
1157
  const { bundle, path, prefix } = parseRemoteId(chunkId);
993
1158
  const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
994
1159
  if (remoteRuntime === RUNTIME_WEBPACK) {
@@ -999,35 +1164,31 @@ function loadChunkWithScope(scope, chunkId) {
999
1164
  if (url.endsWith(".css")) {
1000
1165
  return;
1001
1166
  }
1002
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1003
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
1004
- }
1005
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1006
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1167
+ if (ns.chunkCache[url]) {
1168
+ logDebug("ChunkLoader", `Cache hit for "${chunkId}" (url="${url}")`);
1169
+ return ns.chunkCache[url];
1007
1170
  }
1008
1171
  const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1009
1172
  if (resolvedUrl !== url) {
1010
1173
  logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1011
1174
  }
1012
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1013
- (resolve, reject) => {
1014
- fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1015
- const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1016
- if (hasTurbopack) {
1017
- return handleTurbopackChunk(code, scope, url);
1018
- }
1019
- }).then(resolve).catch((error) => {
1020
- const isProxied = isProxiedUrl(resolvedUrl);
1021
- if (isProxied) {
1022
- reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1023
- } else {
1024
- warnCrossOriginFetchError("ChunkLoader", url);
1025
- reject(error);
1026
- }
1027
- });
1028
- }
1029
- );
1030
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1175
+ ns.chunkCache[url] = new Promise((resolve, reject) => {
1176
+ fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1177
+ const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1178
+ if (hasTurbopack) {
1179
+ return handleTurbopackChunk(code, scope, url);
1180
+ }
1181
+ }).then(resolve).catch((error) => {
1182
+ const isProxied = isProxiedUrl(resolvedUrl);
1183
+ if (isProxied) {
1184
+ reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1185
+ } else {
1186
+ warnCrossOriginFetchError("ChunkLoader", url);
1187
+ reject(error);
1188
+ }
1189
+ });
1190
+ });
1191
+ return ns.chunkCache[url];
1031
1192
  }
1032
1193
  function createChunkDispatcher() {
1033
1194
  return function __chunk_dispatcher__(chunkId, scriptBundle) {
@@ -1076,19 +1237,39 @@ async function handleTurbopackChunk(code, scope, url) {
1076
1237
  `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1077
1238
  );
1078
1239
  if (!self[`TURBOPACK_${globalKey}`]) {
1079
- const chunkData = [];
1080
- const turbopackObject = {
1081
- push: (item) => {
1082
- if (Array.isArray(item)) {
1083
- chunkData.push(item);
1084
- } else {
1085
- chunkData.push([item]);
1240
+ const wrapPush = (target) => {
1241
+ const originalPush = target.push;
1242
+ if (typeof originalPush !== "function")
1243
+ return target;
1244
+ target.push = (...items) => {
1245
+ for (const item of items) {
1246
+ if (Array.isArray(item)) {
1247
+ for (const entry of item) {
1248
+ scope.turbopackModules.push(entry);
1249
+ }
1250
+ } else {
1251
+ scope.turbopackModules.push(item);
1252
+ }
1086
1253
  }
1087
- return chunkData.length;
1088
- },
1089
- __chunks__: chunkData
1254
+ return originalPush.apply(target, items);
1255
+ };
1256
+ return target;
1090
1257
  };
1091
- self[`TURBOPACK_${globalKey}`] = turbopackObject;
1258
+ const globalProp = `TURBOPACK_${globalKey}`;
1259
+ let currentValue = wrapPush([]);
1260
+ Object.defineProperty(self, globalProp, {
1261
+ get() {
1262
+ return currentValue;
1263
+ },
1264
+ set(newValue) {
1265
+ if (newValue && typeof newValue === "object") {
1266
+ wrapPush(newValue);
1267
+ }
1268
+ currentValue = newValue;
1269
+ },
1270
+ configurable: true,
1271
+ enumerable: true
1272
+ });
1092
1273
  }
1093
1274
  await new Promise((scriptResolve, scriptReject) => {
1094
1275
  const blob = new Blob([transformedCode], {
@@ -1140,13 +1321,13 @@ async function handleTurbopackChunk(code, scope, url) {
1140
1321
  // src/runtime/turbopack/shared-modules.ts
1141
1322
  var DEDUPLICATION_WARNING = "This module will not be deduplicated \u2014 the remote may load its own copy, which can cause duplicate instance errors (e.g. invalid hook calls if React is loaded twice).";
1142
1323
  function getTurbopackModules(scope) {
1324
+ if (scope.turbopackModules.length > 0) {
1325
+ return scope.turbopackModules;
1326
+ }
1143
1327
  const self = globalThis;
1144
1328
  const raw = self[`TURBOPACK_${scope.globalKey}`];
1145
1329
  if (!raw)
1146
1330
  return void 0;
1147
- if (typeof raw === "object" && "__chunks__" in raw) {
1148
- return raw.__chunks__.flat();
1149
- }
1150
1331
  if (Array.isArray(raw)) {
1151
1332
  return raw.flat();
1152
1333
  }
@@ -1170,7 +1351,11 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1170
1351
  if (sharedModuleInitializerIndex > 0) {
1171
1352
  const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1172
1353
  const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1173
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1354
+ const sharedModuleId = extractGroup(
1355
+ REMOTE_SHARED_ASSIGNMENT_RE,
1356
+ sharedModuleInitializerCode,
1357
+ "sharedModuleId"
1358
+ );
1174
1359
  if (sharedModuleId) {
1175
1360
  const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1176
1361
  scope,
@@ -1228,20 +1413,22 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1228
1413
  }
1229
1414
  function extractSharedModuleIds(shared, scope) {
1230
1415
  return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1231
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1416
+ const asyncSharedModuleId = extractGroup(
1417
+ ASYNC_MODULE_LOADER_RE,
1418
+ value.toString(),
1419
+ "asyncSharedModuleId"
1420
+ );
1232
1421
  if (asyncSharedModuleId) {
1233
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1234
- let asyncSharedModule;
1235
- const turbopackModules = getTurbopackModules(scope) ?? [];
1236
- const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1237
- asyncSharedModuleIdNumber
1422
+ const asyncSharedModule = findModuleInit(
1423
+ getTurbopackModules(scope),
1424
+ asyncSharedModuleId
1238
1425
  );
1239
- if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1240
- asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1241
- }
1242
1426
  if (asyncSharedModule) {
1243
- const asyncSharedModuleCode = asyncSharedModule.toString();
1244
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1427
+ const sharedModuleId = extractGroup(
1428
+ ASYNC_MODULE_CALLBACK_RE,
1429
+ asyncSharedModule.toString(),
1430
+ "sharedModuleId"
1431
+ );
1245
1432
  acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1246
1433
  "__remote_shared_module_",
1247
1434
  ""
@@ -1332,9 +1519,17 @@ function findModuleInit(modules, moduleId) {
1332
1519
  if (idx >= 0) {
1333
1520
  return flat.slice(idx + 1).find((e) => typeof e === "function");
1334
1521
  }
1335
- return flat.find(
1336
- (e) => Boolean(e && typeof e === "object" && moduleId in e)
1337
- )?.[moduleId];
1522
+ for (const entry of flat) {
1523
+ if (!entry || typeof entry !== "object")
1524
+ continue;
1525
+ const obj = entry;
1526
+ if (moduleId in obj)
1527
+ return obj[moduleId];
1528
+ const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));
1529
+ if (prefixKey)
1530
+ return obj[prefixKey];
1531
+ }
1532
+ return void 0;
1338
1533
  }
1339
1534
  function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1340
1535
  const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
@@ -1413,7 +1608,10 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1413
1608
  }
1414
1609
  if (typeof mod !== "object" || mod === null) {
1415
1610
  mod = { default: mod };
1416
- } else if (!("default" in mod) && mod.toString() !== "[object Module]") {
1611
+ } else if (!("default" in mod) && // ES module namespace objects have a null prototype, so calling
1612
+ // mod.toString() directly throws. Use Object.prototype.toString
1613
+ // to safely detect them.
1614
+ Object.prototype.toString.call(mod) !== "[object Module]") {
1417
1615
  try {
1418
1616
  mod.default = mod;
1419
1617
  } catch {
@@ -1477,21 +1675,38 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1477
1675
  };
1478
1676
  }
1479
1677
 
1480
- // src/runtime/turbopack/webpack-runtime.ts
1481
- async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1678
+ // src/runtime/turbopack/remote-scope-setup.ts
1679
+ async function setupRemoteScope(runtime, scripts = [], url = new URL(location.href), bundle, resolveClientUrl) {
1482
1680
  const self = globalThis;
1681
+ const ns = getNamespace();
1483
1682
  const bundleName = bundle ?? "default";
1683
+ const existingScope = getScope(bundleName);
1684
+ if (existingScope && existingScope.url.origin === url.origin) {
1685
+ logDebug(
1686
+ "WebpackRuntime",
1687
+ `Reusing scope "${existingScope.scopedName}" (turbopackModules=${existingScope.turbopackModules.length})`
1688
+ );
1689
+ existingScope.resolveClientUrl = resolveClientUrl;
1690
+ if (runtime === RUNTIME_TURBOPACK) {
1691
+ await Promise.allSettled(
1692
+ scripts.map(
1693
+ (script) => script.src ? loadChunkWithScope(existingScope, script.src) : Promise.resolve(void 0)
1694
+ )
1695
+ );
1696
+ }
1697
+ return existingScope;
1698
+ }
1484
1699
  const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1485
1700
  registerScope(scope);
1486
- if (!self.__remote_bundle_url__) {
1487
- self.__remote_bundle_url__ = {};
1701
+ if (runtime === RUNTIME_WEBPACK && self.__remote_webpack_require__?.[bundleName]) {
1702
+ scope.webpackRequire = self.__remote_webpack_require__[bundleName];
1488
1703
  }
1489
- self.__remote_bundle_url__[bundleName] = url;
1704
+ ns.bundleUrls[bundleName] = url;
1490
1705
  if (scope.scopedName !== bundleName) {
1491
- self.__remote_bundle_url__[scope.scopedName] = url;
1706
+ ns.bundleUrls[scope.scopedName] = url;
1492
1707
  }
1493
1708
  self.__webpack_get_script_filename__ = () => null;
1494
- const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1709
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || ns.dispatcherRuntime !== "turbopack";
1495
1710
  if (willCreateDispatchers) {
1496
1711
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1497
1712
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
@@ -1499,6 +1714,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1499
1714
  }
1500
1715
  self.__webpack_chunk_load__ = createChunkDispatcher();
1501
1716
  self.__webpack_require__ = createModuleDispatcher(runtime);
1717
+ ns.dispatcherRuntime = runtime;
1502
1718
  self.__webpack_require_type__ = runtime;
1503
1719
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1504
1720
  self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
@@ -1526,15 +1742,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1526
1742
  }
1527
1743
  }
1528
1744
  }
1529
- const coreShared = {
1530
- react: async () => (await import("react")).default,
1531
- "react-dom": async () => (await import("react-dom")).default,
1532
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
1533
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
1534
- "react-dom/client": async () => (await import("react-dom/client")).default,
1535
- ...shared
1536
- };
1537
- await initializeSharedModules(scope, coreShared, remoteShared);
1745
+ return scope;
1538
1746
  }
1539
1747
  function createModuleDispatcher(runtime) {
1540
1748
  return (id) => {
@@ -1551,6 +1759,9 @@ function createModuleDispatcher(runtime) {
1551
1759
  );
1552
1760
  try {
1553
1761
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1762
+ const scope2 = getScope(bundle);
1763
+ if (scope2?.webpackRequire)
1764
+ return scope2.webpackRequire(moduleId);
1554
1765
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1555
1766
  }
1556
1767
  const scope = getScope(bundleName);
@@ -1668,44 +1879,33 @@ async function loadRemoteComponent({
1668
1879
  "ComponentLoader",
1669
1880
  `Remote shared modules requested: ${JSON.stringify(remoteShared)}`
1670
1881
  );
1671
- await setupWebpackRuntime(
1882
+ const scope = await setupRemoteScope(
1672
1883
  runtime,
1673
1884
  scripts,
1674
1885
  url,
1675
1886
  bundle,
1676
- hostShared,
1677
- remoteShared,
1678
1887
  resolveClientUrl
1679
1888
  );
1889
+ if (runtime === "turbopack") {
1890
+ await initializeSharedModules(
1891
+ scope,
1892
+ buildCoreShared(hostShared),
1893
+ remoteShared
1894
+ );
1895
+ }
1680
1896
  if (bundle) {
1681
- const resolve = {
1682
- "/react/index.js": React,
1683
- "/react/jsx-dev-runtime.js": JSXDevRuntime,
1684
- "/react/jsx-runtime.js": JSXRuntime,
1685
- "/react-dom/index.js": ReactDOM,
1686
- "/react-dom/client.js": ReactDOMClient,
1687
- ...Object.entries(remoteShared).reduce(
1688
- (acc, [key, value]) => {
1689
- if (typeof hostShared[value] !== "undefined") {
1690
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
1691
- } else {
1692
- logDebug(
1693
- "ComponentLoader",
1694
- `Remote requests "${value}" but host doesn't provide it`
1695
- );
1696
- }
1697
- return acc;
1698
- },
1699
- {}
1700
- )
1701
- };
1702
- await Promise.all(
1703
- Object.entries(resolve).map(async ([key, value]) => {
1704
- if (typeof value === "function") {
1705
- resolve[key] = await value(bundle);
1706
- }
1707
- return Promise.resolve(value);
1708
- })
1897
+ const resolve = await buildWebpackResolve(
1898
+ hostShared,
1899
+ remoteShared,
1900
+ bundle,
1901
+ {
1902
+ "/react/index.js": React,
1903
+ "/react/jsx-dev-runtime.js": JSXDevRuntime,
1904
+ "/react/jsx-runtime.js": JSXRuntime,
1905
+ "/react-dom/index.js": ReactDOM,
1906
+ "/react-dom/client.js": ReactDOMClient
1907
+ },
1908
+ "ComponentLoader"
1709
1909
  );
1710
1910
  applySharedModules(bundle, resolve);
1711
1911
  } else {
@@ -1733,19 +1933,8 @@ async function loadRemoteComponent({
1733
1933
  };
1734
1934
  }
1735
1935
  }
1736
- async function importCreateFromReadableStream() {
1737
- try {
1738
- const { createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1739
- return createFromReadableStream;
1740
- } catch {
1741
- const {
1742
- default: { createFromReadableStream }
1743
- } = await import("react-server-dom-webpack/client.browser");
1744
- return createFromReadableStream;
1745
- }
1746
- }
1747
1936
  async function loadRSCComponent(rscName, data) {
1748
- const createFromReadableStream = await importCreateFromReadableStream();
1937
+ const { createFromReadableStream } = await importRSCClientBrowser();
1749
1938
  if (typeof createFromReadableStream !== "function") {
1750
1939
  throw new RemoteComponentsError(
1751
1940
  'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
@@ -1809,10 +1998,9 @@ async function importViaCallback(absoluteSrc, resolveClientUrl) {
1809
1998
  URL.revokeObjectURL(moduleBlobUrl);
1810
1999
  URL.revokeObjectURL(wrapperBlobUrl);
1811
2000
  }
1812
- const registry = globalThis.__rc_module_registry__;
1813
- const mod = registry?.[absoluteSrc] ?? {};
1814
- if (registry)
1815
- delete registry[absoluteSrc];
2001
+ const registry = getNamespace().moduleRegistry;
2002
+ const mod = registry[absoluteSrc] ?? {};
2003
+ delete registry[absoluteSrc];
1816
2004
  return mod;
1817
2005
  }
1818
2006
  async function importDirectly(absoluteSrc) {
@@ -1842,12 +2030,12 @@ function resolveScriptSrc(script, url) {
1842
2030
  return rawSrc;
1843
2031
  }
1844
2032
  async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1845
- const self = globalThis;
1846
- if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1847
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
2033
+ const ns = getNamespace();
2034
+ if (ns.mountFns[url.href]) {
2035
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1848
2036
  }
1849
- if (self.__remote_script_entrypoint_unmount__?.[url.href]) {
1850
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
2037
+ if (ns.unmountFns[url.href]) {
2038
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1851
2039
  }
1852
2040
  const mountUnmountSets = await Promise.all(
1853
2041
  scripts.map(async (script) => {
@@ -1859,25 +2047,19 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1859
2047
  URL.revokeObjectURL(src);
1860
2048
  }
1861
2049
  if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
1862
- if (!self.__remote_script_entrypoint_mount__) {
1863
- self.__remote_script_entrypoint_mount__ = {};
1864
- }
1865
- if (!self.__remote_script_entrypoint_mount__[url.href]) {
1866
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
2050
+ if (!ns.mountFns[url.href]) {
2051
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1867
2052
  }
1868
- self.__remote_script_entrypoint_mount__[url.href]?.add(
2053
+ ns.mountFns[url.href]?.add(
1869
2054
  mod.mount || mod.default?.mount || (() => {
1870
2055
  })
1871
2056
  );
1872
2057
  }
1873
2058
  if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
1874
- if (!self.__remote_script_entrypoint_unmount__) {
1875
- self.__remote_script_entrypoint_unmount__ = {};
2059
+ if (!ns.unmountFns[url.href]) {
2060
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1876
2061
  }
1877
- if (!self.__remote_script_entrypoint_unmount__[url.href]) {
1878
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
1879
- }
1880
- self.__remote_script_entrypoint_unmount__[url.href]?.add(
2062
+ ns.unmountFns[url.href]?.add(
1881
2063
  mod.unmount || mod.default?.unmount || (() => {
1882
2064
  })
1883
2065
  );
@@ -1960,27 +2142,25 @@ function useShadowRoot({
1960
2142
  }) {
1961
2143
  const shadowRootContainerRef = useRef(null);
1962
2144
  const [shadowRoot, setShadowRoot] = useState(() => {
1963
- const self = globalThis;
1964
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2145
+ const shadowRoots = getNamespace().shadowRoots;
1965
2146
  const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
1966
2147
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
1967
- )?.shadowRoot ?? self[shadowRootKey] ?? null : null;
1968
- self[shadowRootKey] = null;
2148
+ )?.shadowRoot ?? shadowRoots[keySuffix] ?? null : null;
2149
+ shadowRoots[keySuffix] = null;
1969
2150
  return ssrShadowRoot;
1970
2151
  });
1971
2152
  useLayoutEffect(() => {
2153
+ const shadowRoots = getNamespace().shadowRoots;
1972
2154
  if (isolate !== false && typeof document !== "undefined" && (!shadowRoot || !shadowRoot.isConnected)) {
1973
- const self = globalThis;
1974
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
1975
2155
  let shadowRootElement = null;
1976
2156
  const element = document.querySelector(
1977
2157
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
1978
2158
  );
1979
- shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;
2159
+ shadowRootElement = shadowRoots[keySuffix] ?? element?.shadowRoot ?? null;
1980
2160
  if (!shadowRootElement && element) {
1981
2161
  try {
1982
2162
  shadowRootElement = element.attachShadow({ mode });
1983
- self[shadowRootKey] = shadowRootElement;
2163
+ shadowRoots[keySuffix] = shadowRootElement;
1984
2164
  } catch {
1985
2165
  }
1986
2166
  }
@@ -1991,9 +2171,7 @@ function useShadowRoot({
1991
2171
  setShadowRoot(shadowRootElement);
1992
2172
  }
1993
2173
  } else if (isolate === false && shadowRoot) {
1994
- const self = globalThis;
1995
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
1996
- self[shadowRootKey] = null;
2174
+ shadowRoots[keySuffix] = null;
1997
2175
  setShadowRoot(null);
1998
2176
  }
1999
2177
  }, [isolate, shadowRoot, mode, keySuffix]);
@@ -2089,9 +2267,8 @@ function ConsumeRemoteComponent({
2089
2267
  const prevRemoteComponentContainerRef = useRef2(null);
2090
2268
  const unmountRef = useRef2(null);
2091
2269
  useLayoutEffect2(() => {
2092
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2093
2270
  return () => {
2094
- delete globalThis[shadowRootKey];
2271
+ delete getNamespace().shadowRoots[keySuffix];
2095
2272
  };
2096
2273
  }, [keySuffix]);
2097
2274
  useLayoutEffect2(() => {
@@ -2184,9 +2361,8 @@ function ConsumeRemoteComponent({
2184
2361
  if (shadowRoot) {
2185
2362
  shadowRoot.innerHTML = "";
2186
2363
  }
2187
- const self = globalThis;
2188
2364
  const prevUrl = hostStateRef.current.prevUrl;
2189
- if (prevUrl && self.__remote_script_entrypoint_unmount__?.[prevUrl.href]) {
2365
+ if (prevUrl && getNamespace().unmountFns[prevUrl.href]) {
2190
2366
  const unmountPromises = Promise.all(
2191
2367
  Array.from(unmountRef.current ?? []).map(
2192
2368
  async (unmount) => unmount(
@@ -2376,10 +2552,7 @@ function ConsumeRemoteComponent({
2376
2552
  ).href
2377
2553
  };
2378
2554
  }),
2379
- shared: {
2380
- ...sharedPolyfills(userShared, resolveClientUrl),
2381
- ...userShared
2382
- },
2555
+ shared: buildHostShared(userShared, resolveClientUrl),
2383
2556
  remoteShared,
2384
2557
  container: shadowRoot,
2385
2558
  resolveClientUrl
@@ -2511,8 +2684,10 @@ function ConsumeRemoteComponent({
2511
2684
  alt="" decoding="async" style="display:none"
2512
2685
  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
2513
2686
  onload="(function(el){
2687
+ // Capture the shadow root during SSR hydration so the client-side
2688
+ // useShadowRoot hook can find it.
2514
2689
  const root = el.getRootNode();
2515
- globalThis.__remote_components_shadowroot_${keySuffix} = root;
2690
+ globalThis.__remote_components_shadowroot_${keySuffix}=root;
2516
2691
  el.parentElement.remove();
2517
2692
  })(this)"
2518
2693
  />`