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
@@ -152,7 +152,7 @@ Docs: ${CORS_DOCS_URL}`
152
152
 
153
153
  // src/utils/logger.ts
154
154
  var PREFIX = "remote-components";
155
- var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
155
+ var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
156
156
  function logDebug(location2, message) {
157
157
  if (DEBUG) {
158
158
  console.debug(`[${PREFIX}:${location2}]: ${message}`);
@@ -237,6 +237,24 @@ function getClientOrServerUrl(src, serverFallback) {
237
237
  return typeof src === "string" ? new URL(src, fallback) : src;
238
238
  }
239
239
 
240
+ // src/host/shared/lifecycle.ts
241
+ function makeReactEmitter(callbacks) {
242
+ return {
243
+ beforeLoad(src) {
244
+ callbacks.onBeforeLoad?.(src);
245
+ },
246
+ load(src) {
247
+ callbacks.onLoad?.(src);
248
+ },
249
+ error(error, _src) {
250
+ callbacks.onError?.(error);
251
+ },
252
+ change(info) {
253
+ callbacks.onChange?.(info);
254
+ }
255
+ };
256
+ }
257
+
240
258
  // src/utils/index.ts
241
259
  function escapeString(str) {
242
260
  return str.replace(/[^a-z0-9]/g, "_");
@@ -263,6 +281,62 @@ function getBundleKey(bundle) {
263
281
  return escapeString(bundle);
264
282
  }
265
283
 
284
+ // src/runtime/namespace.ts
285
+ var SHADOW_ROOT_PREFIX = "__remote_components_shadowroot_";
286
+ var LEGACY_ALIASES = [
287
+ { global: "__remote_component_scopes__", prop: "scopes" },
288
+ {
289
+ global: "__remote_components_turbopack_chunk_loader_promise__",
290
+ prop: "chunkCache"
291
+ },
292
+ { global: "__remote_script_entrypoint_mount__", prop: "mountFns" },
293
+ { global: "__remote_script_entrypoint_unmount__", prop: "unmountFns" },
294
+ { global: "__remote_bundle_url__", prop: "bundleUrls" },
295
+ { global: "__rc_module_registry__", prop: "moduleRegistry" },
296
+ {
297
+ global: "__remote_component_host_shared_modules__",
298
+ prop: "hostSharedModules"
299
+ },
300
+ { global: "__remote_next_css__", prop: "cssCache" }
301
+ ];
302
+ function getNamespace() {
303
+ const g = globalThis;
304
+ const existing = g.__remote_components__;
305
+ if (existing) {
306
+ return existing;
307
+ }
308
+ const ns = {
309
+ scopes: /* @__PURE__ */ new Map(),
310
+ chunkCache: {},
311
+ mountFns: {},
312
+ unmountFns: {},
313
+ bundleUrls: {},
314
+ moduleRegistry: {},
315
+ dispatcherRuntime: void 0,
316
+ hostSharedModules: {},
317
+ cssCache: {},
318
+ shadowRoots: {}
319
+ };
320
+ const nsRecord = ns;
321
+ for (const { global, prop } of LEGACY_ALIASES) {
322
+ const legacyValue = g[global];
323
+ if (legacyValue != null) {
324
+ nsRecord[prop] = legacyValue;
325
+ }
326
+ g[global] = ns[prop];
327
+ }
328
+ const gRecord = g;
329
+ for (const key of Object.keys(gRecord)) {
330
+ if (key.startsWith(SHADOW_ROOT_PREFIX)) {
331
+ const suffix = key.slice(SHADOW_ROOT_PREFIX.length);
332
+ ns.shadowRoots[suffix] = gRecord[key];
333
+ delete gRecord[key];
334
+ }
335
+ }
336
+ g.__remote_components__ = ns;
337
+ return ns;
338
+ }
339
+
266
340
  // src/runtime/patterns.ts
267
341
  var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
268
342
  var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
@@ -273,11 +347,7 @@ function collapseDoubleSlashes(path) {
273
347
 
274
348
  // src/runtime/turbopack/remote-scope.ts
275
349
  function getRegistry() {
276
- const self = globalThis;
277
- if (!self.__remote_component_scopes__) {
278
- self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
279
- }
280
- return self.__remote_component_scopes__;
350
+ return getNamespace().scopes;
281
351
  }
282
352
  function createScope(name, url, runtime, resolveClientUrl) {
283
353
  const isCrossOrigin = url.origin !== location.origin;
@@ -295,7 +365,8 @@ function createScope(name, url, runtime, resolveClientUrl) {
295
365
  resolveClientUrl,
296
366
  moduleCache: {},
297
367
  sharedModules: {},
298
- moduleGlobal: {}
368
+ moduleGlobal: {},
369
+ turbopackModules: []
299
370
  };
300
371
  }
301
372
  function registerScope(scope) {
@@ -360,9 +431,9 @@ function createRemoteImageLoader(bundle, resolveClientUrl) {
360
431
  // src/host/shared/polyfill.tsx
361
432
  var import_jsx_runtime = require("react/jsx-runtime");
362
433
  function sharedPolyfills(shared, resolveClientUrl) {
363
- const self = globalThis;
434
+ const hostShared = getNamespace().hostSharedModules;
364
435
  const polyfill = {
365
- "next/dist/client/components/navigation": self.__remote_component_host_shared_modules__?.["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
436
+ "next/dist/client/components/navigation": hostShared["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
366
437
  useRouter() {
367
438
  return {
368
439
  push: (routerUrl) => {
@@ -393,7 +464,7 @@ function sharedPolyfills(shared, resolveClientUrl) {
393
464
  },
394
465
  __esModule: true
395
466
  })),
396
- "next/dist/client/app-dir/link": self.__remote_component_host_shared_modules__?.["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
467
+ "next/dist/client/app-dir/link": hostShared["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
397
468
  default: ({
398
469
  scroll: _,
399
470
  replace,
@@ -443,7 +514,7 @@ function sharedPolyfills(shared, resolveClientUrl) {
443
514
  },
444
515
  __esModule: true
445
516
  })),
446
- "next/dist/client/app-dir/form": self.__remote_component_host_shared_modules__?.["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
517
+ "next/dist/client/app-dir/form": hostShared["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
447
518
  default: () => {
448
519
  throw new Error("Next.js <Form> component not implemented");
449
520
  },
@@ -454,17 +525,17 @@ function sharedPolyfills(shared, resolveClientUrl) {
454
525
  // This gives us full next/image fidelity (fill, priority, srcSet, blur
455
526
  // placeholders, error handling) while routing image optimization through the
456
527
  // remote app's /_next/image endpoint.
457
- "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({
528
+ "next/dist/shared/lib/image-loader": hostShared["next/dist/shared/lib/image-loader"] ?? shared?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
458
529
  default: createRemoteImageLoader(bundle, resolveClientUrl),
459
530
  __esModule: true
460
531
  })),
461
- "next/dist/client/script": self.__remote_component_host_shared_modules__?.["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
532
+ "next/dist/client/script": hostShared["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
462
533
  // TODO: implement <Script> component for non-Next.js host applications
463
534
  // do not throw an error for now
464
535
  default: () => null,
465
536
  __esModule: true
466
537
  })),
467
- "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared?.["next/router"] ?? (() => (
538
+ "next/router": hostShared["next/router"] ?? shared?.["next/router"] ?? (() => (
468
539
  // TODO: incomplete implementation
469
540
  Promise.resolve({
470
541
  useRouter() {
@@ -500,34 +571,70 @@ function sharedPolyfills(shared, resolveClientUrl) {
500
571
  return polyfill;
501
572
  }
502
573
 
503
- // src/host/shared/state.ts
504
- function createHostState() {
574
+ // src/host/shared/shared-module-resolver.ts
575
+ var CORE_REACT_PATH_MAP = {
576
+ react: "/react/index.js",
577
+ "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
578
+ "react/jsx-runtime": "/react/jsx-runtime.js",
579
+ "react-dom": "/react-dom/index.js",
580
+ "react-dom/client": "/react-dom/client.js"
581
+ };
582
+ var VENDOR_SHARED = Object.fromEntries(
583
+ Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
584
+ );
585
+ function buildCoreShared(userShared) {
505
586
  return {
506
- stage: "idle",
507
- prevSrc: void 0,
508
- prevUrl: void 0,
509
- prevName: void 0,
510
- prevIsRemoteComponent: false,
511
- abortController: void 0
587
+ react: async () => (await import("react")).default,
588
+ "react-dom": async () => (await import("react-dom")).default,
589
+ "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
590
+ "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
591
+ "react-dom/client": async () => (await import("react-dom/client")).default,
592
+ ...userShared
512
593
  };
513
594
  }
514
-
515
- // src/host/utils/resolve-name-from-src.ts
516
- function resolveNameFromSrc(src, defaultName) {
517
- if (!src) {
518
- return defaultName;
519
- }
520
- const hash = typeof src === "string" ? src : src.hash;
521
- const hashIndex = hash.indexOf("#");
522
- if (hashIndex < 0) {
523
- return defaultName;
524
- }
525
- const name = hash.slice(hashIndex + 1);
526
- return name || defaultName;
595
+ function buildHostShared(userShared, resolveClientUrl, options) {
596
+ const self = globalThis;
597
+ const result = {
598
+ ...sharedPolyfills(userShared, resolveClientUrl),
599
+ ...self.__remote_component_host_shared_modules__,
600
+ ...userShared
601
+ };
602
+ if (options?.includeRemoteComponentShared) {
603
+ Object.assign(result, self.__remote_component_shared__);
604
+ }
605
+ return result;
606
+ }
607
+ async function buildWebpackResolve(hostShared, remoteShared, bundle, reactModules, callerTag = "SharedModuleResolver") {
608
+ const resolve = {
609
+ ...reactModules,
610
+ ...Object.entries(remoteShared).reduce(
611
+ (acc, [key, value]) => {
612
+ if (typeof hostShared[value] !== "undefined") {
613
+ acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
614
+ } else {
615
+ logDebug(
616
+ callerTag,
617
+ `Remote requests "${value}" but host doesn't provide it`
618
+ );
619
+ }
620
+ return acc;
621
+ },
622
+ {}
623
+ )
624
+ };
625
+ await Promise.all(
626
+ Object.entries(resolve).map(async ([key, value]) => {
627
+ if (typeof value === "function") {
628
+ resolve[key] = await value(bundle);
629
+ }
630
+ return Promise.resolve(value);
631
+ })
632
+ );
633
+ return resolve;
527
634
  }
528
635
 
529
- // src/runtime/html/apply-origin.ts
530
- var tagNames = [
636
+ // src/runtime/html/html-spec.ts
637
+ var ORIGIN_REWRITE_TAGS = [
531
638
  "img",
532
639
  "source",
533
640
  "video",
@@ -538,10 +645,37 @@ var tagNames = [
538
645
  "script",
539
646
  "link"
540
647
  ];
648
+ var ID_SUFFIX_RSC = "_rsc";
649
+ var ID_SUFFIX_SSR = "_ssr";
650
+ var ID_SUFFIX_SHARED = "_shared";
651
+ var DATA_BUNDLE = "data-bundle";
652
+ var DATA_ROUTE = "data-route";
653
+ var DATA_RUNTIME = "data-runtime";
654
+ var DATA_TYPE = "data-type";
655
+ var DATA_SRC = "data-src";
656
+ var DATA_REMOTE_COMPONENTS_SHARED = "data-remote-components-shared";
657
+ var TAG_REMOTE_COMPONENT = "remote-component";
658
+ var NEXT_DATA_ID = "__NEXT_DATA__";
659
+ var REMOTE_NEXT_DATA_ID = "__REMOTE_NEXT_DATA__";
660
+ var NEXT_CONTAINER_ID = "__next";
661
+
662
+ // src/runtime/html/rewrite-srcset.ts
663
+ function rewriteSrcset(srcset, base, resolve) {
664
+ return srcset.split(",").map((entry) => {
665
+ const [url, descriptor] = entry.trim().split(/\s+/);
666
+ if (!url)
667
+ return entry;
668
+ const absoluteUrl = new URL(url, base).href;
669
+ const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;
670
+ return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
671
+ }).join(", ");
672
+ }
673
+
674
+ // src/runtime/html/apply-origin.ts
541
675
  function applyOriginToNodes(doc, url, resolveClientUrl) {
542
676
  if (url.origin !== location.origin) {
543
677
  const nodes = doc.querySelectorAll(
544
- tagNames.map(
678
+ ORIGIN_REWRITE_TAGS.map(
545
679
  (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
546
680
  ).join(",")
547
681
  );
@@ -559,29 +693,17 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
559
693
  );
560
694
  }
561
695
  if (node.hasAttribute("srcset")) {
562
- const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
563
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
564
- if (!urlPart)
565
- return entry;
566
- const absoluteUrl = new URL(urlPart, url).href;
567
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
568
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
569
- }).join(", ");
570
- if (srcSet) {
571
- node.setAttribute("srcset", srcSet);
696
+ const raw = node.getAttribute("srcset");
697
+ if (raw) {
698
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
699
+ node.setAttribute("srcset", rewriteSrcset(raw, url, resolve));
572
700
  }
573
701
  }
574
702
  if (node.hasAttribute("imagesrcset")) {
575
- const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
576
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
577
- if (!urlPart)
578
- return entry;
579
- const absoluteUrl = new URL(urlPart, url).href;
580
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
581
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
582
- }).join(", ");
583
- if (srcSet) {
584
- node.setAttribute("imagesrcset", srcSet);
703
+ const raw = node.getAttribute("imagesrcset");
704
+ if (raw) {
705
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
706
+ node.setAttribute("imagesrcset", rewriteSrcset(raw, url, resolve));
585
707
  }
586
708
  }
587
709
  });
@@ -622,26 +744,28 @@ function buildMetadata(attrs, url) {
622
744
 
623
745
  // src/runtime/html/parse-remote-html.ts
624
746
  function validateSingleComponent(doc, name, url) {
625
- 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}"]`)) {
747
+ if (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 && !doc.querySelector(
748
+ `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`
749
+ ) || doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 && !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]`)) {
626
750
  throw multipleRemoteComponentsError(url);
627
751
  }
628
752
  }
629
753
  function findComponentElement(doc, name) {
630
- 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])");
754
+ 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])`);
631
755
  }
632
756
  function parseNextData(doc) {
633
757
  return JSON.parse(
634
- (doc.querySelector("#__NEXT_DATA__") ?? doc.querySelector("#__REMOTE_NEXT_DATA__"))?.textContent ?? "null"
758
+ (doc.querySelector(`#${NEXT_DATA_ID}`) ?? doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`))?.textContent ?? "null"
635
759
  );
636
760
  }
637
761
  function resolveComponentName(component, nextData, fallbackName) {
638
- const isRemoteComponent = component?.tagName.toLowerCase() === "remote-component";
639
- const name = component?.getAttribute("id")?.replace(/_ssr$/, "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
762
+ const isRemoteComponent = component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;
763
+ const name = component?.getAttribute("id")?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
640
764
  return { name, isRemoteComponent };
641
765
  }
642
766
  function extractRemoteShared(doc, name, nextData) {
643
767
  const remoteSharedEl = doc.querySelector(
644
- `#${name}_shared[data-remote-components-shared]`
768
+ `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`
645
769
  );
646
770
  const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
647
771
  remoteSharedEl?.remove();
@@ -662,7 +786,7 @@ function extractLinks(doc, component) {
662
786
  function extractScripts(doc, component, isRemoteComponent) {
663
787
  return Array.from(
664
788
  (isRemoteComponent ? component : doc).querySelectorAll(
665
- "script[src],script[data-src]"
789
+ `script[src],script[${DATA_SRC}]`
666
790
  )
667
791
  );
668
792
  }
@@ -675,15 +799,15 @@ function parseRemoteComponentDocument(doc, name, url) {
675
799
  nextData,
676
800
  name
677
801
  );
678
- const rsc = doc.querySelector(`#${resolvedName}_rsc`);
802
+ const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);
679
803
  const metadata = buildMetadata(
680
804
  {
681
805
  name: resolvedName,
682
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
683
- route: component?.getAttribute("data-route") ?? nextData?.page,
684
- runtime: component?.getAttribute("data-runtime") ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
806
+ bundle: component?.getAttribute(DATA_BUNDLE) || nextData?.props.__REMOTE_COMPONENT__?.bundle,
807
+ route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,
808
+ runtime: component?.getAttribute(DATA_RUNTIME) ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
685
809
  id: component?.getAttribute("id"),
686
- type: component?.getAttribute("data-type")
810
+ type: component?.getAttribute(DATA_TYPE)
687
811
  },
688
812
  url
689
813
  );
@@ -711,48 +835,6 @@ function parseRemoteComponentDocument(doc, name, url) {
711
835
  };
712
836
  }
713
837
 
714
- // src/runtime/html/set-attributes-from-props.ts
715
- var DOMAttributeNames = {
716
- acceptCharset: "accept-charset",
717
- className: "class",
718
- htmlFor: "for",
719
- httpEquiv: "http-equiv",
720
- noModule: "noModule"
721
- };
722
- var ignoreProps = [
723
- "onLoad",
724
- "onReady",
725
- "dangerouslySetInnerHTML",
726
- "children",
727
- "onError",
728
- "strategy",
729
- "stylesheets"
730
- ];
731
- function isBooleanScriptAttribute(attr) {
732
- return ["async", "defer", "noModule"].includes(attr);
733
- }
734
- function setAttributesFromProps(el, props) {
735
- for (const [p, value] of Object.entries(props)) {
736
- if (!Object.hasOwn(props, p))
737
- continue;
738
- if (ignoreProps.includes(p))
739
- continue;
740
- if (value === void 0) {
741
- continue;
742
- }
743
- const attr = DOMAttributeNames[p] || p.toLowerCase();
744
- if (el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr)) {
745
- el[attr] = Boolean(value);
746
- } else {
747
- el.setAttribute(attr, String(value));
748
- }
749
- if (value === false || el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr) && (!value || value === "false")) {
750
- el.setAttribute(attr, "");
751
- el.removeAttribute(attr);
752
- }
753
- }
754
- }
755
-
756
838
  // src/runtime/loaders/component-loader.ts
757
839
  var React = __toESM(require("react"), 1);
758
840
  var JSXDevRuntime = __toESM(require("react/jsx-dev-runtime"), 1);
@@ -772,13 +854,15 @@ function applySharedModules(bundle, resolve) {
772
854
  `Shared modules to resolve: ${Object.keys(resolve)}`
773
855
  );
774
856
  const self = globalThis;
775
- if (self.__remote_webpack_require__?.[bundle]) {
857
+ const scope = getScope(bundle);
858
+ const webpackBundle = scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];
859
+ if (webpackBundle) {
776
860
  const modulePaths = Object.keys(
777
- self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
861
+ self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {}
778
862
  );
779
863
  logDebug(
780
864
  "SharedModules",
781
- `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`
865
+ `Available module paths for bundle "${bundle}": ${modulePaths}`
782
866
  );
783
867
  for (const [key, value] of Object.entries(resolve)) {
784
868
  const exactIds = modulePaths.filter((p) => p === key);
@@ -790,7 +874,6 @@ function applySharedModules(bundle, resolve) {
790
874
  );
791
875
  }
792
876
  for (const id of ids) {
793
- const webpackBundle = self.__remote_webpack_require__[bundle];
794
877
  if (webpackBundle.m) {
795
878
  const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
796
879
  if (resolvedId !== id) {
@@ -888,10 +971,8 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
888
971
  ];
889
972
  const { default: Component } = componentLoader();
890
973
  const { default: App } = appLoader();
891
- if (!self.__remote_next_css__) {
892
- self.__remote_next_css__ = {};
893
- }
894
- if (!self.__remote_next_css__[bundle]) {
974
+ const cssCache = getNamespace().cssCache;
975
+ if (!cssCache[bundle]) {
895
976
  const cssRE = /\.s?css$/;
896
977
  Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
897
978
  self.__remote_webpack_require__?.[bundle]?.(id);
@@ -909,15 +990,15 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
909
990
  node.remove();
910
991
  node = nextCss.previousSibling;
911
992
  }
912
- self.__remote_next_css__[bundle] = elements;
993
+ cssCache[bundle] = elements;
913
994
  }
914
995
  if (styleContainer) {
915
- const elements = self.__remote_next_css__[bundle];
996
+ const elements = cssCache[bundle];
916
997
  elements.forEach((el) => {
917
998
  styleContainer.appendChild(el.cloneNode(true));
918
999
  });
919
1000
  } else {
920
- const elements = self.__remote_next_css__[bundle];
1001
+ const elements = cssCache[bundle];
921
1002
  elements.forEach((el) => {
922
1003
  document.head.appendChild(el);
923
1004
  });
@@ -954,6 +1035,18 @@ function fixPayload(payload) {
954
1035
  }
955
1036
  }
956
1037
  }
1038
+ function buildRSCChunks(rscName, data) {
1039
+ const chunks = [];
1040
+ for (const chunk of data) {
1041
+ for (const line of chunk.split("\n")) {
1042
+ const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1043
+ if (match?.groups?.rsc) {
1044
+ chunks.push(JSON.parse(`"${match.groups.rsc}"`));
1045
+ }
1046
+ }
1047
+ }
1048
+ return chunks;
1049
+ }
957
1050
  function createRSCStream(rscName, data) {
958
1051
  return new import_web_streams_polyfill.ReadableStream({
959
1052
  type: "bytes",
@@ -961,16 +1054,11 @@ function createRSCStream(rscName, data) {
961
1054
  const encoder = new TextEncoder();
962
1055
  const self = globalThis;
963
1056
  if (data.length > 0) {
964
- data.forEach((chunk) => {
965
- const lines = chunk.split("\n");
966
- for (const line of lines) {
967
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
968
- if (match?.groups?.rsc) {
969
- self[rscName] = self[rscName] ?? [];
970
- self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
971
- }
972
- }
973
- });
1057
+ const parsed = buildRSCChunks(rscName, data);
1058
+ if (parsed.length > 0) {
1059
+ self[rscName] = self[rscName] ?? [];
1060
+ self[rscName].push(...parsed);
1061
+ }
974
1062
  }
975
1063
  const allChunks = (self[rscName] ?? [`0:[null]
976
1064
  `]).join("");
@@ -1000,12 +1088,38 @@ function createRSCStream(rscName, data) {
1000
1088
  });
1001
1089
  }
1002
1090
 
1091
+ // src/runtime/rsc-imports.ts
1092
+ async function importRSCClientBrowser() {
1093
+ try {
1094
+ return await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1095
+ } catch {
1096
+ const mod = await import("react-server-dom-webpack/client.browser");
1097
+ return mod.default ?? mod;
1098
+ }
1099
+ }
1100
+
1003
1101
  // src/runtime/turbopack/patterns.ts
1102
+ var MODULE_ID_PATTERN = '"[^"]+"|[0-9]+';
1103
+ function stripQuotes(value) {
1104
+ if (value.startsWith('"') && value.endsWith('"')) {
1105
+ return value.slice(1, -1);
1106
+ }
1107
+ return value;
1108
+ }
1109
+ function extractGroup(re, input, group) {
1110
+ const raw = re.exec(input)?.groups?.[group];
1111
+ return raw ? stripQuotes(raw) : void 0;
1112
+ }
1004
1113
  var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
1005
- var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
1006
- var ASYNC_MODULE_LOADER_RE = /(?:__turbopack_context__|e)\.A\((?<asyncSharedModuleId>[0-9]+)\)/;
1007
- var ASYNC_MODULE_RESOLVE_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<inner>parentImport|e)=>Promise\.resolve\(\)\.then\(\(\)=>\k<inner>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
1008
- 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]+)\)\)\)\}/;
1114
+ var REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(
1115
+ `\\.TURBOPACK_REMOTE_SHARED\\s*=\\s*await (?:__turbopack_context__|[a-z])\\.A\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1116
+ );
1117
+ var ASYNC_MODULE_LOADER_RE = new RegExp(
1118
+ `(?:__turbopack_context__|[a-z])\\.A\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\)`
1119
+ );
1120
+ var ASYNC_MODULE_CALLBACK_RE = new RegExp(
1121
+ `(?:parentImport|[a-z])\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1122
+ );
1009
1123
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
1010
1124
 
1011
1125
  // src/runtime/turbopack/chunk-loader.ts
@@ -1015,6 +1129,7 @@ function loadChunkWithScope(scope, chunkId) {
1015
1129
  `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
1016
1130
  );
1017
1131
  const self = globalThis;
1132
+ const ns = getNamespace();
1018
1133
  const { bundle, path, prefix } = parseRemoteId(chunkId);
1019
1134
  const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
1020
1135
  if (remoteRuntime === RUNTIME_WEBPACK) {
@@ -1025,35 +1140,31 @@ function loadChunkWithScope(scope, chunkId) {
1025
1140
  if (url.endsWith(".css")) {
1026
1141
  return;
1027
1142
  }
1028
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1029
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
1030
- }
1031
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1032
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1143
+ if (ns.chunkCache[url]) {
1144
+ logDebug("ChunkLoader", `Cache hit for "${chunkId}" (url="${url}")`);
1145
+ return ns.chunkCache[url];
1033
1146
  }
1034
1147
  const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1035
1148
  if (resolvedUrl !== url) {
1036
1149
  logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1037
1150
  }
1038
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1039
- (resolve, reject) => {
1040
- fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1041
- const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1042
- if (hasTurbopack) {
1043
- return handleTurbopackChunk(code, scope, url);
1044
- }
1045
- }).then(resolve).catch((error) => {
1046
- const isProxied = isProxiedUrl(resolvedUrl);
1047
- if (isProxied) {
1048
- reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1049
- } else {
1050
- warnCrossOriginFetchError("ChunkLoader", url);
1051
- reject(error);
1052
- }
1053
- });
1054
- }
1055
- );
1056
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1151
+ ns.chunkCache[url] = new Promise((resolve, reject) => {
1152
+ fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1153
+ const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1154
+ if (hasTurbopack) {
1155
+ return handleTurbopackChunk(code, scope, url);
1156
+ }
1157
+ }).then(resolve).catch((error) => {
1158
+ const isProxied = isProxiedUrl(resolvedUrl);
1159
+ if (isProxied) {
1160
+ reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1161
+ } else {
1162
+ warnCrossOriginFetchError("ChunkLoader", url);
1163
+ reject(error);
1164
+ }
1165
+ });
1166
+ });
1167
+ return ns.chunkCache[url];
1057
1168
  }
1058
1169
  function createChunkDispatcher() {
1059
1170
  return function __chunk_dispatcher__(chunkId, scriptBundle) {
@@ -1102,19 +1213,39 @@ async function handleTurbopackChunk(code, scope, url) {
1102
1213
  `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1103
1214
  );
1104
1215
  if (!self[`TURBOPACK_${globalKey}`]) {
1105
- const chunkData = [];
1106
- const turbopackObject = {
1107
- push: (item) => {
1108
- if (Array.isArray(item)) {
1109
- chunkData.push(item);
1110
- } else {
1111
- chunkData.push([item]);
1216
+ const wrapPush = (target) => {
1217
+ const originalPush = target.push;
1218
+ if (typeof originalPush !== "function")
1219
+ return target;
1220
+ target.push = (...items) => {
1221
+ for (const item of items) {
1222
+ if (Array.isArray(item)) {
1223
+ for (const entry of item) {
1224
+ scope.turbopackModules.push(entry);
1225
+ }
1226
+ } else {
1227
+ scope.turbopackModules.push(item);
1228
+ }
1112
1229
  }
1113
- return chunkData.length;
1114
- },
1115
- __chunks__: chunkData
1230
+ return originalPush.apply(target, items);
1231
+ };
1232
+ return target;
1116
1233
  };
1117
- self[`TURBOPACK_${globalKey}`] = turbopackObject;
1234
+ const globalProp = `TURBOPACK_${globalKey}`;
1235
+ let currentValue = wrapPush([]);
1236
+ Object.defineProperty(self, globalProp, {
1237
+ get() {
1238
+ return currentValue;
1239
+ },
1240
+ set(newValue) {
1241
+ if (newValue && typeof newValue === "object") {
1242
+ wrapPush(newValue);
1243
+ }
1244
+ currentValue = newValue;
1245
+ },
1246
+ configurable: true,
1247
+ enumerable: true
1248
+ });
1118
1249
  }
1119
1250
  await new Promise((scriptResolve, scriptReject) => {
1120
1251
  const blob = new Blob([transformedCode], {
@@ -1166,13 +1297,13 @@ async function handleTurbopackChunk(code, scope, url) {
1166
1297
  // src/runtime/turbopack/shared-modules.ts
1167
1298
  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).";
1168
1299
  function getTurbopackModules(scope) {
1300
+ if (scope.turbopackModules.length > 0) {
1301
+ return scope.turbopackModules;
1302
+ }
1169
1303
  const self = globalThis;
1170
1304
  const raw = self[`TURBOPACK_${scope.globalKey}`];
1171
1305
  if (!raw)
1172
1306
  return void 0;
1173
- if (typeof raw === "object" && "__chunks__" in raw) {
1174
- return raw.__chunks__.flat();
1175
- }
1176
1307
  if (Array.isArray(raw)) {
1177
1308
  return raw.flat();
1178
1309
  }
@@ -1196,7 +1327,11 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1196
1327
  if (sharedModuleInitializerIndex > 0) {
1197
1328
  const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1198
1329
  const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1199
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1330
+ const sharedModuleId = extractGroup(
1331
+ REMOTE_SHARED_ASSIGNMENT_RE,
1332
+ sharedModuleInitializerCode,
1333
+ "sharedModuleId"
1334
+ );
1200
1335
  if (sharedModuleId) {
1201
1336
  const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1202
1337
  scope,
@@ -1254,20 +1389,22 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1254
1389
  }
1255
1390
  function extractSharedModuleIds(shared, scope) {
1256
1391
  return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1257
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1392
+ const asyncSharedModuleId = extractGroup(
1393
+ ASYNC_MODULE_LOADER_RE,
1394
+ value.toString(),
1395
+ "asyncSharedModuleId"
1396
+ );
1258
1397
  if (asyncSharedModuleId) {
1259
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1260
- let asyncSharedModule;
1261
- const turbopackModules = getTurbopackModules(scope) ?? [];
1262
- const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1263
- asyncSharedModuleIdNumber
1398
+ const asyncSharedModule = findModuleInit(
1399
+ getTurbopackModules(scope),
1400
+ asyncSharedModuleId
1264
1401
  );
1265
- if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1266
- asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1267
- }
1268
1402
  if (asyncSharedModule) {
1269
- const asyncSharedModuleCode = asyncSharedModule.toString();
1270
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1403
+ const sharedModuleId = extractGroup(
1404
+ ASYNC_MODULE_CALLBACK_RE,
1405
+ asyncSharedModule.toString(),
1406
+ "sharedModuleId"
1407
+ );
1271
1408
  acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1272
1409
  "__remote_shared_module_",
1273
1410
  ""
@@ -1358,9 +1495,17 @@ function findModuleInit(modules, moduleId) {
1358
1495
  if (idx >= 0) {
1359
1496
  return flat.slice(idx + 1).find((e) => typeof e === "function");
1360
1497
  }
1361
- return flat.find(
1362
- (e) => Boolean(e && typeof e === "object" && moduleId in e)
1363
- )?.[moduleId];
1498
+ for (const entry of flat) {
1499
+ if (!entry || typeof entry !== "object")
1500
+ continue;
1501
+ const obj = entry;
1502
+ if (moduleId in obj)
1503
+ return obj[moduleId];
1504
+ const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));
1505
+ if (prefixKey)
1506
+ return obj[prefixKey];
1507
+ }
1508
+ return void 0;
1364
1509
  }
1365
1510
  function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1366
1511
  const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
@@ -1439,7 +1584,10 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1439
1584
  }
1440
1585
  if (typeof mod !== "object" || mod === null) {
1441
1586
  mod = { default: mod };
1442
- } else if (!("default" in mod) && mod.toString() !== "[object Module]") {
1587
+ } else if (!("default" in mod) && // ES module namespace objects have a null prototype, so calling
1588
+ // mod.toString() directly throws. Use Object.prototype.toString
1589
+ // to safely detect them.
1590
+ Object.prototype.toString.call(mod) !== "[object Module]") {
1443
1591
  try {
1444
1592
  mod.default = mod;
1445
1593
  } catch {
@@ -1503,21 +1651,38 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1503
1651
  };
1504
1652
  }
1505
1653
 
1506
- // src/runtime/turbopack/webpack-runtime.ts
1507
- async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1654
+ // src/runtime/turbopack/remote-scope-setup.ts
1655
+ async function setupRemoteScope(runtime, scripts = [], url = new URL(location.href), bundle, resolveClientUrl) {
1508
1656
  const self = globalThis;
1657
+ const ns = getNamespace();
1509
1658
  const bundleName = bundle ?? "default";
1659
+ const existingScope = getScope(bundleName);
1660
+ if (existingScope && existingScope.url.origin === url.origin) {
1661
+ logDebug(
1662
+ "WebpackRuntime",
1663
+ `Reusing scope "${existingScope.scopedName}" (turbopackModules=${existingScope.turbopackModules.length})`
1664
+ );
1665
+ existingScope.resolveClientUrl = resolveClientUrl;
1666
+ if (runtime === RUNTIME_TURBOPACK) {
1667
+ await Promise.allSettled(
1668
+ scripts.map(
1669
+ (script) => script.src ? loadChunkWithScope(existingScope, script.src) : Promise.resolve(void 0)
1670
+ )
1671
+ );
1672
+ }
1673
+ return existingScope;
1674
+ }
1510
1675
  const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1511
1676
  registerScope(scope);
1512
- if (!self.__remote_bundle_url__) {
1513
- self.__remote_bundle_url__ = {};
1677
+ if (runtime === RUNTIME_WEBPACK && self.__remote_webpack_require__?.[bundleName]) {
1678
+ scope.webpackRequire = self.__remote_webpack_require__[bundleName];
1514
1679
  }
1515
- self.__remote_bundle_url__[bundleName] = url;
1680
+ ns.bundleUrls[bundleName] = url;
1516
1681
  if (scope.scopedName !== bundleName) {
1517
- self.__remote_bundle_url__[scope.scopedName] = url;
1682
+ ns.bundleUrls[scope.scopedName] = url;
1518
1683
  }
1519
1684
  self.__webpack_get_script_filename__ = () => null;
1520
- const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1685
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || ns.dispatcherRuntime !== "turbopack";
1521
1686
  if (willCreateDispatchers) {
1522
1687
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1523
1688
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
@@ -1525,6 +1690,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1525
1690
  }
1526
1691
  self.__webpack_chunk_load__ = createChunkDispatcher();
1527
1692
  self.__webpack_require__ = createModuleDispatcher(runtime);
1693
+ ns.dispatcherRuntime = runtime;
1528
1694
  self.__webpack_require_type__ = runtime;
1529
1695
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1530
1696
  self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
@@ -1552,15 +1718,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1552
1718
  }
1553
1719
  }
1554
1720
  }
1555
- const coreShared = {
1556
- react: async () => (await import("react")).default,
1557
- "react-dom": async () => (await import("react-dom")).default,
1558
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
1559
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
1560
- "react-dom/client": async () => (await import("react-dom/client")).default,
1561
- ...shared
1562
- };
1563
- await initializeSharedModules(scope, coreShared, remoteShared);
1721
+ return scope;
1564
1722
  }
1565
1723
  function createModuleDispatcher(runtime) {
1566
1724
  return (id) => {
@@ -1577,6 +1735,9 @@ function createModuleDispatcher(runtime) {
1577
1735
  );
1578
1736
  try {
1579
1737
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1738
+ const scope2 = getScope(bundle);
1739
+ if (scope2?.webpackRequire)
1740
+ return scope2.webpackRequire(moduleId);
1580
1741
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1581
1742
  }
1582
1743
  const scope = getScope(bundleName);
@@ -1694,44 +1855,33 @@ async function loadRemoteComponent({
1694
1855
  "ComponentLoader",
1695
1856
  `Remote shared modules requested: ${JSON.stringify(remoteShared)}`
1696
1857
  );
1697
- await setupWebpackRuntime(
1858
+ const scope = await setupRemoteScope(
1698
1859
  runtime,
1699
1860
  scripts,
1700
1861
  url,
1701
1862
  bundle,
1702
- hostShared,
1703
- remoteShared,
1704
1863
  resolveClientUrl
1705
1864
  );
1865
+ if (runtime === "turbopack") {
1866
+ await initializeSharedModules(
1867
+ scope,
1868
+ buildCoreShared(hostShared),
1869
+ remoteShared
1870
+ );
1871
+ }
1706
1872
  if (bundle) {
1707
- const resolve = {
1708
- "/react/index.js": React,
1709
- "/react/jsx-dev-runtime.js": JSXDevRuntime,
1710
- "/react/jsx-runtime.js": JSXRuntime,
1711
- "/react-dom/index.js": ReactDOM,
1712
- "/react-dom/client.js": ReactDOMClient,
1713
- ...Object.entries(remoteShared).reduce(
1714
- (acc, [key, value]) => {
1715
- if (typeof hostShared[value] !== "undefined") {
1716
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
1717
- } else {
1718
- logDebug(
1719
- "ComponentLoader",
1720
- `Remote requests "${value}" but host doesn't provide it`
1721
- );
1722
- }
1723
- return acc;
1724
- },
1725
- {}
1726
- )
1727
- };
1728
- await Promise.all(
1729
- Object.entries(resolve).map(async ([key, value]) => {
1730
- if (typeof value === "function") {
1731
- resolve[key] = await value(bundle);
1732
- }
1733
- return Promise.resolve(value);
1734
- })
1873
+ const resolve = await buildWebpackResolve(
1874
+ hostShared,
1875
+ remoteShared,
1876
+ bundle,
1877
+ {
1878
+ "/react/index.js": React,
1879
+ "/react/jsx-dev-runtime.js": JSXDevRuntime,
1880
+ "/react/jsx-runtime.js": JSXRuntime,
1881
+ "/react-dom/index.js": ReactDOM,
1882
+ "/react-dom/client.js": ReactDOMClient
1883
+ },
1884
+ "ComponentLoader"
1735
1885
  );
1736
1886
  applySharedModules(bundle, resolve);
1737
1887
  } else {
@@ -1759,19 +1909,8 @@ async function loadRemoteComponent({
1759
1909
  };
1760
1910
  }
1761
1911
  }
1762
- async function importCreateFromReadableStream() {
1763
- try {
1764
- const { createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1765
- return createFromReadableStream;
1766
- } catch {
1767
- const {
1768
- default: { createFromReadableStream }
1769
- } = await import("react-server-dom-webpack/client.browser");
1770
- return createFromReadableStream;
1771
- }
1772
- }
1773
1912
  async function loadRSCComponent(rscName, data) {
1774
- const createFromReadableStream = await importCreateFromReadableStream();
1913
+ const { createFromReadableStream } = await importRSCClientBrowser();
1775
1914
  if (typeof createFromReadableStream !== "function") {
1776
1915
  throw new RemoteComponentsError(
1777
1916
  'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
@@ -1835,10 +1974,9 @@ async function importViaCallback(absoluteSrc, resolveClientUrl) {
1835
1974
  URL.revokeObjectURL(moduleBlobUrl);
1836
1975
  URL.revokeObjectURL(wrapperBlobUrl);
1837
1976
  }
1838
- const registry = globalThis.__rc_module_registry__;
1839
- const mod = registry?.[absoluteSrc] ?? {};
1840
- if (registry)
1841
- delete registry[absoluteSrc];
1977
+ const registry = getNamespace().moduleRegistry;
1978
+ const mod = registry[absoluteSrc] ?? {};
1979
+ delete registry[absoluteSrc];
1842
1980
  return mod;
1843
1981
  }
1844
1982
  async function importDirectly(absoluteSrc) {
@@ -1868,12 +2006,12 @@ function resolveScriptSrc(script, url) {
1868
2006
  return rawSrc;
1869
2007
  }
1870
2008
  async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1871
- const self = globalThis;
1872
- if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1873
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
2009
+ const ns = getNamespace();
2010
+ if (ns.mountFns[url.href]) {
2011
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1874
2012
  }
1875
- if (self.__remote_script_entrypoint_unmount__?.[url.href]) {
1876
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
2013
+ if (ns.unmountFns[url.href]) {
2014
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1877
2015
  }
1878
2016
  const mountUnmountSets = await Promise.all(
1879
2017
  scripts.map(async (script) => {
@@ -1885,25 +2023,19 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1885
2023
  URL.revokeObjectURL(src);
1886
2024
  }
1887
2025
  if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
1888
- if (!self.__remote_script_entrypoint_mount__) {
1889
- self.__remote_script_entrypoint_mount__ = {};
2026
+ if (!ns.mountFns[url.href]) {
2027
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1890
2028
  }
1891
- if (!self.__remote_script_entrypoint_mount__[url.href]) {
1892
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
1893
- }
1894
- self.__remote_script_entrypoint_mount__[url.href]?.add(
2029
+ ns.mountFns[url.href]?.add(
1895
2030
  mod.mount || mod.default?.mount || (() => {
1896
2031
  })
1897
2032
  );
1898
2033
  }
1899
2034
  if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
1900
- if (!self.__remote_script_entrypoint_unmount__) {
1901
- self.__remote_script_entrypoint_unmount__ = {};
1902
- }
1903
- if (!self.__remote_script_entrypoint_unmount__[url.href]) {
1904
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
2035
+ if (!ns.unmountFns[url.href]) {
2036
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1905
2037
  }
1906
- self.__remote_script_entrypoint_unmount__[url.href]?.add(
2038
+ ns.unmountFns[url.href]?.add(
1907
2039
  mod.unmount || mod.default?.unmount || (() => {
1908
2040
  })
1909
2041
  );
@@ -1942,6 +2074,188 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1942
2074
  );
1943
2075
  }
1944
2076
 
2077
+ // src/host/shared/pipeline.ts
2078
+ function preparePipeline(input) {
2079
+ const parser = new DOMParser();
2080
+ const doc = parser.parseFromString(input.html, "text/html");
2081
+ const parsed = parseRemoteComponentDocument(doc, input.name, input.url);
2082
+ const remoteShared = input.remoteShared ?? parsed.remoteShared;
2083
+ if ("__remote_components_missing_shared__" in remoteShared) {
2084
+ throw new RemoteComponentsError(
2085
+ remoteShared.__remote_components_missing_shared__
2086
+ );
2087
+ }
2088
+ applyOriginToNodes(doc, input.url, input.resolveClientUrl);
2089
+ const scriptDescriptors = buildScriptDescriptors(parsed.scripts, input.url);
2090
+ return { doc, parsed, scriptDescriptors };
2091
+ }
2092
+ async function loadPrepared(input) {
2093
+ const { prepared, url, signal, resolveClientUrl, container, rscName } = input;
2094
+ const { doc, parsed, scriptDescriptors } = prepared;
2095
+ if (signal.aborted) {
2096
+ return { status: "aborted" };
2097
+ }
2098
+ const userShared = await input.shared;
2099
+ if (signal.aborted) {
2100
+ return { status: "aborted" };
2101
+ }
2102
+ if (parsed.isRemoteComponent) {
2103
+ return loadStaticPath({
2104
+ parsed,
2105
+ doc,
2106
+ url,
2107
+ resolveClientUrl
2108
+ });
2109
+ }
2110
+ return loadDynamicPath({
2111
+ parsed,
2112
+ doc,
2113
+ url,
2114
+ scriptDescriptors,
2115
+ shared: userShared,
2116
+ resolveClientUrl,
2117
+ container,
2118
+ rscName
2119
+ });
2120
+ }
2121
+ function buildScriptDescriptors(scripts, url) {
2122
+ return scripts.map((script) => {
2123
+ const scriptSrc = script.getAttribute("data-src") || script.getAttribute("src") || script.src;
2124
+ const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(scriptSrc)?.groups ?? {
2125
+ prefix: void 0,
2126
+ id: scriptSrc
2127
+ };
2128
+ return {
2129
+ src: new URL(collapseDoubleSlashes(`${prefix ?? ""}${path}`), url).href
2130
+ };
2131
+ });
2132
+ }
2133
+ async function loadStaticPath(input) {
2134
+ const { parsed, doc, url, resolveClientUrl } = input;
2135
+ const scripts = Array.from(
2136
+ parsed.component.querySelectorAll("script")
2137
+ );
2138
+ const { mount, unmount } = await loadStaticRemoteComponent(
2139
+ scripts,
2140
+ url,
2141
+ resolveClientUrl
2142
+ );
2143
+ return {
2144
+ status: "static",
2145
+ mount,
2146
+ unmount,
2147
+ metadata: parsed.metadata,
2148
+ parsed,
2149
+ doc
2150
+ };
2151
+ }
2152
+ async function loadDynamicPath(input) {
2153
+ const {
2154
+ parsed,
2155
+ doc,
2156
+ url,
2157
+ scriptDescriptors,
2158
+ shared,
2159
+ resolveClientUrl,
2160
+ container
2161
+ } = input;
2162
+ const rscName = input.rscName ?? (parsed.rsc ? `__remote_component_rsc_${escapeString(url.href)}_${escapeString(parsed.name)}` : void 0);
2163
+ const rscData = parsed.rsc ? (parsed.rsc.textContent || "").split("\n").filter(Boolean) : [];
2164
+ const result = await loadRemoteComponent({
2165
+ url,
2166
+ name: parsed.name,
2167
+ rscName,
2168
+ bundle: parsed.metadata.bundle,
2169
+ route: parsed.metadata.route,
2170
+ runtime: parsed.metadata.runtime,
2171
+ data: rscData,
2172
+ nextData: parsed.nextData,
2173
+ scripts: scriptDescriptors,
2174
+ shared: buildHostShared(shared, resolveClientUrl),
2175
+ remoteShared: parsed.remoteShared,
2176
+ container,
2177
+ resolveClientUrl
2178
+ });
2179
+ if (result.error) {
2180
+ return { status: "error", error: result.error };
2181
+ }
2182
+ return {
2183
+ status: "loaded",
2184
+ component: result.component,
2185
+ metadata: parsed.metadata,
2186
+ parsed,
2187
+ doc
2188
+ };
2189
+ }
2190
+
2191
+ // src/host/shared/state.ts
2192
+ function createHostState() {
2193
+ return {
2194
+ stage: "idle",
2195
+ prevSrc: void 0,
2196
+ prevUrl: void 0,
2197
+ prevName: void 0,
2198
+ prevIsRemoteComponent: false,
2199
+ abortController: void 0
2200
+ };
2201
+ }
2202
+
2203
+ // src/host/utils/resolve-name-from-src.ts
2204
+ function resolveNameFromSrc(src, defaultName) {
2205
+ if (!src) {
2206
+ return defaultName;
2207
+ }
2208
+ const hash = typeof src === "string" ? src : src.hash;
2209
+ const hashIndex = hash.indexOf("#");
2210
+ if (hashIndex < 0) {
2211
+ return defaultName;
2212
+ }
2213
+ const name = hash.slice(hashIndex + 1);
2214
+ return name || defaultName;
2215
+ }
2216
+
2217
+ // src/runtime/html/set-attributes-from-props.ts
2218
+ var DOMAttributeNames = {
2219
+ acceptCharset: "accept-charset",
2220
+ className: "class",
2221
+ htmlFor: "for",
2222
+ httpEquiv: "http-equiv",
2223
+ noModule: "noModule"
2224
+ };
2225
+ var ignoreProps = [
2226
+ "onLoad",
2227
+ "onReady",
2228
+ "dangerouslySetInnerHTML",
2229
+ "children",
2230
+ "onError",
2231
+ "strategy",
2232
+ "stylesheets"
2233
+ ];
2234
+ function isBooleanScriptAttribute(attr) {
2235
+ return ["async", "defer", "noModule"].includes(attr);
2236
+ }
2237
+ function setAttributesFromProps(el, props) {
2238
+ for (const [p, value] of Object.entries(props)) {
2239
+ if (!Object.hasOwn(props, p))
2240
+ continue;
2241
+ if (ignoreProps.includes(p))
2242
+ continue;
2243
+ if (value === void 0) {
2244
+ continue;
2245
+ }
2246
+ const attr = DOMAttributeNames[p] || p.toLowerCase();
2247
+ if (el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr)) {
2248
+ el[attr] = Boolean(value);
2249
+ } else {
2250
+ el.setAttribute(attr, String(value));
2251
+ }
2252
+ if (value === false || el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr) && (!value || value === "false")) {
2253
+ el.setAttribute(attr, "");
2254
+ el.removeAttribute(attr);
2255
+ }
2256
+ }
2257
+ }
2258
+
1945
2259
  // src/host/react/hooks/use-resolve-client-url.ts
1946
2260
  var import_react = require("react");
1947
2261
  var import_context = require("#internal/host/react/context");
@@ -1986,27 +2300,25 @@ function useShadowRoot({
1986
2300
  }) {
1987
2301
  const shadowRootContainerRef = (0, import_react2.useRef)(null);
1988
2302
  const [shadowRoot, setShadowRoot] = (0, import_react2.useState)(() => {
1989
- const self = globalThis;
1990
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2303
+ const shadowRoots = getNamespace().shadowRoots;
1991
2304
  const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
1992
2305
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
1993
- )?.shadowRoot ?? self[shadowRootKey] ?? null : null;
1994
- self[shadowRootKey] = null;
2306
+ )?.shadowRoot ?? shadowRoots[keySuffix] ?? null : null;
2307
+ shadowRoots[keySuffix] = null;
1995
2308
  return ssrShadowRoot;
1996
2309
  });
1997
2310
  (0, import_react2.useLayoutEffect)(() => {
2311
+ const shadowRoots = getNamespace().shadowRoots;
1998
2312
  if (isolate !== false && typeof document !== "undefined" && (!shadowRoot || !shadowRoot.isConnected)) {
1999
- const self = globalThis;
2000
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2001
2313
  let shadowRootElement = null;
2002
2314
  const element = document.querySelector(
2003
2315
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2004
2316
  );
2005
- shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;
2317
+ shadowRootElement = shadowRoots[keySuffix] ?? element?.shadowRoot ?? null;
2006
2318
  if (!shadowRootElement && element) {
2007
2319
  try {
2008
2320
  shadowRootElement = element.attachShadow({ mode });
2009
- self[shadowRootKey] = shadowRootElement;
2321
+ shadowRoots[keySuffix] = shadowRootElement;
2010
2322
  } catch {
2011
2323
  }
2012
2324
  }
@@ -2017,9 +2329,7 @@ function useShadowRoot({
2017
2329
  setShadowRoot(shadowRootElement);
2018
2330
  }
2019
2331
  } else if (isolate === false && shadowRoot) {
2020
- const self = globalThis;
2021
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2022
- self[shadowRootKey] = null;
2332
+ shadowRoots[keySuffix] = null;
2023
2333
  setShadowRoot(null);
2024
2334
  }
2025
2335
  }, [isolate, shadowRoot, mode, keySuffix]);
@@ -2075,6 +2385,10 @@ function ConsumeRemoteComponent({
2075
2385
  const { credentials: contextCredentials, shared: contextShared } = (0, import_context2.useRemoteComponentsContext)();
2076
2386
  const credentials = credentialsProp ?? contextCredentials ?? "same-origin";
2077
2387
  const shared = sharedProp ?? contextShared ?? {};
2388
+ const emitter = (0, import_react3.useMemo)(
2389
+ () => makeReactEmitter({ onBeforeLoad, onLoad, onError, onChange }),
2390
+ [onBeforeLoad, onLoad, onError, onChange]
2391
+ );
2078
2392
  const name = (0, import_react3.useMemo)(
2079
2393
  () => resolveNameFromSrc(src, nameProp),
2080
2394
  [src, nameProp]
@@ -2118,9 +2432,8 @@ function ConsumeRemoteComponent({
2118
2432
  const prevRemoteComponentContainerRef = (0, import_react3.useRef)(null);
2119
2433
  const unmountRef = (0, import_react3.useRef)(null);
2120
2434
  (0, import_react3.useLayoutEffect)(() => {
2121
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2122
2435
  return () => {
2123
- delete globalThis[shadowRootKey];
2436
+ delete getNamespace().shadowRoots[keySuffix];
2124
2437
  };
2125
2438
  }, [keySuffix]);
2126
2439
  (0, import_react3.useLayoutEffect)(() => {
@@ -2165,7 +2478,7 @@ function ConsumeRemoteComponent({
2165
2478
  hostStateRef.current.abortController?.abort();
2166
2479
  hostStateRef.current.abortController = new AbortController();
2167
2480
  const { signal } = hostStateRef.current.abortController;
2168
- onBeforeLoad?.(src);
2481
+ emitter.beforeLoad(src);
2169
2482
  hostStateRef.current.stage = "loading";
2170
2483
  (0, import_react3.startTransition)(async () => {
2171
2484
  try {
@@ -2196,26 +2509,32 @@ function ConsumeRemoteComponent({
2196
2509
  }
2197
2510
  if (signal.aborted)
2198
2511
  return;
2199
- const parser = new DOMParser();
2200
- const doc = parser.parseFromString(html, "text/html");
2512
+ const userShared = await shared;
2513
+ if (signal.aborted)
2514
+ return;
2515
+ const prepared = preparePipeline({
2516
+ html,
2517
+ name,
2518
+ url,
2519
+ shared: userShared,
2520
+ resolveClientUrl
2521
+ });
2522
+ const { doc, parsed } = prepared;
2201
2523
  const {
2202
2524
  component,
2203
2525
  name: remoteName,
2204
2526
  isRemoteComponent,
2205
2527
  metadata,
2206
- nextData,
2207
2528
  rsc,
2208
2529
  remoteShared,
2209
- links: linkElements,
2210
- scripts: scriptElements
2211
- } = parseRemoteComponentDocument(doc, name, url);
2530
+ links: linkElements
2531
+ } = parsed;
2212
2532
  if (hostStateRef.current.prevIsRemoteComponent) {
2213
2533
  if (shadowRoot) {
2214
2534
  shadowRoot.innerHTML = "";
2215
2535
  }
2216
- const self = globalThis;
2217
2536
  const prevUrl = hostStateRef.current.prevUrl;
2218
- if (prevUrl && self.__remote_script_entrypoint_unmount__?.[prevUrl.href]) {
2537
+ if (prevUrl && getNamespace().unmountFns[prevUrl.href]) {
2219
2538
  const unmountPromises = Promise.all(
2220
2539
  Array.from(unmountRef.current ?? []).map(
2221
2540
  async (unmount) => unmount(
@@ -2230,7 +2549,6 @@ function ConsumeRemoteComponent({
2230
2549
  hostStateRef.current.prevIsRemoteComponent = isRemoteComponent;
2231
2550
  hostStateRef.current.prevUrl = url;
2232
2551
  hostStateRef.current.prevName = remoteName;
2233
- applyOriginToNodes(doc, url, resolveClientUrl);
2234
2552
  const links = linkElements.map((link) => ({
2235
2553
  href: new URL(link.getAttribute("href") ?? link.href, url).href,
2236
2554
  ...link.getAttributeNames().reduce((acc, key) => {
@@ -2240,7 +2558,6 @@ function ConsumeRemoteComponent({
2240
2558
  return acc;
2241
2559
  }, {})
2242
2560
  }));
2243
- const scripts = scriptElements;
2244
2561
  const inlineScripts = (isRemoteComponent ? component : doc).querySelectorAll(
2245
2562
  "script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])"
2246
2563
  );
@@ -2319,20 +2636,10 @@ function ConsumeRemoteComponent({
2319
2636
  componentHydrationHtml.current = `${Array.from(
2320
2637
  doc.querySelectorAll("link,style")
2321
2638
  ).map((link) => link.outerHTML).join("")}${reset ? `<style data-remote-components-reset="">:host { all: initial; }</style>` : ""}${component.innerHTML}`;
2322
- const userShared = await shared;
2323
- if ("__remote_components_missing_shared__" in userShared) {
2324
- userShared.__remote_components_missing_shared__().catch((e) => {
2325
- throw e;
2326
- });
2327
- } else if ("__remote_components_missing_shared__" in remoteShared) {
2328
- throw new RemoteComponentsError(
2329
- remoteShared.__remote_components_missing_shared__
2330
- );
2331
- }
2332
2639
  if (isRemoteComponent) {
2333
2640
  if (previousSrc !== void 0) {
2334
- onChange?.({
2335
- previousSrc,
2641
+ emitter.change({
2642
+ previousSrc: previousSrc ?? null,
2336
2643
  nextSrc: src,
2337
2644
  previousName,
2338
2645
  nextName: remoteName
@@ -2353,7 +2660,7 @@ function ConsumeRemoteComponent({
2353
2660
  await Promise.all(
2354
2661
  Array.from(mount).map((mountFn) => mountFn(shadowRoot))
2355
2662
  );
2356
- onLoad?.(src);
2663
+ emitter.load(src);
2357
2664
  } else if (isolate === false) {
2358
2665
  setRemoteComponent(
2359
2666
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
@@ -2376,62 +2683,42 @@ function ConsumeRemoteComponent({
2376
2683
  (mountFn) => mountFn(prevRemoteComponentContainerRef.current)
2377
2684
  )
2378
2685
  );
2379
- onLoad?.(src);
2686
+ emitter.load(src);
2380
2687
  }
2381
2688
  hostStateRef.current.stage = "loaded";
2382
2689
  } else {
2383
- const result = await loadRemoteComponent({
2690
+ const result = await loadPrepared({
2691
+ prepared,
2384
2692
  url,
2385
- name: remoteName,
2386
- rscName,
2387
- bundle: metadata.bundle,
2388
- route: metadata.route,
2389
- runtime: metadata.runtime,
2390
- data: newData.data,
2391
- nextData,
2392
- scripts: Array.from(scripts).map((script) => {
2393
- const scriptSrc = script.getAttribute("data-src") || script.getAttribute("src") || script.src;
2394
- const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(
2395
- scriptSrc
2396
- )?.groups ?? {
2397
- prefix: void 0,
2398
- id: scriptSrc
2399
- };
2400
- return {
2401
- src: new URL(
2402
- collapseDoubleSlashes(`${prefix ?? ""}${path}`),
2403
- url
2404
- ).href
2405
- };
2406
- }),
2407
- shared: {
2408
- ...sharedPolyfills(userShared, resolveClientUrl),
2409
- ...userShared
2410
- },
2411
- remoteShared,
2693
+ signal,
2694
+ shared: userShared,
2695
+ resolveClientUrl,
2412
2696
  container: shadowRoot,
2413
- resolveClientUrl
2697
+ rscName
2414
2698
  });
2415
2699
  if (rsc) {
2416
2700
  rsc.remove();
2417
2701
  }
2418
2702
  setData(newData);
2419
2703
  if (previousSrc !== void 0) {
2420
- onChange?.({
2421
- previousSrc,
2704
+ emitter.change({
2705
+ previousSrc: previousSrc ?? null,
2422
2706
  nextSrc: src,
2423
2707
  previousName,
2424
2708
  nextName: remoteName
2425
2709
  });
2426
2710
  }
2427
- if (result.error) {
2711
+ if (result.status === "aborted") {
2712
+ return;
2713
+ }
2714
+ if (result.status === "error") {
2428
2715
  hostStateRef.current.stage = "error";
2429
2716
  setRemoteComponent(result.error);
2430
- onError?.(result.error);
2431
- } else {
2717
+ emitter.error(result.error);
2718
+ } else if (result.status === "loaded") {
2432
2719
  hostStateRef.current.stage = "loaded";
2433
2720
  setRemoteComponent(result.component);
2434
- onLoad?.(src);
2721
+ emitter.load(src);
2435
2722
  }
2436
2723
  }
2437
2724
  } catch (error) {
@@ -2441,7 +2728,7 @@ function ConsumeRemoteComponent({
2441
2728
  }
2442
2729
  hostStateRef.current.stage = "error";
2443
2730
  setRemoteComponent(error);
2444
- onError?.(error);
2731
+ emitter.error(error);
2445
2732
  }
2446
2733
  });
2447
2734
  }
@@ -2455,10 +2742,10 @@ function ConsumeRemoteComponent({
2455
2742
  shadowRoot,
2456
2743
  reset,
2457
2744
  id,
2458
- onBeforeLoad,
2459
- onLoad,
2460
- onError,
2461
- onChange,
2745
+ emitter.beforeLoad,
2746
+ emitter.load,
2747
+ emitter.error,
2748
+ emitter.change,
2462
2749
  onRequest,
2463
2750
  onResponse,
2464
2751
  resolveClientUrl
@@ -2500,7 +2787,7 @@ function ConsumeRemoteComponent({
2500
2787
  );
2501
2788
  }).then(() => {
2502
2789
  if (src) {
2503
- onLoad?.(src);
2790
+ emitter.load(src);
2504
2791
  }
2505
2792
  }).catch((e) => {
2506
2793
  const error = new RemoteComponentsError(
@@ -2510,7 +2797,7 @@ function ConsumeRemoteComponent({
2510
2797
  }
2511
2798
  );
2512
2799
  setRemoteComponent(error);
2513
- onError?.(error);
2800
+ emitter.error(error);
2514
2801
  });
2515
2802
  }
2516
2803
  }
@@ -2539,8 +2826,10 @@ function ConsumeRemoteComponent({
2539
2826
  alt="" decoding="async" style="display:none"
2540
2827
  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
2541
2828
  onload="(function(el){
2829
+ // Capture the shadow root during SSR hydration so the client-side
2830
+ // useShadowRoot hook can find it.
2542
2831
  const root = el.getRootNode();
2543
- globalThis.__remote_components_shadowroot_${keySuffix} = root;
2832
+ globalThis.__remote_components_shadowroot_${keySuffix}=root;
2544
2833
  el.parentElement.remove();
2545
2834
  })(this)"
2546
2835
  />`