remote-components 0.0.36 → 0.0.38

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 (48) hide show
  1. package/dist/{component-loader-8951c052.d.ts → component-loader-2ca91ad8.d.ts} +4 -1
  2. package/dist/internal/next/host/app-router-client.cjs +55 -38
  3. package/dist/internal/next/host/app-router-client.cjs.map +1 -1
  4. package/dist/internal/next/host/app-router-client.d.ts +2 -2
  5. package/dist/internal/next/host/app-router-client.js +55 -38
  6. package/dist/internal/next/host/app-router-client.js.map +1 -1
  7. package/dist/internal/shared/client/get-client-src.cjs +39 -0
  8. package/dist/internal/shared/client/get-client-src.cjs.map +1 -0
  9. package/dist/internal/shared/client/get-client-src.d.ts +7 -0
  10. package/dist/internal/shared/client/get-client-src.js +15 -0
  11. package/dist/internal/shared/client/get-client-src.js.map +1 -0
  12. package/dist/internal/shared/client/remote-component.d.ts +2 -2
  13. package/dist/internal/shared/ssr/fetch-remote-component.cjs +26 -22
  14. package/dist/internal/shared/ssr/fetch-remote-component.cjs.map +1 -1
  15. package/dist/internal/shared/ssr/fetch-remote-component.d.ts +1 -1
  16. package/dist/internal/shared/ssr/fetch-remote-component.js +26 -22
  17. package/dist/internal/shared/ssr/fetch-remote-component.js.map +1 -1
  18. package/dist/internal/shared/ssr/get-client-or-server-url.cjs +35 -0
  19. package/dist/internal/shared/ssr/get-client-or-server-url.cjs.map +1 -0
  20. package/dist/internal/shared/ssr/get-client-or-server-url.d.ts +3 -0
  21. package/dist/internal/shared/ssr/get-client-or-server-url.js +11 -0
  22. package/dist/internal/shared/ssr/get-client-or-server-url.js.map +1 -0
  23. package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.cjs +34 -0
  24. package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.cjs.map +1 -0
  25. package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.d.ts +10 -0
  26. package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.js +10 -0
  27. package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.js.map +1 -0
  28. package/dist/next/host/app-router-server.cjs +3 -2
  29. package/dist/next/host/app-router-server.cjs.map +1 -1
  30. package/dist/next/host/app-router-server.js +3 -2
  31. package/dist/next/host/app-router-server.js.map +1 -1
  32. package/dist/next/host/client/index.cjs +31 -27
  33. package/dist/next/host/client/index.cjs.map +1 -1
  34. package/dist/next/host/client/index.d.ts +1 -1
  35. package/dist/next/host/client/index.js +31 -27
  36. package/dist/next/host/client/index.js.map +1 -1
  37. package/dist/next/host/pages-router-server.cjs +4 -8
  38. package/dist/next/host/pages-router-server.cjs.map +1 -1
  39. package/dist/next/host/pages-router-server.d.ts +0 -1
  40. package/dist/next/host/pages-router-server.js +4 -8
  41. package/dist/next/host/pages-router-server.js.map +1 -1
  42. package/dist/react/index.cjs +23 -27
  43. package/dist/react/index.cjs.map +1 -1
  44. package/dist/react/index.d.ts +1 -1
  45. package/dist/react/index.js +23 -27
  46. package/dist/react/index.js.map +1 -1
  47. package/dist/{types-4e7dea94.d.ts → types-235b68a5.d.ts} +4 -1
  48. package/package.json +1 -1
@@ -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 { 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\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 : 'http://localhost',\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 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_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}` as const;\n const ssrShadowRoot =\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}\"]`,\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_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}\"]`,\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_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}` as const;\n\n let shadowRootElement: ShadowRoot | null = null;\n const element = document.querySelector(\n `[data-remote-component-id=\"shadowroot_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}\"]`,\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 }, [name, isolate, shadowRoot, remoteComponent, mode, src, data]);\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 const url = useMemo(() => {\n if (typeof src !== 'string')\n return new URL(\n typeof document !== 'undefined' ? location.href : 'http://localhost',\n );\n try {\n return typeof document !== 'undefined'\n ? new URL(src, location.href)\n : new URL(src);\n } catch {\n return new URL(src, 'http://localhost');\n }\n }, [src]);\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}.${remoteName !== '__vercel_remote_component' ? `The name for the <RemoteComponent> is \"${remoteName}\". Check <RemoteComponent> usage.` : ''} 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(url.href)}_${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 url: 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 '',\n )}${reset ? `<style data-remote-components-reset=\"\">:host { all: initial; }</style>` : ''}${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: new URL(url, location.origin),\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 ]);\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_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)}`}\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_${src ? escapeString(new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href) : ''}_${escapeString(data?.name ?? name)} = 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":";;;;;;;;;;;;;;;;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AS,IAAI,GAAG,cAAc;AAAA,gBAC9B;AAAA,gBACA;AAAA,gBACA;AAAA,gBACD,4CAAC,cAAS,IAAI,GAAG,YAAY,KAAK,gBAAgB;AAAA,iBACpD;AAAA,cACA;AAAA,YACF,IACA;AAAA;AAAA;AAAA,MACN;AAAA,OACF;AAAA,EAEJ;AACA,UAAQ,UAAU;AAGlB,SACE,4EACE;AAAA,gDAAC,cAAS,IAAI,GAAG,cAAc;AAAA,IAC9B;AAAA,IACA;AAAA,IACD,4CAAC,cAAS,IAAI,GAAG,YAAY,KAAK,gBAAgB;AAAA,KACpD;AAEJ;","names":["import_react","url","parser","doc"]}
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,G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AAA,EAEJ;AACA,UAAQ,UAAU;AAGlB,SACE,4EACE;AAAA,gDAAC,cAAS,IAAI,GAAG,cAAc;AAAA,IAC9B;AAAA,IACA;AAAA,IACD,4CAAC,cAAS,IAAI,GAAG,YAAY,KAAK,gBAAgB;AAAA,KACpD;AAEJ;","names":["import_react","url","parser","doc"]}
@@ -1,5 +1,5 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { R as RemoteComponentProps$1 } from '../types-4e7dea94.js';
2
+ import { R as RemoteComponentProps$1 } from '../types-235b68a5.js';
3
3
  import 'react';
4
4
  import '../types-cbf6c34f.js';
5
5
 
@@ -26,6 +26,7 @@ import {
26
26
  multipleRemoteComponentsError
27
27
  } from "#internal/shared/error";
28
28
  import { remoteFetchHeaders } from "#internal/shared/ssr/fetch-headers";
29
+ import { getClientOrServerUrl } from "#internal/shared/ssr/get-client-or-server-url";
29
30
  import { attrToProp, escapeString } from "#internal/shared/utils";
30
31
  function getRemoteComponentHtml(html) {
31
32
  if (typeof document === "undefined")
@@ -46,6 +47,7 @@ function getRemoteComponentHtml(html) {
46
47
  }
47
48
  return "";
48
49
  }
50
+ const DUMMY_FALLBACK = "http://remote-components-dummy-fallback";
49
51
  function RemoteComponent({
50
52
  src,
51
53
  isolate,
@@ -61,7 +63,7 @@ function RemoteComponent({
61
63
  if (typeof src === "string") {
62
64
  const url2 = new URL(
63
65
  src,
64
- typeof document !== "undefined" ? location.href : "http://localhost"
66
+ typeof document !== "undefined" ? location.href : DUMMY_FALLBACK
65
67
  );
66
68
  if (url2.hash) {
67
69
  return url2.hash.slice(1);
@@ -72,20 +74,23 @@ function RemoteComponent({
72
74
  return nameProp;
73
75
  }, [src, nameProp]);
74
76
  const [data, setData] = useState(null);
77
+ const url = useMemo(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);
78
+ const id = url.origin === (typeof location !== "undefined" ? location.origin : DUMMY_FALLBACK) ? url.pathname : url.href;
79
+ const keySuffix = `${escapeString(id)}_${escapeString(data?.name ?? name)}`;
75
80
  const [remoteComponent, setRemoteComponent] = useState(null);
76
81
  const shadowRootContainerRef = useRef(null);
77
82
  const [shadowRoot, setShadowRoot] = useState(() => {
78
83
  const self = globalThis;
79
- const shadowRootKey = `__remote_components_shadowroot_${src ? escapeString(new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href) : ""}_${escapeString(data?.name ?? name)}`;
84
+ const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
80
85
  const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
81
- `[data-remote-component-id="shadowroot_${src ? escapeString(new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href) : ""}_${escapeString(data?.name ?? name)}"]`
86
+ `[data-remote-component-id="shadowroot_${keySuffix}"]`
82
87
  )?.shadowRoot ?? self[shadowRootKey] ?? null : null;
83
88
  self[shadowRootKey] = null;
84
89
  return ssrShadowRoot;
85
90
  });
86
91
  const htmlRef = useRef(
87
92
  typeof document !== "undefined" ? document.querySelector(
88
- `[data-remote-component-id="shadowroot_${src ? escapeString(new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href) : ""}_${escapeString(data?.name ?? name)}"]`
93
+ `[data-remote-component-id="shadowroot_${keySuffix}"]`
89
94
  )?.shadowRoot?.innerHTML ?? document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ?? document.querySelector(`div[data-bundle][data-route][id^="${name}"]`)?.innerHTML ?? document.querySelector("div[data-bundle][data-route]")?.innerHTML : null
90
95
  );
91
96
  const endTemplateRef = useRef(null);
@@ -117,10 +122,10 @@ function RemoteComponent({
117
122
  }
118
123
  if (isolate !== false && typeof document !== "undefined" && !shadowRoot) {
119
124
  const self = globalThis;
120
- const shadowRootKey = `__remote_components_shadowroot_${src ? escapeString(new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href) : ""}_${escapeString(data?.name ?? name)}`;
125
+ const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
121
126
  let shadowRootElement = null;
122
127
  const element = document.querySelector(
123
- `[data-remote-component-id="shadowroot_${src ? escapeString(new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href) : ""}_${escapeString(data?.name ?? name)}"]`
128
+ `[data-remote-component-id="shadowroot_${keySuffix}"]`
124
129
  );
125
130
  shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;
126
131
  if (!shadowRootElement && element) {
@@ -137,7 +142,7 @@ function RemoteComponent({
137
142
  setShadowRoot(shadowRootElement);
138
143
  }
139
144
  }
140
- }, [name, isolate, shadowRoot, remoteComponent, mode, src, data]);
145
+ }, [isolate, shadowRoot, remoteComponent, mode, keySuffix]);
141
146
  useLayoutEffect(() => {
142
147
  if (shadowRoot && remoteComponent) {
143
148
  const resetStyles = shadowRoot.querySelectorAll(
@@ -161,17 +166,6 @@ function RemoteComponent({
161
166
  }
162
167
  }
163
168
  }, [shadowRoot, remoteComponent, name]);
164
- const url = useMemo(() => {
165
- if (typeof src !== "string")
166
- return new URL(
167
- typeof document !== "undefined" ? location.href : "http://localhost"
168
- );
169
- try {
170
- return typeof document !== "undefined" ? new URL(src, location.href) : new URL(src);
171
- } catch {
172
- return new URL(src, "http://localhost");
173
- }
174
- }, [src]);
175
169
  useEffect(() => {
176
170
  if (src && src !== prevSrcRef.current) {
177
171
  prevSrcRef.current = src;
@@ -346,7 +340,9 @@ function RemoteComponent({
346
340
  }
347
341
  let rscName;
348
342
  if (rsc) {
349
- rscName = `__remote_component_rsc_${escapeString(url.href)}_${escapeString(remoteName)}`;
343
+ rscName = `__remote_component_rsc_${escapeString(
344
+ id
345
+ )}_${escapeString(remoteName)}`;
350
346
  rsc.textContent = rsc.textContent?.replace(
351
347
  new RegExp(`self\\["${remoteName}"\\]`, "g"),
352
348
  `self["${rscName}"]`
@@ -357,14 +353,13 @@ function RemoteComponent({
357
353
  ...metadata,
358
354
  links,
359
355
  remoteShared,
360
- url: url.href,
356
+ src: typeof src === "string" ? src : src.href,
357
+ serverUrl: url.href,
361
358
  data: rsc ? (rsc.textContent || "").split("\n").filter(Boolean) : []
362
359
  };
363
360
  componentHydrationHtml.current = `${Array.from(
364
361
  doc.querySelectorAll("link,style")
365
- ).map((link) => link.outerHTML).join(
366
- ""
367
- )}${reset ? `<style data-remote-components-reset="">:host { all: initial; }</style>` : ""}${component.innerHTML}`;
362
+ ).map((link) => link.outerHTML).join("")}${reset ? `<style data-remote-components-reset="">:host { all: initial; }</style>` : ""}${component.innerHTML}`;
368
363
  const userShared = await shared;
369
364
  if ("__remote_components_missing_shared__" in userShared) {
370
365
  userShared.__remote_components_missing_shared__().catch((e) => {
@@ -416,7 +411,7 @@ function RemoteComponent({
416
411
  }
417
412
  } else {
418
413
  const result = await loadRemoteComponent({
419
- url: new URL(url, location.origin),
414
+ url,
420
415
  name: remoteName,
421
416
  rscName,
422
417
  bundle,
@@ -473,7 +468,8 @@ function RemoteComponent({
473
468
  shared,
474
469
  shadowRoot,
475
470
  additionalHeaders,
476
- reset
471
+ reset,
472
+ id
477
473
  ]);
478
474
  if (remoteComponent instanceof Error) {
479
475
  throw remoteComponent;
@@ -530,7 +526,7 @@ function RemoteComponent({
530
526
  /* @__PURE__ */ jsxs(
531
527
  "div",
532
528
  {
533
- "data-remote-component-id": `shadowroot_${src ? escapeString(new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href) : ""}_${escapeString(data?.name ?? name)}`,
529
+ "data-remote-component-id": `shadowroot_${keySuffix}`,
534
530
  id: `shadowroot_${data?.name ?? name}`,
535
531
  ref: shadowRootContainerRef,
536
532
  children: [
@@ -546,7 +542,7 @@ function RemoteComponent({
546
542
  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
547
543
  onload="(function(el){
548
544
  const root = el.getRootNode();
549
- globalThis.__remote_components_shadowroot_${src ? escapeString(new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href) : ""}_${escapeString(data?.name ?? name)} = root;
545
+ globalThis.__remote_components_shadowroot_${keySuffix} = root;
550
546
  el.parentElement.remove();
551
547
  })(this)"
552
548
  />`