remote-components 0.0.27 → 0.0.28
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.
- package/dist/html/host.cjs +27 -3
- package/dist/html/host.cjs.map +1 -1
- package/dist/html/host.js +27 -3
- package/dist/html/host.js.map +1 -1
- package/dist/internal/shared/ssr/fetch-headers.cjs +42 -0
- package/dist/internal/shared/ssr/fetch-headers.cjs.map +1 -0
- package/dist/internal/shared/ssr/fetch-headers.d.ts +14 -0
- package/dist/internal/shared/ssr/fetch-headers.js +18 -0
- package/dist/internal/shared/ssr/fetch-headers.js.map +1 -0
- package/dist/internal/shared/ssr/fetch-remote-component.cjs +5 -7
- package/dist/internal/shared/ssr/fetch-remote-component.cjs.map +1 -1
- package/dist/internal/shared/ssr/fetch-remote-component.js +5 -7
- package/dist/internal/shared/ssr/fetch-remote-component.js.map +1 -1
- package/dist/next/host/app-router-server.cjs +6 -1
- package/dist/next/host/app-router-server.cjs.map +1 -1
- package/dist/next/host/app-router-server.d.ts +8 -1
- package/dist/next/host/app-router-server.js +6 -1
- package/dist/next/host/app-router-server.js.map +1 -1
- package/dist/next/host/pages-router-server.cjs +2 -0
- package/dist/next/host/pages-router-server.cjs.map +1 -1
- package/dist/next/host/pages-router-server.d.ts +1 -0
- package/dist/next/host/pages-router-server.js +2 -0
- package/dist/next/host/pages-router-server.js.map +1 -1
- package/dist/next/index.cjs +3 -7
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.d.ts +8 -5
- package/dist/next/index.js +3 -7
- package/dist/next/index.js.map +1 -1
- package/dist/react/index.cjs +13 -4
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.ts +3 -1
- package/dist/react/index.js +13 -4
- package/dist/react/index.js.map +1 -1
- package/package.json +1 -1
package/dist/next/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/next/index.tsx"],"sourcesContent":["import type { RemoteComponent as RemoteComponentRenderType } from '#internal/next/remote/render-server';\nimport type { RemoteComponent as RemoteComponentAppServerType } from '#remote-components/next/host/app-router-server';\n\ntype RemoteComponentAppServerProps = Parameters<\n typeof RemoteComponentAppServerType\n>[0];\ntype RemoteComponentRenderProps = Parameters<\n typeof RemoteComponentRenderType\n>[0];\ntype RemoteComponentProps =\n | RemoteComponentAppServerProps\n | RemoteComponentRenderProps;\n\n/**\n * RemoteComponent is a Next.js component that exposes or consumes a remote component\n * that can be used in a host application.\n *\n * @param src - The source URL of the remote component. Use this to consume a remote component from another application.\n * @param isolate - Whether to isolate the remote component's styles and scripts. Defaults to true.\n * @param
|
|
1
|
+
{"version":3,"sources":["../../src/next/index.tsx"],"sourcesContent":["import type { RemoteComponent as RemoteComponentRenderType } from '#internal/next/remote/render-server';\nimport type { RemoteComponent as RemoteComponentAppServerType } from '#remote-components/next/host/app-router-server';\n\ntype RemoteComponentAppServerProps = Parameters<\n typeof RemoteComponentAppServerType\n>[0];\ntype RemoteComponentRenderProps = Parameters<\n typeof RemoteComponentRenderType\n>[0];\ntype RemoteComponentProps =\n | RemoteComponentAppServerProps\n | RemoteComponentRenderProps;\n\n/**\n * RemoteComponent is a Next.js component that exposes or consumes a remote component\n * that can be used in a host application.\n *\n * @param src - [host] The source URL of the remote component. Use this to consume a remote component from another application.\n * @param name - [host & remote] The name of the remote component. Use a unique name to expose multiple remote components from the same page.\n * @param isolate - [host] Whether to isolate the remote component's styles and scripts. Defaults to true.\n * @param mode - [host] The mode of the Shadow DOM. Defaults to `open`.\n * @param reset - [host] Whether to include a CSS reset style in the shadow DOM. Defaults to `false`.\n * @param additionalHeaders - [host] Additional headers to use when fetching the remote component.\n * @param children - [host & remote] Either the content of the remote component. Or when src is supplied, the fallback content to display while the remote component is being fetched.\n * @returns Either a React component that renders the remote component or a Next.js component that exposes the children as a remote component.\n *\n * @example\n *\n * Use the `<RemoteComponent>` in your Next.js App Router application to expose the children as a remote component without the `src` prop:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/next';\n *\n * export default function MyPage() {\n * return (\n * <RemoteComponent>\n * <h1>Hello from the remote component!</h1>\n * <p>This is a remote component that can be used in a host application.</p>\n * </RemoteComponent>\n * );\n * }\n * ```\n *\n * Use the `<RemoteComponent>` in your Next.js App Router application to consume a remote component from another application with the `src` prop:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/next';\n *\n * export default function MyPage() {\n * return (\n * <>\n * <RemoteComponent src=\"https://example.com/remote-component\" />\n * </>\n * );\n * }\n * ```\n *\n * The `children` of the `<RemoteComponent>` will be exposed as a remote component or it will be used as the loading fallback when consuming a remote component.\n */\nexport async function RemoteComponent(\n props: RemoteComponentProps,\n): Promise<React.ReactElement> {\n if ('src' in props) {\n const { RemoteComponent: RemoteComponentAppServer } = await import(\n '#remote-components/next/host/app-router-server'\n );\n return RemoteComponentAppServer(props);\n }\n\n if ('children' in props) {\n const { RemoteComponent: RemoteComponentRender } = await import(\n '#internal/next/remote/render-server'\n );\n return RemoteComponentRender(props);\n }\n\n throw new Error(\n 'Invalid props passed to RemoteComponent. Expected either \"src\" or \"children\".',\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA2DA,eAAsB,gBACpB,OAC6B;AAC7B,MAAI,SAAS,OAAO;AAClB,UAAM,EAAE,iBAAiB,yBAAyB,IAAI,MAAM,OAC1D,gDACF;AACA,WAAO,yBAAyB,KAAK;AAAA,EACvC;AAEA,MAAI,cAAc,OAAO;AACvB,UAAM,EAAE,iBAAiB,sBAAsB,IAAI,MAAM,OACvD,qCACF;AACA,WAAO,sBAAsB,KAAK;AAAA,EACpC;AAEA,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF;","names":[]}
|
package/dist/next/index.d.ts
CHANGED
|
@@ -8,11 +8,14 @@ type RemoteComponentProps = RemoteComponentAppServerProps | RemoteComponentRende
|
|
|
8
8
|
* RemoteComponent is a Next.js component that exposes or consumes a remote component
|
|
9
9
|
* that can be used in a host application.
|
|
10
10
|
*
|
|
11
|
-
* @param src - The source URL of the remote component. Use this to consume a remote component from another application.
|
|
12
|
-
* @param
|
|
13
|
-
* @param
|
|
14
|
-
* @param
|
|
15
|
-
* @
|
|
11
|
+
* @param src - [host] The source URL of the remote component. Use this to consume a remote component from another application.
|
|
12
|
+
* @param name - [host & remote] The name of the remote component. Use a unique name to expose multiple remote components from the same page.
|
|
13
|
+
* @param isolate - [host] Whether to isolate the remote component's styles and scripts. Defaults to true.
|
|
14
|
+
* @param mode - [host] The mode of the Shadow DOM. Defaults to `open`.
|
|
15
|
+
* @param reset - [host] Whether to include a CSS reset style in the shadow DOM. Defaults to `false`.
|
|
16
|
+
* @param additionalHeaders - [host] Additional headers to use when fetching the remote component.
|
|
17
|
+
* @param children - [host & remote] Either the content of the remote component. Or when src is supplied, the fallback content to display while the remote component is being fetched.
|
|
18
|
+
* @returns Either a React component that renders the remote component or a Next.js component that exposes the children as a remote component.
|
|
16
19
|
*
|
|
17
20
|
* @example
|
|
18
21
|
*
|
package/dist/next/index.js
CHANGED
|
@@ -1,15 +1,11 @@
|
|
|
1
1
|
async function RemoteComponent(props) {
|
|
2
|
-
if ("src" in props
|
|
2
|
+
if ("src" in props) {
|
|
3
3
|
const { RemoteComponent: RemoteComponentAppServer } = await import("#remote-components/next/host/app-router-server");
|
|
4
|
-
return RemoteComponentAppServer(
|
|
5
|
-
props
|
|
6
|
-
);
|
|
4
|
+
return RemoteComponentAppServer(props);
|
|
7
5
|
}
|
|
8
6
|
if ("children" in props) {
|
|
9
7
|
const { RemoteComponent: RemoteComponentRender } = await import("#internal/next/remote/render-server");
|
|
10
|
-
return RemoteComponentRender(
|
|
11
|
-
props
|
|
12
|
-
);
|
|
8
|
+
return RemoteComponentRender(props);
|
|
13
9
|
}
|
|
14
10
|
throw new Error(
|
|
15
11
|
'Invalid props passed to RemoteComponent. Expected either "src" or "children".'
|
package/dist/next/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/next/index.tsx"],"sourcesContent":["import type { RemoteComponent as RemoteComponentRenderType } from '#internal/next/remote/render-server';\nimport type { RemoteComponent as RemoteComponentAppServerType } from '#remote-components/next/host/app-router-server';\n\ntype RemoteComponentAppServerProps = Parameters<\n typeof RemoteComponentAppServerType\n>[0];\ntype RemoteComponentRenderProps = Parameters<\n typeof RemoteComponentRenderType\n>[0];\ntype RemoteComponentProps =\n | RemoteComponentAppServerProps\n | RemoteComponentRenderProps;\n\n/**\n * RemoteComponent is a Next.js component that exposes or consumes a remote component\n * that can be used in a host application.\n *\n * @param src - The source URL of the remote component. Use this to consume a remote component from another application.\n * @param isolate - Whether to isolate the remote component's styles and scripts. Defaults to true.\n * @param
|
|
1
|
+
{"version":3,"sources":["../../src/next/index.tsx"],"sourcesContent":["import type { RemoteComponent as RemoteComponentRenderType } from '#internal/next/remote/render-server';\nimport type { RemoteComponent as RemoteComponentAppServerType } from '#remote-components/next/host/app-router-server';\n\ntype RemoteComponentAppServerProps = Parameters<\n typeof RemoteComponentAppServerType\n>[0];\ntype RemoteComponentRenderProps = Parameters<\n typeof RemoteComponentRenderType\n>[0];\ntype RemoteComponentProps =\n | RemoteComponentAppServerProps\n | RemoteComponentRenderProps;\n\n/**\n * RemoteComponent is a Next.js component that exposes or consumes a remote component\n * that can be used in a host application.\n *\n * @param src - [host] The source URL of the remote component. Use this to consume a remote component from another application.\n * @param name - [host & remote] The name of the remote component. Use a unique name to expose multiple remote components from the same page.\n * @param isolate - [host] Whether to isolate the remote component's styles and scripts. Defaults to true.\n * @param mode - [host] The mode of the Shadow DOM. Defaults to `open`.\n * @param reset - [host] Whether to include a CSS reset style in the shadow DOM. Defaults to `false`.\n * @param additionalHeaders - [host] Additional headers to use when fetching the remote component.\n * @param children - [host & remote] Either the content of the remote component. Or when src is supplied, the fallback content to display while the remote component is being fetched.\n * @returns Either a React component that renders the remote component or a Next.js component that exposes the children as a remote component.\n *\n * @example\n *\n * Use the `<RemoteComponent>` in your Next.js App Router application to expose the children as a remote component without the `src` prop:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/next';\n *\n * export default function MyPage() {\n * return (\n * <RemoteComponent>\n * <h1>Hello from the remote component!</h1>\n * <p>This is a remote component that can be used in a host application.</p>\n * </RemoteComponent>\n * );\n * }\n * ```\n *\n * Use the `<RemoteComponent>` in your Next.js App Router application to consume a remote component from another application with the `src` prop:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/next';\n *\n * export default function MyPage() {\n * return (\n * <>\n * <RemoteComponent src=\"https://example.com/remote-component\" />\n * </>\n * );\n * }\n * ```\n *\n * The `children` of the `<RemoteComponent>` will be exposed as a remote component or it will be used as the loading fallback when consuming a remote component.\n */\nexport async function RemoteComponent(\n props: RemoteComponentProps,\n): Promise<React.ReactElement> {\n if ('src' in props) {\n const { RemoteComponent: RemoteComponentAppServer } = await import(\n '#remote-components/next/host/app-router-server'\n );\n return RemoteComponentAppServer(props);\n }\n\n if ('children' in props) {\n const { RemoteComponent: RemoteComponentRender } = await import(\n '#internal/next/remote/render-server'\n );\n return RemoteComponentRender(props);\n }\n\n throw new Error(\n 'Invalid props passed to RemoteComponent. Expected either \"src\" or \"children\".',\n );\n}\n"],"mappings":"AA2DA,eAAsB,gBACpB,OAC6B;AAC7B,MAAI,SAAS,OAAO;AAClB,UAAM,EAAE,iBAAiB,yBAAyB,IAAI,MAAM,OAC1D,gDACF;AACA,WAAO,yBAAyB,KAAK;AAAA,EACvC;AAEA,MAAI,cAAc,OAAO;AACvB,UAAM,EAAE,iBAAiB,sBAAsB,IAAI,MAAM,OACvD,qCACF;AACA,WAAO,sBAAsB,KAAK;AAAA,EACpC;AAEA,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF;","names":[]}
|
package/dist/react/index.cjs
CHANGED
|
@@ -29,6 +29,7 @@ var import_remote_component = require("#internal/shared/client/remote-component"
|
|
|
29
29
|
var import_polyfill = require("#internal/shared/client/polyfill");
|
|
30
30
|
var import_apply_origin = require("#internal/shared/client/apply-origin");
|
|
31
31
|
var import_utils = require("#internal/shared/utils");
|
|
32
|
+
var import_fetch_headers = require("#internal/shared/ssr/fetch-headers");
|
|
32
33
|
function getRemoteComponentHtml(html) {
|
|
33
34
|
if (typeof document === "undefined")
|
|
34
35
|
return html;
|
|
@@ -60,6 +61,7 @@ function RemoteComponent({
|
|
|
60
61
|
credentials = "same-origin",
|
|
61
62
|
name: nameProp = "__vercel_remote_component",
|
|
62
63
|
shared = {},
|
|
64
|
+
additionalHeaders,
|
|
63
65
|
children
|
|
64
66
|
}) {
|
|
65
67
|
const name = (0, import_react2.useMemo)(() => {
|
|
@@ -184,9 +186,7 @@ function RemoteComponent({
|
|
|
184
186
|
if (!html && src) {
|
|
185
187
|
const fetchInit = {
|
|
186
188
|
method: "GET",
|
|
187
|
-
headers:
|
|
188
|
-
Accept: "text/html"
|
|
189
|
-
},
|
|
189
|
+
headers: (0, import_fetch_headers.remoteFetchHeaders)(additionalHeaders),
|
|
190
190
|
credentials
|
|
191
191
|
};
|
|
192
192
|
const res = await fetch(url, fetchInit);
|
|
@@ -366,7 +366,16 @@ function RemoteComponent({
|
|
|
366
366
|
return () => {
|
|
367
367
|
mounted = false;
|
|
368
368
|
};
|
|
369
|
-
}, [
|
|
369
|
+
}, [
|
|
370
|
+
url,
|
|
371
|
+
src,
|
|
372
|
+
isolate,
|
|
373
|
+
credentials,
|
|
374
|
+
name,
|
|
375
|
+
shared,
|
|
376
|
+
shadowRoot,
|
|
377
|
+
additionalHeaders
|
|
378
|
+
]);
|
|
370
379
|
if (remoteComponent instanceof Error) {
|
|
371
380
|
throw remoteComponent;
|
|
372
381
|
}
|
package/dist/react/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/react/index.tsx"],"sourcesContent":["import {\n useState,\n useEffect,\n useLayoutEffect,\n useRef,\n useMemo,\n startTransition,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport {\n loadRemoteComponent,\n setAttributesFromProps,\n DEFAULT_ROUTE,\n RUNTIME_WEBPACK,\n REMOTE_COMPONENT_REGEX,\n type LoadRemoteComponentProps,\n} from '#internal/shared/client/remote-component';\nimport type { RemoteComponentProps as RemoteComponentPropsType } from '#remote-components/shared/client/types';\nimport { sharedPolyfills } from '#internal/shared/client/polyfill';\nimport { applyOriginToNodes } from '#internal/shared/client/apply-origin';\nimport { escapeString } from '#internal/shared/utils';\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 /** 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`,\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 attrToProp = {\n fetchpriority: 'fetchPriority',\n crossorigin: 'crossOrigin',\n} as Record<string, string>;\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 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\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 let mounted = true;\n\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: {\n Accept: 'text/html',\n },\n credentials,\n } as RequestInit;\n\n const res = await fetch(url, fetchInit);\n\n if (!res.ok) {\n throw new Error(\n `Failed to fetch remote component \"${name}\": ${res.status}`,\n );\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 // 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 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';\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 metadata = {\n name: remoteName,\n bundle,\n route:\n component?.getAttribute('data-route') ??\n nextData?.page ??\n DEFAULT_ROUTE,\n runtime: (component?.getAttribute('data-runtime') ??\n (nextData?.props.__REMOTE_COMPONENT__?.runtime ||\n RUNTIME_WEBPACK)) 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)) {\n throw new Error(`Failed to find component with id \"${remoteName}\"`);\n }\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 = doc.querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src]',\n );\n\n // handle inline scripts in the remote component\n const inlineScripts = doc.querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\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 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 const userShared = await shared;\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 } catch (error) {\n if (mounted) {\n setRemoteComponent(error as Error);\n }\n }\n });\n }\n\n return () => {\n mounted = false;\n };\n }, [url, src, isolate, credentials, name, shared, shadowRoot]);\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: 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 (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":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAmmBI;AAcE;AAjnBN,IAAAA,gBAOO;AACP,uBAA6B;AAC7B,8BAOO;AAEP,sBAAgC;AAChC,0BAAmC;AACnC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A;AAAA;AAAA;AAAA,oBAIvL;AAAA;AAAA,gBACF,IACE;AAAA,gBACH;AAAA,gBACA;AAAA,gBACA;AAAA,iBACH;AAAA,gBACE;AAAA,YACH,cAAc,sBACX;AAAA,cACE,4EACE;AAAA,4DAAC,cAAS,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"]}
|
|
1
|
+
{"version":3,"sources":["../../src/react/index.tsx"],"sourcesContent":["import {\n useState,\n useEffect,\n useLayoutEffect,\n useRef,\n useMemo,\n startTransition,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport {\n loadRemoteComponent,\n setAttributesFromProps,\n DEFAULT_ROUTE,\n RUNTIME_WEBPACK,\n REMOTE_COMPONENT_REGEX,\n type LoadRemoteComponentProps,\n} from '#internal/shared/client/remote-component';\nimport type { RemoteComponentProps as RemoteComponentPropsType } from '#remote-components/shared/client/types';\nimport { sharedPolyfills } from '#internal/shared/client/polyfill';\nimport { applyOriginToNodes } from '#internal/shared/client/apply-origin';\nimport { escapeString } from '#internal/shared/utils';\nimport { remoteFetchHeaders } from '#internal/shared/ssr/fetch-headers';\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`,\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 attrToProp = {\n fetchpriority: 'fetchPriority',\n crossorigin: 'crossOrigin',\n} as Record<string, string>;\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\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 let mounted = true;\n\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 throw new Error(\n `Failed to fetch remote component \"${name}\": ${res.status}`,\n );\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 // 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 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';\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 metadata = {\n name: remoteName,\n bundle,\n route:\n component?.getAttribute('data-route') ??\n nextData?.page ??\n DEFAULT_ROUTE,\n runtime: (component?.getAttribute('data-runtime') ??\n (nextData?.props.__REMOTE_COMPONENT__?.runtime ||\n RUNTIME_WEBPACK)) 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)) {\n throw new Error(`Failed to find component with id \"${remoteName}\"`);\n }\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 = doc.querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src]',\n );\n\n // handle inline scripts in the remote component\n const inlineScripts = doc.querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\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 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 const userShared = await shared;\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 } catch (error) {\n if (mounted) {\n setRemoteComponent(error as Error);\n }\n }\n });\n }\n\n return () => {\n mounted = false;\n };\n }, [\n url,\n src,\n isolate,\n credentials,\n name,\n shared,\n shadowRoot,\n additionalHeaders,\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: 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 (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":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA8mBI;AAcE;AA5nBN,IAAAA,gBAOO;AACP,uBAA6B;AAC7B,8BAOO;AAEP,sBAAgC;AAChC,0BAAmC;AACnC,mBAA6B;AAC7B,2BAAmC;AAwCnC,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,KA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F,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"]}
|
package/dist/react/index.d.ts
CHANGED
|
@@ -40,6 +40,8 @@ interface RemoteComponentProps {
|
|
|
40
40
|
name?: string;
|
|
41
41
|
/** Shared modules to include in the remote component's context. */
|
|
42
42
|
shared?: LoadRemoteComponentProps['shared'];
|
|
43
|
+
/** Additional headers to use when fetching the remote component. */
|
|
44
|
+
additionalHeaders?: Headers | Record<string, string>;
|
|
43
45
|
/** The children to use as a loading fallback until the remote component is loaded. */
|
|
44
46
|
children?: React.ReactNode;
|
|
45
47
|
}
|
|
@@ -79,6 +81,6 @@ interface RemoteComponentProps {
|
|
|
79
81
|
* />
|
|
80
82
|
* ```
|
|
81
83
|
*/
|
|
82
|
-
declare function RemoteComponent({ src, isolate, mode, reset, credentials, name: nameProp, shared, children, }: RemoteComponentProps): react_jsx_runtime.JSX.Element;
|
|
84
|
+
declare function RemoteComponent({ src, isolate, mode, reset, credentials, name: nameProp, shared, additionalHeaders, children, }: RemoteComponentProps): react_jsx_runtime.JSX.Element;
|
|
83
85
|
|
|
84
86
|
export { RemoteComponent, RemoteComponentProps };
|
package/dist/react/index.js
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
import { sharedPolyfills } from "#internal/shared/client/polyfill";
|
|
20
20
|
import { applyOriginToNodes } from "#internal/shared/client/apply-origin";
|
|
21
21
|
import { escapeString } from "#internal/shared/utils";
|
|
22
|
+
import { remoteFetchHeaders } from "#internal/shared/ssr/fetch-headers";
|
|
22
23
|
function getRemoteComponentHtml(html) {
|
|
23
24
|
if (typeof document === "undefined")
|
|
24
25
|
return html;
|
|
@@ -50,6 +51,7 @@ function RemoteComponent({
|
|
|
50
51
|
credentials = "same-origin",
|
|
51
52
|
name: nameProp = "__vercel_remote_component",
|
|
52
53
|
shared = {},
|
|
54
|
+
additionalHeaders,
|
|
53
55
|
children
|
|
54
56
|
}) {
|
|
55
57
|
const name = useMemo(() => {
|
|
@@ -174,9 +176,7 @@ function RemoteComponent({
|
|
|
174
176
|
if (!html && src) {
|
|
175
177
|
const fetchInit = {
|
|
176
178
|
method: "GET",
|
|
177
|
-
headers:
|
|
178
|
-
Accept: "text/html"
|
|
179
|
-
},
|
|
179
|
+
headers: remoteFetchHeaders(additionalHeaders),
|
|
180
180
|
credentials
|
|
181
181
|
};
|
|
182
182
|
const res = await fetch(url, fetchInit);
|
|
@@ -356,7 +356,16 @@ function RemoteComponent({
|
|
|
356
356
|
return () => {
|
|
357
357
|
mounted = false;
|
|
358
358
|
};
|
|
359
|
-
}, [
|
|
359
|
+
}, [
|
|
360
|
+
url,
|
|
361
|
+
src,
|
|
362
|
+
isolate,
|
|
363
|
+
credentials,
|
|
364
|
+
name,
|
|
365
|
+
shared,
|
|
366
|
+
shadowRoot,
|
|
367
|
+
additionalHeaders
|
|
368
|
+
]);
|
|
360
369
|
if (remoteComponent instanceof Error) {
|
|
361
370
|
throw remoteComponent;
|
|
362
371
|
}
|
package/dist/react/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/react/index.tsx"],"sourcesContent":["import {\n useState,\n useEffect,\n useLayoutEffect,\n useRef,\n useMemo,\n startTransition,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport {\n loadRemoteComponent,\n setAttributesFromProps,\n DEFAULT_ROUTE,\n RUNTIME_WEBPACK,\n REMOTE_COMPONENT_REGEX,\n type LoadRemoteComponentProps,\n} from '#internal/shared/client/remote-component';\nimport type { RemoteComponentProps as RemoteComponentPropsType } from '#remote-components/shared/client/types';\nimport { sharedPolyfills } from '#internal/shared/client/polyfill';\nimport { applyOriginToNodes } from '#internal/shared/client/apply-origin';\nimport { escapeString } from '#internal/shared/utils';\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 /** 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`,\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 attrToProp = {\n fetchpriority: 'fetchPriority',\n crossorigin: 'crossOrigin',\n} as Record<string, string>;\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 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\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 let mounted = true;\n\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: {\n Accept: 'text/html',\n },\n credentials,\n } as RequestInit;\n\n const res = await fetch(url, fetchInit);\n\n if (!res.ok) {\n throw new Error(\n `Failed to fetch remote component \"${name}\": ${res.status}`,\n );\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 // 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 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';\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 metadata = {\n name: remoteName,\n bundle,\n route:\n component?.getAttribute('data-route') ??\n nextData?.page ??\n DEFAULT_ROUTE,\n runtime: (component?.getAttribute('data-runtime') ??\n (nextData?.props.__REMOTE_COMPONENT__?.runtime ||\n RUNTIME_WEBPACK)) 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)) {\n throw new Error(`Failed to find component with id \"${remoteName}\"`);\n }\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 = doc.querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src]',\n );\n\n // handle inline scripts in the remote component\n const inlineScripts = doc.querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\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 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 const userShared = await shared;\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 } catch (error) {\n if (mounted) {\n setRemoteComponent(error as Error);\n }\n }\n });\n }\n\n return () => {\n mounted = false;\n };\n }, [url, src, isolate, credentials, name, shared, shadowRoot]);\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: 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 (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":"AAmmBI,SAqBA,UArBA,KAqBA,YArBA;AAcE;AAjnBN;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAsC7B,SAAS,uBAAuB,MAAc;AAC5C,MAAI,OAAO,aAAa;AAAa,WAAO;AAG5C,QAAM,SAAS,IAAI,UAAU;AAC7B,QAAM,OAA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,oCAAC,cAAS,IAAI,GAAG,cAAc;AAAA,gBAC9B;AAAA,gBACA;AAAA,gBACA;AAAA,gBACD,oBAAC,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,iCACE;AAAA,wBAAC,cAAS,IAAI,GAAG,cAAc;AAAA,IAC9B;AAAA,IACA;AAAA,IACD,oBAAC,cAAS,IAAI,GAAG,YAAY,KAAK,gBAAgB;AAAA,KACpD;AAEJ;","names":["url"]}
|
|
1
|
+
{"version":3,"sources":["../../src/react/index.tsx"],"sourcesContent":["import {\n useState,\n useEffect,\n useLayoutEffect,\n useRef,\n useMemo,\n startTransition,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport {\n loadRemoteComponent,\n setAttributesFromProps,\n DEFAULT_ROUTE,\n RUNTIME_WEBPACK,\n REMOTE_COMPONENT_REGEX,\n type LoadRemoteComponentProps,\n} from '#internal/shared/client/remote-component';\nimport type { RemoteComponentProps as RemoteComponentPropsType } from '#remote-components/shared/client/types';\nimport { sharedPolyfills } from '#internal/shared/client/polyfill';\nimport { applyOriginToNodes } from '#internal/shared/client/apply-origin';\nimport { escapeString } from '#internal/shared/utils';\nimport { remoteFetchHeaders } from '#internal/shared/ssr/fetch-headers';\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`,\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 attrToProp = {\n fetchpriority: 'fetchPriority',\n crossorigin: 'crossOrigin',\n} as Record<string, string>;\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\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 let mounted = true;\n\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 throw new Error(\n `Failed to fetch remote component \"${name}\": ${res.status}`,\n );\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 // 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 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';\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 metadata = {\n name: remoteName,\n bundle,\n route:\n component?.getAttribute('data-route') ??\n nextData?.page ??\n DEFAULT_ROUTE,\n runtime: (component?.getAttribute('data-runtime') ??\n (nextData?.props.__REMOTE_COMPONENT__?.runtime ||\n RUNTIME_WEBPACK)) 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)) {\n throw new Error(`Failed to find component with id \"${remoteName}\"`);\n }\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 = doc.querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src]',\n );\n\n // handle inline scripts in the remote component\n const inlineScripts = doc.querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\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 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 const userShared = await shared;\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 } catch (error) {\n if (mounted) {\n setRemoteComponent(error as Error);\n }\n }\n });\n }\n\n return () => {\n mounted = false;\n };\n }, [\n url,\n src,\n isolate,\n credentials,\n name,\n shared,\n shadowRoot,\n additionalHeaders,\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: 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 (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":"AA8mBI,SAqBA,UArBA,KAqBA,YArBA;AAcE;AA5nBN;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AAwCnC,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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