remote-components 0.0.37 → 0.0.39

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 (36) hide show
  1. package/dist/html/host.cjs +78 -0
  2. package/dist/html/host.cjs.map +1 -1
  3. package/dist/html/host.js +78 -0
  4. package/dist/html/host.js.map +1 -1
  5. package/dist/internal/next/host/app-router-client.cjs +5 -1
  6. package/dist/internal/next/host/app-router-client.cjs.map +1 -1
  7. package/dist/internal/next/host/app-router-client.js +5 -1
  8. package/dist/internal/next/host/app-router-client.js.map +1 -1
  9. package/dist/internal/next/remote/render-server.cjs.map +1 -1
  10. package/dist/internal/next/remote/render-server.d.ts +13 -0
  11. package/dist/internal/next/remote/render-server.js.map +1 -1
  12. package/dist/internal/shared/client/get-client-src.cjs +39 -0
  13. package/dist/internal/shared/client/get-client-src.cjs.map +1 -0
  14. package/dist/internal/shared/client/get-client-src.d.ts +7 -0
  15. package/dist/internal/shared/client/get-client-src.js +15 -0
  16. package/dist/internal/shared/client/get-client-src.js.map +1 -0
  17. package/dist/internal/shared/ssr/fetch-remote-component.cjs +14 -10
  18. package/dist/internal/shared/ssr/fetch-remote-component.cjs.map +1 -1
  19. package/dist/internal/shared/ssr/fetch-remote-component.js +14 -10
  20. package/dist/internal/shared/ssr/fetch-remote-component.js.map +1 -1
  21. package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.cjs +34 -0
  22. package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.cjs.map +1 -0
  23. package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.d.ts +10 -0
  24. package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.js +10 -0
  25. package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.js.map +1 -0
  26. package/dist/next/host/client/index.cjs +41 -2
  27. package/dist/next/host/client/index.cjs.map +1 -1
  28. package/dist/next/host/client/index.d.ts +13 -0
  29. package/dist/next/host/client/index.js +41 -2
  30. package/dist/next/host/client/index.js.map +1 -1
  31. package/dist/react/index.cjs +41 -2
  32. package/dist/react/index.cjs.map +1 -1
  33. package/dist/react/index.d.ts +14 -1
  34. package/dist/react/index.js +41 -2
  35. package/dist/react/index.js.map +1 -1
  36. package/package.json +1 -1
@@ -64,7 +64,11 @@ function RemoteComponent({
64
64
  name: nameProp = "__vercel_remote_component",
65
65
  shared = {},
66
66
  additionalHeaders,
67
- children
67
+ children,
68
+ onBeforeLoad,
69
+ onLoad,
70
+ onError,
71
+ onChange
68
72
  }) {
69
73
  const name = (0, import_react2.useMemo)(() => {
70
74
  if (typeof src === "string") {
@@ -120,6 +124,7 @@ function RemoteComponent({
120
124
  const prevUrlRef = (0, import_react2.useRef)(null);
121
125
  const prevRemoteComponentContainerRef = (0, import_react2.useRef)(null);
122
126
  const unmountRef = (0, import_react2.useRef)(null);
127
+ const prevNameRef = (0, import_react2.useRef)(void 0);
123
128
  (0, import_react2.useLayoutEffect)(() => {
124
129
  if (childrenRef.current.length > 0 && remoteComponent) {
125
130
  childrenRef.current.forEach((el) => {
@@ -175,7 +180,10 @@ function RemoteComponent({
175
180
  }, [shadowRoot, remoteComponent, name]);
176
181
  (0, import_react2.useEffect)(() => {
177
182
  if (src && src !== prevSrcRef.current) {
183
+ const previousSrc = prevSrcRef.current;
184
+ const previousName = prevNameRef.current;
178
185
  prevSrcRef.current = src;
186
+ onBeforeLoad?.(src);
179
187
  (0, import_react2.startTransition)(async () => {
180
188
  try {
181
189
  let html = getRemoteComponentHtml(
@@ -273,6 +281,7 @@ function RemoteComponent({
273
281
  }
274
282
  prevIsRemoteComponentRef.current = isRemoteComponent;
275
283
  prevUrlRef.current = url;
284
+ prevNameRef.current = remoteName;
276
285
  (0, import_apply_origin.applyOriginToNodes)(doc, url);
277
286
  const links = Array.from(
278
287
  doc.querySelectorAll("link[href]")
@@ -378,6 +387,14 @@ function RemoteComponent({
378
387
  );
379
388
  }
380
389
  if (isRemoteComponent) {
390
+ if (previousSrc !== null) {
391
+ onChange?.({
392
+ previousSrc,
393
+ nextSrc: src,
394
+ previousName,
395
+ nextName: remoteName
396
+ });
397
+ }
381
398
  setData(newData);
382
399
  if (shadowRoot) {
383
400
  let shadowRootHtml = component.innerHTML;
@@ -394,6 +411,7 @@ function RemoteComponent({
394
411
  await Promise.all(
395
412
  Array.from(mount).map((mountFn) => mountFn(shadowRoot))
396
413
  );
414
+ onLoad?.(src);
397
415
  } else if (isolate === false) {
398
416
  setRemoteComponent(
399
417
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
@@ -414,6 +432,7 @@ function RemoteComponent({
414
432
  (mountFn) => mountFn(prevRemoteComponentContainerRef.current)
415
433
  )
416
434
  );
435
+ onLoad?.(src);
417
436
  }
418
437
  } else {
419
438
  const result = await (0, import_remote_component.loadRemoteComponent)({
@@ -454,14 +473,25 @@ function RemoteComponent({
454
473
  rsc.remove();
455
474
  }
456
475
  setData(newData);
476
+ if (previousSrc !== null) {
477
+ onChange?.({
478
+ previousSrc,
479
+ nextSrc: src,
480
+ previousName,
481
+ nextName: remoteName
482
+ });
483
+ }
457
484
  if (result.error) {
458
485
  setRemoteComponent(result.error);
486
+ onError?.(result.error);
459
487
  } else {
460
488
  setRemoteComponent(result.component);
489
+ onLoad?.(src);
461
490
  }
462
491
  }
463
492
  } catch (error) {
464
493
  setRemoteComponent(error);
494
+ onError?.(error);
465
495
  }
466
496
  });
467
497
  }
@@ -475,7 +505,11 @@ function RemoteComponent({
475
505
  shadowRoot,
476
506
  additionalHeaders,
477
507
  reset,
478
- id
508
+ id,
509
+ onBeforeLoad,
510
+ onLoad,
511
+ onError,
512
+ onChange
479
513
  ]);
480
514
  if (remoteComponent instanceof Error) {
481
515
  throw remoteComponent;
@@ -511,6 +545,10 @@ function RemoteComponent({
511
545
  return Promise.all(
512
546
  Array.from(mount).map((mountFn) => mountFn(shadowRoot))
513
547
  );
548
+ }).then(() => {
549
+ if (src) {
550
+ onLoad?.(src);
551
+ }
514
552
  }).catch((e) => {
515
553
  const error = new import_remote_component.RemoteComponentsError(
516
554
  `Error mounting remote component from "${url.href}"`,
@@ -519,6 +557,7 @@ function RemoteComponent({
519
557
  }
520
558
  );
521
559
  setRemoteComponent(error);
560
+ onError?.(error);
522
561
  });
523
562
  }
524
563
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/react/index.tsx"],"sourcesContent":["import {\n startTransition,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { applyOriginToNodes } from '#internal/shared/client/apply-origin';\nimport { sharedPolyfills } from '#internal/shared/client/polyfill';\nimport {\n DEFAULT_ROUTE,\n type LoadRemoteComponentProps,\n loadRemoteComponent,\n loadStaticRemoteComponent,\n REMOTE_COMPONENT_REGEX,\n RemoteComponentsError,\n RUNTIME_SCRIPT,\n RUNTIME_WEBPACK,\n setAttributesFromProps,\n} from '#internal/shared/client/remote-component';\nimport {\n failedToFetchRemoteComponentError,\n multipleRemoteComponentsError,\n} from '#internal/shared/error';\nimport { remoteFetchHeaders } from '#internal/shared/ssr/fetch-headers';\nimport { getClientOrServerUrl } from '#internal/shared/ssr/get-client-or-server-url';\nimport { attrToProp, escapeString } from '#internal/shared/utils';\nimport type {\n MountOrUnmountFunction,\n RemoteComponentMountUnmount,\n RemoteComponentProps as RemoteComponentPropsType,\n} from '#remote-components/shared/client/types';\n\n// patch react/jsx-runtime to support the shadowrootmode attribute on template elements\ndeclare module 'react/jsx-runtime' {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace JSX {\n interface IntrinsicElements {\n template: {\n shadowrootmode?: 'open' | 'closed';\n id?: string;\n ref?: React.Ref<HTMLTemplateElement>;\n dangerouslySetInnerHTML?: {\n __html: string;\n };\n children?: React.ReactNode;\n };\n }\n }\n}\n\nexport interface RemoteComponentProps {\n /** The source URL of the remote component. */\n src?: string | URL;\n /** Whether to isolate the remote component using a Shadow DOM wrapper. */\n isolate?: boolean;\n /** The shadow DOM mode to use when isolating the remote component. */\n mode?: 'open' | 'closed';\n /** Whether to include a CSS reset style in the shadow DOM. Defaults to `false`. */\n reset?: boolean;\n /** The credentials to use for the fetch request. Defaults to `same-origin`. */\n credentials?: RequestCredentials;\n name?: string;\n /** Shared modules to include in the remote component's context. */\n shared?: LoadRemoteComponentProps['shared'];\n /** Additional headers to use when fetching the remote component. */\n additionalHeaders?: Headers | Record<string, string>;\n /** The children to use as a loading fallback until the remote component is loaded. */\n children?: React.ReactNode;\n}\n\nfunction getRemoteComponentHtml(html: string) {\n if (typeof document === 'undefined') return html;\n\n // parse the HTML string to extract the relevant parts\n const parser = new DOMParser();\n const temp = parser.parseFromString(html, 'text/html');\n\n // used by the Next.js Pages Router remote as a wrapper\n const ssrRemoteComponentContainer = temp.querySelector(\n 'div[id^=\"__REMOTE_COMPONENT\"]',\n );\n if (ssrRemoteComponentContainer) {\n return ssrRemoteComponentContainer.innerHTML;\n }\n\n // remote component content\n const remoteComponentContainer = temp.querySelectorAll(\n `div[data-bundle][data-route][data-runtime][id^=\"__vercel_remote_component\"],div[data-bundle][data-route],div#__next,remote-component:not([src])`,\n );\n if (remoteComponentContainer.length > 0) {\n return `${Array.from(temp.querySelectorAll('link,script'))\n .map((link) => link.outerHTML)\n .join('')}${Array.from(remoteComponentContainer)\n .map((container) => container.outerHTML)\n .join('')}`;\n }\n\n return '';\n}\n\nconst DUMMY_FALLBACK = 'http://remote-components-dummy-fallback';\n\n/**\n * RemoteComponent is a React component that fetches and renders a remote component.\n * It supports SSR and can isolate the remote component in a shadow DOM.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n *\n * @example\n *\n * Use the `<RemoteComponent>` in your React application to consume a remote component from a remote application:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/react';\n *\n * export default function App() {\n * return (\n * <>\n * <h1>Welcome to My App</h1>\n * <p>This page consumes a remote component from another application.</p>\n * <RemoteComponent src=\"/nextjs-app-remote/components/header\" />\n * </>\n * );\n * }\n * ```\n *\n * To share modules, you can provide a shared module map with references to the shared modules:\n *\n * ```tsx\n * <RemoteComponent\n * src=\"/nextjs-app-remote/components/header\"\n * shared={{\n * '@/components/provider': () => import('@/components/host-provider')\n * }}\n * />\n * ```\n */\nexport function RemoteComponent({\n src,\n isolate,\n mode = 'open',\n reset,\n credentials = 'same-origin',\n name: nameProp = '__vercel_remote_component',\n shared = {},\n additionalHeaders,\n children,\n}: RemoteComponentProps) {\n const name = useMemo(() => {\n if (typeof src === 'string') {\n const url = new URL(\n src,\n typeof document !== 'undefined' ? location.href : DUMMY_FALLBACK,\n );\n if (url.hash) {\n return url.hash.slice(1);\n }\n } else if (typeof src === 'object' && 'hash' in src && src.hash) {\n return src.hash.slice(1) || nameProp;\n }\n return nameProp;\n }, [src, nameProp]);\n\n const [data, setData] = useState<Omit<\n RemoteComponentPropsType,\n 'children'\n > | null>(null);\n\n const url = useMemo(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);\n\n // for relative src paths, use just the pathname as the unique id.\n // for static urls, use the full url as the unique id as the path may not be unique.\n // this id needs to be the same for server and client side rendering.\n // note that if this needs to be more unique, can pass through the bundle as an id prop and ammend it to this id.\n const id =\n url.origin ===\n (typeof location !== 'undefined' ? location.origin : DUMMY_FALLBACK)\n ? url.pathname\n : url.href;\n\n const keySuffix = `${escapeString(id)}_${escapeString(data?.name ?? name)}`;\n\n const [remoteComponent, setRemoteComponent] = useState<\n React.ReactNode | Error\n >(null);\n const shadowRootContainerRef = useRef<HTMLDivElement | null>(null);\n const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(() => {\n const self = globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n >;\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n const ssrShadowRoot =\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot ??\n self[shadowRootKey] ??\n null)\n : null;\n self[shadowRootKey] = null;\n return ssrShadowRoot;\n });\n const htmlRef = useRef<string | null>(\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot?.innerHTML ??\n document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ??\n document.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`)\n ?.innerHTML ??\n document.querySelector('div[data-bundle][data-route]')?.innerHTML)\n : null,\n );\n const endTemplateRef = useRef<HTMLTemplateElement | null>(null);\n // collect initial content that needs to be removed after remote component renders\n const childrenRef = useRef(\n typeof document !== 'undefined'\n ? (() => {\n let el = document.querySelector(`template[id=\"${name}_start\"]`);\n const elements = [];\n while (el && el.id !== `${name}_end`) {\n if (\n el.id !== `${name}_start` &&\n !el.getAttribute('data-remote-component')\n ) {\n elements.push(el);\n }\n el = el.nextElementSibling as HTMLTemplateElement | null;\n }\n return elements;\n })()\n : [],\n );\n const prevSrcRef = useRef<string | URL | null>(null);\n const componentHydrationHtml = useRef<string | null>(null);\n const prevIsRemoteComponentRef = useRef<boolean>(false);\n const prevUrlRef = useRef<URL | null>(null);\n const prevRemoteComponentContainerRef = useRef<HTMLDivElement | null>(null);\n const unmountRef = useRef<Set<MountOrUnmountFunction> | null>(null);\n\n useLayoutEffect(() => {\n // clear initial content\n if (childrenRef.current.length > 0 && remoteComponent) {\n childrenRef.current.forEach((el) => {\n el.remove();\n });\n childrenRef.current = [];\n }\n\n if (isolate !== false && typeof document !== 'undefined' && !shadowRoot) {\n const self = globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n >;\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n\n let shadowRootElement: ShadowRoot | null = null;\n const element = document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n );\n shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;\n\n if (!shadowRootElement && element) {\n // create a shadow root if it doesn't exist\n // this is a fallback for browsers that don't support declarative shadow DOM\n try {\n shadowRootElement = element.attachShadow({ mode });\n self[shadowRootKey] = shadowRootElement;\n } catch {\n // do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n // remove all nodes from the shadow root except links\n shadowRootElement.querySelectorAll('*:not(link)').forEach((node) => {\n node.remove();\n });\n setShadowRoot(shadowRootElement);\n }\n }\n }, [isolate, shadowRoot, remoteComponent, mode, keySuffix]);\n\n useLayoutEffect(() => {\n if (shadowRoot && remoteComponent) {\n const resetStyles = shadowRoot.querySelectorAll(\n 'style[data-remote-components-reset]',\n );\n // ensure we only have one reset style in the shadow root\n if (resetStyles.length > 1) {\n resetStyles.forEach((style, index) => {\n if (index > 0) {\n style.remove();\n }\n });\n }\n\n // clear the html ref after hydration\n htmlRef.current = null;\n\n // clear all nodes except links and styles until the start marker\n // the marker gets only rendered on hydration\n let el: ChildNode | null = shadowRoot.childNodes[0] ?? null;\n while (el && (!('id' in el) || el.id !== `${name}_start`)) {\n const nextEl = el.nextSibling;\n if (el.nodeName !== 'LINK' && el.nodeName !== 'STYLE') {\n el.parentNode?.removeChild(el);\n }\n el = nextEl;\n }\n }\n }, [shadowRoot, remoteComponent, name]);\n\n useEffect(() => {\n if (src && src !== prevSrcRef.current) {\n prevSrcRef.current = src;\n\n startTransition(async () => {\n try {\n let html = getRemoteComponentHtml(\n htmlRef.current ??\n (endTemplateRef.current?.previousElementSibling?.tagName === 'div'\n ? endTemplateRef.current.previousElementSibling.innerHTML\n : ''),\n );\n\n if (!html && src) {\n // fetch the remote component\n const fetchInit = {\n method: 'GET',\n headers: remoteFetchHeaders(additionalHeaders),\n credentials,\n } as RequestInit;\n\n const res = await fetch(url, fetchInit);\n\n if (!res.ok) {\n let error: Error = failedToFetchRemoteComponentError(url.href, {\n cause: new Error(`${res.status} ${res.statusText}`),\n });\n try {\n const body = await res.text();\n const parser = new DOMParser();\n const doc = parser.parseFromString(body, 'text/html');\n const errorTemplate = doc.querySelector(\n 'template[data-next-error-message]',\n );\n const errorMessage = errorTemplate?.getAttribute(\n 'data-next-error-message',\n );\n const errorStack = errorTemplate?.getAttribute(\n 'data-next-error-stack',\n );\n\n if (errorMessage) {\n error = new RemoteComponentsError(errorMessage);\n if (errorStack) {\n error.stack = errorStack;\n }\n }\n } catch {\n // ignore\n }\n\n throw error;\n }\n\n // get the full HTML content as a string\n const remoteHtml = await res.text();\n htmlRef.current = remoteHtml;\n html = getRemoteComponentHtml(remoteHtml);\n }\n\n // create a virtual element which will be used to parse the HTML and extract the component and RSC flight data\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, 'text/html');\n\n if (\n (doc.querySelectorAll('div[data-bundle][data-route]').length > 1 &&\n !doc.querySelector(\n `div[data-bundle][data-route][id^=\"${name}\"]`,\n )) ||\n (doc.querySelectorAll('remote-component:not([src])').length > 1 &&\n !doc.querySelector(`remote-component[name=\"${name}\"]`))\n ) {\n throw multipleRemoteComponentsError(url.href);\n }\n\n // reference to the remote component content\n const component =\n doc.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`) ??\n // fallback to the first element with the data-bundle and data-route attributes when not using a named remote component\n doc.querySelector('div[data-bundle][data-route]') ??\n // fallback to Next.js Pages Router\n doc.querySelector('div#__next') ??\n // fallback to the remote-component web component\n doc.querySelector(`remote-component[name=\"${name}\"]:not([src])`) ??\n doc.querySelector('remote-component:not([src])');\n const nextData = JSON.parse(\n (\n doc.querySelector('#__NEXT_DATA__') ??\n doc.querySelector('#__REMOTE_NEXT_DATA__')\n )?.textContent ?? 'null',\n ) as {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: 'turbopack' | 'webpack' | 'script';\n shared?: Record<string, string>;\n };\n };\n page: string;\n buildId: string;\n } | null;\n\n const remoteName =\n component?.getAttribute('id')?.replace(/_ssr$/, '') ||\n (nextData ? '__next' : name);\n // reference to the RSC flight data\n const rsc = doc.querySelector(`#${remoteName}_rsc`);\n\n // reference to the bundle containing the client components\n const bundle =\n component?.getAttribute('data-bundle') ||\n nextData?.props.__REMOTE_COMPONENT__?.bundle ||\n 'default';\n\n const isRemoteComponent =\n component?.tagName.toLowerCase() === 'remote-component';\n\n const metadata = {\n name: remoteName,\n bundle,\n route:\n component?.getAttribute('data-route') ??\n nextData?.page ??\n (url.pathname || DEFAULT_ROUTE),\n runtime: (component?.getAttribute('data-runtime') ??\n (nextData?.props.__REMOTE_COMPONENT__?.runtime ||\n RUNTIME_SCRIPT)) as RemoteComponentPropsType['runtime'],\n };\n\n const remoteSharedEl = doc.querySelector(\n `#${remoteName}_shared[data-remote-components-shared]`,\n );\n const remoteShared =\n nextData?.props.__REMOTE_COMPONENT__?.shared ??\n ((JSON.parse(remoteSharedEl?.textContent ?? '{}') ?? {}) as Record<\n string,\n string\n >);\n remoteSharedEl?.remove();\n\n if (!component || !(rsc || nextData || isRemoteComponent)) {\n throw new RemoteComponentsError(\n `Remote Component not found on ${url.href}.${\n remoteName !== '__vercel_remote_component'\n ? `The name for the <RemoteComponent> is \"${remoteName}\". Check <RemoteComponent> usage.`\n : ''\n } Did you forget to wrap the content in <RemoteComponent>?`,\n );\n }\n\n if (prevIsRemoteComponentRef.current) {\n if (shadowRoot) {\n shadowRoot.innerHTML = '';\n }\n const self = globalThis as typeof globalThis &\n RemoteComponentMountUnmount;\n const prevUrl = prevUrlRef.current;\n if (\n prevUrl &&\n self.__remote_script_entrypoint_unmount__?.[prevUrl.href]\n ) {\n const unmountPromises = Promise.all(\n Array.from(unmountRef.current ?? []).map(async (unmount) =>\n unmount(\n shadowRoot ?? prevRemoteComponentContainerRef.current,\n ),\n ),\n );\n unmountRef.current = null;\n await unmountPromises;\n }\n }\n prevIsRemoteComponentRef.current = isRemoteComponent;\n prevUrlRef.current = url;\n\n // update all relative URLs to absolute URLs based on the remote component URL\n applyOriginToNodes(doc, url);\n\n // reference to all link elements in the remote component\n const links = Array.from(\n doc.querySelectorAll<HTMLLinkElement>('link[href]'),\n )\n .filter((link) => {\n return !component.contains(link);\n })\n .map((link) => ({\n href: new URL(link.getAttribute('href') ?? link.href, url).href,\n ...link\n .getAttributeNames()\n .reduce<Record<string, string>>((acc, key) => {\n if (key !== 'href') {\n acc[attrToProp[key] ?? key] = link.getAttribute(key) ?? '';\n }\n return acc;\n }, {}),\n }));\n\n const scripts = (\n isRemoteComponent ? component : doc\n ).querySelectorAll<HTMLScriptElement>('script[src],script[data-src]');\n\n // handle inline scripts in the remote component\n const inlineScripts = (\n isRemoteComponent ? component : doc\n ).querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\n\n if (!isRemoteComponent) {\n // Next.js Script support\n const self = globalThis as typeof globalThis & {\n __next_s: [string, Record<string, string>][];\n };\n const prevNextScripts = self.__next_s;\n const nextScripts = [] as [string, Record<string, string>][];\n // eslint-disable-next-line camelcase\n self.__next_s = nextScripts;\n\n await Promise.all(\n Array.from(inlineScripts)\n .filter(\n (script) =>\n !(\n script.id.endsWith('_shared') &&\n script.getAttribute('type') === 'application/json' &&\n typeof script.getAttribute(\n 'data-remote-components-shared',\n ) === 'string'\n ),\n )\n .map((script) => {\n return new Promise((resolve) => {\n // only handle inline scripts with content, but not Next.js RSC scripts\n if (\n script.textContent &&\n !script.textContent.includes('self.__next_f=') &&\n !script.textContent.includes('self.__next_f.push')\n ) {\n // if script is inline javascript, then execute using blob\n if (\n !script.getAttribute('type') ||\n script.getAttribute('type') === 'text/javascript' ||\n script.getAttribute('type') === 'application/javascript'\n ) {\n const newScript = document.createElement('script');\n\n // scripts loaded from external sources needs this workaround\n const blob = new Blob([script.textContent], {\n type: 'application/javascript',\n });\n const blobUrl = URL.createObjectURL(blob);\n\n newScript.onload = () => {\n resolve(undefined);\n // script executed and safe to remove\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n };\n // on error we still want to resolve to not block the remote component loading\n newScript.onerror = () => {\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n resolve(undefined);\n };\n\n newScript.src = blobUrl;\n document.body.appendChild(newScript);\n } else {\n resolve(undefined);\n document.body.appendChild(script);\n }\n } else {\n resolve(undefined);\n }\n });\n }),\n );\n // process the remote component Next.js Script container\n nextScripts.forEach(([scriptSrc, props]) => {\n const script = document.createElement('script');\n // when we have a script src, apply it (inline scripts have `0` as src)\n if (scriptSrc) {\n script.src = scriptSrc;\n }\n // apply Script props\n if (typeof props.children === 'string') {\n script.textContent = props.children;\n }\n setAttributesFromProps(script, props);\n document.head.appendChild(script);\n });\n // restore previous Next.js Script container\n // eslint-disable-next-line camelcase\n self.__next_s = prevNextScripts;\n }\n\n let rscName;\n if (rsc) {\n rscName = `__remote_component_rsc_${escapeString(\n id,\n )}_${escapeString(remoteName)}`;\n rsc.textContent =\n rsc.textContent?.replace(\n new RegExp(`self\\\\[\"${remoteName}\"\\\\]`, 'g'),\n `self[\"${rscName}\"]`,\n ) ?? '';\n document.body.appendChild(rsc);\n }\n\n const newData = {\n ...metadata,\n links,\n remoteShared,\n src: typeof src === 'string' ? src : src.href,\n serverUrl: url.href,\n data: rsc\n ? (rsc.textContent || '').split('\\n').filter(Boolean)\n : [],\n };\n\n componentHydrationHtml.current = `${Array.from(\n doc.querySelectorAll('link,style'),\n )\n .map((link) => link.outerHTML)\n .join('')}${\n reset\n ? `<style data-remote-components-reset=\"\">:host { all: initial; }</style>`\n : ''\n }${component.innerHTML}`;\n\n const userShared = await shared;\n\n if ('__remote_components_missing_shared__' in userShared) {\n userShared.__remote_components_missing_shared__().catch((e) => {\n throw e;\n });\n } else if ('__remote_components_missing_shared__' in remoteShared) {\n throw new RemoteComponentsError(\n remoteShared.__remote_components_missing_shared__,\n );\n }\n\n if (isRemoteComponent) {\n setData(newData);\n if (shadowRoot) {\n let shadowRootHtml = component.innerHTML;\n if (reset) {\n shadowRootHtml = `<style data-remote-components-reset=\"\">:host { all: initial; }</style>${shadowRootHtml}`;\n }\n shadowRoot.innerHTML = shadowRootHtml;\n setRemoteComponent(null);\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n } else if (isolate === false) {\n setRemoteComponent(\n // TODO: remove wrapper div by converting HTML to RSC or React tree\n <div\n dangerouslySetInnerHTML={{ __html: component.innerHTML }}\n ref={prevRemoteComponentContainerRef}\n />,\n );\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(component.querySelectorAll('script')),\n url,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) =>\n mountFn(prevRemoteComponentContainerRef.current),\n ),\n );\n }\n } else {\n const result = await loadRemoteComponent({\n url,\n name: remoteName,\n rscName,\n bundle,\n route: metadata.route,\n runtime: metadata.runtime,\n data: newData.data,\n nextData,\n scripts: Array.from(scripts).map((script) => {\n const scriptSrc =\n script.getAttribute('data-src') ||\n script.getAttribute('src') ||\n script.src;\n const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(\n scriptSrc,\n )?.groups ?? {\n prefix: undefined,\n id: scriptSrc,\n };\n return {\n src: new URL(\n `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n ),\n url,\n ).href,\n };\n }),\n shared: {\n ...sharedPolyfills(userShared),\n ...userShared,\n },\n remoteShared,\n container: shadowRoot,\n });\n if (rsc) {\n rsc.remove();\n }\n\n setData(newData);\n if (result.error) {\n setRemoteComponent(result.error);\n } else {\n setRemoteComponent(result.component);\n }\n }\n } catch (error) {\n setRemoteComponent(error as Error);\n }\n });\n }\n }, [\n url,\n src,\n isolate,\n credentials,\n name,\n shared,\n shadowRoot,\n additionalHeaders,\n reset,\n id,\n ]);\n\n if (remoteComponent instanceof Error) {\n throw remoteComponent;\n }\n\n const metadataJson = (\n <script data-remote-component type=\"application/json\">\n {JSON.stringify({\n name: data?.name || name,\n bundle: data?.bundle || 'default',\n route: data?.route || DEFAULT_ROUTE,\n runtime: prevIsRemoteComponentRef.current\n ? RUNTIME_SCRIPT\n : data?.runtime || RUNTIME_WEBPACK,\n })}\n </script>\n );\n const resetStyle = reset ? (\n <style data-remote-components-reset=\"\">{`:host { all: initial; }`}</style>\n ) : null;\n const linksToRender: React.ReactNode[] | null =\n data?.links?.map((link) => (\n <link\n {...link}\n href={new URL(link.href as string, url).href}\n key={JSON.stringify(link)}\n />\n )) || null;\n const componentToRender = (\n <>\n {resetStyle}\n {linksToRender}\n {remoteComponent ?? children}\n </>\n );\n\n if (componentHydrationHtml.current && shadowRoot && !shadowRoot.innerHTML) {\n shadowRoot.innerHTML = componentHydrationHtml.current;\n componentHydrationHtml.current = null;\n\n if (prevIsRemoteComponentRef.current) {\n // ensure we load static resources when hydrating a remote component in shadow DOM\n loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n )\n .then(({ mount }) => {\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n })\n .catch((e) => {\n const error = new RemoteComponentsError(\n `Error mounting remote component from \"${url.href}\"`,\n {\n cause: e,\n },\n );\n setRemoteComponent(error);\n });\n }\n }\n\n if (isolate !== false) {\n const shadowRemoteComponentHtml =\n shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ??\n shadowRoot?.querySelector('div[data-bundle][data-route]');\n if (shadowRemoteComponentHtml) {\n shadowRemoteComponentHtml.remove();\n }\n\n return (\n <>\n {metadataJson}\n <div\n data-remote-component-id={`shadowroot_${keySuffix}`}\n id={`shadowroot_${data?.name ?? name}`}\n ref={shadowRootContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {typeof document === 'undefined' ? (\n <div\n dangerouslySetInnerHTML={{\n __html: `<img\n alt=\"\" decoding=\"async\" style=\"display:none\"\n src=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==\"\n onload=\"(function(el){\n const root = el.getRootNode();\n globalThis.__remote_components_shadowroot_${keySuffix} = root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {resetStyle}\n {linksToRender}\n {children}\n </template>\n ) : null}\n {shadowRoot && remoteComponent\n ? createPortal(\n <>\n <template id={`${name}_start`} />\n {resetStyle}\n {linksToRender}\n {remoteComponent}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>,\n shadowRoot,\n )\n : null}\n </div>\n </>\n );\n }\n htmlRef.current = null;\n\n // render start/end markers for the remote component\n return (\n <>\n <template id={`${name}_start`} />\n {metadataJson}\n {componentToRender}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA2qBgB;AAAA;AAAA;AAAA;AAwGV;AAnxBN,IAAAA,gBAOO;AACP,uBAA6B;AAC7B,0BAAmC;AACnC,sBAAgC;AAChC,8BAUO;AACP,mBAGO;AACP,2BAAmC;AACnC,sCAAqC;AACrC,mBAAyC;AA6CzC,SAAS,uBAAuB,MAAc;AAC5C,MAAI,OAAO,aAAa;AAAa,WAAO;AAG5C,QAAM,SAAS,IAAI,UAAU;AAC7B,QAAM,OAAO,OAAO,gBAAgB,MAAM,WAAW;AAGrD,QAAM,8BAA8B,KAAK;AAAA,IACvC;AAAA,EACF;AACA,MAAI,6BAA6B;AAC/B,WAAO,4BAA4B;AAAA,EACrC;AAGA,QAAM,2BAA2B,KAAK;AAAA,IACpC;AAAA,EACF;AACA,MAAI,yBAAyB,SAAS,GAAG;AACvC,WAAO,GAAG,MAAM,KAAK,KAAK,iBAAiB,aAAa,CAAC,EACtD,IAAI,CAAC,SAAS,KAAK,SAAS,EAC5B,KAAK,EAAE,IAAI,MAAM,KAAK,wBAAwB,EAC9C,IAAI,CAAC,cAAc,UAAU,SAAS,EACtC,KAAK,EAAE;AAAA,EACZ;AAEA,SAAO;AACT;AAEA,M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.tsx"],"sourcesContent":["import {\n startTransition,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { applyOriginToNodes } from '#internal/shared/client/apply-origin';\nimport { sharedPolyfills } from '#internal/shared/client/polyfill';\nimport {\n DEFAULT_ROUTE,\n type LoadRemoteComponentProps,\n loadRemoteComponent,\n loadStaticRemoteComponent,\n REMOTE_COMPONENT_REGEX,\n RemoteComponentsError,\n RUNTIME_SCRIPT,\n RUNTIME_WEBPACK,\n setAttributesFromProps,\n} from '#internal/shared/client/remote-component';\nimport {\n failedToFetchRemoteComponentError,\n multipleRemoteComponentsError,\n} from '#internal/shared/error';\nimport { remoteFetchHeaders } from '#internal/shared/ssr/fetch-headers';\nimport { getClientOrServerUrl } from '#internal/shared/ssr/get-client-or-server-url';\nimport { attrToProp, escapeString } from '#internal/shared/utils';\nimport type {\n MountOrUnmountFunction,\n RemoteComponentMountUnmount,\n RemoteComponentProps as RemoteComponentPropsType,\n} from '#remote-components/shared/client/types';\n\n// patch react/jsx-runtime to support the shadowrootmode attribute on template elements\ndeclare module 'react/jsx-runtime' {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace JSX {\n interface IntrinsicElements {\n template: {\n shadowrootmode?: 'open' | 'closed';\n id?: string;\n ref?: React.Ref<HTMLTemplateElement>;\n dangerouslySetInnerHTML?: {\n __html: string;\n };\n children?: React.ReactNode;\n };\n }\n }\n}\n\nexport interface RemoteComponentProps {\n /** The source URL of the remote component. */\n src?: string | URL;\n /** Whether to isolate the remote component using a Shadow DOM wrapper. */\n isolate?: boolean;\n /** The shadow DOM mode to use when isolating the remote component. */\n mode?: 'open' | 'closed';\n /** Whether to include a CSS reset style in the shadow DOM. Defaults to `false`. */\n reset?: boolean;\n /** The credentials to use for the fetch request. Defaults to `same-origin`. */\n credentials?: RequestCredentials;\n name?: string;\n /** Shared modules to include in the remote component's context. */\n shared?: LoadRemoteComponentProps['shared'];\n /** Additional headers to use when fetching the remote component. */\n additionalHeaders?: Headers | Record<string, string>;\n /** The children to use as a loading fallback until the remote component is loaded. */\n children?: React.ReactNode;\n /** Called right before a new remote component load starts. */\n onBeforeLoad?: (src: string | URL) => void;\n /** Called when the remote component has been successfully loaded and mounted. */\n onLoad?: (src: string | URL) => void;\n /** Called when an error occurs while loading or mounting the remote component. */\n onError?: (error: unknown) => void;\n /** Called when a different remote component is loaded into the same wrapper. */\n onChange?: (info: {\n previousSrc: string | URL | null;\n nextSrc: string | URL | null;\n previousName: string | undefined;\n nextName: string | undefined;\n }) => void;\n}\n\nfunction getRemoteComponentHtml(html: string) {\n if (typeof document === 'undefined') return html;\n\n // parse the HTML string to extract the relevant parts\n const parser = new DOMParser();\n const temp = parser.parseFromString(html, 'text/html');\n\n // used by the Next.js Pages Router remote as a wrapper\n const ssrRemoteComponentContainer = temp.querySelector(\n 'div[id^=\"__REMOTE_COMPONENT\"]',\n );\n if (ssrRemoteComponentContainer) {\n return ssrRemoteComponentContainer.innerHTML;\n }\n\n // remote component content\n const remoteComponentContainer = temp.querySelectorAll(\n `div[data-bundle][data-route][data-runtime][id^=\"__vercel_remote_component\"],div[data-bundle][data-route],div#__next,remote-component:not([src])`,\n );\n if (remoteComponentContainer.length > 0) {\n return `${Array.from(temp.querySelectorAll('link,script'))\n .map((link) => link.outerHTML)\n .join('')}${Array.from(remoteComponentContainer)\n .map((container) => container.outerHTML)\n .join('')}`;\n }\n\n return '';\n}\n\nconst DUMMY_FALLBACK = 'http://remote-components-dummy-fallback';\n\n/**\n * RemoteComponent is a React component that fetches and renders a remote component.\n * It supports SSR and can isolate the remote component in a shadow DOM.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n *\n * @example\n *\n * Use the `<RemoteComponent>` in your React application to consume a remote component from a remote application:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/react';\n *\n * export default function App() {\n * return (\n * <>\n * <h1>Welcome to My App</h1>\n * <p>This page consumes a remote component from another application.</p>\n * <RemoteComponent src=\"/nextjs-app-remote/components/header\" />\n * </>\n * );\n * }\n * ```\n *\n * To share modules, you can provide a shared module map with references to the shared modules:\n *\n * ```tsx\n * <RemoteComponent\n * src=\"/nextjs-app-remote/components/header\"\n * shared={{\n * '@/components/provider': () => import('@/components/host-provider')\n * }}\n * />\n * ```\n */\nexport function RemoteComponent({\n src,\n isolate,\n mode = 'open',\n reset,\n credentials = 'same-origin',\n name: nameProp = '__vercel_remote_component',\n shared = {},\n additionalHeaders,\n children,\n onBeforeLoad,\n onLoad,\n onError,\n onChange,\n}: RemoteComponentProps) {\n const name = useMemo(() => {\n if (typeof src === 'string') {\n const url = new URL(\n src,\n typeof document !== 'undefined' ? location.href : DUMMY_FALLBACK,\n );\n if (url.hash) {\n return url.hash.slice(1);\n }\n } else if (typeof src === 'object' && 'hash' in src && src.hash) {\n return src.hash.slice(1) || nameProp;\n }\n return nameProp;\n }, [src, nameProp]);\n\n const [data, setData] = useState<Omit<\n RemoteComponentPropsType,\n 'children'\n > | null>(null);\n\n const url = useMemo(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);\n\n // for relative src paths, use just the pathname as the unique id.\n // for static urls, use the full url as the unique id as the path may not be unique.\n // this id needs to be the same for server and client side rendering.\n // note that if this needs to be more unique, can pass through the bundle as an id prop and ammend it to this id.\n const id =\n url.origin ===\n (typeof location !== 'undefined' ? location.origin : DUMMY_FALLBACK)\n ? url.pathname\n : url.href;\n\n const keySuffix = `${escapeString(id)}_${escapeString(data?.name ?? name)}`;\n\n const [remoteComponent, setRemoteComponent] = useState<\n React.ReactNode | Error\n >(null);\n const shadowRootContainerRef = useRef<HTMLDivElement | null>(null);\n const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(() => {\n const self = globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n >;\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n const ssrShadowRoot =\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot ??\n self[shadowRootKey] ??\n null)\n : null;\n self[shadowRootKey] = null;\n return ssrShadowRoot;\n });\n const htmlRef = useRef<string | null>(\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot?.innerHTML ??\n document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ??\n document.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`)\n ?.innerHTML ??\n document.querySelector('div[data-bundle][data-route]')?.innerHTML)\n : null,\n );\n const endTemplateRef = useRef<HTMLTemplateElement | null>(null);\n // collect initial content that needs to be removed after remote component renders\n const childrenRef = useRef(\n typeof document !== 'undefined'\n ? (() => {\n let el = document.querySelector(`template[id=\"${name}_start\"]`);\n const elements = [];\n while (el && el.id !== `${name}_end`) {\n if (\n el.id !== `${name}_start` &&\n !el.getAttribute('data-remote-component')\n ) {\n elements.push(el);\n }\n el = el.nextElementSibling as HTMLTemplateElement | null;\n }\n return elements;\n })()\n : [],\n );\n const prevSrcRef = useRef<string | URL | null>(null);\n const componentHydrationHtml = useRef<string | null>(null);\n const prevIsRemoteComponentRef = useRef<boolean>(false);\n const prevUrlRef = useRef<URL | null>(null);\n const prevRemoteComponentContainerRef = useRef<HTMLDivElement | null>(null);\n const unmountRef = useRef<Set<MountOrUnmountFunction> | null>(null);\n const prevNameRef = useRef<string | undefined>(undefined);\n\n useLayoutEffect(() => {\n // clear initial content\n if (childrenRef.current.length > 0 && remoteComponent) {\n childrenRef.current.forEach((el) => {\n el.remove();\n });\n childrenRef.current = [];\n }\n\n if (isolate !== false && typeof document !== 'undefined' && !shadowRoot) {\n const self = globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n >;\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n\n let shadowRootElement: ShadowRoot | null = null;\n const element = document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n );\n shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;\n\n if (!shadowRootElement && element) {\n // create a shadow root if it doesn't exist\n // this is a fallback for browsers that don't support declarative shadow DOM\n try {\n shadowRootElement = element.attachShadow({ mode });\n self[shadowRootKey] = shadowRootElement;\n } catch {\n // do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n // remove all nodes from the shadow root except links\n shadowRootElement.querySelectorAll('*:not(link)').forEach((node) => {\n node.remove();\n });\n setShadowRoot(shadowRootElement);\n }\n }\n }, [isolate, shadowRoot, remoteComponent, mode, keySuffix]);\n\n useLayoutEffect(() => {\n if (shadowRoot && remoteComponent) {\n const resetStyles = shadowRoot.querySelectorAll(\n 'style[data-remote-components-reset]',\n );\n // ensure we only have one reset style in the shadow root\n if (resetStyles.length > 1) {\n resetStyles.forEach((style, index) => {\n if (index > 0) {\n style.remove();\n }\n });\n }\n\n // clear the html ref after hydration\n htmlRef.current = null;\n\n // clear all nodes except links and styles until the start marker\n // the marker gets only rendered on hydration\n let el: ChildNode | null = shadowRoot.childNodes[0] ?? null;\n while (el && (!('id' in el) || el.id !== `${name}_start`)) {\n const nextEl = el.nextSibling;\n if (el.nodeName !== 'LINK' && el.nodeName !== 'STYLE') {\n el.parentNode?.removeChild(el);\n }\n el = nextEl;\n }\n }\n }, [shadowRoot, remoteComponent, name]);\n\n useEffect(() => {\n if (src && src !== prevSrcRef.current) {\n const previousSrc = prevSrcRef.current;\n const previousName = prevNameRef.current;\n prevSrcRef.current = src;\n\n onBeforeLoad?.(src);\n\n startTransition(async () => {\n try {\n let html = getRemoteComponentHtml(\n htmlRef.current ??\n (endTemplateRef.current?.previousElementSibling?.tagName === 'div'\n ? endTemplateRef.current.previousElementSibling.innerHTML\n : ''),\n );\n\n if (!html && src) {\n // fetch the remote component\n const fetchInit = {\n method: 'GET',\n headers: remoteFetchHeaders(additionalHeaders),\n credentials,\n } as RequestInit;\n\n const res = await fetch(url, fetchInit);\n\n if (!res.ok) {\n let error: Error = failedToFetchRemoteComponentError(url.href, {\n cause: new Error(`${res.status} ${res.statusText}`),\n });\n try {\n const body = await res.text();\n const parser = new DOMParser();\n const doc = parser.parseFromString(body, 'text/html');\n const errorTemplate = doc.querySelector(\n 'template[data-next-error-message]',\n );\n const errorMessage = errorTemplate?.getAttribute(\n 'data-next-error-message',\n );\n const errorStack = errorTemplate?.getAttribute(\n 'data-next-error-stack',\n );\n\n if (errorMessage) {\n error = new RemoteComponentsError(errorMessage);\n if (errorStack) {\n error.stack = errorStack;\n }\n }\n } catch {\n // ignore\n }\n\n throw error;\n }\n\n // get the full HTML content as a string\n const remoteHtml = await res.text();\n htmlRef.current = remoteHtml;\n html = getRemoteComponentHtml(remoteHtml);\n }\n\n // create a virtual element which will be used to parse the HTML and extract the component and RSC flight data\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, 'text/html');\n\n if (\n (doc.querySelectorAll('div[data-bundle][data-route]').length > 1 &&\n !doc.querySelector(\n `div[data-bundle][data-route][id^=\"${name}\"]`,\n )) ||\n (doc.querySelectorAll('remote-component:not([src])').length > 1 &&\n !doc.querySelector(`remote-component[name=\"${name}\"]`))\n ) {\n throw multipleRemoteComponentsError(url.href);\n }\n\n // reference to the remote component content\n const component =\n doc.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`) ??\n // fallback to the first element with the data-bundle and data-route attributes when not using a named remote component\n doc.querySelector('div[data-bundle][data-route]') ??\n // fallback to Next.js Pages Router\n doc.querySelector('div#__next') ??\n // fallback to the remote-component web component\n doc.querySelector(`remote-component[name=\"${name}\"]:not([src])`) ??\n doc.querySelector('remote-component:not([src])');\n const nextData = JSON.parse(\n (\n doc.querySelector('#__NEXT_DATA__') ??\n doc.querySelector('#__REMOTE_NEXT_DATA__')\n )?.textContent ?? 'null',\n ) as {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: 'turbopack' | 'webpack' | 'script';\n shared?: Record<string, string>;\n };\n };\n page: string;\n buildId: string;\n } | null;\n\n const remoteName =\n component?.getAttribute('id')?.replace(/_ssr$/, '') ||\n (nextData ? '__next' : name);\n // reference to the RSC flight data\n const rsc = doc.querySelector(`#${remoteName}_rsc`);\n\n // reference to the bundle containing the client components\n const bundle =\n component?.getAttribute('data-bundle') ||\n nextData?.props.__REMOTE_COMPONENT__?.bundle ||\n 'default';\n\n const isRemoteComponent =\n component?.tagName.toLowerCase() === 'remote-component';\n\n const metadata = {\n name: remoteName,\n bundle,\n route:\n component?.getAttribute('data-route') ??\n nextData?.page ??\n (url.pathname || DEFAULT_ROUTE),\n runtime: (component?.getAttribute('data-runtime') ??\n (nextData?.props.__REMOTE_COMPONENT__?.runtime ||\n RUNTIME_SCRIPT)) as RemoteComponentPropsType['runtime'],\n };\n\n const remoteSharedEl = doc.querySelector(\n `#${remoteName}_shared[data-remote-components-shared]`,\n );\n const remoteShared =\n nextData?.props.__REMOTE_COMPONENT__?.shared ??\n ((JSON.parse(remoteSharedEl?.textContent ?? '{}') ?? {}) as Record<\n string,\n string\n >);\n remoteSharedEl?.remove();\n\n if (!component || !(rsc || nextData || isRemoteComponent)) {\n throw new RemoteComponentsError(\n `Remote Component not found on ${url.href}.${\n remoteName !== '__vercel_remote_component'\n ? `The name for the <RemoteComponent> is \"${remoteName}\". Check <RemoteComponent> usage.`\n : ''\n } Did you forget to wrap the content in <RemoteComponent>?`,\n );\n }\n\n if (prevIsRemoteComponentRef.current) {\n if (shadowRoot) {\n shadowRoot.innerHTML = '';\n }\n const self = globalThis as typeof globalThis &\n RemoteComponentMountUnmount;\n const prevUrl = prevUrlRef.current;\n if (\n prevUrl &&\n self.__remote_script_entrypoint_unmount__?.[prevUrl.href]\n ) {\n const unmountPromises = Promise.all(\n Array.from(unmountRef.current ?? []).map(async (unmount) =>\n unmount(\n shadowRoot ?? prevRemoteComponentContainerRef.current,\n ),\n ),\n );\n unmountRef.current = null;\n await unmountPromises;\n }\n }\n prevIsRemoteComponentRef.current = isRemoteComponent;\n prevUrlRef.current = url;\n prevNameRef.current = remoteName;\n\n // update all relative URLs to absolute URLs based on the remote component URL\n applyOriginToNodes(doc, url);\n\n // reference to all link elements in the remote component\n const links = Array.from(\n doc.querySelectorAll<HTMLLinkElement>('link[href]'),\n )\n .filter((link) => {\n return !component.contains(link);\n })\n .map((link) => ({\n href: new URL(link.getAttribute('href') ?? link.href, url).href,\n ...link\n .getAttributeNames()\n .reduce<Record<string, string>>((acc, key) => {\n if (key !== 'href') {\n acc[attrToProp[key] ?? key] = link.getAttribute(key) ?? '';\n }\n return acc;\n }, {}),\n }));\n\n const scripts = (\n isRemoteComponent ? component : doc\n ).querySelectorAll<HTMLScriptElement>('script[src],script[data-src]');\n\n // handle inline scripts in the remote component\n const inlineScripts = (\n isRemoteComponent ? component : doc\n ).querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\n\n if (!isRemoteComponent) {\n // Next.js Script support\n const self = globalThis as typeof globalThis & {\n __next_s: [string, Record<string, string>][];\n };\n const prevNextScripts = self.__next_s;\n const nextScripts = [] as [string, Record<string, string>][];\n // eslint-disable-next-line camelcase\n self.__next_s = nextScripts;\n\n await Promise.all(\n Array.from(inlineScripts)\n .filter(\n (script) =>\n !(\n script.id.endsWith('_shared') &&\n script.getAttribute('type') === 'application/json' &&\n typeof script.getAttribute(\n 'data-remote-components-shared',\n ) === 'string'\n ),\n )\n .map((script) => {\n return new Promise((resolve) => {\n // only handle inline scripts with content, but not Next.js RSC scripts\n if (\n script.textContent &&\n !script.textContent.includes('self.__next_f=') &&\n !script.textContent.includes('self.__next_f.push')\n ) {\n // if script is inline javascript, then execute using blob\n if (\n !script.getAttribute('type') ||\n script.getAttribute('type') === 'text/javascript' ||\n script.getAttribute('type') === 'application/javascript'\n ) {\n const newScript = document.createElement('script');\n\n // scripts loaded from external sources needs this workaround\n const blob = new Blob([script.textContent], {\n type: 'application/javascript',\n });\n const blobUrl = URL.createObjectURL(blob);\n\n newScript.onload = () => {\n resolve(undefined);\n // script executed and safe to remove\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n };\n // on error we still want to resolve to not block the remote component loading\n newScript.onerror = () => {\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n resolve(undefined);\n };\n\n newScript.src = blobUrl;\n document.body.appendChild(newScript);\n } else {\n resolve(undefined);\n document.body.appendChild(script);\n }\n } else {\n resolve(undefined);\n }\n });\n }),\n );\n // process the remote component Next.js Script container\n nextScripts.forEach(([scriptSrc, props]) => {\n const script = document.createElement('script');\n // when we have a script src, apply it (inline scripts have `0` as src)\n if (scriptSrc) {\n script.src = scriptSrc;\n }\n // apply Script props\n if (typeof props.children === 'string') {\n script.textContent = props.children;\n }\n setAttributesFromProps(script, props);\n document.head.appendChild(script);\n });\n // restore previous Next.js Script container\n // eslint-disable-next-line camelcase\n self.__next_s = prevNextScripts;\n }\n\n let rscName;\n if (rsc) {\n rscName = `__remote_component_rsc_${escapeString(\n id,\n )}_${escapeString(remoteName)}`;\n rsc.textContent =\n rsc.textContent?.replace(\n new RegExp(`self\\\\[\"${remoteName}\"\\\\]`, 'g'),\n `self[\"${rscName}\"]`,\n ) ?? '';\n document.body.appendChild(rsc);\n }\n\n const newData = {\n ...metadata,\n links,\n remoteShared,\n src: typeof src === 'string' ? src : src.href,\n serverUrl: url.href,\n data: rsc\n ? (rsc.textContent || '').split('\\n').filter(Boolean)\n : [],\n };\n\n componentHydrationHtml.current = `${Array.from(\n doc.querySelectorAll('link,style'),\n )\n .map((link) => link.outerHTML)\n .join('')}${\n reset\n ? `<style data-remote-components-reset=\"\">:host { all: initial; }</style>`\n : ''\n }${component.innerHTML}`;\n\n const userShared = await shared;\n\n if ('__remote_components_missing_shared__' in userShared) {\n userShared.__remote_components_missing_shared__().catch((e) => {\n throw e;\n });\n } else if ('__remote_components_missing_shared__' in remoteShared) {\n throw new RemoteComponentsError(\n remoteShared.__remote_components_missing_shared__,\n );\n }\n\n if (isRemoteComponent) {\n // Only call onChange when not on first load (matching HTML implementation)\n if (previousSrc !== null) {\n onChange?.({\n previousSrc,\n nextSrc: src,\n previousName,\n nextName: remoteName,\n });\n }\n setData(newData);\n if (shadowRoot) {\n let shadowRootHtml = component.innerHTML;\n if (reset) {\n shadowRootHtml = `<style data-remote-components-reset=\"\">:host { all: initial; }</style>${shadowRootHtml}`;\n }\n shadowRoot.innerHTML = shadowRootHtml;\n setRemoteComponent(null);\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n onLoad?.(src);\n } else if (isolate === false) {\n setRemoteComponent(\n // TODO: remove wrapper div by converting HTML to RSC or React tree\n <div\n dangerouslySetInnerHTML={{ __html: component.innerHTML }}\n ref={prevRemoteComponentContainerRef}\n />,\n );\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(component.querySelectorAll('script')),\n url,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) =>\n mountFn(prevRemoteComponentContainerRef.current),\n ),\n );\n onLoad?.(src);\n }\n } else {\n const result = await loadRemoteComponent({\n url,\n name: remoteName,\n rscName,\n bundle,\n route: metadata.route,\n runtime: metadata.runtime,\n data: newData.data,\n nextData,\n scripts: Array.from(scripts).map((script) => {\n const scriptSrc =\n script.getAttribute('data-src') ||\n script.getAttribute('src') ||\n script.src;\n const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(\n scriptSrc,\n )?.groups ?? {\n prefix: undefined,\n id: scriptSrc,\n };\n return {\n src: new URL(\n `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n ),\n url,\n ).href,\n };\n }),\n shared: {\n ...sharedPolyfills(userShared),\n ...userShared,\n },\n remoteShared,\n container: shadowRoot,\n });\n if (rsc) {\n rsc.remove();\n }\n\n setData(newData);\n // Only call onChange when not on first load (matching HTML implementation)\n if (previousSrc !== null) {\n onChange?.({\n previousSrc,\n nextSrc: src,\n previousName,\n nextName: remoteName,\n });\n }\n if (result.error) {\n setRemoteComponent(result.error);\n onError?.(result.error);\n } else {\n setRemoteComponent(result.component);\n onLoad?.(src);\n }\n }\n } catch (error) {\n setRemoteComponent(error as Error);\n onError?.(error);\n }\n });\n }\n }, [\n url,\n src,\n isolate,\n credentials,\n name,\n shared,\n shadowRoot,\n additionalHeaders,\n reset,\n id,\n onBeforeLoad,\n onLoad,\n onError,\n onChange,\n ]);\n\n if (remoteComponent instanceof Error) {\n throw remoteComponent;\n }\n\n const metadataJson = (\n <script data-remote-component type=\"application/json\">\n {JSON.stringify({\n name: data?.name || name,\n bundle: data?.bundle || 'default',\n route: data?.route || DEFAULT_ROUTE,\n runtime: prevIsRemoteComponentRef.current\n ? RUNTIME_SCRIPT\n : data?.runtime || RUNTIME_WEBPACK,\n })}\n </script>\n );\n const resetStyle = reset ? (\n <style data-remote-components-reset=\"\">{`:host { all: initial; }`}</style>\n ) : null;\n const linksToRender: React.ReactNode[] | null =\n data?.links?.map((link) => (\n <link\n {...link}\n href={new URL(link.href as string, url).href}\n key={JSON.stringify(link)}\n />\n )) || null;\n const componentToRender = (\n <>\n {resetStyle}\n {linksToRender}\n {remoteComponent ?? children}\n </>\n );\n\n if (componentHydrationHtml.current && shadowRoot && !shadowRoot.innerHTML) {\n shadowRoot.innerHTML = componentHydrationHtml.current;\n componentHydrationHtml.current = null;\n\n if (prevIsRemoteComponentRef.current) {\n // ensure we load static resources when hydrating a remote component in shadow DOM\n loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n )\n .then(({ mount }) => {\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n })\n .then(() => {\n if (src) {\n onLoad?.(src);\n }\n })\n .catch((e) => {\n const error = new RemoteComponentsError(\n `Error mounting remote component from \"${url.href}\"`,\n {\n cause: e,\n },\n );\n setRemoteComponent(error);\n onError?.(error);\n });\n }\n }\n\n if (isolate !== false) {\n const shadowRemoteComponentHtml =\n shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ??\n shadowRoot?.querySelector('div[data-bundle][data-route]');\n if (shadowRemoteComponentHtml) {\n shadowRemoteComponentHtml.remove();\n }\n\n return (\n <>\n {metadataJson}\n <div\n data-remote-component-id={`shadowroot_${keySuffix}`}\n id={`shadowroot_${data?.name ?? name}`}\n ref={shadowRootContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {typeof document === 'undefined' ? (\n <div\n dangerouslySetInnerHTML={{\n __html: `<img\n alt=\"\" decoding=\"async\" style=\"display:none\"\n src=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==\"\n onload=\"(function(el){\n const root = el.getRootNode();\n globalThis.__remote_components_shadowroot_${keySuffix} = root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {resetStyle}\n {linksToRender}\n {children}\n </template>\n ) : null}\n {shadowRoot && remoteComponent\n ? createPortal(\n <>\n <template id={`${name}_start`} />\n {resetStyle}\n {linksToRender}\n {remoteComponent}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>,\n shadowRoot,\n )\n : null}\n </div>\n </>\n );\n }\n htmlRef.current = null;\n\n // render start/end markers for the remote component\n return (\n <>\n <template id={`${name}_start`} />\n {metadataJson}\n {componentToRender}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA4sBgB;AAAA;AAAA;AAAA;AAyHV;AAr0BN,IAAAA,gBAOO;AACP,uBAA6B;AAC7B,0BAAmC;AACnC,sBAAgC;AAChC,8BAUO;AACP,mBAGO;AACP,2BAAmC;AACnC,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 @@ interface RemoteComponentProps {
44
44
  additionalHeaders?: Headers | Record<string, string>;
45
45
  /** The children to use as a loading fallback until the remote component is loaded. */
46
46
  children?: React.ReactNode;
47
+ /** Called right before a new remote component load starts. */
48
+ onBeforeLoad?: (src: string | URL) => void;
49
+ /** Called when the remote component has been successfully loaded and mounted. */
50
+ onLoad?: (src: string | URL) => void;
51
+ /** Called when an error occurs while loading or mounting the remote component. */
52
+ onError?: (error: unknown) => void;
53
+ /** Called when a different remote component is loaded into the same wrapper. */
54
+ onChange?: (info: {
55
+ previousSrc: string | URL | null;
56
+ nextSrc: string | URL | null;
57
+ previousName: string | undefined;
58
+ nextName: string | undefined;
59
+ }) => void;
47
60
  }
48
61
  /**
49
62
  * RemoteComponent is a React component that fetches and renders a remote component.
@@ -81,6 +94,6 @@ interface RemoteComponentProps {
81
94
  * />
82
95
  * ```
83
96
  */
84
- declare function RemoteComponent({ src, isolate, mode, reset, credentials, name: nameProp, shared, additionalHeaders, children, }: RemoteComponentProps): react_jsx_runtime.JSX.Element;
97
+ declare function RemoteComponent({ src, isolate, mode, reset, credentials, name: nameProp, shared, additionalHeaders, children, onBeforeLoad, onLoad, onError, onChange, }: RemoteComponentProps): react_jsx_runtime.JSX.Element;
85
98
 
86
99
  export { RemoteComponent, RemoteComponentProps };
@@ -57,7 +57,11 @@ function RemoteComponent({
57
57
  name: nameProp = "__vercel_remote_component",
58
58
  shared = {},
59
59
  additionalHeaders,
60
- children
60
+ children,
61
+ onBeforeLoad,
62
+ onLoad,
63
+ onError,
64
+ onChange
61
65
  }) {
62
66
  const name = useMemo(() => {
63
67
  if (typeof src === "string") {
@@ -113,6 +117,7 @@ function RemoteComponent({
113
117
  const prevUrlRef = useRef(null);
114
118
  const prevRemoteComponentContainerRef = useRef(null);
115
119
  const unmountRef = useRef(null);
120
+ const prevNameRef = useRef(void 0);
116
121
  useLayoutEffect(() => {
117
122
  if (childrenRef.current.length > 0 && remoteComponent) {
118
123
  childrenRef.current.forEach((el) => {
@@ -168,7 +173,10 @@ function RemoteComponent({
168
173
  }, [shadowRoot, remoteComponent, name]);
169
174
  useEffect(() => {
170
175
  if (src && src !== prevSrcRef.current) {
176
+ const previousSrc = prevSrcRef.current;
177
+ const previousName = prevNameRef.current;
171
178
  prevSrcRef.current = src;
179
+ onBeforeLoad?.(src);
172
180
  startTransition(async () => {
173
181
  try {
174
182
  let html = getRemoteComponentHtml(
@@ -266,6 +274,7 @@ function RemoteComponent({
266
274
  }
267
275
  prevIsRemoteComponentRef.current = isRemoteComponent;
268
276
  prevUrlRef.current = url;
277
+ prevNameRef.current = remoteName;
269
278
  applyOriginToNodes(doc, url);
270
279
  const links = Array.from(
271
280
  doc.querySelectorAll("link[href]")
@@ -371,6 +380,14 @@ function RemoteComponent({
371
380
  );
372
381
  }
373
382
  if (isRemoteComponent) {
383
+ if (previousSrc !== null) {
384
+ onChange?.({
385
+ previousSrc,
386
+ nextSrc: src,
387
+ previousName,
388
+ nextName: remoteName
389
+ });
390
+ }
374
391
  setData(newData);
375
392
  if (shadowRoot) {
376
393
  let shadowRootHtml = component.innerHTML;
@@ -387,6 +404,7 @@ function RemoteComponent({
387
404
  await Promise.all(
388
405
  Array.from(mount).map((mountFn) => mountFn(shadowRoot))
389
406
  );
407
+ onLoad?.(src);
390
408
  } else if (isolate === false) {
391
409
  setRemoteComponent(
392
410
  // TODO: remove wrapper div by converting HTML to RSC or React tree
@@ -408,6 +426,7 @@ function RemoteComponent({
408
426
  (mountFn) => mountFn(prevRemoteComponentContainerRef.current)
409
427
  )
410
428
  );
429
+ onLoad?.(src);
411
430
  }
412
431
  } else {
413
432
  const result = await loadRemoteComponent({
@@ -448,14 +467,25 @@ function RemoteComponent({
448
467
  rsc.remove();
449
468
  }
450
469
  setData(newData);
470
+ if (previousSrc !== null) {
471
+ onChange?.({
472
+ previousSrc,
473
+ nextSrc: src,
474
+ previousName,
475
+ nextName: remoteName
476
+ });
477
+ }
451
478
  if (result.error) {
452
479
  setRemoteComponent(result.error);
480
+ onError?.(result.error);
453
481
  } else {
454
482
  setRemoteComponent(result.component);
483
+ onLoad?.(src);
455
484
  }
456
485
  }
457
486
  } catch (error) {
458
487
  setRemoteComponent(error);
488
+ onError?.(error);
459
489
  }
460
490
  });
461
491
  }
@@ -469,7 +499,11 @@ function RemoteComponent({
469
499
  shadowRoot,
470
500
  additionalHeaders,
471
501
  reset,
472
- id
502
+ id,
503
+ onBeforeLoad,
504
+ onLoad,
505
+ onError,
506
+ onChange
473
507
  ]);
474
508
  if (remoteComponent instanceof Error) {
475
509
  throw remoteComponent;
@@ -505,6 +539,10 @@ function RemoteComponent({
505
539
  return Promise.all(
506
540
  Array.from(mount).map((mountFn) => mountFn(shadowRoot))
507
541
  );
542
+ }).then(() => {
543
+ if (src) {
544
+ onLoad?.(src);
545
+ }
508
546
  }).catch((e) => {
509
547
  const error = new RemoteComponentsError(
510
548
  `Error mounting remote component from "${url.href}"`,
@@ -513,6 +551,7 @@ function RemoteComponent({
513
551
  }
514
552
  );
515
553
  setRemoteComponent(error);
554
+ onError?.(error);
516
555
  });
517
556
  }
518
557
  }