remote-components 0.3.3 → 0.3.5

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 (176) 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 +861 -617
  10. package/dist/host/html.cjs.map +1 -1
  11. package/dist/host/html.js +861 -617
  12. package/dist/host/html.js.map +1 -1
  13. package/dist/host/nextjs/app/client-only.cjs +700 -383
  14. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  15. package/dist/host/nextjs/app/client-only.js +674 -357
  16. package/dist/host/nextjs/app/client-only.js.map +1 -1
  17. package/dist/host/nextjs/app.cjs +34 -2
  18. package/dist/host/nextjs/app.cjs.map +1 -1
  19. package/dist/host/nextjs/app.js +35 -3
  20. package/dist/host/nextjs/app.js.map +1 -1
  21. package/dist/host/react.cjs +641 -352
  22. package/dist/host/react.cjs.map +1 -1
  23. package/dist/host/react.js +641 -352
  24. package/dist/host/react.js.map +1 -1
  25. package/dist/internal/config/webpack/apply-shared-modules.cjs +6 -4
  26. package/dist/internal/config/webpack/apply-shared-modules.cjs.map +1 -1
  27. package/dist/internal/config/webpack/apply-shared-modules.js +6 -4
  28. package/dist/internal/config/webpack/apply-shared-modules.js.map +1 -1
  29. package/dist/internal/config/webpack/next-client-pages-loader.cjs +6 -7
  30. package/dist/internal/config/webpack/next-client-pages-loader.cjs.map +1 -1
  31. package/dist/internal/config/webpack/next-client-pages-loader.js +6 -7
  32. package/dist/internal/config/webpack/next-client-pages-loader.js.map +1 -1
  33. package/dist/internal/host/nextjs/app-client.cjs +42 -27
  34. package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
  35. package/dist/internal/host/nextjs/app-client.js +42 -27
  36. package/dist/internal/host/nextjs/app-client.js.map +1 -1
  37. package/dist/internal/host/nextjs/dom-flight.cjs +19 -39
  38. package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
  39. package/dist/internal/host/nextjs/dom-flight.js +31 -39
  40. package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
  41. package/dist/internal/host/nextjs/image-shared.cjs +39 -3
  42. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  43. package/dist/internal/host/nextjs/image-shared.d.ts +5 -10
  44. package/dist/internal/host/nextjs/image-shared.js +29 -3
  45. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  46. package/dist/internal/host/nextjs/remote-component-links.cjs +24 -13
  47. package/dist/internal/host/nextjs/remote-component-links.cjs.map +1 -1
  48. package/dist/internal/host/nextjs/remote-component-links.d.ts +3 -0
  49. package/dist/internal/host/nextjs/remote-component-links.js +24 -13
  50. package/dist/internal/host/nextjs/remote-component-links.js.map +1 -1
  51. package/dist/internal/host/server/fetch-remote-component.cjs +2 -1
  52. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  53. package/dist/internal/host/server/fetch-remote-component.js +2 -1
  54. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  55. package/dist/internal/host/shared/lifecycle.cjs +69 -0
  56. package/dist/internal/host/shared/lifecycle.cjs.map +1 -0
  57. package/dist/internal/host/shared/lifecycle.d.ts +34 -0
  58. package/dist/internal/host/shared/lifecycle.js +44 -0
  59. package/dist/internal/host/shared/lifecycle.js.map +1 -0
  60. package/dist/internal/host/shared/pipeline.cjs +222 -0
  61. package/dist/internal/host/shared/pipeline.cjs.map +1 -0
  62. package/dist/internal/host/shared/pipeline.d.ts +153 -0
  63. package/dist/internal/host/shared/pipeline.js +200 -0
  64. package/dist/internal/host/shared/pipeline.js.map +1 -0
  65. package/dist/internal/host/shared/polyfill.cjs +8 -7
  66. package/dist/internal/host/shared/polyfill.cjs.map +1 -1
  67. package/dist/internal/host/shared/polyfill.js +8 -7
  68. package/dist/internal/host/shared/polyfill.js.map +1 -1
  69. package/dist/internal/host/shared/shared-module-resolver.cjs +117 -0
  70. package/dist/internal/host/shared/shared-module-resolver.cjs.map +1 -0
  71. package/dist/internal/host/shared/shared-module-resolver.d.ts +64 -0
  72. package/dist/internal/host/shared/shared-module-resolver.js +78 -0
  73. package/dist/internal/host/shared/shared-module-resolver.js.map +1 -0
  74. package/dist/internal/remote/nextjs/next-internals.cjs +53 -0
  75. package/dist/internal/remote/nextjs/next-internals.cjs.map +1 -0
  76. package/dist/internal/remote/nextjs/next-internals.d.ts +42 -0
  77. package/dist/internal/remote/nextjs/next-internals.js +26 -0
  78. package/dist/internal/remote/nextjs/next-internals.js.map +1 -0
  79. package/dist/internal/runtime/html/apply-origin.cjs +11 -32
  80. package/dist/internal/runtime/html/apply-origin.cjs.map +1 -1
  81. package/dist/internal/runtime/html/apply-origin.js +11 -32
  82. package/dist/internal/runtime/html/apply-origin.js.map +1 -1
  83. package/dist/internal/runtime/html/html-spec.cjs +78 -0
  84. package/dist/internal/runtime/html/html-spec.cjs.map +1 -0
  85. package/dist/internal/runtime/html/html-spec.d.ts +23 -0
  86. package/dist/internal/runtime/html/html-spec.js +41 -0
  87. package/dist/internal/runtime/html/html-spec.js.map +1 -0
  88. package/dist/internal/runtime/html/parse-remote-html.cjs +15 -12
  89. package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
  90. package/dist/internal/runtime/html/parse-remote-html.js +29 -12
  91. package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
  92. package/dist/internal/runtime/html/rewrite-srcset.cjs +38 -0
  93. package/dist/internal/runtime/html/rewrite-srcset.cjs.map +1 -0
  94. package/dist/internal/runtime/html/rewrite-srcset.d.ts +12 -0
  95. package/dist/internal/runtime/html/rewrite-srcset.js +14 -0
  96. package/dist/internal/runtime/html/rewrite-srcset.js.map +1 -0
  97. package/dist/internal/runtime/loaders/component-loader.cjs +25 -44
  98. package/dist/internal/runtime/loaders/component-loader.cjs.map +1 -1
  99. package/dist/internal/runtime/loaders/component-loader.d.ts +3 -1
  100. package/dist/internal/runtime/loaders/component-loader.js +28 -44
  101. package/dist/internal/runtime/loaders/component-loader.js.map +1 -1
  102. package/dist/internal/runtime/loaders/static-loader.cjs +15 -21
  103. package/dist/internal/runtime/loaders/static-loader.cjs.map +1 -1
  104. package/dist/internal/runtime/loaders/static-loader.d.ts +3 -1
  105. package/dist/internal/runtime/loaders/static-loader.js +15 -21
  106. package/dist/internal/runtime/loaders/static-loader.js.map +1 -1
  107. package/dist/internal/runtime/namespace.cjs +82 -0
  108. package/dist/internal/runtime/namespace.cjs.map +1 -0
  109. package/dist/internal/runtime/namespace.d.ts +5 -0
  110. package/dist/internal/runtime/namespace.js +58 -0
  111. package/dist/internal/runtime/namespace.js.map +1 -0
  112. package/dist/internal/runtime/rsc-imports.cjs +86 -0
  113. package/dist/internal/runtime/rsc-imports.cjs.map +1 -0
  114. package/dist/internal/runtime/rsc-imports.d.ts +39 -0
  115. package/dist/internal/runtime/rsc-imports.js +50 -0
  116. package/dist/internal/runtime/rsc-imports.js.map +1 -0
  117. package/dist/internal/runtime/rsc-runtime.cjs +17 -0
  118. package/dist/internal/runtime/rsc-runtime.cjs.map +1 -0
  119. package/dist/internal/runtime/rsc-runtime.d.ts +37 -0
  120. package/dist/internal/runtime/rsc-runtime.js +1 -0
  121. package/dist/internal/runtime/rsc-runtime.js.map +1 -0
  122. package/dist/internal/runtime/rsc.cjs +23 -12
  123. package/dist/internal/runtime/rsc.cjs.map +1 -1
  124. package/dist/internal/runtime/rsc.d.ts +19 -2
  125. package/dist/internal/runtime/rsc.js +20 -11
  126. package/dist/internal/runtime/rsc.js.map +1 -1
  127. package/dist/internal/runtime/turbopack/chunk-loader.cjs +53 -35
  128. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  129. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +1 -1
  130. package/dist/internal/runtime/turbopack/chunk-loader.js +53 -35
  131. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  132. package/dist/internal/runtime/turbopack/module.cjs +17 -4
  133. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  134. package/dist/internal/runtime/turbopack/module.d.ts +23 -1
  135. package/dist/internal/runtime/turbopack/module.js +16 -4
  136. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  137. package/dist/internal/runtime/turbopack/patterns.cjs +26 -10
  138. package/dist/internal/runtime/turbopack/patterns.cjs.map +1 -1
  139. package/dist/internal/runtime/turbopack/patterns.d.ts +44 -49
  140. package/dist/internal/runtime/turbopack/patterns.js +23 -7
  141. package/dist/internal/runtime/turbopack/patterns.js.map +1 -1
  142. package/dist/internal/runtime/turbopack/{webpack-runtime.cjs → remote-scope-setup.cjs} +35 -32
  143. package/dist/internal/runtime/turbopack/remote-scope-setup.cjs.map +1 -0
  144. package/dist/internal/runtime/turbopack/remote-scope-setup.d.ts +25 -0
  145. package/dist/internal/runtime/turbopack/{webpack-runtime.js → remote-scope-setup.js} +36 -19
  146. package/dist/internal/runtime/turbopack/remote-scope-setup.js.map +1 -0
  147. package/dist/internal/runtime/turbopack/remote-scope.cjs +4 -6
  148. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -1
  149. package/dist/internal/runtime/turbopack/remote-scope.d.ts +20 -1
  150. package/dist/internal/runtime/turbopack/remote-scope.js +4 -6
  151. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -1
  152. package/dist/internal/runtime/turbopack/shared-modules.cjs +21 -15
  153. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  154. package/dist/internal/runtime/turbopack/shared-modules.d.ts +9 -2
  155. package/dist/internal/runtime/turbopack/shared-modules.js +24 -18
  156. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  157. package/dist/internal/runtime/types.cjs.map +1 -1
  158. package/dist/internal/runtime/types.d.ts +5 -41
  159. package/dist/internal/utils/logger.cjs +1 -1
  160. package/dist/internal/utils/logger.cjs.map +1 -1
  161. package/dist/internal/utils/logger.d.ts +2 -2
  162. package/dist/internal/utils/logger.js +1 -1
  163. package/dist/internal/utils/logger.js.map +1 -1
  164. package/dist/remote/html.cjs +78 -22
  165. package/dist/remote/html.cjs.map +1 -1
  166. package/dist/remote/html.js +78 -22
  167. package/dist/remote/html.js.map +1 -1
  168. package/dist/remote/nextjs/app.cjs +14 -55
  169. package/dist/remote/nextjs/app.cjs.map +1 -1
  170. package/dist/remote/nextjs/app.js +24 -45
  171. package/dist/remote/nextjs/app.js.map +1 -1
  172. package/dist/types-59251814.d.ts +94 -0
  173. package/package.json +2 -2
  174. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +0 -1
  175. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +0 -23
  176. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +0 -1
@@ -47,6 +47,9 @@ var init_app = __esm({
47
47
  // src/host/nextjs/app-client-only.tsx
48
48
  import { useMemo as useMemo3 } from "react";
49
49
 
50
+ // src/host/nextjs/image-shared.ts
51
+ import { createElement, forwardRef } from "react";
52
+
50
53
  // src/utils/index.ts
51
54
  function escapeString(str) {
52
55
  return str.replace(/[^a-z0-9]/g, "_");
@@ -73,6 +76,62 @@ function getBundleKey(bundle) {
73
76
  return escapeString(bundle);
74
77
  }
75
78
 
79
+ // src/runtime/namespace.ts
80
+ var SHADOW_ROOT_PREFIX = "__remote_components_shadowroot_";
81
+ var LEGACY_ALIASES = [
82
+ { global: "__remote_component_scopes__", prop: "scopes" },
83
+ {
84
+ global: "__remote_components_turbopack_chunk_loader_promise__",
85
+ prop: "chunkCache"
86
+ },
87
+ { global: "__remote_script_entrypoint_mount__", prop: "mountFns" },
88
+ { global: "__remote_script_entrypoint_unmount__", prop: "unmountFns" },
89
+ { global: "__remote_bundle_url__", prop: "bundleUrls" },
90
+ { global: "__rc_module_registry__", prop: "moduleRegistry" },
91
+ {
92
+ global: "__remote_component_host_shared_modules__",
93
+ prop: "hostSharedModules"
94
+ },
95
+ { global: "__remote_next_css__", prop: "cssCache" }
96
+ ];
97
+ function getNamespace() {
98
+ const g = globalThis;
99
+ const existing = g.__remote_components__;
100
+ if (existing) {
101
+ return existing;
102
+ }
103
+ const ns = {
104
+ scopes: /* @__PURE__ */ new Map(),
105
+ chunkCache: {},
106
+ mountFns: {},
107
+ unmountFns: {},
108
+ bundleUrls: {},
109
+ moduleRegistry: {},
110
+ dispatcherRuntime: void 0,
111
+ hostSharedModules: {},
112
+ cssCache: {},
113
+ shadowRoots: {}
114
+ };
115
+ const nsRecord = ns;
116
+ for (const { global, prop } of LEGACY_ALIASES) {
117
+ const legacyValue = g[global];
118
+ if (legacyValue != null) {
119
+ nsRecord[prop] = legacyValue;
120
+ }
121
+ g[global] = ns[prop];
122
+ }
123
+ const gRecord = g;
124
+ for (const key of Object.keys(gRecord)) {
125
+ if (key.startsWith(SHADOW_ROOT_PREFIX)) {
126
+ const suffix = key.slice(SHADOW_ROOT_PREFIX.length);
127
+ ns.shadowRoots[suffix] = gRecord[key];
128
+ delete gRecord[key];
129
+ }
130
+ }
131
+ g.__remote_components__ = ns;
132
+ return ns;
133
+ }
134
+
76
135
  // src/runtime/patterns.ts
77
136
  var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
78
137
  var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
@@ -197,7 +256,7 @@ Docs: ${CORS_DOCS_URL}`
197
256
 
198
257
  // src/utils/logger.ts
199
258
  var PREFIX = "remote-components";
200
- var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
259
+ var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
201
260
  function logDebug(location2, message) {
202
261
  if (DEBUG) {
203
262
  console.debug(`[${PREFIX}:${location2}]: ${message}`);
@@ -229,11 +288,7 @@ function warnCrossOriginFetchError(logLocation, url) {
229
288
 
230
289
  // src/runtime/turbopack/remote-scope.ts
231
290
  function getRegistry() {
232
- const self = globalThis;
233
- if (!self.__remote_component_scopes__) {
234
- self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
235
- }
236
- return self.__remote_component_scopes__;
291
+ return getNamespace().scopes;
237
292
  }
238
293
  function createScope(name, url, runtime, resolveClientUrl) {
239
294
  const isCrossOrigin = url.origin !== location.origin;
@@ -251,7 +306,8 @@ function createScope(name, url, runtime, resolveClientUrl) {
251
306
  resolveClientUrl,
252
307
  moduleCache: {},
253
308
  sharedModules: {},
254
- moduleGlobal: {}
309
+ moduleGlobal: {},
310
+ turbopackModules: []
255
311
  };
256
312
  }
257
313
  function registerScope(scope) {
@@ -348,16 +404,41 @@ function createImageLoaderSharedEntries({
348
404
  bound,
349
405
  unbound
350
406
  } = {}) {
351
- const entry = (bundle) => {
407
+ const loaderEntry = (bundle) => {
352
408
  const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
353
409
  return Promise.resolve({
354
410
  default: createRemoteImageLoader(bundle, resolveClientUrl),
355
411
  __esModule: true
356
412
  });
357
413
  };
414
+ const imageEntry = async (bundle) => {
415
+ const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
416
+ const rawLoader = createRemoteImageLoader(bundle, resolveClientUrl);
417
+ const remoteLoader = Object.assign(
418
+ (p) => rawLoader({ ...p, config: { path: "/_next/image" } }),
419
+ { __next_img_default: true }
420
+ );
421
+ const mod = await import("next/image");
422
+ const OriginalImage = mod.default;
423
+ const RemoteImage = forwardRef(
424
+ (props, ref) => createElement(OriginalImage, {
425
+ ...props,
426
+ loader: props.loader ?? remoteLoader,
427
+ ref
428
+ })
429
+ );
430
+ RemoteImage.displayName = "RemoteImage";
431
+ return { ...mod, default: RemoteImage, __esModule: true };
432
+ };
358
433
  return {
359
- "next/dist/shared/lib/image-loader": entry,
360
- "next/dist/esm/shared/lib/image-loader": entry
434
+ "next/dist/shared/lib/image-loader": loaderEntry,
435
+ "next/dist/esm/shared/lib/image-loader": loaderEntry,
436
+ // Can be removed once 0.2.x support is dropped.
437
+ "next/image": imageEntry,
438
+ // Can be removed once 0.2.x support is dropped.
439
+ "next/dist/client/image-component": imageEntry,
440
+ // Can be removed once 0.2.x support is dropped.
441
+ "next/dist/api/image": imageEntry
361
442
  };
362
443
  }
363
444
 
@@ -442,12 +523,30 @@ function getClientOrServerUrl(src, serverFallback) {
442
523
  return typeof src === "string" ? new URL(src, fallback) : src;
443
524
  }
444
525
 
526
+ // src/host/shared/lifecycle.ts
527
+ function makeReactEmitter(callbacks) {
528
+ return {
529
+ beforeLoad(src) {
530
+ callbacks.onBeforeLoad?.(src);
531
+ },
532
+ load(src) {
533
+ callbacks.onLoad?.(src);
534
+ },
535
+ error(error, _src) {
536
+ callbacks.onError?.(error);
537
+ },
538
+ change(info) {
539
+ callbacks.onChange?.(info);
540
+ }
541
+ };
542
+ }
543
+
445
544
  // src/host/shared/polyfill.tsx
446
545
  import { jsx } from "react/jsx-runtime";
447
546
  function sharedPolyfills(shared2, resolveClientUrl) {
448
- const self = globalThis;
547
+ const hostShared = getNamespace().hostSharedModules;
449
548
  const polyfill = {
450
- "next/dist/client/components/navigation": self.__remote_component_host_shared_modules__?.["next/navigation"] ?? shared2?.["next/navigation"] ?? (() => Promise.resolve({
549
+ "next/dist/client/components/navigation": hostShared["next/navigation"] ?? shared2?.["next/navigation"] ?? (() => Promise.resolve({
451
550
  useRouter() {
452
551
  return {
453
552
  push: (routerUrl) => {
@@ -478,7 +577,7 @@ function sharedPolyfills(shared2, resolveClientUrl) {
478
577
  },
479
578
  __esModule: true
480
579
  })),
481
- "next/dist/client/app-dir/link": self.__remote_component_host_shared_modules__?.["next/link"] ?? shared2?.["next/link"] ?? (() => Promise.resolve({
580
+ "next/dist/client/app-dir/link": hostShared["next/link"] ?? shared2?.["next/link"] ?? (() => Promise.resolve({
482
581
  default: ({
483
582
  scroll: _,
484
583
  replace,
@@ -528,7 +627,7 @@ function sharedPolyfills(shared2, resolveClientUrl) {
528
627
  },
529
628
  __esModule: true
530
629
  })),
531
- "next/dist/client/app-dir/form": self.__remote_component_host_shared_modules__?.["next/form"] ?? shared2?.["next/form"] ?? (() => Promise.resolve({
630
+ "next/dist/client/app-dir/form": hostShared["next/form"] ?? shared2?.["next/form"] ?? (() => Promise.resolve({
532
631
  default: () => {
533
632
  throw new Error("Next.js <Form> component not implemented");
534
633
  },
@@ -539,17 +638,17 @@ function sharedPolyfills(shared2, resolveClientUrl) {
539
638
  // This gives us full next/image fidelity (fill, priority, srcSet, blur
540
639
  // placeholders, error handling) while routing image optimization through the
541
640
  // remote app's /_next/image endpoint.
542
- "next/dist/shared/lib/image-loader": self.__remote_component_host_shared_modules__?.["next/dist/shared/lib/image-loader"] ?? shared2?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
641
+ "next/dist/shared/lib/image-loader": hostShared["next/dist/shared/lib/image-loader"] ?? shared2?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
543
642
  default: createRemoteImageLoader(bundle, resolveClientUrl),
544
643
  __esModule: true
545
644
  })),
546
- "next/dist/client/script": self.__remote_component_host_shared_modules__?.["next/script"] ?? shared2?.["next/script"] ?? (() => Promise.resolve({
645
+ "next/dist/client/script": hostShared["next/script"] ?? shared2?.["next/script"] ?? (() => Promise.resolve({
547
646
  // TODO: implement <Script> component for non-Next.js host applications
548
647
  // do not throw an error for now
549
648
  default: () => null,
550
649
  __esModule: true
551
650
  })),
552
- "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared2?.["next/router"] ?? (() => (
651
+ "next/router": hostShared["next/router"] ?? shared2?.["next/router"] ?? (() => (
553
652
  // TODO: incomplete implementation
554
653
  Promise.resolve({
555
654
  useRouter() {
@@ -585,34 +684,70 @@ function sharedPolyfills(shared2, resolveClientUrl) {
585
684
  return polyfill;
586
685
  }
587
686
 
588
- // src/host/shared/state.ts
589
- function createHostState() {
687
+ // src/host/shared/shared-module-resolver.ts
688
+ var CORE_REACT_PATH_MAP = {
689
+ react: "/react/index.js",
690
+ "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
691
+ "react/jsx-runtime": "/react/jsx-runtime.js",
692
+ "react-dom": "/react-dom/index.js",
693
+ "react-dom/client": "/react-dom/client.js"
694
+ };
695
+ var VENDOR_SHARED = Object.fromEntries(
696
+ Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
697
+ );
698
+ function buildCoreShared(userShared) {
590
699
  return {
591
- stage: "idle",
592
- prevSrc: void 0,
593
- prevUrl: void 0,
594
- prevName: void 0,
595
- prevIsRemoteComponent: false,
596
- abortController: void 0
700
+ react: async () => (await import("react")).default,
701
+ "react-dom": async () => (await import("react-dom")).default,
702
+ "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
703
+ "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
704
+ "react-dom/client": async () => (await import("react-dom/client")).default,
705
+ ...userShared
597
706
  };
598
707
  }
599
-
600
- // src/host/utils/resolve-name-from-src.ts
601
- function resolveNameFromSrc(src, defaultName) {
602
- if (!src) {
603
- return defaultName;
604
- }
605
- const hash = typeof src === "string" ? src : src.hash;
606
- const hashIndex = hash.indexOf("#");
607
- if (hashIndex < 0) {
608
- return defaultName;
609
- }
610
- const name = hash.slice(hashIndex + 1);
611
- return name || defaultName;
708
+ function buildHostShared(userShared, resolveClientUrl, options) {
709
+ const self = globalThis;
710
+ const result = {
711
+ ...sharedPolyfills(userShared, resolveClientUrl),
712
+ ...self.__remote_component_host_shared_modules__,
713
+ ...userShared
714
+ };
715
+ if (options?.includeRemoteComponentShared) {
716
+ Object.assign(result, self.__remote_component_shared__);
717
+ }
718
+ return result;
719
+ }
720
+ async function buildWebpackResolve(hostShared, remoteShared, bundle, reactModules, callerTag = "SharedModuleResolver") {
721
+ const resolve = {
722
+ ...reactModules,
723
+ ...Object.entries(remoteShared).reduce(
724
+ (acc, [key, value]) => {
725
+ if (typeof hostShared[value] !== "undefined") {
726
+ acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
727
+ } else {
728
+ logDebug(
729
+ callerTag,
730
+ `Remote requests "${value}" but host doesn't provide it`
731
+ );
732
+ }
733
+ return acc;
734
+ },
735
+ {}
736
+ )
737
+ };
738
+ await Promise.all(
739
+ Object.entries(resolve).map(async ([key, value]) => {
740
+ if (typeof value === "function") {
741
+ resolve[key] = await value(bundle);
742
+ }
743
+ return Promise.resolve(value);
744
+ })
745
+ );
746
+ return resolve;
612
747
  }
613
748
 
614
- // src/runtime/html/apply-origin.ts
615
- var tagNames = [
749
+ // src/runtime/html/html-spec.ts
750
+ var ORIGIN_REWRITE_TAGS = [
616
751
  "img",
617
752
  "source",
618
753
  "video",
@@ -623,10 +758,37 @@ var tagNames = [
623
758
  "script",
624
759
  "link"
625
760
  ];
761
+ var ID_SUFFIX_RSC = "_rsc";
762
+ var ID_SUFFIX_SSR = "_ssr";
763
+ var ID_SUFFIX_SHARED = "_shared";
764
+ var DATA_BUNDLE = "data-bundle";
765
+ var DATA_ROUTE = "data-route";
766
+ var DATA_RUNTIME = "data-runtime";
767
+ var DATA_TYPE = "data-type";
768
+ var DATA_SRC = "data-src";
769
+ var DATA_REMOTE_COMPONENTS_SHARED = "data-remote-components-shared";
770
+ var TAG_REMOTE_COMPONENT = "remote-component";
771
+ var NEXT_DATA_ID = "__NEXT_DATA__";
772
+ var REMOTE_NEXT_DATA_ID = "__REMOTE_NEXT_DATA__";
773
+ var NEXT_CONTAINER_ID = "__next";
774
+
775
+ // src/runtime/html/rewrite-srcset.ts
776
+ function rewriteSrcset(srcset, base, resolve) {
777
+ return srcset.split(",").map((entry) => {
778
+ const [url, descriptor] = entry.trim().split(/\s+/);
779
+ if (!url)
780
+ return entry;
781
+ const absoluteUrl = new URL(url, base).href;
782
+ const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;
783
+ return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
784
+ }).join(", ");
785
+ }
786
+
787
+ // src/runtime/html/apply-origin.ts
626
788
  function applyOriginToNodes(doc, url, resolveClientUrl) {
627
789
  if (url.origin !== location.origin) {
628
790
  const nodes = doc.querySelectorAll(
629
- tagNames.map(
791
+ ORIGIN_REWRITE_TAGS.map(
630
792
  (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
631
793
  ).join(",")
632
794
  );
@@ -644,29 +806,17 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
644
806
  );
645
807
  }
646
808
  if (node.hasAttribute("srcset")) {
647
- const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
648
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
649
- if (!urlPart)
650
- return entry;
651
- const absoluteUrl = new URL(urlPart, url).href;
652
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
653
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
654
- }).join(", ");
655
- if (srcSet) {
656
- node.setAttribute("srcset", srcSet);
809
+ const raw = node.getAttribute("srcset");
810
+ if (raw) {
811
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
812
+ node.setAttribute("srcset", rewriteSrcset(raw, url, resolve));
657
813
  }
658
814
  }
659
815
  if (node.hasAttribute("imagesrcset")) {
660
- const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
661
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
662
- if (!urlPart)
663
- return entry;
664
- const absoluteUrl = new URL(urlPart, url).href;
665
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
666
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
667
- }).join(", ");
668
- if (srcSet) {
669
- node.setAttribute("imagesrcset", srcSet);
816
+ const raw = node.getAttribute("imagesrcset");
817
+ if (raw) {
818
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
819
+ node.setAttribute("imagesrcset", rewriteSrcset(raw, url, resolve));
670
820
  }
671
821
  }
672
822
  });
@@ -707,26 +857,28 @@ function buildMetadata(attrs, url) {
707
857
 
708
858
  // src/runtime/html/parse-remote-html.ts
709
859
  function validateSingleComponent(doc, name, url) {
710
- 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}"]`)) {
860
+ if (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 && !doc.querySelector(
861
+ `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`
862
+ ) || doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 && !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]`)) {
711
863
  throw multipleRemoteComponentsError(url);
712
864
  }
713
865
  }
714
866
  function findComponentElement(doc, name) {
715
- 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])");
867
+ 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])`);
716
868
  }
717
869
  function parseNextData(doc) {
718
870
  return JSON.parse(
719
- (doc.querySelector("#__NEXT_DATA__") ?? doc.querySelector("#__REMOTE_NEXT_DATA__"))?.textContent ?? "null"
871
+ (doc.querySelector(`#${NEXT_DATA_ID}`) ?? doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`))?.textContent ?? "null"
720
872
  );
721
873
  }
722
874
  function resolveComponentName(component, nextData, fallbackName) {
723
- const isRemoteComponent = component?.tagName.toLowerCase() === "remote-component";
724
- const name = component?.getAttribute("id")?.replace(/_ssr$/, "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
875
+ const isRemoteComponent = component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;
876
+ const name = component?.getAttribute("id")?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
725
877
  return { name, isRemoteComponent };
726
878
  }
727
879
  function extractRemoteShared(doc, name, nextData) {
728
880
  const remoteSharedEl = doc.querySelector(
729
- `#${name}_shared[data-remote-components-shared]`
881
+ `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`
730
882
  );
731
883
  const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
732
884
  remoteSharedEl?.remove();
@@ -747,7 +899,7 @@ function extractLinks(doc, component) {
747
899
  function extractScripts(doc, component, isRemoteComponent) {
748
900
  return Array.from(
749
901
  (isRemoteComponent ? component : doc).querySelectorAll(
750
- "script[src],script[data-src]"
902
+ `script[src],script[${DATA_SRC}]`
751
903
  )
752
904
  );
753
905
  }
@@ -760,15 +912,15 @@ function parseRemoteComponentDocument(doc, name, url) {
760
912
  nextData,
761
913
  name
762
914
  );
763
- const rsc = doc.querySelector(`#${resolvedName}_rsc`);
915
+ const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);
764
916
  const metadata = buildMetadata(
765
917
  {
766
918
  name: resolvedName,
767
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
768
- route: component?.getAttribute("data-route") ?? nextData?.page,
769
- runtime: component?.getAttribute("data-runtime") ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
919
+ bundle: component?.getAttribute(DATA_BUNDLE) || nextData?.props.__REMOTE_COMPONENT__?.bundle,
920
+ route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,
921
+ runtime: component?.getAttribute(DATA_RUNTIME) ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
770
922
  id: component?.getAttribute("id"),
771
- type: component?.getAttribute("data-type")
923
+ type: component?.getAttribute(DATA_TYPE)
772
924
  },
773
925
  url
774
926
  );
@@ -796,48 +948,6 @@ function parseRemoteComponentDocument(doc, name, url) {
796
948
  };
797
949
  }
798
950
 
799
- // src/runtime/html/set-attributes-from-props.ts
800
- var DOMAttributeNames = {
801
- acceptCharset: "accept-charset",
802
- className: "class",
803
- htmlFor: "for",
804
- httpEquiv: "http-equiv",
805
- noModule: "noModule"
806
- };
807
- var ignoreProps = [
808
- "onLoad",
809
- "onReady",
810
- "dangerouslySetInnerHTML",
811
- "children",
812
- "onError",
813
- "strategy",
814
- "stylesheets"
815
- ];
816
- function isBooleanScriptAttribute(attr) {
817
- return ["async", "defer", "noModule"].includes(attr);
818
- }
819
- function setAttributesFromProps(el, props) {
820
- for (const [p, value] of Object.entries(props)) {
821
- if (!Object.hasOwn(props, p))
822
- continue;
823
- if (ignoreProps.includes(p))
824
- continue;
825
- if (value === void 0) {
826
- continue;
827
- }
828
- const attr = DOMAttributeNames[p] || p.toLowerCase();
829
- if (el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr)) {
830
- el[attr] = Boolean(value);
831
- } else {
832
- el.setAttribute(attr, String(value));
833
- }
834
- if (value === false || el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr) && (!value || value === "false")) {
835
- el.setAttribute(attr, "");
836
- el.removeAttribute(attr);
837
- }
838
- }
839
- }
840
-
841
951
  // src/runtime/loaders/component-loader.ts
842
952
  import * as React from "react";
843
953
  import * as JSXDevRuntime from "react/jsx-dev-runtime";
@@ -857,13 +967,15 @@ function applySharedModules(bundle, resolve) {
857
967
  `Shared modules to resolve: ${Object.keys(resolve)}`
858
968
  );
859
969
  const self = globalThis;
860
- if (self.__remote_webpack_require__?.[bundle]) {
970
+ const scope = getScope(bundle);
971
+ const webpackBundle = scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];
972
+ if (webpackBundle) {
861
973
  const modulePaths = Object.keys(
862
- self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
974
+ self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {}
863
975
  );
864
976
  logDebug(
865
977
  "SharedModules",
866
- `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`
978
+ `Available module paths for bundle "${bundle}": ${modulePaths}`
867
979
  );
868
980
  for (const [key, value] of Object.entries(resolve)) {
869
981
  const exactIds = modulePaths.filter((p) => p === key);
@@ -875,7 +987,6 @@ function applySharedModules(bundle, resolve) {
875
987
  );
876
988
  }
877
989
  for (const id of ids) {
878
- const webpackBundle = self.__remote_webpack_require__[bundle];
879
990
  if (webpackBundle.m) {
880
991
  const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
881
992
  if (resolvedId !== id) {
@@ -973,10 +1084,8 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
973
1084
  ];
974
1085
  const { default: Component } = componentLoader();
975
1086
  const { default: App } = appLoader();
976
- if (!self.__remote_next_css__) {
977
- self.__remote_next_css__ = {};
978
- }
979
- if (!self.__remote_next_css__[bundle]) {
1087
+ const cssCache = getNamespace().cssCache;
1088
+ if (!cssCache[bundle]) {
980
1089
  const cssRE = /\.s?css$/;
981
1090
  Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
982
1091
  self.__remote_webpack_require__?.[bundle]?.(id);
@@ -994,15 +1103,15 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
994
1103
  node.remove();
995
1104
  node = nextCss.previousSibling;
996
1105
  }
997
- self.__remote_next_css__[bundle] = elements;
1106
+ cssCache[bundle] = elements;
998
1107
  }
999
1108
  if (styleContainer) {
1000
- const elements = self.__remote_next_css__[bundle];
1109
+ const elements = cssCache[bundle];
1001
1110
  elements.forEach((el) => {
1002
1111
  styleContainer.appendChild(el.cloneNode(true));
1003
1112
  });
1004
1113
  } else {
1005
- const elements = self.__remote_next_css__[bundle];
1114
+ const elements = cssCache[bundle];
1006
1115
  elements.forEach((el) => {
1007
1116
  document.head.appendChild(el);
1008
1117
  });
@@ -1039,6 +1148,18 @@ function fixPayload(payload) {
1039
1148
  }
1040
1149
  }
1041
1150
  }
1151
+ function buildRSCChunks(rscName, data) {
1152
+ const chunks = [];
1153
+ for (const chunk of data) {
1154
+ for (const line of chunk.split("\n")) {
1155
+ const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1156
+ if (match?.groups?.rsc) {
1157
+ chunks.push(JSON.parse(`"${match.groups.rsc}"`));
1158
+ }
1159
+ }
1160
+ }
1161
+ return chunks;
1162
+ }
1042
1163
  function createRSCStream(rscName, data) {
1043
1164
  return new ReadableStream({
1044
1165
  type: "bytes",
@@ -1046,16 +1167,11 @@ function createRSCStream(rscName, data) {
1046
1167
  const encoder = new TextEncoder();
1047
1168
  const self = globalThis;
1048
1169
  if (data.length > 0) {
1049
- data.forEach((chunk) => {
1050
- const lines = chunk.split("\n");
1051
- for (const line of lines) {
1052
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1053
- if (match?.groups?.rsc) {
1054
- self[rscName] = self[rscName] ?? [];
1055
- self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
1056
- }
1057
- }
1058
- });
1170
+ const parsed = buildRSCChunks(rscName, data);
1171
+ if (parsed.length > 0) {
1172
+ self[rscName] = self[rscName] ?? [];
1173
+ self[rscName].push(...parsed);
1174
+ }
1059
1175
  }
1060
1176
  const allChunks = (self[rscName] ?? [`0:[null]
1061
1177
  `]).join("");
@@ -1085,12 +1201,38 @@ function createRSCStream(rscName, data) {
1085
1201
  });
1086
1202
  }
1087
1203
 
1204
+ // src/runtime/rsc-imports.ts
1205
+ async function importRSCClientBrowser() {
1206
+ try {
1207
+ return await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1208
+ } catch {
1209
+ const mod = await import("react-server-dom-webpack/client.browser");
1210
+ return mod.default ?? mod;
1211
+ }
1212
+ }
1213
+
1088
1214
  // src/runtime/turbopack/patterns.ts
1215
+ var MODULE_ID_PATTERN = '"[^"]+"|[0-9]+';
1216
+ function stripQuotes(value) {
1217
+ if (value.startsWith('"') && value.endsWith('"')) {
1218
+ return value.slice(1, -1);
1219
+ }
1220
+ return value;
1221
+ }
1222
+ function extractGroup(re, input, group) {
1223
+ const raw = re.exec(input)?.groups?.[group];
1224
+ return raw ? stripQuotes(raw) : void 0;
1225
+ }
1089
1226
  var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
1090
- var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
1091
- var ASYNC_MODULE_LOADER_RE = /(?:__turbopack_context__|e)\.A\((?<asyncSharedModuleId>[0-9]+)\)/;
1092
- var ASYNC_MODULE_RESOLVE_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<inner>parentImport|e)=>Promise\.resolve\(\)\.then\(\(\)=>\k<inner>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
1093
- 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]+)\)\)\)\}/;
1227
+ var REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(
1228
+ `\\.TURBOPACK_REMOTE_SHARED\\s*=\\s*await (?:__turbopack_context__|[a-z])\\.A\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1229
+ );
1230
+ var ASYNC_MODULE_LOADER_RE = new RegExp(
1231
+ `(?:__turbopack_context__|[a-z])\\.A\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\)`
1232
+ );
1233
+ var ASYNC_MODULE_CALLBACK_RE = new RegExp(
1234
+ `(?:parentImport|[a-z])\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1235
+ );
1094
1236
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
1095
1237
 
1096
1238
  // src/runtime/turbopack/chunk-loader.ts
@@ -1100,6 +1242,7 @@ function loadChunkWithScope(scope, chunkId) {
1100
1242
  `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
1101
1243
  );
1102
1244
  const self = globalThis;
1245
+ const ns = getNamespace();
1103
1246
  const { bundle, path, prefix } = parseRemoteId(chunkId);
1104
1247
  const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
1105
1248
  if (remoteRuntime === RUNTIME_WEBPACK) {
@@ -1110,35 +1253,31 @@ function loadChunkWithScope(scope, chunkId) {
1110
1253
  if (url.endsWith(".css")) {
1111
1254
  return;
1112
1255
  }
1113
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1114
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
1115
- }
1116
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1117
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1256
+ if (ns.chunkCache[url]) {
1257
+ logDebug("ChunkLoader", `Cache hit for "${chunkId}" (url="${url}")`);
1258
+ return ns.chunkCache[url];
1118
1259
  }
1119
1260
  const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1120
1261
  if (resolvedUrl !== url) {
1121
1262
  logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1122
1263
  }
1123
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1124
- (resolve, reject) => {
1125
- fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1126
- const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1127
- if (hasTurbopack) {
1128
- return handleTurbopackChunk(code, scope, url);
1129
- }
1130
- }).then(resolve).catch((error) => {
1131
- const isProxied = isProxiedUrl(resolvedUrl);
1132
- if (isProxied) {
1133
- reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1134
- } else {
1135
- warnCrossOriginFetchError("ChunkLoader", url);
1136
- reject(error);
1137
- }
1138
- });
1139
- }
1140
- );
1141
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1264
+ ns.chunkCache[url] = new Promise((resolve, reject) => {
1265
+ fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1266
+ const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1267
+ if (hasTurbopack) {
1268
+ return handleTurbopackChunk(code, scope, url);
1269
+ }
1270
+ }).then(resolve).catch((error) => {
1271
+ const isProxied = isProxiedUrl(resolvedUrl);
1272
+ if (isProxied) {
1273
+ reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1274
+ } else {
1275
+ warnCrossOriginFetchError("ChunkLoader", url);
1276
+ reject(error);
1277
+ }
1278
+ });
1279
+ });
1280
+ return ns.chunkCache[url];
1142
1281
  }
1143
1282
  function createChunkDispatcher() {
1144
1283
  return function __chunk_dispatcher__(chunkId, scriptBundle) {
@@ -1187,19 +1326,39 @@ async function handleTurbopackChunk(code, scope, url) {
1187
1326
  `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1188
1327
  );
1189
1328
  if (!self[`TURBOPACK_${globalKey}`]) {
1190
- const chunkData = [];
1191
- const turbopackObject = {
1192
- push: (item) => {
1193
- if (Array.isArray(item)) {
1194
- chunkData.push(item);
1195
- } else {
1196
- chunkData.push([item]);
1329
+ const wrapPush = (target) => {
1330
+ const originalPush = target.push;
1331
+ if (typeof originalPush !== "function")
1332
+ return target;
1333
+ target.push = (...items) => {
1334
+ for (const item of items) {
1335
+ if (Array.isArray(item)) {
1336
+ for (const entry of item) {
1337
+ scope.turbopackModules.push(entry);
1338
+ }
1339
+ } else {
1340
+ scope.turbopackModules.push(item);
1341
+ }
1197
1342
  }
1198
- return chunkData.length;
1199
- },
1200
- __chunks__: chunkData
1343
+ return originalPush.apply(target, items);
1344
+ };
1345
+ return target;
1201
1346
  };
1202
- self[`TURBOPACK_${globalKey}`] = turbopackObject;
1347
+ const globalProp = `TURBOPACK_${globalKey}`;
1348
+ let currentValue = wrapPush([]);
1349
+ Object.defineProperty(self, globalProp, {
1350
+ get() {
1351
+ return currentValue;
1352
+ },
1353
+ set(newValue) {
1354
+ if (newValue && typeof newValue === "object") {
1355
+ wrapPush(newValue);
1356
+ }
1357
+ currentValue = newValue;
1358
+ },
1359
+ configurable: true,
1360
+ enumerable: true
1361
+ });
1203
1362
  }
1204
1363
  await new Promise((scriptResolve, scriptReject) => {
1205
1364
  const blob = new Blob([transformedCode], {
@@ -1251,13 +1410,13 @@ async function handleTurbopackChunk(code, scope, url) {
1251
1410
  // src/runtime/turbopack/shared-modules.ts
1252
1411
  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).";
1253
1412
  function getTurbopackModules(scope) {
1413
+ if (scope.turbopackModules.length > 0) {
1414
+ return scope.turbopackModules;
1415
+ }
1254
1416
  const self = globalThis;
1255
1417
  const raw = self[`TURBOPACK_${scope.globalKey}`];
1256
1418
  if (!raw)
1257
1419
  return void 0;
1258
- if (typeof raw === "object" && "__chunks__" in raw) {
1259
- return raw.__chunks__.flat();
1260
- }
1261
1420
  if (Array.isArray(raw)) {
1262
1421
  return raw.flat();
1263
1422
  }
@@ -1281,7 +1440,11 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1281
1440
  if (sharedModuleInitializerIndex > 0) {
1282
1441
  const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1283
1442
  const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1284
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1443
+ const sharedModuleId = extractGroup(
1444
+ REMOTE_SHARED_ASSIGNMENT_RE,
1445
+ sharedModuleInitializerCode,
1446
+ "sharedModuleId"
1447
+ );
1285
1448
  if (sharedModuleId) {
1286
1449
  const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1287
1450
  scope,
@@ -1339,20 +1502,22 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1339
1502
  }
1340
1503
  function extractSharedModuleIds(shared2, scope) {
1341
1504
  return Object.entries(shared2).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1342
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1505
+ const asyncSharedModuleId = extractGroup(
1506
+ ASYNC_MODULE_LOADER_RE,
1507
+ value.toString(),
1508
+ "asyncSharedModuleId"
1509
+ );
1343
1510
  if (asyncSharedModuleId) {
1344
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1345
- let asyncSharedModule;
1346
- const turbopackModules = getTurbopackModules(scope) ?? [];
1347
- const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1348
- asyncSharedModuleIdNumber
1511
+ const asyncSharedModule = findModuleInit(
1512
+ getTurbopackModules(scope),
1513
+ asyncSharedModuleId
1349
1514
  );
1350
- if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1351
- asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1352
- }
1353
1515
  if (asyncSharedModule) {
1354
- const asyncSharedModuleCode = asyncSharedModule.toString();
1355
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1516
+ const sharedModuleId = extractGroup(
1517
+ ASYNC_MODULE_CALLBACK_RE,
1518
+ asyncSharedModule.toString(),
1519
+ "sharedModuleId"
1520
+ );
1356
1521
  acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1357
1522
  "__remote_shared_module_",
1358
1523
  ""
@@ -1443,9 +1608,17 @@ function findModuleInit(modules, moduleId) {
1443
1608
  if (idx >= 0) {
1444
1609
  return flat.slice(idx + 1).find((e) => typeof e === "function");
1445
1610
  }
1446
- return flat.find(
1447
- (e) => Boolean(e && typeof e === "object" && moduleId in e)
1448
- )?.[moduleId];
1611
+ for (const entry of flat) {
1612
+ if (!entry || typeof entry !== "object")
1613
+ continue;
1614
+ const obj = entry;
1615
+ if (moduleId in obj)
1616
+ return obj[moduleId];
1617
+ const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));
1618
+ if (prefixKey)
1619
+ return obj[prefixKey];
1620
+ }
1621
+ return void 0;
1449
1622
  }
1450
1623
  function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1451
1624
  const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
@@ -1524,7 +1697,10 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1524
1697
  }
1525
1698
  if (typeof mod !== "object" || mod === null) {
1526
1699
  mod = { default: mod };
1527
- } else if (!("default" in mod) && mod.toString() !== "[object Module]") {
1700
+ } else if (!("default" in mod) && // ES module namespace objects have a null prototype, so calling
1701
+ // mod.toString() directly throws. Use Object.prototype.toString
1702
+ // to safely detect them.
1703
+ Object.prototype.toString.call(mod) !== "[object Module]") {
1528
1704
  try {
1529
1705
  mod.default = mod;
1530
1706
  } catch {
@@ -1588,21 +1764,38 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1588
1764
  };
1589
1765
  }
1590
1766
 
1591
- // src/runtime/turbopack/webpack-runtime.ts
1592
- async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared2 = {}, remoteShared = {}, resolveClientUrl) {
1767
+ // src/runtime/turbopack/remote-scope-setup.ts
1768
+ async function setupRemoteScope(runtime, scripts = [], url = new URL(location.href), bundle, resolveClientUrl) {
1593
1769
  const self = globalThis;
1770
+ const ns = getNamespace();
1594
1771
  const bundleName = bundle ?? "default";
1772
+ const existingScope = getScope(bundleName);
1773
+ if (existingScope && existingScope.url.origin === url.origin) {
1774
+ logDebug(
1775
+ "WebpackRuntime",
1776
+ `Reusing scope "${existingScope.scopedName}" (turbopackModules=${existingScope.turbopackModules.length})`
1777
+ );
1778
+ existingScope.resolveClientUrl = resolveClientUrl;
1779
+ if (runtime === RUNTIME_TURBOPACK) {
1780
+ await Promise.allSettled(
1781
+ scripts.map(
1782
+ (script) => script.src ? loadChunkWithScope(existingScope, script.src) : Promise.resolve(void 0)
1783
+ )
1784
+ );
1785
+ }
1786
+ return existingScope;
1787
+ }
1595
1788
  const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1596
1789
  registerScope(scope);
1597
- if (!self.__remote_bundle_url__) {
1598
- self.__remote_bundle_url__ = {};
1790
+ if (runtime === RUNTIME_WEBPACK && self.__remote_webpack_require__?.[bundleName]) {
1791
+ scope.webpackRequire = self.__remote_webpack_require__[bundleName];
1599
1792
  }
1600
- self.__remote_bundle_url__[bundleName] = url;
1793
+ ns.bundleUrls[bundleName] = url;
1601
1794
  if (scope.scopedName !== bundleName) {
1602
- self.__remote_bundle_url__[scope.scopedName] = url;
1795
+ ns.bundleUrls[scope.scopedName] = url;
1603
1796
  }
1604
1797
  self.__webpack_get_script_filename__ = () => null;
1605
- const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1798
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || ns.dispatcherRuntime !== "turbopack";
1606
1799
  if (willCreateDispatchers) {
1607
1800
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1608
1801
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
@@ -1610,6 +1803,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1610
1803
  }
1611
1804
  self.__webpack_chunk_load__ = createChunkDispatcher();
1612
1805
  self.__webpack_require__ = createModuleDispatcher(runtime);
1806
+ ns.dispatcherRuntime = runtime;
1613
1807
  self.__webpack_require_type__ = runtime;
1614
1808
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1615
1809
  self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
@@ -1637,15 +1831,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1637
1831
  }
1638
1832
  }
1639
1833
  }
1640
- const coreShared = {
1641
- react: async () => (await import("react")).default,
1642
- "react-dom": async () => (await import("react-dom")).default,
1643
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
1644
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
1645
- "react-dom/client": async () => (await import("react-dom/client")).default,
1646
- ...shared2
1647
- };
1648
- await initializeSharedModules(scope, coreShared, remoteShared);
1834
+ return scope;
1649
1835
  }
1650
1836
  function createModuleDispatcher(runtime) {
1651
1837
  return (id) => {
@@ -1662,6 +1848,9 @@ function createModuleDispatcher(runtime) {
1662
1848
  );
1663
1849
  try {
1664
1850
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1851
+ const scope2 = getScope(bundle);
1852
+ if (scope2?.webpackRequire)
1853
+ return scope2.webpackRequire(moduleId);
1665
1854
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1666
1855
  }
1667
1856
  const scope = getScope(bundleName);
@@ -1779,44 +1968,33 @@ async function loadRemoteComponent({
1779
1968
  "ComponentLoader",
1780
1969
  `Remote shared modules requested: ${JSON.stringify(remoteShared)}`
1781
1970
  );
1782
- await setupWebpackRuntime(
1971
+ const scope = await setupRemoteScope(
1783
1972
  runtime,
1784
1973
  scripts,
1785
1974
  url,
1786
1975
  bundle,
1787
- hostShared,
1788
- remoteShared,
1789
1976
  resolveClientUrl
1790
1977
  );
1978
+ if (runtime === "turbopack") {
1979
+ await initializeSharedModules(
1980
+ scope,
1981
+ buildCoreShared(hostShared),
1982
+ remoteShared
1983
+ );
1984
+ }
1791
1985
  if (bundle) {
1792
- const resolve = {
1793
- "/react/index.js": React,
1794
- "/react/jsx-dev-runtime.js": JSXDevRuntime,
1795
- "/react/jsx-runtime.js": JSXRuntime,
1796
- "/react-dom/index.js": ReactDOM,
1797
- "/react-dom/client.js": ReactDOMClient,
1798
- ...Object.entries(remoteShared).reduce(
1799
- (acc, [key, value]) => {
1800
- if (typeof hostShared[value] !== "undefined") {
1801
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
1802
- } else {
1803
- logDebug(
1804
- "ComponentLoader",
1805
- `Remote requests "${value}" but host doesn't provide it`
1806
- );
1807
- }
1808
- return acc;
1809
- },
1810
- {}
1811
- )
1812
- };
1813
- await Promise.all(
1814
- Object.entries(resolve).map(async ([key, value]) => {
1815
- if (typeof value === "function") {
1816
- resolve[key] = await value(bundle);
1817
- }
1818
- return Promise.resolve(value);
1819
- })
1986
+ const resolve = await buildWebpackResolve(
1987
+ hostShared,
1988
+ remoteShared,
1989
+ bundle,
1990
+ {
1991
+ "/react/index.js": React,
1992
+ "/react/jsx-dev-runtime.js": JSXDevRuntime,
1993
+ "/react/jsx-runtime.js": JSXRuntime,
1994
+ "/react-dom/index.js": ReactDOM,
1995
+ "/react-dom/client.js": ReactDOMClient
1996
+ },
1997
+ "ComponentLoader"
1820
1998
  );
1821
1999
  applySharedModules(bundle, resolve);
1822
2000
  } else {
@@ -1844,19 +2022,8 @@ async function loadRemoteComponent({
1844
2022
  };
1845
2023
  }
1846
2024
  }
1847
- async function importCreateFromReadableStream() {
1848
- try {
1849
- const { createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1850
- return createFromReadableStream;
1851
- } catch {
1852
- const {
1853
- default: { createFromReadableStream }
1854
- } = await import("react-server-dom-webpack/client.browser");
1855
- return createFromReadableStream;
1856
- }
1857
- }
1858
2025
  async function loadRSCComponent(rscName, data) {
1859
- const createFromReadableStream = await importCreateFromReadableStream();
2026
+ const { createFromReadableStream } = await importRSCClientBrowser();
1860
2027
  if (typeof createFromReadableStream !== "function") {
1861
2028
  throw new RemoteComponentsError(
1862
2029
  'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
@@ -1920,10 +2087,9 @@ async function importViaCallback(absoluteSrc, resolveClientUrl) {
1920
2087
  URL.revokeObjectURL(moduleBlobUrl);
1921
2088
  URL.revokeObjectURL(wrapperBlobUrl);
1922
2089
  }
1923
- const registry = globalThis.__rc_module_registry__;
1924
- const mod = registry?.[absoluteSrc] ?? {};
1925
- if (registry)
1926
- delete registry[absoluteSrc];
2090
+ const registry = getNamespace().moduleRegistry;
2091
+ const mod = registry[absoluteSrc] ?? {};
2092
+ delete registry[absoluteSrc];
1927
2093
  return mod;
1928
2094
  }
1929
2095
  async function importDirectly(absoluteSrc) {
@@ -1953,12 +2119,12 @@ function resolveScriptSrc(script, url) {
1953
2119
  return rawSrc;
1954
2120
  }
1955
2121
  async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1956
- const self = globalThis;
1957
- if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1958
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
2122
+ const ns = getNamespace();
2123
+ if (ns.mountFns[url.href]) {
2124
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1959
2125
  }
1960
- if (self.__remote_script_entrypoint_unmount__?.[url.href]) {
1961
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
2126
+ if (ns.unmountFns[url.href]) {
2127
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1962
2128
  }
1963
2129
  const mountUnmountSets = await Promise.all(
1964
2130
  scripts.map(async (script) => {
@@ -1970,25 +2136,19 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1970
2136
  URL.revokeObjectURL(src);
1971
2137
  }
1972
2138
  if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
1973
- if (!self.__remote_script_entrypoint_mount__) {
1974
- self.__remote_script_entrypoint_mount__ = {};
1975
- }
1976
- if (!self.__remote_script_entrypoint_mount__[url.href]) {
1977
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
2139
+ if (!ns.mountFns[url.href]) {
2140
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1978
2141
  }
1979
- self.__remote_script_entrypoint_mount__[url.href]?.add(
2142
+ ns.mountFns[url.href]?.add(
1980
2143
  mod.mount || mod.default?.mount || (() => {
1981
2144
  })
1982
2145
  );
1983
2146
  }
1984
2147
  if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
1985
- if (!self.__remote_script_entrypoint_unmount__) {
1986
- self.__remote_script_entrypoint_unmount__ = {};
2148
+ if (!ns.unmountFns[url.href]) {
2149
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1987
2150
  }
1988
- if (!self.__remote_script_entrypoint_unmount__[url.href]) {
1989
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
1990
- }
1991
- self.__remote_script_entrypoint_unmount__[url.href]?.add(
2151
+ ns.unmountFns[url.href]?.add(
1992
2152
  mod.unmount || mod.default?.unmount || (() => {
1993
2153
  })
1994
2154
  );
@@ -2027,6 +2187,188 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
2027
2187
  );
2028
2188
  }
2029
2189
 
2190
+ // src/host/shared/pipeline.ts
2191
+ function preparePipeline(input) {
2192
+ const parser = new DOMParser();
2193
+ const doc = parser.parseFromString(input.html, "text/html");
2194
+ const parsed = parseRemoteComponentDocument(doc, input.name, input.url);
2195
+ const remoteShared = input.remoteShared ?? parsed.remoteShared;
2196
+ if ("__remote_components_missing_shared__" in remoteShared) {
2197
+ throw new RemoteComponentsError(
2198
+ remoteShared.__remote_components_missing_shared__
2199
+ );
2200
+ }
2201
+ applyOriginToNodes(doc, input.url, input.resolveClientUrl);
2202
+ const scriptDescriptors = buildScriptDescriptors(parsed.scripts, input.url);
2203
+ return { doc, parsed, scriptDescriptors };
2204
+ }
2205
+ async function loadPrepared(input) {
2206
+ const { prepared, url, signal, resolveClientUrl, container, rscName } = input;
2207
+ const { doc, parsed, scriptDescriptors } = prepared;
2208
+ if (signal.aborted) {
2209
+ return { status: "aborted" };
2210
+ }
2211
+ const userShared = await input.shared;
2212
+ if (signal.aborted) {
2213
+ return { status: "aborted" };
2214
+ }
2215
+ if (parsed.isRemoteComponent) {
2216
+ return loadStaticPath({
2217
+ parsed,
2218
+ doc,
2219
+ url,
2220
+ resolveClientUrl
2221
+ });
2222
+ }
2223
+ return loadDynamicPath({
2224
+ parsed,
2225
+ doc,
2226
+ url,
2227
+ scriptDescriptors,
2228
+ shared: userShared,
2229
+ resolveClientUrl,
2230
+ container,
2231
+ rscName
2232
+ });
2233
+ }
2234
+ function buildScriptDescriptors(scripts, url) {
2235
+ return scripts.map((script) => {
2236
+ const scriptSrc = script.getAttribute("data-src") || script.getAttribute("src") || script.src;
2237
+ const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(scriptSrc)?.groups ?? {
2238
+ prefix: void 0,
2239
+ id: scriptSrc
2240
+ };
2241
+ return {
2242
+ src: new URL(collapseDoubleSlashes(`${prefix ?? ""}${path}`), url).href
2243
+ };
2244
+ });
2245
+ }
2246
+ async function loadStaticPath(input) {
2247
+ const { parsed, doc, url, resolveClientUrl } = input;
2248
+ const scripts = Array.from(
2249
+ parsed.component.querySelectorAll("script")
2250
+ );
2251
+ const { mount, unmount } = await loadStaticRemoteComponent(
2252
+ scripts,
2253
+ url,
2254
+ resolveClientUrl
2255
+ );
2256
+ return {
2257
+ status: "static",
2258
+ mount,
2259
+ unmount,
2260
+ metadata: parsed.metadata,
2261
+ parsed,
2262
+ doc
2263
+ };
2264
+ }
2265
+ async function loadDynamicPath(input) {
2266
+ const {
2267
+ parsed,
2268
+ doc,
2269
+ url,
2270
+ scriptDescriptors,
2271
+ shared: shared2,
2272
+ resolveClientUrl,
2273
+ container
2274
+ } = input;
2275
+ const rscName = input.rscName ?? (parsed.rsc ? `__remote_component_rsc_${escapeString(url.href)}_${escapeString(parsed.name)}` : void 0);
2276
+ const rscData = parsed.rsc ? (parsed.rsc.textContent || "").split("\n").filter(Boolean) : [];
2277
+ const result = await loadRemoteComponent({
2278
+ url,
2279
+ name: parsed.name,
2280
+ rscName,
2281
+ bundle: parsed.metadata.bundle,
2282
+ route: parsed.metadata.route,
2283
+ runtime: parsed.metadata.runtime,
2284
+ data: rscData,
2285
+ nextData: parsed.nextData,
2286
+ scripts: scriptDescriptors,
2287
+ shared: buildHostShared(shared2, resolveClientUrl),
2288
+ remoteShared: parsed.remoteShared,
2289
+ container,
2290
+ resolveClientUrl
2291
+ });
2292
+ if (result.error) {
2293
+ return { status: "error", error: result.error };
2294
+ }
2295
+ return {
2296
+ status: "loaded",
2297
+ component: result.component,
2298
+ metadata: parsed.metadata,
2299
+ parsed,
2300
+ doc
2301
+ };
2302
+ }
2303
+
2304
+ // src/host/shared/state.ts
2305
+ function createHostState() {
2306
+ return {
2307
+ stage: "idle",
2308
+ prevSrc: void 0,
2309
+ prevUrl: void 0,
2310
+ prevName: void 0,
2311
+ prevIsRemoteComponent: false,
2312
+ abortController: void 0
2313
+ };
2314
+ }
2315
+
2316
+ // src/host/utils/resolve-name-from-src.ts
2317
+ function resolveNameFromSrc(src, defaultName) {
2318
+ if (!src) {
2319
+ return defaultName;
2320
+ }
2321
+ const hash = typeof src === "string" ? src : src.hash;
2322
+ const hashIndex = hash.indexOf("#");
2323
+ if (hashIndex < 0) {
2324
+ return defaultName;
2325
+ }
2326
+ const name = hash.slice(hashIndex + 1);
2327
+ return name || defaultName;
2328
+ }
2329
+
2330
+ // src/runtime/html/set-attributes-from-props.ts
2331
+ var DOMAttributeNames = {
2332
+ acceptCharset: "accept-charset",
2333
+ className: "class",
2334
+ htmlFor: "for",
2335
+ httpEquiv: "http-equiv",
2336
+ noModule: "noModule"
2337
+ };
2338
+ var ignoreProps = [
2339
+ "onLoad",
2340
+ "onReady",
2341
+ "dangerouslySetInnerHTML",
2342
+ "children",
2343
+ "onError",
2344
+ "strategy",
2345
+ "stylesheets"
2346
+ ];
2347
+ function isBooleanScriptAttribute(attr) {
2348
+ return ["async", "defer", "noModule"].includes(attr);
2349
+ }
2350
+ function setAttributesFromProps(el, props) {
2351
+ for (const [p, value] of Object.entries(props)) {
2352
+ if (!Object.hasOwn(props, p))
2353
+ continue;
2354
+ if (ignoreProps.includes(p))
2355
+ continue;
2356
+ if (value === void 0) {
2357
+ continue;
2358
+ }
2359
+ const attr = DOMAttributeNames[p] || p.toLowerCase();
2360
+ if (el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr)) {
2361
+ el[attr] = Boolean(value);
2362
+ } else {
2363
+ el.setAttribute(attr, String(value));
2364
+ }
2365
+ if (value === false || el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr) && (!value || value === "false")) {
2366
+ el.setAttribute(attr, "");
2367
+ el.removeAttribute(attr);
2368
+ }
2369
+ }
2370
+ }
2371
+
2030
2372
  // src/host/react/hooks/use-resolve-client-url.ts
2031
2373
  import { useMemo } from "react";
2032
2374
  import { useRemoteComponentsContext } from "#internal/host/react/context";
@@ -2045,27 +2387,25 @@ function useShadowRoot({
2045
2387
  }) {
2046
2388
  const shadowRootContainerRef = useRef(null);
2047
2389
  const [shadowRoot, setShadowRoot] = useState(() => {
2048
- const self = globalThis;
2049
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2390
+ const shadowRoots = getNamespace().shadowRoots;
2050
2391
  const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
2051
2392
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2052
- )?.shadowRoot ?? self[shadowRootKey] ?? null : null;
2053
- self[shadowRootKey] = null;
2393
+ )?.shadowRoot ?? shadowRoots[keySuffix] ?? null : null;
2394
+ shadowRoots[keySuffix] = null;
2054
2395
  return ssrShadowRoot;
2055
2396
  });
2056
2397
  useLayoutEffect(() => {
2398
+ const shadowRoots = getNamespace().shadowRoots;
2057
2399
  if (isolate !== false && typeof document !== "undefined" && (!shadowRoot || !shadowRoot.isConnected)) {
2058
- const self = globalThis;
2059
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2060
2400
  let shadowRootElement = null;
2061
2401
  const element = document.querySelector(
2062
2402
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2063
2403
  );
2064
- shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;
2404
+ shadowRootElement = shadowRoots[keySuffix] ?? element?.shadowRoot ?? null;
2065
2405
  if (!shadowRootElement && element) {
2066
2406
  try {
2067
2407
  shadowRootElement = element.attachShadow({ mode });
2068
- self[shadowRootKey] = shadowRootElement;
2408
+ shadowRoots[keySuffix] = shadowRootElement;
2069
2409
  } catch {
2070
2410
  }
2071
2411
  }
@@ -2076,9 +2416,7 @@ function useShadowRoot({
2076
2416
  setShadowRoot(shadowRootElement);
2077
2417
  }
2078
2418
  } else if (isolate === false && shadowRoot) {
2079
- const self = globalThis;
2080
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2081
- self[shadowRootKey] = null;
2419
+ shadowRoots[keySuffix] = null;
2082
2420
  setShadowRoot(null);
2083
2421
  }
2084
2422
  }, [isolate, shadowRoot, mode, keySuffix]);
@@ -2109,7 +2447,7 @@ function getRemoteComponentHtml(html) {
2109
2447
 
2110
2448
  // src/host/react/index.tsx
2111
2449
  import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
2112
- import { createElement as createElement2 } from "react";
2450
+ import { createElement as createElement3 } from "react";
2113
2451
  function ConsumeRemoteComponent({
2114
2452
  src,
2115
2453
  isolate,
@@ -2131,6 +2469,10 @@ function ConsumeRemoteComponent({
2131
2469
  const { credentials: contextCredentials, shared: contextShared } = useRemoteComponentsContext2();
2132
2470
  const credentials = credentialsProp ?? contextCredentials ?? "same-origin";
2133
2471
  const shared2 = sharedProp ?? contextShared ?? {};
2472
+ const emitter = useMemo2(
2473
+ () => makeReactEmitter({ onBeforeLoad, onLoad, onError, onChange }),
2474
+ [onBeforeLoad, onLoad, onError, onChange]
2475
+ );
2134
2476
  const name = useMemo2(
2135
2477
  () => resolveNameFromSrc(src, nameProp),
2136
2478
  [src, nameProp]
@@ -2174,9 +2516,8 @@ function ConsumeRemoteComponent({
2174
2516
  const prevRemoteComponentContainerRef = useRef2(null);
2175
2517
  const unmountRef = useRef2(null);
2176
2518
  useLayoutEffect2(() => {
2177
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2178
2519
  return () => {
2179
- delete globalThis[shadowRootKey];
2520
+ delete getNamespace().shadowRoots[keySuffix];
2180
2521
  };
2181
2522
  }, [keySuffix]);
2182
2523
  useLayoutEffect2(() => {
@@ -2221,7 +2562,7 @@ function ConsumeRemoteComponent({
2221
2562
  hostStateRef.current.abortController?.abort();
2222
2563
  hostStateRef.current.abortController = new AbortController();
2223
2564
  const { signal } = hostStateRef.current.abortController;
2224
- onBeforeLoad?.(src);
2565
+ emitter.beforeLoad(src);
2225
2566
  hostStateRef.current.stage = "loading";
2226
2567
  startTransition(async () => {
2227
2568
  try {
@@ -2252,26 +2593,32 @@ function ConsumeRemoteComponent({
2252
2593
  }
2253
2594
  if (signal.aborted)
2254
2595
  return;
2255
- const parser = new DOMParser();
2256
- const doc = parser.parseFromString(html, "text/html");
2596
+ const userShared = await shared2;
2597
+ if (signal.aborted)
2598
+ return;
2599
+ const prepared = preparePipeline({
2600
+ html,
2601
+ name,
2602
+ url,
2603
+ shared: userShared,
2604
+ resolveClientUrl
2605
+ });
2606
+ const { doc, parsed } = prepared;
2257
2607
  const {
2258
2608
  component,
2259
2609
  name: remoteName,
2260
2610
  isRemoteComponent,
2261
2611
  metadata,
2262
- nextData,
2263
2612
  rsc,
2264
2613
  remoteShared,
2265
- links: linkElements,
2266
- scripts: scriptElements
2267
- } = parseRemoteComponentDocument(doc, name, url);
2614
+ links: linkElements
2615
+ } = parsed;
2268
2616
  if (hostStateRef.current.prevIsRemoteComponent) {
2269
2617
  if (shadowRoot) {
2270
2618
  shadowRoot.innerHTML = "";
2271
2619
  }
2272
- const self = globalThis;
2273
2620
  const prevUrl = hostStateRef.current.prevUrl;
2274
- if (prevUrl && self.__remote_script_entrypoint_unmount__?.[prevUrl.href]) {
2621
+ if (prevUrl && getNamespace().unmountFns[prevUrl.href]) {
2275
2622
  const unmountPromises = Promise.all(
2276
2623
  Array.from(unmountRef.current ?? []).map(
2277
2624
  async (unmount) => unmount(
@@ -2286,7 +2633,6 @@ function ConsumeRemoteComponent({
2286
2633
  hostStateRef.current.prevIsRemoteComponent = isRemoteComponent;
2287
2634
  hostStateRef.current.prevUrl = url;
2288
2635
  hostStateRef.current.prevName = remoteName;
2289
- applyOriginToNodes(doc, url, resolveClientUrl);
2290
2636
  const links = linkElements.map((link) => ({
2291
2637
  href: new URL(link.getAttribute("href") ?? link.href, url).href,
2292
2638
  ...link.getAttributeNames().reduce((acc, key) => {
@@ -2296,7 +2642,6 @@ function ConsumeRemoteComponent({
2296
2642
  return acc;
2297
2643
  }, {})
2298
2644
  }));
2299
- const scripts = scriptElements;
2300
2645
  const inlineScripts = (isRemoteComponent ? component : doc).querySelectorAll(
2301
2646
  "script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])"
2302
2647
  );
@@ -2375,20 +2720,10 @@ function ConsumeRemoteComponent({
2375
2720
  componentHydrationHtml.current = `${Array.from(
2376
2721
  doc.querySelectorAll("link,style")
2377
2722
  ).map((link) => link.outerHTML).join("")}${reset ? `<style data-remote-components-reset="">:host { all: initial; }</style>` : ""}${component.innerHTML}`;
2378
- const userShared = await shared2;
2379
- if ("__remote_components_missing_shared__" in userShared) {
2380
- userShared.__remote_components_missing_shared__().catch((e) => {
2381
- throw e;
2382
- });
2383
- } else if ("__remote_components_missing_shared__" in remoteShared) {
2384
- throw new RemoteComponentsError(
2385
- remoteShared.__remote_components_missing_shared__
2386
- );
2387
- }
2388
2723
  if (isRemoteComponent) {
2389
2724
  if (previousSrc !== void 0) {
2390
- onChange?.({
2391
- previousSrc,
2725
+ emitter.change({
2726
+ previousSrc: previousSrc ?? null,
2392
2727
  nextSrc: src,
2393
2728
  previousName,
2394
2729
  nextName: remoteName
@@ -2409,7 +2744,7 @@ function ConsumeRemoteComponent({
2409
2744
  await Promise.all(
2410
2745
  Array.from(mount).map((mountFn) => mountFn(shadowRoot))
2411
2746
  );
2412
- onLoad?.(src);
2747
+ emitter.load(src);
2413
2748
  } else if (isolate === false) {
2414
2749
  setRemoteComponent(
2415
2750
  // TODO: remove wrapper div by converting HTML to RSC or React tree
@@ -2433,62 +2768,42 @@ function ConsumeRemoteComponent({
2433
2768
  (mountFn) => mountFn(prevRemoteComponentContainerRef.current)
2434
2769
  )
2435
2770
  );
2436
- onLoad?.(src);
2771
+ emitter.load(src);
2437
2772
  }
2438
2773
  hostStateRef.current.stage = "loaded";
2439
2774
  } else {
2440
- const result = await loadRemoteComponent({
2775
+ const result = await loadPrepared({
2776
+ prepared,
2441
2777
  url,
2442
- name: remoteName,
2443
- rscName,
2444
- bundle: metadata.bundle,
2445
- route: metadata.route,
2446
- runtime: metadata.runtime,
2447
- data: newData.data,
2448
- nextData,
2449
- scripts: Array.from(scripts).map((script) => {
2450
- const scriptSrc = script.getAttribute("data-src") || script.getAttribute("src") || script.src;
2451
- const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(
2452
- scriptSrc
2453
- )?.groups ?? {
2454
- prefix: void 0,
2455
- id: scriptSrc
2456
- };
2457
- return {
2458
- src: new URL(
2459
- collapseDoubleSlashes(`${prefix ?? ""}${path}`),
2460
- url
2461
- ).href
2462
- };
2463
- }),
2464
- shared: {
2465
- ...sharedPolyfills(userShared, resolveClientUrl),
2466
- ...userShared
2467
- },
2468
- remoteShared,
2778
+ signal,
2779
+ shared: userShared,
2780
+ resolveClientUrl,
2469
2781
  container: shadowRoot,
2470
- resolveClientUrl
2782
+ rscName
2471
2783
  });
2472
2784
  if (rsc) {
2473
2785
  rsc.remove();
2474
2786
  }
2475
2787
  setData(newData);
2476
2788
  if (previousSrc !== void 0) {
2477
- onChange?.({
2478
- previousSrc,
2789
+ emitter.change({
2790
+ previousSrc: previousSrc ?? null,
2479
2791
  nextSrc: src,
2480
2792
  previousName,
2481
2793
  nextName: remoteName
2482
2794
  });
2483
2795
  }
2484
- if (result.error) {
2796
+ if (result.status === "aborted") {
2797
+ return;
2798
+ }
2799
+ if (result.status === "error") {
2485
2800
  hostStateRef.current.stage = "error";
2486
2801
  setRemoteComponent(result.error);
2487
- onError?.(result.error);
2488
- } else {
2802
+ emitter.error(result.error);
2803
+ } else if (result.status === "loaded") {
2489
2804
  hostStateRef.current.stage = "loaded";
2490
2805
  setRemoteComponent(result.component);
2491
- onLoad?.(src);
2806
+ emitter.load(src);
2492
2807
  }
2493
2808
  }
2494
2809
  } catch (error) {
@@ -2498,7 +2813,7 @@ function ConsumeRemoteComponent({
2498
2813
  }
2499
2814
  hostStateRef.current.stage = "error";
2500
2815
  setRemoteComponent(error);
2501
- onError?.(error);
2816
+ emitter.error(error);
2502
2817
  }
2503
2818
  });
2504
2819
  }
@@ -2512,10 +2827,10 @@ function ConsumeRemoteComponent({
2512
2827
  shadowRoot,
2513
2828
  reset,
2514
2829
  id,
2515
- onBeforeLoad,
2516
- onLoad,
2517
- onError,
2518
- onChange,
2830
+ emitter.beforeLoad,
2831
+ emitter.load,
2832
+ emitter.error,
2833
+ emitter.change,
2519
2834
  onRequest,
2520
2835
  onResponse,
2521
2836
  resolveClientUrl
@@ -2530,7 +2845,7 @@ function ConsumeRemoteComponent({
2530
2845
  runtime: hostStateRef.current.prevIsRemoteComponent ? RUNTIME_SCRIPT : data?.runtime || RUNTIME_WEBPACK
2531
2846
  }) });
2532
2847
  const resetStyle = reset ? /* @__PURE__ */ jsx2("style", { "data-remote-components-reset": "react", children: `:host { all: initial; }` }) : null;
2533
- const linksToRender = data?.links?.map((link) => /* @__PURE__ */ createElement2(
2848
+ const linksToRender = data?.links?.map((link) => /* @__PURE__ */ createElement3(
2534
2849
  "link",
2535
2850
  {
2536
2851
  ...link,
@@ -2557,7 +2872,7 @@ function ConsumeRemoteComponent({
2557
2872
  );
2558
2873
  }).then(() => {
2559
2874
  if (src) {
2560
- onLoad?.(src);
2875
+ emitter.load(src);
2561
2876
  }
2562
2877
  }).catch((e) => {
2563
2878
  const error = new RemoteComponentsError(
@@ -2567,7 +2882,7 @@ function ConsumeRemoteComponent({
2567
2882
  }
2568
2883
  );
2569
2884
  setRemoteComponent(error);
2570
- onError?.(error);
2885
+ emitter.error(error);
2571
2886
  });
2572
2887
  }
2573
2888
  }
@@ -2596,8 +2911,10 @@ function ConsumeRemoteComponent({
2596
2911
  alt="" decoding="async" style="display:none"
2597
2912
  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
2598
2913
  onload="(function(el){
2914
+ // Capture the shadow root during SSR hydration so the client-side
2915
+ // useShadowRoot hook can find it.
2599
2916
  const root = el.getRootNode();
2600
- globalThis.__remote_components_shadowroot_${keySuffix} = root;
2917
+ globalThis.__remote_components_shadowroot_${keySuffix}=root;
2601
2918
  el.parentElement.remove();
2602
2919
  })(this)"
2603
2920
  />`