remote-components 0.0.51 → 0.1.2
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/{component-loader-1838f572.d.ts → component-loader-21865da3.d.ts} +142 -16
- package/dist/host-config-58cdccea.d.ts +87 -0
- package/dist/html/host.cjs +589 -377
- package/dist/html/host.cjs.map +1 -1
- package/dist/html/host.d.ts +2 -0
- package/dist/html/host.js +588 -377
- package/dist/html/host.js.map +1 -1
- package/dist/html/remote.cjs +65 -57
- package/dist/html/remote.cjs.map +1 -1
- package/dist/html/remote.js +65 -57
- package/dist/html/remote.js.map +1 -1
- package/dist/internal/next/host/app-router-client.cjs +21 -10
- package/dist/internal/next/host/app-router-client.cjs.map +1 -1
- package/dist/internal/next/host/app-router-client.d.ts +36 -14
- package/dist/internal/next/host/app-router-client.js +21 -10
- package/dist/internal/next/host/app-router-client.js.map +1 -1
- package/dist/internal/next/remote/render-server.cjs.map +1 -1
- package/dist/internal/next/remote/render-server.d.ts +13 -14
- package/dist/internal/next/remote/render-server.js.map +1 -1
- package/dist/internal/react/context.cjs +43 -0
- package/dist/internal/react/context.cjs.map +1 -0
- package/dist/internal/react/context.d.ts +20 -0
- package/dist/internal/react/context.js +18 -0
- package/dist/internal/react/context.js.map +1 -0
- package/dist/internal/react/hooks/use-resolve-client-url.cjs +39 -0
- package/dist/internal/react/hooks/use-resolve-client-url.cjs.map +1 -0
- package/dist/internal/react/hooks/use-resolve-client-url.d.ts +5 -0
- package/dist/internal/react/hooks/use-resolve-client-url.js +15 -0
- package/dist/internal/react/hooks/use-resolve-client-url.js.map +1 -0
- package/dist/internal/shared/client/apply-origin.cjs +10 -5
- package/dist/internal/shared/client/apply-origin.cjs.map +1 -1
- package/dist/internal/shared/client/apply-origin.d.ts +3 -1
- package/dist/internal/shared/client/apply-origin.js +10 -5
- package/dist/internal/shared/client/apply-origin.js.map +1 -1
- package/dist/internal/shared/client/default-resolve-client-url.cjs +32 -0
- package/dist/internal/shared/client/default-resolve-client-url.cjs.map +1 -0
- package/dist/internal/shared/client/default-resolve-client-url.d.ts +5 -0
- package/dist/internal/shared/client/default-resolve-client-url.js +10 -0
- package/dist/internal/shared/client/default-resolve-client-url.js.map +1 -0
- package/dist/internal/shared/client/protected-rc-fallback.cjs +11 -2
- package/dist/internal/shared/client/protected-rc-fallback.cjs.map +1 -1
- package/dist/internal/shared/client/protected-rc-fallback.d.ts +2 -1
- package/dist/internal/shared/client/protected-rc-fallback.js +9 -1
- package/dist/internal/shared/client/protected-rc-fallback.js.map +1 -1
- package/dist/internal/shared/client/proxy-through-host.cjs +65 -0
- package/dist/internal/shared/client/proxy-through-host.cjs.map +1 -0
- package/dist/internal/shared/client/proxy-through-host.d.ts +62 -0
- package/dist/internal/shared/client/proxy-through-host.js +40 -0
- package/dist/internal/shared/client/proxy-through-host.js.map +1 -0
- package/dist/internal/shared/client/remote-component.cjs +121 -137
- package/dist/internal/shared/client/remote-component.cjs.map +1 -1
- package/dist/internal/shared/client/remote-component.d.ts +7 -5
- package/dist/internal/shared/client/remote-component.js +120 -137
- package/dist/internal/shared/client/remote-component.js.map +1 -1
- package/dist/internal/shared/constants.cjs +3 -0
- package/dist/internal/shared/constants.cjs.map +1 -1
- package/dist/internal/shared/constants.d.ts +2 -1
- package/dist/internal/shared/constants.js +2 -0
- package/dist/internal/shared/constants.js.map +1 -1
- package/dist/internal/shared/contract/host-state.cjs +38 -0
- package/dist/internal/shared/contract/host-state.cjs.map +1 -0
- package/dist/internal/shared/contract/host-state.d.ts +53 -0
- package/dist/internal/shared/contract/host-state.js +14 -0
- package/dist/internal/shared/contract/host-state.js.map +1 -0
- package/dist/internal/shared/contract/resolve-name-from-src.cjs +40 -0
- package/dist/internal/shared/contract/resolve-name-from-src.cjs.map +1 -0
- package/dist/internal/shared/contract/resolve-name-from-src.d.ts +13 -0
- package/dist/internal/shared/contract/resolve-name-from-src.js +16 -0
- package/dist/internal/shared/contract/resolve-name-from-src.js.map +1 -0
- package/dist/internal/shared/error.cjs +70 -0
- package/dist/internal/shared/error.cjs.map +1 -1
- package/dist/internal/shared/error.d.ts +3 -1
- package/dist/internal/shared/error.js +71 -0
- package/dist/internal/shared/error.js.map +1 -1
- package/dist/internal/shared/ssr/dom-flight.d.ts +1 -1
- package/dist/internal/shared/ssr/fetch-remote-component.cjs.map +1 -1
- package/dist/internal/shared/ssr/fetch-remote-component.d.ts +1 -1
- package/dist/internal/shared/ssr/fetch-remote-component.js.map +1 -1
- package/dist/internal/shared/ssr/fetch-with-hooks.cjs +7 -2
- package/dist/internal/shared/ssr/fetch-with-hooks.cjs.map +1 -1
- package/dist/internal/shared/ssr/fetch-with-hooks.d.ts +1 -1
- package/dist/internal/shared/ssr/fetch-with-hooks.js +7 -2
- package/dist/internal/shared/ssr/fetch-with-hooks.js.map +1 -1
- package/dist/internal/shared/utils/logger.cjs +26 -10
- package/dist/internal/shared/utils/logger.cjs.map +1 -1
- package/dist/internal/shared/utils/logger.d.ts +6 -1
- package/dist/internal/shared/utils/logger.js +24 -9
- package/dist/internal/shared/utils/logger.js.map +1 -1
- package/dist/next/config.cjs +2 -2
- package/dist/next/config.cjs.map +1 -1
- package/dist/next/config.js +2 -2
- package/dist/next/config.js.map +1 -1
- package/dist/next/host/app-router-server.cjs.map +1 -1
- package/dist/next/host/app-router-server.d.ts +11 -41
- package/dist/next/host/app-router-server.js.map +1 -1
- package/dist/next/host/client/index.cjs +467 -298
- package/dist/next/host/client/index.cjs.map +1 -1
- package/dist/next/host/client/index.d.ts +3 -1
- package/dist/next/host/client/index.js +445 -277
- package/dist/next/host/client/index.js.map +1 -1
- package/dist/next/host/pages-router-client.cjs +15 -2
- package/dist/next/host/pages-router-client.cjs.map +1 -1
- package/dist/next/host/pages-router-client.d.ts +14 -26
- package/dist/next/host/pages-router-client.js +15 -2
- package/dist/next/host/pages-router-client.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 +17 -31
- 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.map +1 -1
- package/dist/next/index.d.ts +13 -39
- package/dist/next/index.js.map +1 -1
- package/dist/next/proxy.cjs +33 -6
- package/dist/next/proxy.cjs.map +1 -1
- package/dist/next/proxy.js +33 -6
- package/dist/next/proxy.js.map +1 -1
- package/dist/next/remote/server.d.ts +4 -0
- package/dist/proxy-through-host-a676a522.d.ts +52 -0
- package/dist/react/index.cjs +486 -298
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.ts +27 -40
- package/dist/react/index.js +463 -277
- package/dist/react/index.js.map +1 -1
- package/dist/shared/host/proxy.cjs +32 -6
- package/dist/shared/host/proxy.cjs.map +1 -1
- package/dist/shared/host/proxy.js +36 -7
- package/dist/shared/host/proxy.js.map +1 -1
- package/dist/{types-cbe44b51.d.ts → types-2b26a246.d.ts} +23 -6
- package/package.json +1 -1
- package/dist/internal/shared/client/fetch-with-protected-rc-fallback.cjs +0 -65
- package/dist/internal/shared/client/fetch-with-protected-rc-fallback.cjs.map +0 -1
- package/dist/internal/shared/client/fetch-with-protected-rc-fallback.d.ts +0 -13
- package/dist/internal/shared/client/fetch-with-protected-rc-fallback.js +0 -41
- package/dist/internal/shared/client/fetch-with-protected-rc-fallback.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/next/host/client/index.tsx","../../../../src/react/index.tsx","../../../../src/shared/client/apply-origin.ts","../../../../src/shared/error.ts","../../../../src/shared/utils/logger.ts","../../../../src/shared/client/polyfill.tsx","../../../../src/shared/client/component-loader.ts","../../../../src/shared/webpack/next-client-pages-loader.ts","../../../../src/shared/webpack/shared-modules.ts","../../../../src/shared/client/rsc.ts","../../../../src/shared/constants.ts","../../../../src/shared/client/protected-rc-fallback.ts","../../../../src/shared/client/webpack-patterns.ts","../../../../src/shared/client/script-loader.ts","../../../../src/shared/utils/index.ts","../../../../src/shared/client/const.ts","../../../../src/shared/utils/abort.ts","../../../../src/shared/client/fetch-with-protected-rc-fallback.ts","../../../../src/shared/client/turbopack-patterns.ts","../../../../src/shared/client/chunk-loader.ts","../../../../src/shared/client/turbopack-module.ts","../../../../src/shared/client/shared-modules.ts","../../../../src/shared/client/webpack-adapter.ts","../../../../src/shared/client/set-attributes-from-props.ts","../../../../src/shared/client/static-loader.ts","../../../../src/shared/ssr/fetch-headers.ts","../../../../src/shared/ssr/fetch-with-hooks.ts","../../../../src/shared/ssr/get-client-or-server-url.ts","../../../../src/react/hooks/use-shadow-root.ts","../../../../src/react/utils/parse-remote-html.ts","../../../../src/next/host/app-router-compat.tsx"],"sourcesContent":["'use client';\n\nimport * as Image from 'next/image';\nimport {\n type RemoteComponentProps,\n RemoteComponent as RemoteComponentReact,\n} from '../../../react';\nimport { imageImpl, routerImpl } from '../app-router-compat';\n\nasync function tryImportShared() {\n try {\n const { shared } = await import('remote-components/shared/host/app');\n return shared;\n } catch {\n return {};\n }\n}\n\nconst sharedModules = async (userShared?: RemoteComponentProps['shared']) => {\n const [resolvedShared, resolvedUserShared] = await Promise.all([\n tryImportShared(),\n userShared ?? Promise.resolve({}),\n ]);\n\n return {\n ...resolvedShared,\n 'next/router': routerImpl,\n 'next/image': (bundle?: string) =>\n Promise.resolve(imageImpl(Image.default, bundle ?? 'default')),\n 'next/dist/client/image-component': (bundle?: string) =>\n Promise.resolve({ Image: imageImpl(Image.default, bundle ?? 'default') }),\n ...resolvedUserShared,\n };\n};\n\n/**\n * RemoteComponent - Client-side component for rendering remote components\n *\n * This component is used in Next.js App Router to render remote components.\n * It supports both Next.js App Router and Pages Router based components.\n *\n * @param props - The props for the remote component.\n * @returns The rendered remote component.\n */\nexport function RemoteComponent(props: RemoteComponentProps) {\n if (typeof props.src !== 'string' && !(props.src instanceof URL)) {\n return props.children ?? null;\n }\n\n return (\n <RemoteComponentReact {...props} shared={sharedModules(props.shared)} />\n );\n}\n","import {\n startTransition,\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { applyOriginToNodes } from '#internal/shared/client/apply-origin';\nimport { sharedPolyfills } from '#internal/shared/client/polyfill';\nimport {\n DEFAULT_ROUTE,\n type LoadRemoteComponentProps,\n loadRemoteComponent,\n loadStaticRemoteComponent,\n REMOTE_COMPONENT_REGEX,\n RemoteComponentsError,\n RUNTIME_SCRIPT,\n RUNTIME_WEBPACK,\n setAttributesFromProps,\n} from '#internal/shared/client/remote-component';\nimport {\n failedToFetchRemoteComponentError,\n multipleRemoteComponentsError,\n} from '#internal/shared/error';\nimport { fetchWithHooks } from '#internal/shared/ssr/fetch-with-hooks';\nimport { getClientOrServerUrl } from '#internal/shared/ssr/get-client-or-server-url';\nimport type {\n HookOptions,\n OnRequestHook,\n OnResponseHook,\n} from '#internal/shared/ssr/types';\nimport { attrToProp, escapeString } from '#internal/shared/utils';\nimport { isAbortError } from '#internal/shared/utils/abort';\nimport type {\n MountOrUnmountFunction,\n RemoteComponentMountUnmount,\n RemoteComponentProps as RemoteComponentPropsType,\n} from '#remote-components/shared/client/types';\nimport { useShadowRoot } from './hooks/use-shadow-root';\nimport {\n DUMMY_FALLBACK,\n getRemoteComponentHtml,\n} from './utils/parse-remote-html';\n\n// Re-export hook types for consumers\nexport type { HookOptions, OnRequestHook, OnResponseHook };\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 /** Called right before a new remote component load starts. */\n onBeforeLoad?: (src: string | URL) => void;\n /** Called when the remote component has been successfully loaded and mounted. */\n onLoad?: (src: string | URL) => void;\n /** Called when an error occurs while loading or mounting the remote component. */\n onError?: (error: unknown) => void;\n /** Called when a different remote component is loaded into the same wrapper. */\n onChange?: (info: {\n previousSrc: string | URL | null;\n nextSrc: string | URL | null;\n previousName: string | undefined;\n nextName: string | undefined;\n }) => void;\n /**\n * Called when a fetch request is made to retrieve the remote component payload.\n * Can be used to intercept requests, modify headers, or provide a custom response.\n */\n onRequest?: OnRequestHook;\n /**\n * Called after a fetch completes to retrieve the remote component payload.\n * Can be used to inspect the response (e.g., check for redirects) or transform it.\n */\n onResponse?: OnResponseHook;\n}\n\n/**\n * RemoteComponent is a React component that fetches and renders a remote component.\n * It supports SSR and can isolate the remote component in a shadow DOM.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n *\n * @example\n *\n * Use the `<RemoteComponent>` in your React application to consume a remote component from a remote application:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/react';\n *\n * export default function App() {\n * return (\n * <>\n * <h1>Welcome to My App</h1>\n * <p>This page consumes a remote component from another application.</p>\n * <RemoteComponent src=\"/nextjs-app-remote/components/header\" />\n * </>\n * );\n * }\n * ```\n *\n * To share modules, you can provide a shared module map with references to the shared modules:\n *\n * ```tsx\n * <RemoteComponent\n * src=\"/nextjs-app-remote/components/header\"\n * shared={{\n * '@/components/provider': () => import('@/components/host-provider')\n * }}\n * />\n * ```\n */\nexport function RemoteComponent({\n src,\n isolate,\n mode = 'open',\n reset,\n credentials = 'same-origin',\n name: nameProp = '__vercel_remote_component',\n shared = {},\n children,\n onBeforeLoad,\n onLoad,\n onError,\n onChange,\n onRequest,\n onResponse,\n}: RemoteComponentProps) {\n const instanceId = useId();\n\n const name = useMemo(() => {\n if (typeof src === 'string') {\n const url = new URL(\n src,\n typeof document !== 'undefined' ? location.href : DUMMY_FALLBACK,\n );\n if (url.hash) {\n return url.hash.slice(1);\n }\n } else if (typeof src === 'object' && 'hash' in src && src.hash) {\n return src.hash.slice(1) || nameProp;\n }\n return nameProp;\n }, [src, nameProp]);\n\n const [data, setData] = useState<Omit<\n RemoteComponentPropsType,\n 'children'\n > | null>(null);\n\n const url = useMemo(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);\n\n // for relative src paths, use just the pathname as the unique id.\n // for static urls, use the full url as the unique id as the path may not be unique.\n // this id needs to be the same for server and client side rendering.\n // note that if this needs to be more unique, can pass through the bundle as an id prop and ammend it to this id.\n const id =\n url.origin ===\n (typeof location !== 'undefined' ? location.origin : DUMMY_FALLBACK)\n ? url.pathname\n : url.href;\n\n //instanceId prevents multiple components with the same src from sharing a shadow root\n const keySuffix = `${escapeString(id)}_${escapeString(data?.name ?? name)}_${escapeString(instanceId)}`;\n\n const [remoteComponent, setRemoteComponent] = useState<\n React.ReactNode | Error\n >(null);\n\n const { shadowRoot, shadowRootContainerRef } = useShadowRoot({\n isolate,\n mode,\n keySuffix,\n });\n\n const htmlRef = useRef<string | null>(\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot?.innerHTML ??\n document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ??\n document.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`)\n ?.innerHTML ??\n document.querySelector('div[data-bundle][data-route]')?.innerHTML)\n : null,\n );\n const endTemplateRef = useRef<HTMLTemplateElement | null>(null);\n // collect initial content that needs to be removed after remote component renders\n const childrenRef = useRef(\n typeof document !== 'undefined'\n ? (() => {\n let el = document.querySelector(`template[id=\"${name}_start\"]`);\n const elements = [];\n while (el && el.id !== `${name}_end`) {\n if (\n el.id !== `${name}_start` &&\n !el.getAttribute('data-remote-component')\n ) {\n elements.push(el);\n }\n el = el.nextElementSibling as HTMLTemplateElement | null;\n }\n return elements;\n })()\n : [],\n );\n const prevSrcRef = useRef<string | URL | null>(null);\n const componentHydrationHtml = useRef<string | null>(null);\n const prevIsRemoteComponentRef = useRef<boolean>(false);\n const prevUrlRef = useRef<URL | null>(null);\n const prevRemoteComponentContainerRef = useRef<HTMLDivElement | null>(null);\n const unmountRef = useRef<Set<MountOrUnmountFunction> | null>(null);\n const prevNameRef = useRef<string | undefined>(undefined);\n\n // Clean up the shadow root cache on unmount to prevent memory leaks\n useLayoutEffect(() => {\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n return () => {\n delete (\n globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n >\n )[shadowRootKey];\n };\n }, [keySuffix]);\n\n useLayoutEffect(() => {\n // Clear initial content after remote component renders\n if (childrenRef.current.length > 0 && remoteComponent) {\n childrenRef.current.forEach((el) => {\n el.remove();\n });\n childrenRef.current = [];\n }\n }, [remoteComponent]);\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 (\n index > 0 &&\n style.getAttribute('data-remote-components-reset') !== 'react'\n ) {\n style.remove();\n }\n });\n }\n\n // clear the html ref after hydration\n htmlRef.current = null;\n\n // clear all nodes except links and styles until the start marker\n // the marker gets only rendered on hydration\n let el: ChildNode | null = shadowRoot.childNodes[0] ?? null;\n while (el && (!('id' in el) || el.id !== `${name}_start`)) {\n const nextEl = el.nextSibling;\n if (el.nodeName !== 'LINK' && el.nodeName !== 'STYLE') {\n el.parentNode?.removeChild(el);\n }\n el = nextEl;\n }\n }\n }, [shadowRoot, remoteComponent, name]);\n\n useEffect(() => {\n if (src && src !== prevSrcRef.current) {\n const previousSrc = prevSrcRef.current;\n const previousName = prevNameRef.current;\n prevSrcRef.current = src;\n\n if (previousSrc !== null) {\n htmlRef.current = null;\n }\n\n onBeforeLoad?.(src);\n\n startTransition(async () => {\n try {\n let html = getRemoteComponentHtml(\n htmlRef.current ??\n (endTemplateRef.current?.previousElementSibling?.tagName === 'div'\n ? endTemplateRef.current.previousElementSibling.innerHTML\n : ''),\n );\n\n if (!html && src) {\n // fetch the remote component\n const fetchInit = {\n credentials,\n } as RequestInit;\n\n const abortController = new AbortController();\n const res = await fetchWithHooks(url, fetchInit, {\n onRequest,\n onResponse,\n abortController,\n });\n\n if (!res || !res.ok) {\n let error: Error = failedToFetchRemoteComponentError(\n url.href,\n res ?? new Response(null, { status: 0 }),\n );\n try {\n const body = await res.text();\n const parser = new DOMParser();\n const doc = parser.parseFromString(body, 'text/html');\n const errorTemplate = doc.querySelector(\n 'template[data-next-error-message]',\n );\n const errorMessage = errorTemplate?.getAttribute(\n 'data-next-error-message',\n );\n const errorStack = errorTemplate?.getAttribute(\n 'data-next-error-stack',\n );\n\n if (errorMessage) {\n error = new RemoteComponentsError(errorMessage);\n if (errorStack) {\n error.stack = errorStack;\n }\n }\n } catch (parseError) {\n // Re-throw abort errors, ignore parse errors\n if (isAbortError(parseError)) throw parseError;\n }\n\n throw error;\n }\n\n // get the full HTML content as a string\n const remoteHtml = await res.text();\n htmlRef.current = remoteHtml;\n html = getRemoteComponentHtml(remoteHtml);\n }\n\n // create a virtual element which will be used to parse the HTML and extract the component and RSC flight data\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, 'text/html');\n\n if (\n (doc.querySelectorAll('div[data-bundle][data-route]').length > 1 &&\n !doc.querySelector(\n `div[data-bundle][data-route][id^=\"${name}\"]`,\n )) ||\n (doc.querySelectorAll('remote-component:not([src])').length > 1 &&\n !doc.querySelector(`remote-component[name=\"${name}\"]`))\n ) {\n throw multipleRemoteComponentsError(url.href);\n }\n\n // reference to the remote component content\n const component =\n doc.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`) ??\n // fallback to the first element with the data-bundle and data-route attributes when not using a named remote component\n doc.querySelector('div[data-bundle][data-route]') ??\n // fallback to Next.js Pages Router\n doc.querySelector('div#__next') ??\n // fallback to the remote-component web component\n doc.querySelector(`remote-component[name=\"${name}\"]:not([src])`) ??\n doc.querySelector('remote-component:not([src])');\n const nextData = JSON.parse(\n (\n doc.querySelector('#__NEXT_DATA__') ??\n doc.querySelector('#__REMOTE_NEXT_DATA__')\n )?.textContent ?? 'null',\n ) as {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: 'turbopack' | 'webpack' | 'script';\n shared?: Record<string, string>;\n };\n };\n page: string;\n buildId: string;\n } | null;\n\n const remoteName =\n component?.getAttribute('id')?.replace(/_ssr$/, '') ||\n (nextData ? '__next' : name);\n // reference to the RSC flight data\n const rsc = doc.querySelector(`#${remoteName}_rsc`);\n\n // reference to the bundle containing the client components\n const bundle =\n component?.getAttribute('data-bundle') ||\n nextData?.props.__REMOTE_COMPONENT__?.bundle ||\n 'default';\n\n const isRemoteComponent =\n component?.tagName.toLowerCase() === 'remote-component';\n\n const metadata = {\n name: remoteName,\n bundle,\n route:\n component?.getAttribute('data-route') ??\n nextData?.page ??\n (url.pathname || DEFAULT_ROUTE),\n runtime: (component?.getAttribute('data-runtime') ??\n (nextData?.props.__REMOTE_COMPONENT__?.runtime ||\n RUNTIME_SCRIPT)) as RemoteComponentPropsType['runtime'],\n };\n\n const remoteSharedEl = doc.querySelector(\n `#${remoteName}_shared[data-remote-components-shared]`,\n );\n const remoteShared =\n nextData?.props.__REMOTE_COMPONENT__?.shared ??\n ((JSON.parse(remoteSharedEl?.textContent ?? '{}') ?? {}) as Record<\n string,\n string\n >);\n remoteSharedEl?.remove();\n\n if (!component || !(rsc || nextData || isRemoteComponent)) {\n throw new RemoteComponentsError(\n `Remote Component not found on ${url.href}.${\n remoteName !== '__vercel_remote_component'\n ? `The name for the <RemoteComponent> is \"${remoteName}\". Check <RemoteComponent> usage.`\n : ''\n } Did you forget to wrap the content in <RemoteComponent>?`,\n );\n }\n\n if (prevIsRemoteComponentRef.current) {\n if (shadowRoot) {\n shadowRoot.innerHTML = '';\n }\n const self = globalThis as typeof globalThis &\n RemoteComponentMountUnmount;\n const prevUrl = prevUrlRef.current;\n if (\n prevUrl &&\n self.__remote_script_entrypoint_unmount__?.[prevUrl.href]\n ) {\n const unmountPromises = Promise.all(\n Array.from(unmountRef.current ?? []).map(async (unmount) =>\n unmount(\n shadowRoot ?? prevRemoteComponentContainerRef.current,\n ),\n ),\n );\n unmountRef.current = null;\n await unmountPromises;\n }\n }\n prevIsRemoteComponentRef.current = isRemoteComponent;\n prevUrlRef.current = url;\n prevNameRef.current = remoteName;\n\n // update all relative URLs to absolute URLs based on the remote component URL\n applyOriginToNodes(doc, url);\n\n // reference to all link elements in the remote component\n const links = Array.from(\n doc.querySelectorAll<HTMLLinkElement>('link[href]'),\n )\n .filter((link) => {\n return !component.contains(link);\n })\n .map((link) => ({\n href: new URL(link.getAttribute('href') ?? link.href, url).href,\n ...link\n .getAttributeNames()\n .reduce<Record<string, string>>((acc, key) => {\n if (key !== 'href') {\n acc[attrToProp[key] ?? key] = link.getAttribute(key) ?? '';\n }\n return acc;\n }, {}),\n }));\n\n const scripts = (\n isRemoteComponent ? component : doc\n ).querySelectorAll<HTMLScriptElement>('script[src],script[data-src]');\n\n // handle inline scripts in the remote component\n const inlineScripts = (\n isRemoteComponent ? component : doc\n ).querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\n\n if (!isRemoteComponent) {\n // Next.js Script support\n const self = globalThis as typeof globalThis & {\n __next_s: [string, Record<string, string>][];\n };\n const prevNextScripts = self.__next_s;\n const nextScripts = [] as [string, Record<string, string>][];\n // eslint-disable-next-line camelcase\n self.__next_s = nextScripts;\n\n // TODO: needs to be cancellable with a singular listener for the abort signal https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\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 // TODO: needs to be cancellable https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n document.body.appendChild(newScript);\n } else {\n resolve(undefined);\n document.body.appendChild(script);\n }\n } else {\n resolve(undefined);\n }\n });\n }),\n );\n // process the remote component Next.js Script container\n nextScripts.forEach(([scriptSrc, props]) => {\n const script = document.createElement('script');\n // when we have a script src, apply it (inline scripts have `0` as src)\n if (scriptSrc) {\n script.src = scriptSrc;\n }\n // apply Script props\n if (typeof props.children === 'string') {\n script.textContent = props.children;\n }\n setAttributesFromProps(script, props);\n document.head.appendChild(script);\n });\n // restore previous Next.js Script container\n // eslint-disable-next-line camelcase\n self.__next_s = prevNextScripts;\n }\n\n let rscName;\n if (rsc) {\n rscName = `__remote_component_rsc_${escapeString(\n id,\n )}_${escapeString(remoteName)}`;\n rsc.textContent =\n rsc.textContent?.replace(\n new RegExp(`self\\\\[\"${remoteName}\"\\\\]`, 'g'),\n `self[\"${rscName}\"]`,\n ) ?? '';\n document.body.appendChild(rsc);\n }\n\n const newData = {\n ...metadata,\n links,\n remoteShared,\n src: typeof src === 'string' ? src : src.href,\n serverUrl: url.href,\n data: rsc\n ? (rsc.textContent || '').split('\\n').filter(Boolean)\n : [],\n };\n\n componentHydrationHtml.current = `${Array.from(\n doc.querySelectorAll('link,style'),\n )\n .map((link) => link.outerHTML)\n .join('')}${\n reset\n ? `<style data-remote-components-reset=\"\">:host { all: initial; }</style>`\n : ''\n }${component.innerHTML}`;\n\n const userShared = await shared;\n\n if ('__remote_components_missing_shared__' in userShared) {\n userShared.__remote_components_missing_shared__().catch((e) => {\n throw e;\n });\n } else if ('__remote_components_missing_shared__' in remoteShared) {\n throw new RemoteComponentsError(\n remoteShared.__remote_components_missing_shared__,\n );\n }\n\n if (isRemoteComponent) {\n // Only call onChange when not on first load (matching HTML implementation)\n if (previousSrc !== null) {\n onChange?.({\n previousSrc,\n nextSrc: src,\n previousName,\n nextName: remoteName,\n });\n }\n setData(newData);\n if (shadowRoot) {\n let shadowRootHtml = component.innerHTML;\n if (reset) {\n shadowRootHtml = `<style data-remote-components-reset=\"\">:host { all: initial; }</style>${shadowRootHtml}`;\n }\n shadowRoot.innerHTML = shadowRootHtml;\n htmlRef.current = null;\n setRemoteComponent(null);\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n onLoad?.(src);\n } else if (isolate === false) {\n setRemoteComponent(\n // TODO: remove wrapper div by converting HTML to RSC or React tree\n <div\n dangerouslySetInnerHTML={{ __html: component.innerHTML }}\n ref={prevRemoteComponentContainerRef}\n />,\n );\n htmlRef.current = null;\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(component.querySelectorAll('script')),\n url,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) =>\n mountFn(prevRemoteComponentContainerRef.current),\n ),\n );\n onLoad?.(src);\n }\n } else {\n const result = await loadRemoteComponent({\n url,\n name: remoteName,\n rscName,\n bundle,\n route: metadata.route,\n runtime: metadata.runtime,\n data: newData.data,\n nextData,\n scripts: Array.from(scripts).map((script) => {\n const scriptSrc =\n script.getAttribute('data-src') ||\n script.getAttribute('src') ||\n script.src;\n const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(\n scriptSrc,\n )?.groups ?? {\n prefix: undefined,\n id: scriptSrc,\n };\n return {\n src: new URL(\n `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n ),\n url,\n ).href,\n };\n }),\n shared: {\n ...sharedPolyfills(userShared),\n ...userShared,\n },\n remoteShared,\n container: shadowRoot,\n });\n if (rsc) {\n rsc.remove();\n }\n\n setData(newData);\n // Only call onChange when not on first load (matching HTML implementation)\n if (previousSrc !== null) {\n onChange?.({\n previousSrc,\n nextSrc: src,\n previousName,\n nextName: remoteName,\n });\n }\n if (result.error) {\n setRemoteComponent(result.error);\n onError?.(result.error);\n } else {\n setRemoteComponent(result.component);\n onLoad?.(src);\n }\n }\n } catch (error) {\n // AbortError is expected when loading is cancelled - exit cleanly\n if (isAbortError(error)) {\n return;\n }\n setRemoteComponent(error as Error);\n onError?.(error);\n }\n });\n }\n }, [\n url,\n src,\n isolate,\n credentials,\n name,\n shared,\n shadowRoot,\n reset,\n id,\n onBeforeLoad,\n onLoad,\n onError,\n onChange,\n onRequest,\n onResponse,\n ]);\n\n if (remoteComponent instanceof Error) {\n throw remoteComponent;\n }\n\n const metadataJson = (\n <script data-remote-component type=\"application/json\">\n {JSON.stringify({\n name: data?.name || name,\n bundle: data?.bundle || 'default',\n route: data?.route || DEFAULT_ROUTE,\n runtime: prevIsRemoteComponentRef.current\n ? RUNTIME_SCRIPT\n : data?.runtime || RUNTIME_WEBPACK,\n })}\n </script>\n );\n const resetStyle = reset ? (\n <style data-remote-components-reset=\"react\">{`:host { all: initial; }`}</style>\n ) : null;\n const linksToRender: React.ReactNode[] | null =\n data?.links?.map((link) => (\n <link\n {...link}\n href={new URL(link.href as string, url).href}\n key={JSON.stringify(link)}\n />\n )) || null;\n const componentToRender = (\n <>\n {resetStyle}\n {linksToRender}\n {remoteComponent ?? children}\n </>\n );\n\n if (componentHydrationHtml.current && shadowRoot && !shadowRoot.innerHTML) {\n shadowRoot.innerHTML = componentHydrationHtml.current;\n componentHydrationHtml.current = null;\n\n if (prevIsRemoteComponentRef.current) {\n // ensure we load static resources when hydrating a remote component in shadow DOM\n loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n )\n .then(({ mount }) => {\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n })\n .then(() => {\n if (src) {\n onLoad?.(src);\n }\n })\n .catch((e) => {\n const error = new RemoteComponentsError(\n `Error mounting remote component from \"${url.href}\"`,\n {\n cause: e,\n },\n );\n setRemoteComponent(error);\n onError?.(error);\n });\n }\n }\n\n if (isolate !== false) {\n const shadowRemoteComponentHtml =\n shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ??\n shadowRoot?.querySelector('div[data-bundle][data-route]');\n if (shadowRemoteComponentHtml) {\n shadowRemoteComponentHtml.remove();\n }\n\n return (\n <>\n {metadataJson}\n <div\n data-remote-component-id={`shadowroot_${keySuffix}`}\n id={`shadowroot_${data?.name ?? name}`}\n ref={shadowRootContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {typeof document === 'undefined' ? (\n <div\n dangerouslySetInnerHTML={{\n __html: `<img\n alt=\"\" decoding=\"async\" style=\"display:none\"\n src=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==\"\n onload=\"(function(el){\n const root = el.getRootNode();\n globalThis.__remote_components_shadowroot_${keySuffix} = root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {resetStyle}\n {linksToRender}\n {children}\n </template>\n ) : null}\n {shadowRoot && remoteComponent\n ? createPortal(\n <>\n <template id={`${name}_start`} />\n {resetStyle}\n {linksToRender}\n {remoteComponent}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>,\n shadowRoot,\n )\n : null}\n </div>\n </>\n );\n }\n htmlRef.current = null;\n\n // render start/end markers for the remote component\n return (\n <>\n <template id={`${name}_start`} />\n {metadataJson}\n {componentToRender}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>\n );\n}\n","const tagNames = [\n 'img',\n 'source',\n 'video',\n 'audio',\n 'track',\n 'iframe',\n 'embed',\n 'script',\n 'link',\n];\n\nexport function applyOriginToNodes(doc: Document | HTMLElement, url: URL) {\n if (url.origin !== location.origin) {\n const nodes = doc.querySelectorAll<HTMLImageElement>(\n tagNames\n .map(\n (type) =>\n `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`,\n )\n .join(','),\n );\n nodes.forEach((node) => {\n if (\n node.hasAttribute('src') &&\n /^[./]+\\/?/.test(node.getAttribute('src') ?? '')\n ) {\n node.src = new URL(node.getAttribute('src') ?? '/', url).href;\n }\n if (\n node.hasAttribute('href') &&\n /^[./]+\\/?/.test(node.getAttribute('href') ?? '')\n ) {\n node.setAttribute(\n 'href',\n new URL(node.getAttribute('href') ?? '/', url).href,\n );\n }\n if (node.hasAttribute('srcset')) {\n const srcSet = node\n .getAttribute('srcset')\n ?.split(',')\n .map((entry) => {\n const [urlPart, descriptor] = entry.trim().split(/\\s+/);\n if (!urlPart) return entry;\n\n const absoluteUrl = new URL(urlPart, url).href;\n return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;\n })\n .join(', ');\n if (srcSet) {\n node.setAttribute('srcset', srcSet);\n }\n }\n if (node.hasAttribute('imagesrcset')) {\n const srcSet = node\n .getAttribute('imagesrcset')\n ?.split(',')\n .map((entry) => {\n const [urlPart, descriptor] = entry.trim().split(/\\s+/);\n if (!urlPart) return entry;\n\n const absoluteUrl = new URL(urlPart, url).href;\n return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;\n })\n .join(', ');\n if (srcSet) {\n node.setAttribute('imagesrcset', srcSet);\n }\n }\n });\n }\n}\n","export class RemoteComponentsError extends Error {\n code = 'REMOTE_COMPONENTS_ERROR';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'RemoteComponentsError';\n }\n}\n\nexport function multipleRemoteComponentsError(url: string | undefined) {\n return new RemoteComponentsError(\n `Multiple Remote Components found at \"${url}\". When a page exposes multiple Remote Components you must specify the \"name\" prop to select which one to load.`,\n );\n}\n\nexport function failedToFetchRemoteComponentError(\n url: string,\n { status, statusText }: { status: number; statusText: string },\n help: string = 'Is the URL correct and accessible?',\n) {\n return new RemoteComponentsError(\n `Failed to fetch Remote Component from \"${url}\". ${help}`,\n { cause: new Error(`${status} ${statusText}`) },\n );\n}\n","import { RemoteComponentsError } from '#internal/shared/error';\n\ntype LogLocation =\n | 'ChunkLoader'\n | 'ComponentLoader'\n | 'SharedModules'\n | 'WebpackAdapter'\n | 'TurbopackModule'\n | 'StaticLoader'\n | 'ScriptLoader'\n | 'Polyfill'\n | 'HtmlRemote'\n | 'HtmlHost'\n | 'Config'\n | 'NextAppRouter'\n | 'NextAppRouterCompat'\n | 'FetchRemoteComponent';\n\nconst PREFIX = 'remote-components';\nconst DEBUG =\n typeof window !== 'undefined' && localStorage.getItem('RC_DEBUG') === 'true';\n\nexport function logDebug(location: LogLocation, message: string) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.debug(`[${PREFIX}:${location}]: ${message}`);\n }\n}\n\nexport function logInfo(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.info(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logWarn(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.warn(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logError(\n location: LogLocation,\n message: string,\n cause?: unknown,\n) {\n // eslint-disable-next-line no-console\n console.error(\n new RemoteComponentsError(`[${PREFIX}:${location}]: ${message}`, {\n cause,\n }),\n );\n}\n","import type { ImageProps, StaticImageData } from 'next/image';\nimport type { LinkProps } from 'next/link';\nimport { logWarn } from '../utils/logger';\n\nfunction applyBundleUrlToSrc(bundle: string, src: string) {\n const self = globalThis as typeof globalThis & {\n __remote_bundle_url__?: Record<string, URL>;\n };\n\n if (self.__remote_bundle_url__?.[bundle]?.origin === location.origin) {\n return src;\n }\n\n const { assetPrefix, path } =\n /^(?<assetPrefix>.*?)\\/_next\\/(?<path>.*)/.exec(src)?.groups ?? {};\n if (!path) {\n return new URL(src, self.__remote_bundle_url__?.[bundle]?.origin).href;\n }\n return `${self.__remote_bundle_url__?.[bundle]?.origin ?? ''}${assetPrefix}/_next/${path}`;\n}\n\nexport function applyBundleUrlToImagePropsSrc(\n bundle: string,\n src: ImageProps['src'],\n) {\n if (typeof src === 'string') {\n return applyBundleUrlToSrc(bundle, src);\n }\n const propSrc = src as StaticImageData;\n return applyBundleUrlToSrc(bundle, propSrc.src);\n}\n\nconst imageImpl = (bundle: string) =>\n function RemoteImage({\n fill: _fill,\n loader: _loader,\n quality: _quality,\n priority: _priority,\n loading: _loading,\n placeholder: _placeholder,\n blurDataURL: _blurDataURL,\n unoptimized: _unoptimized,\n overrideSrc: _overrideSrc,\n src,\n ...props\n }: ImageProps) {\n const newSrc = applyBundleUrlToImagePropsSrc(\n bundle,\n typeof src === 'string' ? src : (src as StaticImageData).src,\n );\n\n return (\n // eslint-disable-next-line @next/next/no-img-element, jsx-a11y/alt-text\n <img\n decoding=\"async\"\n style={{ color: 'transparent' }}\n {...props}\n src={newSrc}\n suppressHydrationWarning\n />\n );\n };\n\n// polyfill Next.js App Router client API (minimal)\n// implementations are minimal and do not cover all use cases\n// developer can override these shared modules from configuration\nexport function sharedPolyfills(\n shared?: Record<string, () => Promise<unknown>>,\n) {\n const self = globalThis as typeof globalThis & {\n __remote_component_host_shared_modules__?: Record<\n string,\n () => Promise<unknown>\n >;\n };\n const polyfill = {\n 'next/dist/client/components/navigation':\n self.__remote_component_host_shared_modules__?.['next/navigation'] ??\n shared?.['next/navigation'] ??\n (() =>\n Promise.resolve({\n useRouter() {\n return {\n push: (routerUrl: string) => {\n history.pushState({}, '', routerUrl);\n },\n replace: (routerUrl: string) => {\n history.replaceState({}, '', routerUrl);\n },\n back: () => {\n history.back();\n },\n };\n },\n usePathname() {\n return location.pathname;\n },\n useParams() {\n return {};\n },\n useSearchParams() {\n return new URLSearchParams(location.search);\n },\n useSelectedLayoutSegment() {\n return null;\n },\n useSelectedLayoutSegments() {\n return [];\n },\n __esModule: true,\n })),\n 'next/dist/client/app-dir/link':\n self.__remote_component_host_shared_modules__?.['next/link'] ??\n shared?.['next/link'] ??\n (() =>\n Promise.resolve({\n default: ({\n scroll: _,\n replace,\n prefetch,\n onNavigate,\n children,\n ...props\n }: React.PropsWithChildren<LinkProps>) => {\n if (prefetch) {\n logWarn(\n 'Polyfill',\n 'Next.js Link prefetch is not supported in remote components',\n );\n }\n return (\n <a\n {...props}\n href={props.href as string}\n onClick={(e) => {\n e.preventDefault();\n let preventDefaulted = false;\n e.preventDefault = () => {\n preventDefaulted = true;\n e.defaultPrevented = true;\n };\n if (typeof props.onClick === 'function') {\n props.onClick(e);\n }\n onNavigate?.(e);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (preventDefaulted) {\n return;\n }\n if (replace) {\n history.replaceState({}, '', props.href as string);\n } else {\n history.pushState({}, '', props.href as string);\n }\n }}\n suppressHydrationWarning\n >\n {children ?? null}\n </a>\n );\n },\n useLinkStatus() {\n return { pending: false };\n },\n __esModule: true,\n })),\n 'next/dist/client/app-dir/form':\n self.__remote_component_host_shared_modules__?.['next/form'] ??\n shared?.['next/form'] ??\n (() =>\n Promise.resolve({\n default: () => {\n // TODO: implement <Form> component for non-Next.js host applications\n throw new Error('Next.js <Form> component not implemented');\n },\n __esModule: true,\n })),\n 'next/dist/client/image-component':\n self.__remote_component_host_shared_modules__?.['next/image'] ??\n shared?.['next/image'] ??\n ((bundle: string) =>\n Promise.resolve({\n Image: imageImpl(bundle),\n __esModule: true,\n })),\n 'next/image':\n self.__remote_component_host_shared_modules__?.['next/image'] ??\n shared?.['next/image'] ??\n ((bundle: string) =>\n Promise.resolve({\n default: imageImpl(bundle),\n getImageProps: (_imgProps: ImageProps) => {\n throw new Error(\n 'Next.js getImageProps() is not implemented in remote components',\n );\n },\n __esModule: true,\n })),\n 'next/dist/client/script':\n self.__remote_component_host_shared_modules__?.['next/script'] ??\n shared?.['next/script'] ??\n (() =>\n Promise.resolve({\n // TODO: implement <Script> component for non-Next.js host applications\n // do not throw an error for now\n default: () => null,\n __esModule: true,\n })),\n 'next/router':\n self.__remote_component_host_shared_modules__?.['next/router'] ??\n shared?.['next/router'] ??\n (() =>\n // TODO: incomplete implementation\n Promise.resolve({\n useRouter() {\n return {\n push: (routerUrl: string) => {\n history.pushState({}, '', routerUrl);\n },\n replace: (routerUrl: string) => {\n history.replaceState({}, '', routerUrl);\n },\n back: () => {\n history.back();\n },\n };\n },\n __esModule: true,\n })),\n 'next/dist/build/polyfills/process': () =>\n Promise.resolve({\n default: {\n env: {\n NODE_ENV: 'production',\n },\n },\n __esModule: true,\n }),\n } as Record<string, () => Promise<unknown>>;\n\n polyfill['next/navigation'] = polyfill[\n 'next/dist/client/components/navigation'\n ] as () => Promise<unknown>;\n polyfill['next/link'] = polyfill[\n 'next/dist/client/app-dir/link'\n ] as () => Promise<unknown>;\n polyfill['next/form'] = polyfill[\n 'next/dist/client/app-dir/form'\n ] as () => Promise<unknown>;\n polyfill['next/dist/api/image'] = polyfill[\n 'next/dist/client/image-component'\n ] as () => Promise<unknown>;\n polyfill['next/script'] = polyfill[\n 'next/dist/client/script'\n ] as () => Promise<unknown>;\n\n return polyfill;\n}\n","import * as React from 'react';\nimport * as JSXDevRuntime from 'react/jsx-dev-runtime';\nimport * as JSXRuntime from 'react/jsx-runtime';\nimport * as ReactDOM from 'react-dom';\nimport * as ReactDOMClient from 'react-dom/client';\nimport { RemoteComponentsError } from '../error';\nimport { logDebug, logWarn } from '../utils/logger';\nimport { nextClientPagesLoader } from '../webpack/next-client-pages-loader';\nimport { applySharedModules } from '../webpack/shared-modules';\nimport { createRSCStream } from './rsc';\nimport { loadScripts } from './script-loader';\nimport type { GlobalScope, LoaderResult, RemoteComponentProps } from './types';\nimport { setupWebpackRuntime } from './webpack-adapter';\n\nexport type LoadRemoteComponentProps = Pick<\n RemoteComponentProps,\n 'name' | 'bundle' | 'route' | 'runtime' | 'data' | 'nextData' | 'scripts'\n> & {\n url: URL;\n shared:\n | Promise<Record<string, (bundle?: string) => Promise<unknown>>>\n | Record<string, (bundle?: string) => Promise<unknown>>;\n remoteShared: Record<string, string>;\n container?: HTMLHeadElement | ShadowRoot | null;\n rscName?: string;\n};\n\n/**\n * Main loader function that orchestrates the component loading process\n */\nexport async function loadRemoteComponent({\n url,\n name,\n rscName,\n bundle,\n route = '/',\n runtime = 'webpack',\n data,\n nextData,\n scripts = [],\n shared = Promise.resolve({}),\n remoteShared = {},\n container,\n}: LoadRemoteComponentProps): Promise<LoaderResult> {\n try {\n // Load scripts if using webpack runtime\n if (runtime === 'webpack') {\n const self = globalThis as GlobalScope;\n // disable webpack entrypoint execution for the remote\n if (!self.__DISABLE_WEBPACK_EXEC__) {\n self.__DISABLE_WEBPACK_EXEC__ = {};\n }\n // disable webpack entrypoint execution for the current remote bundle\n self.__DISABLE_WEBPACK_EXEC__[bundle] = true;\n await loadScripts(scripts);\n }\n\n const hostShared = await shared;\n logDebug(\n 'ComponentLoader',\n `loadRemoteComponent: bundle=\"${bundle}\", name=\"${name}\"`,\n );\n logDebug(\n 'ComponentLoader',\n `Host shared modules available: ${Object.keys(hostShared)}`,\n );\n logDebug(\n 'ComponentLoader',\n `Remote shared modules requested: ${JSON.stringify(remoteShared)}`,\n );\n\n // Setup webpack runtime environment\n await setupWebpackRuntime(\n runtime,\n scripts,\n url,\n bundle,\n hostShared,\n remoteShared,\n );\n\n // Setup shared modules\n if (bundle) {\n const resolve = {\n '/react/index.js': React,\n '/react/jsx-dev-runtime.js': JSXDevRuntime,\n '/react/jsx-runtime.js': JSXRuntime,\n '/react-dom/index.js': ReactDOM,\n '/react-dom/client.js': ReactDOMClient,\n ...Object.entries(remoteShared).reduce<Record<string, unknown>>(\n (acc, [key, value]) => {\n if (typeof hostShared[value] !== 'undefined') {\n acc[key.replace(/^\\(ssr\\)\\/(?<relative>\\.\\/)?/, '')] =\n hostShared[value];\n } else {\n logDebug(\n 'ComponentLoader',\n `Remote requests \"${value}\" but host doesn't provide it`,\n );\n }\n return acc;\n },\n {},\n ),\n } as Record<string, unknown>;\n await Promise.all(\n Object.entries(resolve).map(async ([key, value]) => {\n if (typeof value === 'function') {\n resolve[key] = await value(bundle);\n }\n return Promise.resolve(value);\n }),\n );\n applySharedModules(bundle, resolve);\n } else {\n logWarn(\n 'ComponentLoader',\n 'No bundle specified, skipping shared module setup',\n );\n }\n\n // Load component based on data type\n if (data.length > 0) {\n return await loadRSCComponent(rscName ?? name, data);\n } else if (nextData) {\n return loadNextPagesComponent(bundle, route, nextData, name, container);\n }\n\n return loadRSCComponent(rscName ?? name, [`0:[null]\\n`]); // Fallback to empty RSC payload\n } catch (error) {\n return {\n component: null,\n error: new RemoteComponentsError(\n `Failed to load remote component \"${name}\".`,\n {\n cause: error instanceof Error ? error : new Error(String(error)),\n },\n ),\n };\n }\n}\n\n/**\n * Loads RSC (React Server Components) based component\n */\nasync function loadRSCComponent(\n rscName: string,\n data: string[],\n): Promise<LoaderResult> {\n // try to import react-server-dom-webpack from Next.js with a fallback\n let createFromReadableStream;\n try {\n const { createFromReadableStream: _createFromReadableStream } =\n await import(\n 'next/dist/compiled/react-server-dom-webpack/client.browser'\n );\n createFromReadableStream = _createFromReadableStream;\n } catch {\n const {\n default: { createFromReadableStream: _createFromReadableStream },\n } = await import('react-server-dom-webpack/client.browser');\n createFromReadableStream = _createFromReadableStream;\n }\n // remote components with RSC requires react-server-dom-webpack\n if (typeof createFromReadableStream !== 'function') {\n throw new RemoteComponentsError(\n 'Failed to import \"react-server-dom-webpack\". Is Next.js installed correctly?',\n );\n }\n\n const stream = createRSCStream(rscName, data);\n const component = createFromReadableStream(stream);\n\n return { component };\n}\n\n/**\n * Loads Next.js Pages Router based component\n */\nfunction loadNextPagesComponent(\n bundle: string,\n route: string,\n nextData: NonNullable<RemoteComponentProps['nextData']>,\n name: string,\n container?: HTMLHeadElement | ShadowRoot | null,\n): LoaderResult {\n const { Component, App } = nextClientPagesLoader(bundle, route, container);\n\n if (!Component) {\n throw new RemoteComponentsError(\n `Remote Component \"${name}\" is trying to load the component for route \"${route}\" but it is not available.`,\n );\n }\n\n // error tolerance when app component is not found\n const component = App\n ? React.createElement(App, { Component, ...nextData.props })\n : React.createElement(Component, nextData.props);\n\n return { component };\n}\n","import { RemoteComponentsError } from '../error';\n\n// module loader for Next.js Pages Router\nexport function nextClientPagesLoader(\n bundle: string,\n route: string,\n styleContainer: HTMLHeadElement | ShadowRoot | null = document.head,\n) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string | number) => unknown) & {\n c?: Record<\n string | number,\n { id: string; parents: string[]; children: string[] }\n >;\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n type?: 'turbopack' | 'webpack';\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n // Next.js client pages loader reference storage\n __NEXT_P?: [\n (\n | [\n string,\n () => { default?: React.ComponentType<Record<string, unknown>> },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n ];\n // Next.js Pages Router CSS cache\n __remote_next_css__?: Record<string, ChildNode[]>;\n };\n\n // temporarily remove the original Next.js CSS loader\n const nextCssOriginal = document.querySelector(\n `[id=\"__next_css__DO_NOT_USE__\"]:not([data-bundle=\"${bundle}\"][data-route=\"${route}\"])`,\n );\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.removeChild(nextCssOriginal);\n }\n\n // create a new Next.js CSS loader element\n const nextCss = document.createElement('noscript');\n nextCss.id = '__next_css__DO_NOT_USE__';\n nextCss.setAttribute('data-bundle', bundle);\n nextCss.setAttribute('data-route', route);\n const nextCssEnd = document.createElement('noscript');\n nextCssEnd.id = '__next_css__DO_NOT_USE_END__';\n nextCssEnd.setAttribute('data-bundle', bundle);\n nextCssEnd.setAttribute('data-route', route);\n document.head.appendChild(nextCssEnd);\n document.head.appendChild(nextCss);\n\n // find the page component loader chunk\n const componentLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}!`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}!`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // find the app loader chunk\n const appLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // if we didn't find the component loader or app loader, throw an error\n if (!(componentLoaderChunk && appLoaderChunk)) {\n throw new RemoteComponentsError(\n `Next.js client pages loader not found in bundle \"${bundle}\".`,\n );\n }\n\n // temporarily store the original __NEXT_P reference\n // this is required to avoid conflicts with the Next.js client pages loader\n // which uses the same global variable to store the page components\n const __NEXT_P_ORIGINAL = self.__NEXT_P;\n const selfOriginal = self;\n delete selfOriginal.__NEXT_P;\n\n // load the component and app loader chunks\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? componentLoaderChunk\n : `[${bundle}] ${componentLoaderChunk}`,\n );\n if (\n typeof appLoaderChunk === 'string' ||\n (typeof appLoaderChunk === 'number' && appLoaderChunk !== -1)\n ) {\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? appLoaderChunk\n : `[${bundle}] ${appLoaderChunk}`,\n );\n }\n\n // if we have the __NEXT_P global variable, we can extract the component and app\n if (self.__NEXT_P) {\n const [, componentLoader] = self.__NEXT_P[0] ?? [\n undefined,\n () => ({ default: null }),\n ];\n const [, appLoader] = self.__NEXT_P[2] ?? [\n undefined,\n () => ({\n default: null,\n }),\n ];\n const { default: Component } = componentLoader();\n const { default: App } = appLoader();\n\n if (!self.__remote_next_css__) {\n // eslint-disable-next-line camelcase\n self.__remote_next_css__ = {};\n }\n\n if (!self.__remote_next_css__[bundle]) {\n // load the CSS files from the remote bundle\n const cssRE = /\\.s?css$/;\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {})\n .filter((id) => cssRE.test(id))\n .forEach((id) => {\n self.__remote_webpack_require__?.[bundle]?.(id);\n });\n\n Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {})\n .filter((path) => cssRE.test(path))\n .forEach((path) => {\n const id = self.__remote_webpack_module_map__?.[bundle]?.[path];\n if (id) {\n self.__remote_webpack_require__?.[bundle]?.(id);\n }\n });\n\n const elements = [];\n let node = nextCss.previousSibling;\n while (node && node !== nextCssEnd) {\n elements.push(node);\n node.remove();\n node = nextCss.previousSibling;\n }\n self.__remote_next_css__[bundle] = elements;\n }\n\n // if the styleContainer is provided, we need to move the styles to it\n if (styleContainer) {\n const elements = self.__remote_next_css__[bundle];\n elements.forEach((el) => {\n styleContainer.appendChild(el.cloneNode(true));\n });\n } else {\n // if no styleContainer is provided, we need to move the styles back to the head\n const elements = self.__remote_next_css__[bundle];\n elements.forEach((el) => {\n document.head.appendChild(el);\n });\n }\n\n // restore the original __NEXT_P reference\n delete self.__NEXT_P;\n self.__NEXT_P = __NEXT_P_ORIGINAL;\n\n // restore the original Next.js CSS loader\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.appendChild(nextCssOriginal);\n }\n\n nextCss.remove();\n nextCssEnd.remove();\n\n return { Component, App };\n }\n\n return { Component: null, App: null };\n}\n","// Webpack shared module patching\n// used in multiple remote component host types\n// multiple host types includes: HTML custom element for remote components and Next.js host application\n// we are using this shared function to patch a Webpack module map\n// to use shared modules between the host application and the remote component\n\nimport { logDebug, logWarn } from '../utils/logger';\n\nexport function applySharedModules(\n bundle: string,\n resolve: Record<string, unknown>,\n) {\n logDebug(\n 'SharedModules',\n `applySharedModules called for bundle: \"${bundle}\"`,\n );\n logDebug(\n 'SharedModules',\n `Shared modules to resolve: ${Object.keys(resolve)}`,\n );\n\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string) => unknown) & {\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n } & Record<string, string[]>;\n\n // if we have the bundle\n if (self.__remote_webpack_require__?.[bundle]) {\n const modulePaths = Object.keys(\n self.__remote_webpack_module_map__?.[bundle] ??\n self.__remote_webpack_require__[bundle].m ??\n {},\n );\n logDebug(\n 'SharedModules',\n `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`,\n );\n\n // patch all modules in the bundle to use the shared modules\n for (const [key, value] of Object.entries(resolve)) {\n let ids = modulePaths.filter((p) => p === key);\n if (ids.length === 0) {\n ids = modulePaths.filter((p) => p.includes(key));\n }\n\n if (ids.length === 0) {\n logDebug(\n 'SharedModules',\n `No matching module path found for shared module \"${key}\"`,\n );\n }\n\n for (let id of ids) {\n const webpackBundle = self.__remote_webpack_require__[bundle];\n if (webpackBundle.m) {\n // if we have a module map, we need to use the mapped id\n // this is required for production builds where the module ids are module id numbers\n if (self.__remote_webpack_module_map__?.[bundle]?.[id]) {\n const mappedId = `${self.__remote_webpack_module_map__[bundle][id]}`;\n logDebug(\n 'SharedModules',\n `Mapped module id: \"${id}\" -> \"${mappedId}\"`,\n );\n id = mappedId;\n }\n // create a mock module which exports the shared module\n webpackBundle.m[id] = (module) => {\n module.exports = value;\n };\n } else {\n logWarn(\n 'SharedModules',\n `webpackBundle.m is not available for bundle \"${bundle}\"`,\n );\n }\n }\n }\n } else {\n logWarn('SharedModules', `No webpack require found for bundle \"${bundle}\"`);\n logDebug(\n 'SharedModules',\n `Available bundles: ${Object.keys(self.__remote_webpack_require__ ?? {})}`,\n );\n }\n}\n","import { ReadableStream } from 'web-streams-polyfill';\n\n/**\n * Fixes RSC payload to make it compatible with React JSX development runtime\n */\nexport function fixPayload(payload: unknown): void {\n if (Array.isArray(payload)) {\n // if the current node is a React element, we need to fix the payload\n if (payload[0] === '$') {\n // fix the props (children or other React elements)\n fixPayload(payload[3]);\n if (payload.length === 4) {\n // add placeholder for the missing debug info\n payload.push(null, null, 1);\n }\n } else {\n // we are in an array, continue with visiting each item\n for (const item of payload) {\n fixPayload(item);\n }\n }\n } else if (typeof payload === 'object' && payload !== null) {\n // we are in an object, continue with visiting each property\n for (const key in payload) {\n fixPayload((payload as Record<string, unknown>)[key]);\n }\n }\n}\n\n/**\n * Processes RSC flight data and creates a ReadableStream\n */\nexport function createRSCStream(\n rscName: string,\n data: string[],\n): ReadableStream<Uint8Array> {\n return new ReadableStream({\n type: 'bytes',\n start(controller) {\n const encoder = new TextEncoder();\n const self = globalThis as typeof globalThis &\n Record<string, string[] | null>;\n\n // when the remote component RSC scripts are not found or loaded\n // we need to load the RSC flight data parsing the chunks\n if (data.length > 0) {\n data.forEach((chunk) => {\n const lines = chunk.split('\\n');\n for (const line of lines) {\n const match = /\\.push\\(\"(?<rsc>.*)\"\\);$/.exec(line);\n if (match?.groups?.rsc) {\n self[rscName] = self[rscName] ?? [];\n self[rscName].push(JSON.parse(`\"${match.groups.rsc}\"`) as string);\n }\n }\n });\n }\n\n // get the RSC flight data from the global scope\n // the RSC flight data is stored in an array\n // fallback to an empty RSC payload if the data is not found\n const allChunks = (self[rscName] ?? [`0:[null]\\n`]).join('');\n\n // clear the RSC flight data from the global scope\n self[rscName] = null;\n\n // process each line in the RSC flight data\n allChunks.split('\\n').forEach((chunk) => {\n if (chunk.length > 0) {\n // parse the chunk to get the id, prefix and payload\n const { before, id, prefix, payload } =\n /^(?<before>[^:]*?)?(?<id>[0-9a-zA-Z]+):(?<prefix>[A-Z])?(?<payload>\\[.*\\])/.exec(\n chunk,\n )?.groups ?? {};\n\n if (payload) {\n // parse the payload to a JSON object\n const jsonPayload = JSON.parse(payload) as unknown[];\n // fix the payload to make it compatible with React JSX development runtime\n fixPayload(jsonPayload);\n // reconstruct the chunk to a string\n const reconstruct = `${before ?? ''}${id}:${prefix ?? ''}${JSON.stringify(jsonPayload)}`;\n // encode the chunk to a byte buffer\n controller.enqueue(encoder.encode(`${reconstruct}\\n`));\n } else {\n // add empty line before closing the stream\n controller.enqueue(encoder.encode(`${chunk}\\n`));\n }\n } else {\n // add empty line before closing the stream\n controller.enqueue(encoder.encode(`${chunk}\\n`));\n }\n });\n // close the stream when all chunks are enqueued\n controller.close();\n },\n });\n}\n","export const RC_PROTECTED_REMOTE_FETCH_PATHNAME = '/rc-fetch-protected-remote';\n","import { RC_PROTECTED_REMOTE_FETCH_PATHNAME } from '#internal/shared/constants';\n\n/**\n * Generates a fallback URL that proxies the request through the host's protected remote fetch endpoint\n */\nexport function generateProtectedRcFallbackSrc(url: string): string {\n return `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${encodeURIComponent(url)}`;\n}\n","export const NEXT_BUNDLE_PATH_RE = /\\/_next\\/\\[.+\\](?:%20| )/;\n","import { RC_PROTECTED_REMOTE_FETCH_PATHNAME } from '../constants';\nimport { RemoteComponentsError } from '../error';\nimport { logError, logInfo, logWarn } from '../utils/logger';\nimport { generateProtectedRcFallbackSrc } from './protected-rc-fallback';\nimport { NEXT_BUNDLE_PATH_RE } from './webpack-patterns';\n\n/**\n * Loads external scripts for remote components\n */\nexport async function loadScripts(scripts: { src: string }[]): Promise<void> {\n await Promise.all(\n scripts.map((script) => {\n return new Promise<void>((resolve, reject) => {\n const newSrc = new URL(\n // remove the remote component bundle name identifier from the script src\n script.src.replace(NEXT_BUNDLE_PATH_RE, '/_next/'),\n location.origin,\n ).href;\n\n const loadScriptWithProtectedRcFallback = (\n src: string,\n isFallback = false,\n ) => {\n const newScript = document.createElement('script');\n newScript.onload = () => {\n if (isFallback) {\n logInfo(\n 'ScriptLoader',\n `Successfully loaded <script src=\"${newSrc}\"> using fallback.`,\n );\n }\n\n resolve();\n };\n newScript.onerror = () => {\n if (!isFallback) {\n const fallbackSrc = generateProtectedRcFallbackSrc(newSrc);\n\n logWarn(\n 'ScriptLoader',\n `Failed to load <script src=\"${newSrc}\"> for Remote Component. Trying fallback with ${RC_PROTECTED_REMOTE_FETCH_PATHNAME} (withRemoteComponentsHost)...`,\n );\n\n loadScriptWithProtectedRcFallback(fallbackSrc, true);\n } else {\n logError(\n 'ScriptLoader',\n `Failed to load fallback for <script src=\"${newSrc}\"> for Remote Component.`,\n );\n reject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${newSrc}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n }\n };\n newScript.src = src;\n newScript.async = true;\n document.head.appendChild(newScript);\n };\n\n loadScriptWithProtectedRcFallback(newSrc);\n });\n }),\n );\n}\n","export function escapeString(str: string) {\n return str.replace(/[^a-z0-9]/g, '_');\n}\n\nexport const attrToProp = {\n fetchpriority: 'fetchPriority',\n crossorigin: 'crossOrigin',\n imagesrcset: 'imageSrcSet',\n imagesizes: 'imageSizes',\n srcset: 'srcSet',\n} as Record<string, string>;\n","import { escapeString } from '../utils';\n\nexport const DEFAULT_ROUTE = '/';\n\nexport const RUNTIME_WEBPACK = 'webpack';\nexport const RUNTIME_TURBOPACK = 'turbopack';\nexport const RUNTIME_SCRIPT = 'script';\n\nexport const REMOTE_COMPONENT_REGEX =\n /(?<prefix>.*?)\\[(?<bundle>[^\\]]+)\\](?:%20| )(?<id>.+)/;\n\nexport function getBundleKey(bundle: string): string {\n return escapeString(bundle);\n}\n\nexport type Runtime =\n | typeof RUNTIME_WEBPACK\n | typeof RUNTIME_TURBOPACK\n | typeof RUNTIME_SCRIPT;\n","/**\n * Type guard to check if an error is an AbortError.\n * Handles cross-environment differences (Node.js, browsers, JSDOM).\n */\nexport function isAbortError(error: unknown): error is DOMException {\n if (error instanceof DOMException && error.name === 'AbortError') {\n return true;\n }\n\n // Handle Node.js native AbortError which may not be instanceof global DOMException\n if (\n error !== null &&\n typeof error === 'object' &&\n 'name' in error &&\n error.name === 'AbortError' &&\n 'message' in error &&\n typeof (error as { message: unknown }).message === 'string'\n ) {\n // Additional check: verify it has DOMException-like structure\n const e = error as { code?: unknown; constructor?: { name?: string } };\n return typeof e.code === 'number' || e.constructor?.name === 'DOMException';\n }\n\n return false;\n}\n","import { generateProtectedRcFallbackSrc } from '#internal/shared/client/protected-rc-fallback';\nimport { isAbortError } from '#internal/shared/utils/abort';\nimport { logError, logInfo, logWarn } from '#internal/shared/utils/logger';\n\n/**\n * When a vercel host preview fetches a vercel protected remote preview on the\n * client, the request will reject as it's not possible to authenticate for the\n * protected deployment in a client side fetch - cookies cannot be shared across\n * domains. To enable previews, this request is proxied via the host where the\n * process.env.VERCEL_AUTOMATION_BYPASS_SECRET will be added.\n *\n * @param url - The URL to fetch\n * @param init - Fetch init options (should include signal for abort support)\n */\nexport async function fetchWithProtectedRcFallback(\n url: URL | string,\n init?: RequestInit,\n): Promise<Response> {\n try {\n const res = await fetch(url, init);\n return res;\n } catch (error) {\n // Re-throw AbortError immediately - don't try fallback for cancelled requests\n if (isAbortError(error)) {\n throw error;\n }\n\n const parsedUrl = new URL(url);\n if (\n typeof document === 'object' &&\n typeof document.location === 'object' &&\n document.location.origin !== parsedUrl.origin\n ) {\n logWarn(\n 'FetchRemoteComponent',\n 'Request failed due to CORS, attempting to fetch it via the withRemoteComponentsHost proxy.',\n );\n // Pass signal to proxy fetch as well so it can be cancelled\n const proxiedRes = await fetch(\n generateProtectedRcFallbackSrc(parsedUrl.href),\n init?.signal ? { signal: init.signal } : undefined,\n );\n if (proxiedRes.status === 200) {\n logInfo(\n 'FetchRemoteComponent',\n `Successfully fetched ${parsedUrl.href} with fallback withRemoteComponentsHost proxy`,\n );\n return proxiedRes;\n } else {\n logError(\n 'FetchRemoteComponent',\n `Could not proxy remote: [response status ${\n proxiedRes.status\n }] ${await proxiedRes.text()}`,\n );\n }\n }\n\n throw error;\n }\n}\n","/**\n * Regex patterns for parsing Turbopack's minified and development code.\n *\n * Turbopack outputs different variable names in dev vs production builds:\n * - Development: __turbopack_context__, parentImport, chunk, self\n * - Minified: e, t, etc.\n *\n * These patterns use named capture groups and backreferences to ensure\n * consistency within a single match (e.g., if ctx is 'e', all uses of ctx must be 'e').\n */\n\n/**\n * Matches: self.TURBOPACK_REMOTE_SHARED or e.TURBOPACK_REMOTE_SHARED\n *\n * @example\n * // Development:\n * \"self.TURBOPACK_REMOTE_SHARED=await __turbopack_context__.A(984803)\"\n *\n * // Minified:\n * \"e.TURBOPACK_REMOTE_SHARED=await e.A(984803)\"\n */\nexport const REMOTE_SHARED_MARKER_RE =\n /(?:self|[a-z])\\.TURBOPACK_REMOTE_SHARED/;\n\n/**\n * Extracts the module ID from a TURBOPACK_REMOTE_SHARED assignment.\n *\n * Captures:\n * - `sharedModuleId`: The numeric module ID\n *\n * @example\n * // Development:\n * \"self.TURBOPACK_REMOTE_SHARED=await __turbopack_context__.A(984803)\"\n * // -> { sharedModuleId: \"984803\" }\n *\n * // Minified:\n * \"e.TURBOPACK_REMOTE_SHARED=await e.A(123456)\"\n * // -> { sharedModuleId: \"123456\" }\n */\nexport const REMOTE_SHARED_ASSIGNMENT_RE =\n /\\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|e)\\.A\\((?<sharedModuleId>[0-9]+)\\)/;\n\n/**\n * Matches async module loader calls: ctx.A(moduleId)\n *\n * Captures:\n * - `asyncSharedModuleId`: The numeric module ID being loaded asynchronously\n *\n * @example\n * // Development:\n * \"() => __turbopack_context__.A(460400)\"\n * // -> { asyncSharedModuleId: \"460400\" }\n *\n * // Minified:\n * \"() => e.A(460400)\"\n * // -> { asyncSharedModuleId: \"460400\" }\n */\nexport const ASYNC_MODULE_LOADER_RE =\n /(?:__turbopack_context__|e)\\.A\\((?<asyncSharedModuleId>[0-9]+)\\)/;\n\n/**\n * Matches async module with Promise.resolve pattern.\n * Used for modules that can be loaded immediately without chunk loading.\n *\n * Captures:\n * - `ctx`: The context variable (__turbopack_context__ or e)\n * - `inner`: The inner callback variable (parentImport or e)\n * - `sharedModuleId`: The numeric module ID\n *\n * @example\n * // Development:\n * \"__turbopack_context__=>{__turbopack_context__.v(parentImport=>Promise.resolve().then(()=>parentImport(633334)))}\"\n * // -> { ctx: \"__turbopack_context__\", inner: \"parentImport\", sharedModuleId: \"633334\" }\n *\n * // Minified:\n * \"e=>{e.v(e=>Promise.resolve().then(()=>e(633334)))}\"\n * // -> { ctx: \"e\", inner: \"e\", sharedModuleId: \"633334\" }\n */\nexport const ASYNC_MODULE_RESOLVE_RE =\n /(?<ctx>__turbopack_context__|e)=>\\{\\k<ctx>\\.v\\((?<inner>parentImport|e)=>Promise\\.resolve\\(\\)\\.then\\(\\(\\)=>\\k<inner>\\((?<sharedModuleId>[0-9]+)\\)\\)\\)\\}/;\n\n/**\n * Matches async module with Promise.all pattern.\n * Used for modules that require loading additional chunks first.\n *\n * Captures:\n * - `ctx`: The context variable (__turbopack_context__ or e)\n * - `vCb`: The callback passed to .v() (parentImport or t)\n * - `mapCb`: The callback passed to .map() (chunk or t)\n * - `sharedModuleId`: The numeric module ID\n *\n * @example\n * // Development:\n * \"__turbopack_context__=>{__turbopack_context__.v(parentImport=>Promise.all([\\\"static/chunks/82dcf883b4ba22f0.js\\\"].map(chunk=>__turbopack_context__.l(chunk))).then(()=>parentImport(657407)))}\"\n * // -> { ctx: \"__turbopack_context__\", vCb: \"parentImport\", mapCb: \"chunk\", sharedModuleId: \"657407\" }\n *\n * // Minified:\n * \"e=>{e.v(t=>Promise.all([\\\"chunk.js\\\"].map(t=>e.l(t))).then(()=>t(633334)))}\"\n * // -> { ctx: \"e\", vCb: \"t\", mapCb: \"t\", sharedModuleId: \"633334\" }\n */\nexport const ASYNC_MODULE_ALL_RE =\n /(?<ctx>__turbopack_context__|e)=>\\{\\k<ctx>\\.v\\((?<vCb>parentImport|t)=>Promise\\.all\\(\\[\"[^\"]+\"\\]\\.map\\((?<mapCb>chunk|t)=>\\k<ctx>\\.l\\(\\k<mapCb>\\)\\)\\)\\.then\\(\\(\\)=>\\k<vCb>\\((?<sharedModuleId>[0-9]+)\\)\\)\\)\\}/;\n\n/**\n * Detects Turbopack runtime global usage in a chunk.\n *\n * Matches either dot-notation or bracket-notation access off `globalThis` or `self`:\n * - globalThis.TURBOPACK / self.TURBOPACK\n * - globalThis[\"TURBOPACK\"] / self['TURBOPACK'] (whitespace tolerated)\n */\nexport const TURBOPACK_GLOBAL_RE =\n /(?:globalThis|self)\\s*(?:\\.TURBOPACK|\\[\\s*[\"']TURBOPACK[\"']\\s*\\])/;\n","import { RemoteComponentsError } from '../error';\nimport { logDebug } from '../utils/logger';\nimport {\n getBundleKey,\n REMOTE_COMPONENT_REGEX,\n RUNTIME_WEBPACK,\n type Runtime,\n} from './const';\nimport { fetchWithProtectedRcFallback } from './fetch-with-protected-rc-fallback';\nimport { TURBOPACK_GLOBAL_RE } from './turbopack-patterns';\nimport type { GlobalScope } from './types';\n\n/**\n * Creates chunk loader function for webpack runtime.\n * This function is responsible for loading JavaScript chunks from remote applications\n * and transforming Turbopack-specific code to work in the host environment.\n */\nexport function createChunkLoader(\n runtime: Runtime,\n): (chunkId: string, scriptBundle?: string) => Promise<unknown> | undefined {\n return function __turbopack_chunk_load__(\n chunkId: string,\n scriptBundle?: string,\n ) {\n logDebug('ChunkLoader', `Loading chunk: \"${chunkId}\"`);\n const self = globalThis as GlobalScope;\n const {\n bundle,\n id: path,\n prefix,\n } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {\n bundle: scriptBundle ?? '',\n id: chunkId,\n };\n logDebug(\n 'ChunkLoader',\n `Parsed chunk - bundle: \"${bundle}\", path: \"${path}\", prefix: \"${prefix}\"`,\n );\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : runtime;\n logDebug('ChunkLoader', `Remote runtime: \"${remoteRuntime}\"`);\n if (remoteRuntime === RUNTIME_WEBPACK) {\n logDebug('ChunkLoader', 'Skipping chunk load - webpack runtime detected');\n return Promise.resolve(undefined);\n }\n\n const url = new URL(\n path\n ? `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n )\n : '/',\n self.__remote_bundle_url__?.[bundle ?? 'default'] ??\n new URL(location.origin),\n ).href;\n if (url.endsWith('.css')) {\n logDebug('ChunkLoader', `Skipping CSS file: \"${url}\"`);\n return;\n }\n\n if (!self.__remote_components_turbopack_chunk_loader_promise__) {\n self.__remote_components_turbopack_chunk_loader_promise__ = {};\n }\n if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {\n logDebug('ChunkLoader', `Returning cached promise for: \"${url}\"`);\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n }\n\n logDebug('ChunkLoader', `Fetching chunk from: \"${url}\"`);\n self.__remote_components_turbopack_chunk_loader_promise__[url] =\n new Promise((resolve, reject) => {\n fetchWithProtectedRcFallback(url)\n .then((res) => res.text())\n .then((code) => {\n // Turbopack runtime uses either dot-notation or bracket-notation globals.\n const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);\n if (hasTurbopack) {\n return handleTurbopackChunk(code, bundle ?? '', url);\n }\n logDebug(\n 'ChunkLoader',\n `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: \"${url}\"`,\n );\n logDebug(\n 'ChunkLoader',\n `First 500 chars of chunk: ${code.slice(0, 500)}`,\n );\n })\n .then(resolve)\n .catch(reject);\n });\n\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n };\n}\n\n/**\n * Handles Turbopack chunk loading by transforming the chunk code to isolate\n * global variables per bundle and dynamically loading the transformed script.\n */\nasync function handleTurbopackChunk(\n code: string,\n bundle: string,\n url: string,\n): Promise<void> {\n logDebug(\n 'ChunkLoader',\n `Handling Turbopack chunk - bundle: \"${bundle}\", url: \"${url}\"`,\n );\n // skip this chunk as it is not needed for remote components\n if (/importScripts\\(\\.\\.\\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {\n logDebug('ChunkLoader', `Skipping worker chunk: \"${url}\"`);\n // remove preload links for this chunk\n const preloadLinks = document.querySelectorAll(\n `link[rel=\"preload\"][href=\"${new URL(url).pathname}\"]`,\n );\n preloadLinks.forEach((preloadLink) => preloadLink.remove());\n return;\n }\n\n const self = globalThis as GlobalScope;\n const bundleKey = getBundleKey(bundle);\n logDebug('ChunkLoader', `Bundle key: \"${bundleKey}\"`);\n\n // replace global variables with bundle-specific ones to prevent collisions\n // between multiple remote component bundles\n const transformedCode = code\n // Turbopack runtime can reference TURBOPACK via bracket-notation (common in newer Next.js)\n // e.g. globalThis[\"TURBOPACK\"] / self['TURBOPACK']\n .replace(\n /globalThis\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `globalThis[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(\n /self\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `self[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(/globalThis\\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`)\n .replace(/self\\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`)\n .replace(\n /TURBOPACK_WORKER_LOCATION/g,\n `TURBOPACK_WORKER_LOCATION_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_NEXT_CHUNK_URLS/g,\n `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,\n `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`,\n )\n .replace(/__next_require__/g, `__${bundleKey}_next_require__`)\n .replace(\n /\\/\\/# sourceMappingURL=(?<name>.+)(?<optional>\\._)?\\.js\\.map/g,\n `//# sourceMappingURL=${\n new URL(\n '.',\n new URL(\n url,\n self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin),\n ),\n ).href\n }$1$2.js.map`,\n );\n\n // Initialize TURBOPACK bundle with push interceptor for Next.js 16.2.0-canary\n // Use webpack-style chunk loading pattern\n if (!self[`TURBOPACK_${bundleKey}`]) {\n const chunkData: unknown[][] = [];\n const turbopackObject = {\n push: (item: unknown) => {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? 'array' : typeof item}`,\n );\n if (Array.isArray(item)) {\n chunkData.push(item);\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`,\n );\n } else {\n chunkData.push([item]);\n }\n return chunkData.length;\n },\n // Store chunks for later access\n __chunks__: chunkData,\n };\n self[`TURBOPACK_${bundleKey}`] = turbopackObject as unknown as Record<\n string,\n unknown\n >;\n }\n\n // load the script dynamically using a Blob URL\n logDebug('ChunkLoader', `Creating blob script for: \"${url}\"`);\n await new Promise<void>((scriptResolve, scriptReject) => {\n const blob = new Blob([transformedCode], {\n type: 'application/javascript; charset=UTF-8',\n });\n const scriptUrl = URL.createObjectURL(blob);\n const script = document.createElement('script');\n script.setAttribute('data-turbopack-src', url);\n script.src = scriptUrl;\n script.async = true;\n script.onload = () => {\n URL.revokeObjectURL(scriptUrl);\n logDebug(\n 'ChunkLoader',\n `Script loaded successfully for bundle \"${bundle}\"`,\n );\n const turbopackBundle = self[`TURBOPACK_${bundleKey}`];\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${\n turbopackBundle\n ? Object.keys(turbopackBundle as object)\n .slice(0, 10)\n .join(', ')\n : 'none'\n }`,\n );\n if (turbopackBundle && typeof turbopackBundle === 'object') {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle as object).length}`,\n );\n }\n scriptResolve(undefined);\n script.remove();\n };\n script.onerror = () => {\n URL.revokeObjectURL(scriptUrl);\n scriptReject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${script.src}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n script.remove();\n };\n document.head.appendChild(script);\n });\n\n // process any additional chunks that were registered during script execution\n const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`] as\n | { chunks: string[] }[]\n | undefined;\n logDebug(\n 'ChunkLoader',\n `Processing chunk lists for bundle \"${bundle}\": ${chunkLists?.length ?? 0} lists`,\n );\n const loadChunkLists = [] as (Promise<unknown> | undefined)[];\n while (chunkLists?.length) {\n const { chunks } = chunkLists.shift() ?? { chunks: [] };\n if (chunks.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Loading ${chunks.length} additional chunks for bundle \"${bundle}\": [${chunks.join(', ')}]`,\n );\n chunks.forEach((id: string) => {\n const chunkLoadResult = self.__webpack_chunk_load__?.(\n `[${bundle}] ${url.slice(0, url.indexOf('/_next'))}/_next/${id}`,\n );\n if (chunkLoadResult) {\n loadChunkLists.push(chunkLoadResult);\n }\n });\n }\n }\n if (loadChunkLists.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Waiting for ${loadChunkLists.length} additional chunks to load`,\n );\n await Promise.all(loadChunkLists);\n }\n}\n","import { logError } from '../utils/logger';\nimport { getBundleKey } from './const';\nimport type { GlobalScope } from './types';\n\n/**\n * Function signature for Turbopack module initializers.\n * These functions are generated by Turbopack and initialize module exports.\n */\nexport type TurbopackModuleInit = (\n turbopackContext: TurbopackContext,\n module: { exports: Record<string, unknown> },\n exports: Record<string, unknown>,\n) => void;\n\n/**\n * The context object passed to Turbopack module initializers.\n * This provides the runtime API that modules use for imports, exports, and HMR.\n */\ninterface TurbopackContext {\n /** HMR (Hot Module Replacement) - not implemented for remote components */\n k: {\n register(): void;\n registerExports(): void;\n signature(): (fn: unknown) => unknown;\n };\n /** ESM exports setup */\n s: (\n bindings:\n | Record<string, () => unknown>\n | [...([string, () => unknown] | [string, number, () => unknown])],\n esmId?: string | number,\n ) => void;\n /** Import module */\n i: (importId: string | number) => Record<string, unknown> | undefined;\n /** Require module */\n r: (requireId: string) => unknown;\n /** Value exports */\n v: (value: unknown) => void;\n /** Async module initializer */\n a: (\n mod: (\n handleDeps: unknown,\n setResult: (value: unknown) => void,\n ) => Promise<void>,\n ) => Promise<void>;\n /** Async module loader */\n A: (Aid: string) => Promise<unknown>;\n /**\n * Dynamic import tracking. Called in production chunks after ctx.s() to\n * register async/dynamic module relationships. e.g. t.j(importedMod, 58790)\n */\n j: (module: unknown, esmId?: string | number) => void;\n /** Chunk loader */\n l: (url: string) => Promise<unknown> | undefined;\n /** Global object for this bundle */\n g: unknown;\n /** Module object */\n m: { exports: Record<string, unknown> };\n /** Exports object */\n e: Record<string, unknown>;\n}\n\n/**\n * Turbopack pushes chunks as flat arrays in one of two shapes:\n *\n * Module chunk (common case):\n * [scriptElement, id1, factory1, id2, factory2, ...]\n * - index 0: the script Element (document.currentScript) or undefined\n * - alternating pairs: numeric ID (prod) or path string (dev), then factory function\n *\n * Runtime manifest (bootstrapper only, no module factories):\n * [scriptElement, { otherChunks: [...], runtimeModuleIds: [...] }]\n *\n * Newer Next.js canary versions may also store modules as a plain object\n * { [moduleId]: factory } rather than as an array.\n */\ntype BundleModules =\n | (\n | Element\n | string\n | number\n | TurbopackModuleInit\n | Record<string, TurbopackModuleInit>\n | null\n | undefined\n )[]\n | Record<string, TurbopackModuleInit>\n | undefined;\n\n/**\n * Handles Turbopack module resolution and execution.\n * This function finds a module in the Turbopack bundle, executes its initializer,\n * and returns the module exports.\n *\n * The Turbopack bundle stores modules as arrays where each entry is either:\n * - A module ID (string or number)\n * - A module initializer function\n *\n * This function provides a custom runtime context that implements the Turbopack\n * module system API, enabling remote modules to resolve their dependencies.\n */\nexport function handleTurbopackModule(\n bundle: string,\n moduleId: string,\n id: string,\n): unknown {\n const self = globalThis as GlobalScope;\n const bundleKey = getBundleKey(bundle);\n const raw = self[`TURBOPACK_${bundleKey}`];\n\n // Normalize the bundle global to a flat entry list. The chunk-loader push\n // interceptor stores modules as { __chunks__: [[Element, id, fn, ...], ...] }.\n let modules: BundleModules;\n if (raw && typeof raw === 'object' && '__chunks__' in raw) {\n modules = (\n raw as { __chunks__: unknown[][] }\n ).__chunks__.flat() as unknown as BundleModules;\n } else if (Array.isArray(raw)) {\n modules = (raw as unknown[]).flat() as unknown as BundleModules;\n } else {\n modules = raw as BundleModules;\n }\n\n // prepare module cache to handle circular dependencies\n if (!self.__remote_components_turbopack_modules__) {\n self.__remote_components_turbopack_modules__ = {};\n }\n if (!self.__remote_components_turbopack_modules__[bundle]) {\n self.__remote_components_turbopack_modules__[bundle] = {};\n }\n // return cached module if already loaded (CRITICAL: check this FIRST)\n if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {\n return self.__remote_components_turbopack_modules__[bundle][moduleId];\n }\n\n // Log only if bundle is completely missing (critical error)\n if (!modules) {\n logError('TurbopackModule', `TURBOPACK_${bundleKey} is undefined`);\n }\n\n const moduleInit = findModuleInit(modules, moduleId);\n const exports = {} as Record<string, unknown>;\n const moduleExports = { exports };\n\n if (typeof moduleInit !== 'function') {\n throw new Error(\n `Module ${id} not found in bundle ${bundle} with id ${moduleId}`,\n );\n }\n\n // store a reference to the module exports in the cache before execution\n // to handle circular dependencies\n self.__remote_components_turbopack_modules__[bundle][moduleId] =\n moduleExports.exports;\n\n // prepare global object for the bundle\n if (!self.__remote_components_turbopack_global__) {\n self.__remote_components_turbopack_global__ = {};\n }\n if (!self.__remote_components_turbopack_global__[bundle]) {\n self.__remote_components_turbopack_global__[bundle] = {};\n }\n\n // execute the module initializer with our custom Turbopack context\n moduleInit(\n createTurbopackContext(\n bundle,\n exports,\n moduleExports,\n modules,\n moduleInit,\n id,\n self,\n ),\n moduleExports,\n exports,\n );\n\n // update the cache with the final exports (may have changed during execution)\n if (\n self.__remote_components_turbopack_modules__[bundle][moduleId] !==\n moduleExports.exports\n ) {\n self.__remote_components_turbopack_modules__[bundle][moduleId] =\n moduleExports.exports;\n }\n\n return moduleExports.exports;\n}\n\n/**\n * Finds the module initializer function in the Turbopack bundle.\n */\nfunction findModuleInit(\n modules: BundleModules,\n\n moduleId: string,\n): TurbopackModuleInit | undefined {\n if (!modules || typeof modules !== 'object') return;\n\n // Object format: { [id]: factory } (newer Next.js canary builds)\n if (!Array.isArray(modules)) {\n const key =\n moduleId in modules\n ? moduleId\n : Object.keys(modules).find((k) => k.startsWith(moduleId));\n return key !== undefined ? modules[key] : undefined;\n }\n\n const flat = modules.flat();\n\n // Two-pass ID search: exact match first to avoid prefix false positives.\n // The startsWith fallback handles dev-mode IDs with appended qualifiers\n // such as \"[project]/path.tsx [app-client] (ecmascript, async loader)\".\n let idx = flat.findIndex((e) => String(e) === String(moduleId));\n if (idx < 0) {\n idx = flat.findIndex(\n (e) => typeof e === 'string' && e.startsWith(moduleId),\n );\n }\n if (idx >= 0) {\n // Factory is the first function entry that follows the module ID\n return flat\n .slice(idx + 1)\n .find((e): e is TurbopackModuleInit => typeof e === 'function');\n }\n\n // Embedded object map: entries of the form { [moduleId]: factory }\n return flat.find((e): e is Record<string, TurbopackModuleInit> =>\n Boolean(e && typeof e === 'object' && moduleId in (e as object)),\n )?.[moduleId];\n}\n\n/**\n * Creates the Turbopack context object that provides the runtime API for modules.\n */\nfunction createTurbopackContext(\n bundle: string,\n exports: Record<string, unknown>,\n moduleExports: { exports: Record<string, unknown> },\n modules: BundleModules,\n moduleInit: TurbopackModuleInit,\n id: string,\n self: GlobalScope,\n): TurbopackContext {\n return {\n // HMR not implemented for Remote Components\n k: {\n register() {\n // omit\n },\n registerExports() {\n // omit\n },\n signature() {\n return (fn: unknown) => fn;\n },\n },\n\n // ESM exports setup\n s(\n bindings:\n | Record<string, () => unknown>\n | [...([string, () => unknown] | [string, number, () => unknown])],\n esmId?: string | number,\n ) {\n let mod = exports;\n if (typeof esmId === 'string' || typeof esmId === 'number') {\n if (!self.__remote_components_turbopack_modules__) {\n self.__remote_components_turbopack_modules__ = {};\n }\n if (!self.__remote_components_turbopack_modules__[bundle]) {\n self.__remote_components_turbopack_modules__[bundle] = {};\n }\n if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {\n self.__remote_components_turbopack_modules__[bundle][esmId] =\n {} as Record<string, unknown>;\n }\n mod = self.__remote_components_turbopack_modules__[bundle][\n esmId\n ] as Record<string, unknown>;\n }\n\n Object.defineProperty(mod, '__esModule', { value: true });\n if (Array.isArray(bindings)) {\n let i = 0;\n while (i < bindings.length) {\n const propName = bindings[i++] as string;\n const tagOrFunc = bindings[i++];\n if (typeof tagOrFunc === 'number') {\n Object.defineProperty(mod, propName, {\n value: bindings[i++],\n enumerable: true,\n writable: false,\n });\n } else {\n const getterFn = tagOrFunc as () => unknown;\n if (typeof bindings[i] === 'function') {\n const setterFn = bindings[i++] as (v: unknown) => unknown;\n Object.defineProperty(mod, propName, {\n get: getterFn,\n set: setterFn,\n enumerable: true,\n });\n } else {\n Object.defineProperty(mod, propName, {\n get: getterFn,\n enumerable: true,\n });\n }\n }\n }\n }\n },\n\n // import\n i(importId: string | number) {\n let mod: Record<string, unknown> | undefined;\n if (typeof importId === 'string') {\n // parse export syntax if present (e.g., \"module <export foo as bar>\")\n const { exportSource, exportName } =\n /\\s+<export (?<exportSource>.*?) as (?<exportName>.*?)>$/.exec(\n importId,\n )?.groups ?? {};\n const normalizedId = importId.replace(\n /\\s+<export(?<specifier>.*)>$/,\n '',\n );\n mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`) as\n | Record<string, unknown>\n | undefined;\n // map the requested export to the module exports\n if (\n mod &&\n exportSource &&\n exportName &&\n (exportSource === '*' || typeof mod[exportSource] !== 'undefined') &&\n typeof mod[exportName] === 'undefined'\n ) {\n if (exportSource === '*') {\n mod[exportName] = mod;\n } else {\n mod[exportName] = mod[exportSource];\n }\n }\n } else {\n mod = self.__webpack_require__?.(`[${bundle}] ${importId}`) as\n | Record<string, unknown>\n | undefined;\n }\n\n if (typeof mod !== 'object' || mod === null) {\n mod = { default: mod };\n } else if (!('default' in mod) && mod.toString() !== '[object Module]') {\n try {\n mod.default = mod;\n } catch {\n // ignore if mod is not extensible\n }\n }\n return mod;\n },\n\n // require\n r(requireId: string) {\n return self.__webpack_require__?.(`[${bundle}] ${requireId}`);\n },\n\n // value exports\n v(value: unknown) {\n if (typeof value === 'function') {\n exports.default = value((vid: string | number) => {\n return self.__webpack_require__?.(`[${bundle}] ${vid}`);\n });\n } else {\n moduleExports.exports = value as Record<string, unknown>;\n }\n },\n\n // async module initializer\n async a(\n mod: (\n handleDeps: unknown,\n setResult: (value: unknown) => void,\n ) => Promise<void>,\n ) {\n let result;\n await mod(\n () => {\n // not implemented\n },\n (value) => (result = value),\n );\n exports.default = result;\n },\n\n // async module loader\n async A(Aid: string) {\n const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`) as {\n default: (\n parentImport: (parentId: string) => unknown,\n ) => Promise<unknown>;\n };\n return mod.default((parentId: string) =>\n self.__webpack_require__?.(`[${bundle}] ${parentId}`),\n );\n },\n\n // dynamic import tracking — no-op for remote components\n j() {\n // omit\n },\n\n // chunk loader\n l(url: string) {\n // find the script tag that loaded the current module to determine base URL\n const flatModules = Array.isArray(modules) ? modules : [];\n const moduleInitIndex = flatModules.indexOf(moduleInit);\n if (moduleInitIndex !== -1) {\n const scriptIndex = flatModules\n .slice(0, moduleInitIndex)\n .findLastIndex((bundleEntry) => bundleEntry instanceof Element);\n if (scriptIndex !== -1) {\n const script = flatModules[scriptIndex] as HTMLScriptElement;\n const scriptSrc = script.getAttribute('data-turbopack-src') || '';\n const nextIndex = scriptSrc.indexOf('/_next');\n const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : '';\n const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;\n return self.__webpack_chunk_load__?.(bundleUrl, bundle);\n }\n }\n throw new Error(\n `Failed to load Turbopack chunk \"${url}\" for module \"${id}\". Check the URL is correct.`,\n );\n },\n\n // global object for this bundle\n g: self.__remote_components_turbopack_global__?.[bundle],\n m: moduleExports,\n e: exports,\n };\n}\n","import { logError } from '../utils/logger';\nimport { getBundleKey } from './const';\nimport { handleTurbopackModule } from './turbopack-module';\nimport {\n ASYNC_MODULE_ALL_RE,\n ASYNC_MODULE_LOADER_RE,\n ASYNC_MODULE_RESOLVE_RE,\n REMOTE_SHARED_ASSIGNMENT_RE,\n REMOTE_SHARED_MARKER_RE,\n} from './turbopack-patterns';\nimport type { GlobalScope } from './types';\n\n/**\n * Initializes shared modules between the host application and remote components.\n * This enables sharing of common dependencies like React to avoid duplicate instances.\n *\n * The function works by:\n * 1. Looking for a shared module initializer in the Turbopack bundle\n * 2. Extracting module IDs from the initializer\n * 3. Loading the corresponding host modules and mapping them to the remote's expected IDs\n */\nexport async function initializeSharedModules(\n bundle: string,\n hostShared: Record<string, (bundle?: string) => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n // biome-ignore lint/suspicious/noConfusingVoidType: Runtime is undefined but in TS land service it is void\n): Promise<void[]> {\n const self = globalThis as GlobalScope & {\n __next_f?: unknown[];\n };\n self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};\n\n if (!self.__remote_shared_modules__[bundle]) {\n self.__remote_shared_modules__[bundle] = {};\n }\n\n // prepare to load shared module initializers from the Turbopack bundle\n const bundleKey = getBundleKey(bundle);\n let modules = self[`TURBOPACK_${bundleKey}`] as\n | [unknown, Record<string, unknown>][]\n | Record<string, unknown>\n | undefined;\n\n // Check for new push-based format with __chunks__\n if (modules && typeof modules === 'object' && '__chunks__' in modules) {\n const chunks = (modules as { __chunks__: unknown[][] }).__chunks__;\n // Flatten chunks into module array format\n modules = chunks.flat() as [unknown, Record<string, unknown>][];\n }\n let sharedModuleInitializer: Promise<{\n shared: Record<string, string | (() => Promise<unknown>)>;\n }> | null = null;\n\n // find the shared module initializer in the Turbopack bundle\n if (modules) {\n // Handle both array and object formats for modules\n const allModules = Array.isArray(modules)\n ? modules.flat()\n : Object.entries(modules).flat();\n // find the shared module initializer module id by looking for\n // a function that contains the TURBOPACK_REMOTE_SHARED pattern\n const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {\n if (typeof idOrFunc !== 'function') {\n return false;\n }\n const funcCode = idOrFunc.toString();\n return REMOTE_SHARED_MARKER_RE.test(funcCode);\n });\n\n // if found, extract the shared module initializer\n // first element in the array is always the source script element\n if (sharedModuleInitializerIndex > 0) {\n const sharedModuleInitializerCode = (\n allModules[sharedModuleInitializerIndex] as () => unknown\n ).toString();\n const sharedModuleInitializerId = allModules[\n sharedModuleInitializerIndex - 1\n ] as string | number;\n // extract the shared module id from the function code\n const { sharedModuleId } =\n REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ??\n {};\n // load the shared module initializer using the extracted module id\n if (sharedModuleId) {\n const { default: sharedModuleInitializerInstance } =\n handleTurbopackModule(\n bundle,\n sharedModuleId,\n `[${bundle}] ${sharedModuleInitializerId}`,\n ) as {\n default: Promise<{\n shared: Record<string, string | (() => Promise<unknown>)>;\n }>;\n };\n sharedModuleInitializer = sharedModuleInitializerInstance;\n }\n }\n\n // if we have a shared module initializer, load the shared modules from the host application\n if (sharedModuleInitializer) {\n const { shared } = await sharedModuleInitializer;\n // map shared module ids to their initializer functions\n const sharedModuleIds = extractSharedModuleIds(\n shared,\n bundleKey,\n self as GlobalScope,\n );\n\n // load shared modules from the host application\n return Promise.all(\n Object.entries(sharedModuleIds).map(async ([id, module]) => {\n if (self.__remote_shared_modules__?.[bundle]) {\n if (hostShared[module]) {\n self.__remote_shared_modules__[bundle][id] =\n await hostShared[module](bundle);\n } else {\n logError(\n 'SharedModules',\n `Host shared module \"${module}\" not found for ID ${id}`,\n );\n }\n }\n }),\n );\n }\n }\n\n // fallback: ensure that the shared modules are initialized using remoteShared mapping\n return Promise.all(\n Object.entries(remoteShared).map(async ([id, module]) => {\n if (self.__remote_shared_modules__?.[bundle]) {\n if (hostShared[module]) {\n const normalizedId = id.replace('[app-ssr]', '[app-client]');\n self.__remote_shared_modules__[bundle][normalizedId] =\n await hostShared[module](bundle);\n } else {\n logError(\n 'SharedModules',\n `Shared module \"${module}\" not found for \"${bundle}\"`,\n );\n }\n }\n }),\n );\n}\n\n/**\n * Extracts shared module IDs from the shared module initializer functions.\n * This parses the minified Turbopack code to find the module ID mappings.\n */\nfunction extractSharedModuleIds(\n shared: Record<string, string | (() => Promise<unknown>)>,\n bundleKey: string,\n self: GlobalScope,\n): Record<string, string> {\n return Object.entries(shared)\n .filter(([, value]) => typeof value === 'function')\n .reduce<Record<string, string>>((acc, [key, value]) => {\n const { asyncSharedModuleId } =\n ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};\n\n if (asyncSharedModuleId) {\n const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);\n\n let asyncSharedModule;\n let turbopackModules = self[`TURBOPACK_${bundleKey}`] as\n | unknown[]\n | Record<string, unknown>\n | undefined;\n\n // Check for new push-based format with __chunks__\n if (\n turbopackModules &&\n typeof turbopackModules === 'object' &&\n '__chunks__' in turbopackModules\n ) {\n const chunks = (turbopackModules as { __chunks__: unknown[][] })\n .__chunks__;\n turbopackModules = chunks.flat() as unknown[];\n }\n\n const newAllModules = Array.isArray(turbopackModules)\n ? turbopackModules.flat()\n : turbopackModules\n ? Object.entries(turbopackModules).flatMap(([key, value]) => [\n key,\n value,\n ])\n : [];\n const asyncSharedModuleIdIndex = newAllModules.indexOf(\n asyncSharedModuleIdNumber,\n );\n if (\n asyncSharedModuleIdIndex !== -1 &&\n typeof newAllModules[asyncSharedModuleIdIndex + 1] === 'function'\n ) {\n asyncSharedModule = newAllModules[\n asyncSharedModuleIdIndex + 1\n ] as () => unknown;\n }\n if (asyncSharedModule) {\n const asyncSharedModuleCode = asyncSharedModule.toString();\n // Try both Promise.resolve and Promise.all patterns\n const { sharedModuleId } =\n ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ??\n ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ??\n {};\n // map the shared module id to the actual module name\n acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(\n '__remote_shared_module_',\n '',\n );\n }\n }\n return acc;\n }, {});\n}\n\n/**\n * Returns a shared module for the given bundle and module ID.\n * Shared modules are common dependencies like React that are provided by the host.\n */\nexport function getSharedModule(bundle: string, id: string | number): unknown {\n const self = globalThis as {\n __remote_shared_modules__?: Record<string, Record<string, unknown>>;\n };\n\n for (const [key, value] of Object.entries(\n self.__remote_shared_modules__?.[bundle] ?? {},\n )) {\n if (\n typeof value !== 'undefined' &&\n ((typeof id === 'string' && id.includes(key)) || id === key)\n ) {\n return value;\n }\n }\n return null;\n}\n","import { RemoteComponentsError } from '../error';\nimport { logDebug, logWarn } from '../utils/logger';\nimport { createChunkLoader } from './chunk-loader';\nimport {\n REMOTE_COMPONENT_REGEX,\n RUNTIME_TURBOPACK,\n RUNTIME_WEBPACK,\n type Runtime,\n} from './const';\nimport { getSharedModule, initializeSharedModules } from './shared-modules';\nimport { handleTurbopackModule } from './turbopack-module';\nimport type { GlobalScope } from './types';\n\n/**\n * Sets up webpack runtime environment for remote components.\n * This function initializes the global webpack require and chunk loading functions\n * to support loading and executing remote component bundles.\n *\n * @param runtime - The bundler runtime type ('webpack' or 'turbopack')\n * @param scripts - Initial script chunks to load for Turbopack runtime\n * @param url - Base URL for the remote component bundle\n * @param bundle - Bundle identifier (defaults to 'default')\n * @param shared - Host-provided shared modules (e.g., React)\n * @param remoteShared - Mapping of remote module IDs to shared module names\n */\nexport async function setupWebpackRuntime(\n runtime: Runtime,\n scripts: { src: string | null }[] = [],\n url: URL = new URL(location.href),\n bundle?: string,\n shared: Record<string, () => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n): Promise<void> {\n const self = globalThis as GlobalScope;\n\n if (!self.__remote_bundle_url__) {\n self.__remote_bundle_url__ = {};\n }\n self.__remote_bundle_url__[bundle ?? 'default'] = url;\n self.__webpack_get_script_filename__ = () => null;\n\n if (\n typeof self.__webpack_require__ !== 'function' ||\n self.__webpack_require_type__ !== 'turbopack'\n ) {\n // preserve original webpack functions for fallback\n if (\n !self.__original_webpack_require__ &&\n !self.__original_webpack_chunk_load__\n ) {\n self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;\n self.__original_webpack_require__ = self.__webpack_require__;\n }\n\n self.__webpack_chunk_load__ = createChunkLoader(runtime);\n self.__webpack_require__ = createModuleRequire(runtime);\n self.__webpack_require_type__ = runtime;\n\n if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {\n const remoteBundle = bundle ?? 'default';\n self.__remote_webpack_require__[remoteBundle] =\n self.__webpack_require__ as (remoteId: string | number) => unknown;\n self.__remote_webpack_require__[remoteBundle].type = 'turbopack';\n }\n }\n\n // load all initial chunks when using Turbopack runtime\n if (runtime === RUNTIME_TURBOPACK) {\n await Promise.all(\n scripts.map((script) => {\n if (script.src) {\n return self.__webpack_chunk_load__?.(script.src, bundle);\n }\n return Promise.resolve(undefined);\n }),\n );\n }\n\n // initialize shared modules with core React dependencies\n const coreShared = {\n react: async () => (await import('react')).default,\n 'react-dom': async () => (await import('react-dom')).default,\n 'react/jsx-dev-runtime': async () =>\n (await import('react/jsx-dev-runtime')).default,\n 'react/jsx-runtime': async () =>\n (await import('react/jsx-runtime')).default,\n 'react-dom/client': async () => (await import('react-dom/client')).default,\n ...shared,\n };\n await initializeSharedModules(\n bundle ?? 'default',\n // include all core modules as shared\n coreShared,\n remoteShared,\n );\n}\n\n/**\n * Creates module require function for webpack runtime.\n * This function resolves module IDs to their exports, handling:\n * - Webpack remotes (pre-loaded bundles)\n * - Shared modules (React, etc.)\n * - Turbopack modules (dynamically loaded)\n */\nfunction createModuleRequire(runtime: Runtime): (id: string) => unknown {\n return (id: string) => {\n const self = globalThis as GlobalScope;\n const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)\n ?.groups ?? {\n bundle: 'default',\n id,\n };\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : runtime;\n\n logDebug('WebpackAdapter', `remoteRuntime: \"${remoteRuntime}\"`);\n\n try {\n // for webpack remotes, use the pre-loaded require function\n if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {\n return self.__remote_webpack_require__?.[bundle]?.(moduleId);\n }\n const sharedModuleId = moduleId ?? id;\n const sharedModule = getSharedModule(bundle ?? 'default', sharedModuleId);\n if (sharedModule) {\n return sharedModule;\n }\n if (bundle && moduleId) {\n return handleTurbopackModule(bundle, moduleId, id);\n }\n throw new Error(`Module \"${id}\" not found.`);\n } catch (requireError) {\n logWarn(\n 'WebpackAdapter',\n `Module require failed: ${String(requireError)}`,\n );\n if (typeof self.__original_webpack_require__ !== 'function') {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundle}\".`,\n {\n cause: requireError instanceof Error ? requireError : undefined,\n },\n );\n }\n try {\n logDebug('WebpackAdapter', 'Falling back to original webpack require');\n return self.__original_webpack_require__(id);\n } catch (originalError) {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundle}\".`,\n { cause: originalError instanceof Error ? originalError : undefined },\n );\n }\n }\n };\n}\n","// extracted from Next.js source at https://github.com/vercel/next.js/blob/canary/packages/next/src/client/set-attributes-from-props.ts\n\nconst DOMAttributeNames: Record<string, string> = {\n acceptCharset: 'accept-charset',\n className: 'class',\n htmlFor: 'for',\n httpEquiv: 'http-equiv',\n noModule: 'noModule',\n};\n\nconst ignoreProps = [\n 'onLoad',\n 'onReady',\n 'dangerouslySetInnerHTML',\n 'children',\n 'onError',\n 'strategy',\n 'stylesheets',\n];\n\nfunction isBooleanScriptAttribute(\n attr: string,\n): attr is 'async' | 'defer' | 'noModule' {\n return ['async', 'defer', 'noModule'].includes(attr);\n}\n\nexport function setAttributesFromProps(el: HTMLElement, props: object) {\n for (const [p, value] of Object.entries(props)) {\n if (!Object.hasOwn(props, p)) continue;\n if (ignoreProps.includes(p)) continue;\n\n // we don't render undefined props to the DOM\n if (value === undefined) {\n continue;\n }\n\n const attr = DOMAttributeNames[p] || p.toLowerCase();\n\n if (el.tagName === 'SCRIPT' && isBooleanScriptAttribute(attr)) {\n // Correctly assign boolean script attributes\n // https://github.com/vercel/next.js/pull/20748\n (el as HTMLScriptElement)[attr] = Boolean(value);\n } else {\n el.setAttribute(attr, String(value));\n }\n\n // Remove falsy non-zero boolean attributes so they are correctly interpreted\n // (e.g. if we set them to false, this coerces to the string \"false\", which the browser interprets as true)\n if (\n value === false ||\n (el.tagName === 'SCRIPT' &&\n isBooleanScriptAttribute(attr) &&\n (!value || value === 'false'))\n ) {\n // Call setAttribute before, as we need to set and unset the attribute to override force async:\n // https://html.spec.whatwg.org/multipage/scripting.html#script-force-async\n el.setAttribute(attr, '');\n el.removeAttribute(attr);\n }\n }\n}\n","import { logError, logInfo, logWarn } from '../utils/logger';\nimport { generateProtectedRcFallbackSrc } from './protected-rc-fallback';\nimport type {\n MountOrUnmountFunction,\n RemoteComponentMountUnmount,\n} from './types';\n\ntype ScriptMod = {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n default?: {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n };\n};\n\n/**\n * Fetches an ES module via the same-origin protected RC proxy, rewrites its\n * relative imports to also go through the proxy, then loads it by injecting a\n * wrapper <script type=\"module\"> tag (same pattern as loadScriptWithProtectedRcFallback\n * in script-loader.ts). The module's namespace is captured via a temporary\n * global and returned.\n *\n * This is needed when a direct import() of a cross-origin module fails due to\n * CORS restrictions or Vercel preview-deployment auth — the proxy runs\n * server-side where credentials are available.\n */\nasync function importViaProxy<T>(absoluteSrc: string): Promise<T> {\n const proxyUrl = new URL(\n generateProtectedRcFallbackSrc(absoluteSrc),\n location.href,\n ).href;\n const response = await fetch(proxyUrl);\n if (!response.ok) throw new Error(`Proxy fetch failed: ${response.status}`);\n logInfo(\n 'StaticLoader',\n `Successfully loaded ${absoluteSrc} via protected RC proxy fallback.`,\n );\n // Restore import.meta.url to the original module URL so any code that\n // relies on it (e.g. for asset resolution) gets the right value.\n // Rewrite relative imports to absolute proxy URLs so that transitive\n // dependencies (e.g. shared React chunks) also bypass CORS/auth, and so\n // that the paths resolve correctly from within a Blob URL context.\n const content = (await response.text())\n .replace(/import\\.meta\\.url/g, JSON.stringify(absoluteSrc))\n .replace(\n /\\b(from|import)\\s*([\"'])(\\.\\.?\\/[^\"']+)\\2/g,\n (_, keyword, quote, relativePath) => {\n const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;\n const absoluteProxyUrl = new URL(\n generateProtectedRcFallbackSrc(absoluteImportUrl),\n location.href,\n ).href;\n return `${keyword} ${quote}${absoluteProxyUrl}${quote}`;\n },\n );\n const moduleBlobUrl = URL.createObjectURL(\n new Blob([content], { type: 'text/javascript' }),\n );\n // A wrapper module imports everything from the module blob and writes the\n // namespace into a temporary global. We inject it as a <script> tag rather\n // than calling import() again, since import() is equally subject to CORS.\n const wrapperContent = [\n `import*as m from${JSON.stringify(moduleBlobUrl)};`,\n `globalThis.__rc_module_registry__=globalThis.__rc_module_registry__||{};`,\n `globalThis.__rc_module_registry__[${JSON.stringify(absoluteSrc)}]=m;`,\n ].join('');\n const wrapperBlobUrl = URL.createObjectURL(\n new Blob([wrapperContent], { type: 'text/javascript' }),\n );\n const scriptEl = document.createElement('script');\n scriptEl.type = 'module';\n scriptEl.src = wrapperBlobUrl;\n try {\n await new Promise<void>((resolve, reject) => {\n scriptEl.onload = () => resolve();\n scriptEl.onerror = () =>\n reject(new Error(`Failed to load module for ${absoluteSrc}`));\n document.head.appendChild(scriptEl);\n });\n } finally {\n scriptEl.remove();\n URL.revokeObjectURL(moduleBlobUrl);\n URL.revokeObjectURL(wrapperBlobUrl);\n }\n const registry = (\n globalThis as unknown as { __rc_module_registry__?: Record<string, T> }\n ).__rc_module_registry__;\n const mod = registry?.[absoluteSrc] ?? ({} as T);\n if (registry) delete registry[absoluteSrc];\n return mod;\n}\n\nfunction resolveScriptSrc(script: HTMLScriptElement, url: URL): string {\n const rawSrc =\n typeof script.getAttribute === 'function'\n ? (script.getAttribute('src') ?? script.src)\n : script.src;\n if (!rawSrc && script.textContent) {\n return URL.createObjectURL(\n new Blob(\n [script.textContent.replace(/import\\.meta\\.url/g, JSON.stringify(url))],\n { type: 'text/javascript' },\n ),\n );\n }\n return rawSrc;\n}\n\nasync function importScriptMod(absoluteSrc: string): Promise<ScriptMod> {\n try {\n return (await import(\n /* @vite-ignore */\n /* webpackIgnore: true */ absoluteSrc\n )) as ScriptMod;\n } catch (importError) {\n // Direct import failed (likely CORS or auth for cross-origin modules).\n // Blob URLs are same-origin, so they should never fail here — re-throw.\n if (absoluteSrc.startsWith('blob:')) throw importError;\n logWarn(\n 'StaticLoader',\n `Direct import of ${absoluteSrc} failed, attempting via protected RC proxy fallback.`,\n );\n return importViaProxy<ScriptMod>(absoluteSrc);\n }\n}\n\nexport async function loadStaticRemoteComponent(\n scripts: HTMLScriptElement[],\n url: URL,\n) {\n const self = globalThis as typeof globalThis & RemoteComponentMountUnmount;\n if (self.__remote_script_entrypoint_mount__?.[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n if (self.__remote_script_entrypoint_unmount__?.[url.href]) {\n self.__remote_script_entrypoint_unmount__[url.href] = new Set();\n }\n const mountUnmountSets = await Promise.all(\n scripts.map(async (script) => {\n try {\n const src = resolveScriptSrc(script, url);\n const absoluteSrc = new URL(src, url).href;\n const mod = await importScriptMod(absoluteSrc);\n // revoke the object URL if we created one for inline script content\n if (src.startsWith('blob:')) {\n URL.revokeObjectURL(src);\n }\n if (\n typeof mod.mount === 'function' ||\n typeof mod.default?.mount === 'function'\n ) {\n if (!self.__remote_script_entrypoint_mount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_mount__ = {};\n }\n if (!self.__remote_script_entrypoint_mount__[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_mount__[url.href]?.add(\n mod.mount ||\n mod.default?.mount ||\n (() => {\n // noop\n }),\n );\n }\n if (\n typeof mod.unmount === 'function' ||\n typeof mod.default?.unmount === 'function'\n ) {\n if (!self.__remote_script_entrypoint_unmount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_unmount__ = {};\n }\n if (!self.__remote_script_entrypoint_unmount__[url.href]) {\n self.__remote_script_entrypoint_unmount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_unmount__[url.href]?.add(\n mod.unmount ||\n mod.default?.unmount ||\n (() => {\n // noop\n }),\n );\n }\n return {\n mount: mod.mount || mod.default?.mount,\n unmount: mod.unmount || mod.default?.unmount,\n };\n } catch (e) {\n logError(\n 'StaticLoader',\n `Error loading remote component script from \"${script.src || url.href}\".`,\n e,\n );\n return {\n mount: undefined,\n unmount: undefined,\n };\n }\n }),\n );\n return mountUnmountSets.reduce(\n (acc, { mount, unmount }) => {\n if (typeof mount === 'function') {\n acc.mount.add(mount);\n }\n if (typeof unmount === 'function') {\n acc.unmount.add(unmount);\n }\n return acc;\n },\n {\n mount: new Set<MountOrUnmountFunction>(),\n unmount: new Set<MountOrUnmountFunction>(),\n },\n );\n}\n","/**\n * The headers to use when fetching the remote component.\n */\nexport function remoteFetchHeaders() {\n return {\n /**\n * Authenticates deployment protection for the remote. Needed for SSR and SSG clients.\n * If the remote component uses vercel deployment protection, ensure the host and remote vercel\n * projects share a common automation bypass secret, and the shared secret is used as the\n * VERCEL_AUTOMATION_BYPASS_SECRET env var in the host project.\n */\n ...(typeof process === 'object' &&\n typeof process.env === 'object' &&\n typeof process.env.VERCEL_AUTOMATION_BYPASS_SECRET === 'string'\n ? {\n 'x-vercel-protection-bypass':\n process.env.VERCEL_AUTOMATION_BYPASS_SECRET,\n }\n : {}),\n Accept: 'text/html',\n };\n}\n","import { fetchWithProtectedRcFallback } from '../client/fetch-with-protected-rc-fallback';\nimport { remoteFetchHeaders } from './fetch-headers';\nimport type { HookOptions, OnRequestHook, OnResponseHook } from './types';\n\n/**\n * Options for fetching with request/response hooks.\n */\nexport interface FetchWithHooksOptions {\n /** Hook to intercept the request before fetching */\n onRequest?: OnRequestHook;\n /** Hook to process the response after fetching */\n onResponse?: OnResponseHook;\n /** AbortController to cancel loading - aborts will throw AbortError */\n abortController?: AbortController;\n}\n\n/**\n * Performs a fetch with optional request and response lifecycle hooks.\n *\n * This utility centralizes the logic for:\n * 1. Calling onRequest hook - if it returns a Response, use it instead of fetching\n * 2. Performing the actual fetch if onRequest didn't provide a response\n * 3. Calling onResponse hook - if it returns a Response, use that transformed response\n *\n * Hooks receive an AbortSignal and abort function to cancel loading at any point.\n * When aborted, throws AbortError (DOMException with name 'AbortError').\n *\n * @param url - The URL to fetch\n * @param init - The fetch init options\n * @param options - Optional hooks for request/response interception and AbortController\n * @returns The response (never null - throws on abort)\n * @throws DOMException with name 'AbortError' if loading is aborted\n *\n * @example\n * const controller = new AbortController();\n * try {\n * const response = await fetchWithHooks(url, fetchInit, {\n * abortController: controller,\n * onResponse: async (url, response, { abort }) => {\n * if (response.redirected) {\n * abort(); // Throws AbortError\n * }\n * },\n * });\n * } catch (error) {\n * if (error.name === 'AbortError') {\n * console.log('Loading was aborted');\n * }\n * }\n */\nexport async function fetchWithHooks(\n url: URL,\n additionalInit: {\n credentials?: RequestCredentials;\n next?: {\n tags?: string[];\n };\n },\n options: FetchWithHooksOptions = {},\n): Promise<Response> {\n const {\n onRequest,\n onResponse,\n abortController = new AbortController(),\n } = options;\n const signal = abortController.signal;\n\n const hookOptions: HookOptions = {\n signal,\n abort: (reason?: unknown) => abortController.abort(reason),\n };\n\n // Include signal in fetch init for reactive abort support\n const init: RequestInit = {\n method: 'GET',\n headers: remoteFetchHeaders(),\n signal,\n ...additionalInit,\n };\n\n // Call onRequest hook if provided - may return a Response to skip fetching\n let res = await onRequest?.(url, init, hookOptions);\n\n if (!res) {\n res = await fetchWithProtectedRcFallback(url, init);\n }\n\n // Call onResponse hook if provided - may return a transformed Response\n const transformedRes = await onResponse?.(url, res, hookOptions);\n\n if (transformedRes) {\n res = transformedRes;\n }\n\n return res;\n}\n","export function getClientOrServerUrl(\n src: string | URL | undefined,\n serverFallback: string,\n): URL {\n const fallback =\n typeof location !== 'undefined' ? location.href : serverFallback;\n\n if (!src) {\n return new URL(fallback);\n }\n\n return typeof src === 'string' ? new URL(src, fallback) : src;\n}\n","import { useLayoutEffect, useRef, useState } from 'react';\n\nexport interface GlobalThis {\n [key: `__remote_components_shadowroot_${string}`]: ShadowRoot | null;\n}\n\ninterface UseShadowRootOptions {\n /** Whether CSS isolation is enabled */\n isolate: boolean | undefined;\n /** Shadow DOM mode */\n mode: 'open' | 'closed';\n /** Unique key suffix for identifying this shadow root */\n keySuffix: string;\n}\n\ninterface UseShadowRootResult {\n /** The shadow root element, or null if not isolated */\n shadowRoot: ShadowRoot | null;\n /** Ref to attach to the shadow host container element */\n shadowRootContainerRef: React.RefObject<HTMLDivElement | null>;\n}\n\n/**\n * Manages shadow root lifecycle for CSS isolation.\n *\n * Handles:\n * - Initial shadow root discovery from SSR or declarative shadow DOM\n * - Creating shadow root as fallback for browsers without declarative shadow DOM support\n * - Cleanup when isolation is disabled\n * - Re-attachment when isolation is re-enabled\n */\nexport function useShadowRoot({\n isolate,\n mode,\n keySuffix,\n}: UseShadowRootOptions): UseShadowRootResult {\n const shadowRootContainerRef = useRef<HTMLDivElement | null>(null);\n\n const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(() => {\n const self = globalThis as unknown as GlobalThis;\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n const ssrShadowRoot =\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot ??\n self[shadowRootKey] ??\n null)\n : null;\n // Clear the global reference after reading it\n self[shadowRootKey] = null;\n return ssrShadowRoot;\n });\n\n useLayoutEffect(() => {\n if (\n isolate !== false &&\n typeof document !== 'undefined' &&\n (!shadowRoot || !shadowRoot.isConnected)\n ) {\n const self: GlobalThis = globalThis;\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n\n let shadowRootElement: ShadowRoot | null = null;\n const element = document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n );\n shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;\n\n if (!shadowRootElement && element) {\n // Create a shadow root if it doesn't exist.\n // This is a fallback for browsers that don't support declarative shadow DOM.\n try {\n shadowRootElement = element.attachShadow({ mode });\n self[shadowRootKey] = shadowRootElement;\n } catch {\n // Do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n // Remove all nodes from the shadow root except links (preserves stylesheets)\n shadowRootElement.querySelectorAll('*:not(link)').forEach((node) => {\n node.remove();\n });\n setShadowRoot(shadowRootElement);\n }\n } else if (isolate === false && shadowRoot) {\n // Clear the global cache when disabling isolation (only when explicitly false)\n const self: GlobalThis = globalThis;\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n self[shadowRootKey] = null;\n setShadowRoot(null);\n }\n }, [isolate, shadowRoot, mode, keySuffix]);\n\n return { shadowRoot, shadowRootContainerRef };\n}\n","/**\n * Dummy URL used as a fallback base for URL parsing when no real base URL is available.\n * This is used during SSR or when location is not defined.\n */\nexport const DUMMY_FALLBACK = 'http://remote-components-dummy-fallback';\n\n/**\n * Extracts the relevant HTML content from a remote component response.\n *\n * Handles multiple remote component formats:\n * - Next.js Pages Router SSR wrapper (`div[id^=\"__REMOTE_COMPONENT\"]`)\n * - App Router remote components (`div[data-bundle][data-route]`)\n * - Next.js pages (`div#__next`)\n * - Web component format (`remote-component:not([src])`)\n *\n * @param html - Raw HTML string from the remote component response\n * @returns Extracted HTML content with links and scripts, or empty string if not found\n */\nexport function getRemoteComponentHtml(html: string): string {\n if (typeof document === 'undefined') return html;\n\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 from various sources\n const remoteComponentContainer = temp.querySelectorAll(\n `div[data-bundle][data-route][data-runtime][id^=\"__vercel_remote_component\"],div[data-bundle][data-route],div#__next,remote-component:not([src])`,\n );\n if (remoteComponentContainer.length > 0) {\n return `${Array.from(temp.querySelectorAll('link,script'))\n .map((link) => link.outerHTML)\n .join('')}${Array.from(remoteComponentContainer)\n .map((container) => container.outerHTML)\n .join('')}`;\n }\n\n return '';\n}\n","import type { NavigateOptions } from 'next/dist/shared/lib/app-router-context.shared-runtime';\nimport type { default as ImageComponentType, ImageProps } from 'next/image';\nimport { usePathname, useSearchParams } from 'next/navigation';\nimport { applyBundleUrlToImagePropsSrc } from '#internal/shared/client/polyfill';\nimport { logWarn } from '../../shared/utils/logger';\n\nexport function imageImpl(\n ImageComponent: typeof ImageComponentType,\n bundle: string,\n) {\n const component = function RemoteImage(props: ImageProps) {\n return (\n <ImageComponent\n {...props}\n src={applyBundleUrlToImagePropsSrc(bundle, props.src)}\n />\n );\n };\n component.default = component;\n return component;\n}\n\nexport const routerImpl = async () => {\n const { useRouter } = await import('next/navigation');\n return Promise.resolve({\n useRouter: () => {\n const router = useRouter();\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const query = Object.fromEntries(searchParams.entries());\n return {\n pathname,\n query,\n asPath: searchParams.toString()\n ? `${pathname}?${searchParams.toString()}`\n : pathname,\n push: (href: string, _: string, options?: NavigateOptions) => {\n router.push(href, options);\n return Promise.resolve(true);\n },\n replace: (href: string, _: string, options?: NavigateOptions) => {\n router.replace(href, options);\n return Promise.resolve(true);\n },\n refresh: () => Promise.resolve(router.refresh()),\n prefetch: async () => {\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.prefetch() in a remote component loaded in the Next.js App Router. prefetch() is a no-op in the App Router.',\n );\n return Promise.resolve();\n },\n back: () => {\n // there's no back() in the App Router\n if (typeof window !== 'undefined') {\n window.history.back();\n }\n },\n reload: () => {\n router.refresh();\n },\n beforePopState: () => {\n // there's no beforePopState() in the App Router\n },\n events: {\n on: () => {\n // there's no router.events in the App Router\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.events.on() in a remote component loaded in the Next.js App Router. events.on() is a no-op in the App Router.',\n );\n },\n off: () => {\n // there's no router.events in the App Router\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.events.off() in a remote component loaded in the Next.js App Router. events.off() is a no-op in the App Router.',\n );\n },\n emit: () => {\n // there's no router.events in the App Router\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.events.emit() in a remote component loaded in the Next.js App Router. events.emit() is a no-op in the App Router.',\n );\n },\n },\n };\n },\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,yBAAAA;AAAA;AAAA;AAEA,YAAuB;;;ACFvB,IAAAC,gBAQO;AACP,uBAA6B;;;ACT7B,IAAM,WAAW;AAAA,EACf;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,mBAAmB,KAA6B,KAAU;AACxE,MAAI,IAAI,WAAW,SAAS,QAAQ;AAClC,UAAM,QAAQ,IAAI;AAAA,MAChB,SACG;AAAA,QACC,CAAC,SACC,GAAG,aAAa,gBAAgB,cAAc;AAAA,MAClD,EACC,KAAK,GAAG;AAAA,IACb;AACA,UAAM,QAAQ,CAAC,SAAS;AACtB,UACE,KAAK,aAAa,KAAK,KACvB,YAAY,KAAK,KAAK,aAAa,KAAK,KAAK,EAAE,GAC/C;AACA,aAAK,MAAM,IAAI,IAAI,KAAK,aAAa,KAAK,KAAK,KAAK,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ACH;;;A9BxCI,IAAAC,sBAAA;AAzCJ,eAAe,kBAAkB;AAC/B,MAAI;AACF,UAAM,EAAE,OAAO,IAAI,MAAM,OAAO,mCAAmC;AACnE,WAAO;AAAA,EACT,QAAE;AACA,WAAO,CAAC;AAAA,EACV;AACF;AAEA,IAAM,gBAAgB,OAAO,eAAgD;AAC3E,QAAM,CAAC,gBAAgB,kBAAkB,IAAI,MAAM,QAAQ,IAAI;AAAA,IAC7D,gBAAgB;AAAA,IAChB,cAAc,QAAQ,QAAQ,CAAC,CAAC;AAAA,EAClC,CAAC;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH,eAAe;AAAA,IACf,cAAc,CAAC,WACb,QAAQ,QAAQC,WAAgB,eAAS,UAAU,SAAS,CAAC;AAAA,IAC/D,oCAAoC,CAAC,WACnC,QAAQ,QAAQ,EAAE,OAAOA,WAAgB,eAAS,UAAU,SAAS,EAAE,CAAC;AAAA,IAC1E,GAAG;AAAA,EACL;AACF;AAWO,SAASC,iBAAgB,OAA6B;AAC3D,MAAI,OAAO,MAAM,QAAQ,YAAY,EAAE,MAAM,eAAe,MAAM;AAChE,WAAO,MAAM,YAAY;AAAA,EAC3B;AAEA,SACE,6CAAC,mBAAsB,GAAG,OAAO,QAAQ,cAAc,MAAM,MAAM,GAAG;AAE1E;","names":["RemoteComponent","import_react","location","module","module","key","value","import_jsx_runtime","import_react","url","parser","doc","import_jsx_runtime","imageImpl","import_jsx_runtime","imageImpl","RemoteComponent"]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/next/host/client/index.tsx","../../../../src/react/index.tsx","../../../../src/shared/client/apply-origin.ts","../../../../src/shared/constants.ts","../../../../src/shared/client/protected-rc-fallback.ts","../../../../src/shared/utils/abort.ts","../../../../src/shared/error.ts","../../../../src/shared/utils/index.ts","../../../../src/shared/client/const.ts","../../../../src/shared/client/parse-remote-html.ts","../../../../src/shared/utils/logger.ts","../../../../src/shared/client/polyfill.tsx","../../../../src/shared/client/component-loader.ts","../../../../src/shared/webpack/next-client-pages-loader.ts","../../../../src/shared/webpack/shared-modules.ts","../../../../src/shared/client/rsc.ts","../../../../src/shared/client/webpack-patterns.ts","../../../../src/shared/client/script-loader.ts","../../../../src/shared/client/turbopack-patterns.ts","../../../../src/shared/client/chunk-loader.ts","../../../../src/shared/client/turbopack-module.ts","../../../../src/shared/client/shared-modules.ts","../../../../src/shared/client/webpack-adapter.ts","../../../../src/shared/client/proxy-through-host.ts","../../../../src/shared/client/set-attributes-from-props.ts","../../../../src/shared/client/static-loader.ts","../../../../src/shared/contract/host-state.ts","../../../../src/shared/contract/resolve-name-from-src.ts","../../../../src/shared/ssr/fetch-headers.ts","../../../../src/shared/ssr/fetch-with-hooks.ts","../../../../src/shared/ssr/get-client-or-server-url.ts","../../../../src/react/hooks/use-resolve-client-url.ts","../../../../src/shared/client/default-resolve-client-url.ts","../../../../src/react/hooks/use-shadow-root.ts","../../../../src/react/utils/extract-remote-html.ts","../../../../src/next/host/app-router-compat.tsx"],"sourcesContent":["'use client';\n\nimport * as Image from 'next/image';\nimport {\n type RemoteComponentProps,\n RemoteComponent as RemoteComponentReact,\n} from '../../../react';\n\nexport { RemoteComponentsProvider } from '#internal/react/context';\n\nimport { imageImpl, routerImpl } from '../app-router-compat';\n\nasync function tryImportShared() {\n try {\n const { shared } = await import('remote-components/shared/host/app');\n return shared;\n } catch {\n return {};\n }\n}\n\nconst sharedModules = async (userShared?: RemoteComponentProps['shared']) => {\n const [resolvedShared, resolvedUserShared] = await Promise.all([\n tryImportShared(),\n userShared ?? Promise.resolve({}),\n ]);\n\n return {\n ...resolvedShared,\n 'next/router': routerImpl,\n 'next/image': (bundle?: string) =>\n Promise.resolve(imageImpl(Image.default, bundle ?? 'default')),\n 'next/dist/client/image-component': (bundle?: string) =>\n Promise.resolve({ Image: imageImpl(Image.default, bundle ?? 'default') }),\n ...resolvedUserShared,\n };\n};\n\n/**\n * RemoteComponent - Client-side component for rendering remote components\n *\n * This component is used in Next.js App Router to render remote components.\n * It supports both Next.js App Router and Pages Router based components.\n *\n * @param props - The props for the remote component.\n * @returns The rendered remote component.\n */\nexport function RemoteComponent(props: RemoteComponentProps) {\n if (typeof props.src !== 'string' && !(props.src instanceof URL)) {\n return props.children ?? null;\n }\n\n return (\n <RemoteComponentReact {...props} shared={sharedModules(props.shared)} />\n );\n}\n","import {\n startTransition,\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { applyOriginToNodes } from '#internal/shared/client/apply-origin';\nimport { parseRemoteComponentDocument } from '#internal/shared/client/parse-remote-html';\nimport { sharedPolyfills } from '#internal/shared/client/polyfill';\nimport type { ResolveClientUrl } from '#internal/shared/client/proxy-through-host';\nimport {\n DEFAULT_ROUTE,\n type LoadRemoteComponentProps,\n loadRemoteComponent,\n loadStaticRemoteComponent,\n REMOTE_COMPONENT_REGEX,\n RemoteComponentsError,\n RUNTIME_SCRIPT,\n RUNTIME_WEBPACK,\n setAttributesFromProps,\n} from '#internal/shared/client/remote-component';\nimport type {\n ClientHostConfig,\n HostConfig,\n HostLifecycleCallbacks,\n} from '#internal/shared/contract/host-config';\nimport { createHostState } from '#internal/shared/contract/host-state';\nimport { resolveNameFromSrc } from '#internal/shared/contract/resolve-name-from-src';\nimport { errorFromFailedFetch } from '#internal/shared/error';\nimport { fetchWithHooks } from '#internal/shared/ssr/fetch-with-hooks';\nimport { getClientOrServerUrl } from '#internal/shared/ssr/get-client-or-server-url';\nimport type {\n HookOptions,\n OnRequestHook,\n OnResponseHook,\n} from '#internal/shared/ssr/types';\nimport { attrToProp, escapeString } from '#internal/shared/utils';\nimport { isAbortError } from '#internal/shared/utils/abort';\nimport type {\n MountOrUnmountFunction,\n RemoteComponentMountUnmount,\n ResolvedRemoteComponentData,\n} from '#remote-components/shared/client/types';\nimport { useResolveClientUrl } from './hooks/use-resolve-client-url';\nimport { useShadowRoot } from './hooks/use-shadow-root';\nimport {\n DUMMY_FALLBACK,\n getRemoteComponentHtml,\n} from './utils/extract-remote-html';\n\n// Re-export callback and hook types for consumers\nexport type { HookOptions, ResolveClientUrl, OnRequestHook, OnResponseHook };\nexport { RemoteComponentsProvider } from '#internal/react/context';\nexport { proxyClientRequestsThroughHost } from '#internal/shared/client/proxy-through-host';\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\n/**\n * Props for the React remote component host.\n *\n * Extends {@link HostConfig}, {@link ClientHostConfig}, and\n * {@link HostLifecycleCallbacks}. Adds `shared` for module sharing and\n * `children` for loading fallback content.\n */\nexport interface RemoteComponentProps\n extends HostConfig,\n ClientHostConfig,\n HostLifecycleCallbacks {\n /** Shared modules to include in the remote component's context. */\n shared?: LoadRemoteComponentProps['shared'];\n /** Loading fallback content displayed while the remote component is being fetched. */\n children?: React.ReactNode;\n}\n\n/**\n * RemoteComponent is a React component that fetches and renders a remote component.\n * It supports SSR and can isolate the remote component in a shadow DOM.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n *\n * @example\n *\n * Use the `<RemoteComponent>` in your React application to consume a remote component from a remote application:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/react';\n *\n * export default function App() {\n * return (\n * <>\n * <h1>Welcome to My App</h1>\n * <p>This page consumes a remote component from another application.</p>\n * <RemoteComponent src=\"/nextjs-app-remote/components/header\" />\n * </>\n * );\n * }\n * ```\n *\n * To share modules, you can provide a shared module map with references to the shared modules:\n *\n * ```tsx\n * <RemoteComponent\n * src=\"/nextjs-app-remote/components/header\"\n * shared={{\n * '@/components/provider': () => import('@/components/host-provider')\n * }}\n * />\n * ```\n */\nexport function RemoteComponent({\n src,\n isolate,\n mode = 'open',\n reset,\n credentials = 'same-origin',\n name: nameProp = '__vercel_remote_component',\n shared = {},\n children,\n onBeforeLoad,\n onLoad,\n onError,\n onChange,\n onRequest,\n onResponse,\n resolveClientUrl: _resolveClientUrl,\n}: RemoteComponentProps) {\n const instanceId = useId();\n\n const name = useMemo(\n () => resolveNameFromSrc(src, nameProp),\n [src, nameProp],\n );\n\n const [data, setData] = useState<Omit<\n ResolvedRemoteComponentData,\n 'children'\n > | null>(null);\n\n const url = useMemo(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);\n\n const resolveClientUrl = useResolveClientUrl(_resolveClientUrl, url.href);\n\n // for relative src paths, use just the pathname as the unique id.\n // for static urls, use the full url as the unique id as the path may not be unique.\n // this id needs to be the same for server and client side rendering.\n // note that if this needs to be more unique, can pass through the bundle as an id prop and ammend it to this id.\n const id =\n url.origin ===\n (typeof location !== 'undefined' ? location.origin : DUMMY_FALLBACK)\n ? url.pathname\n : url.href;\n\n //instanceId prevents multiple components with the same src from sharing a shadow root\n const keySuffix = `${escapeString(id)}_${escapeString(\n data?.name ?? name,\n )}_${escapeString(instanceId)}`;\n\n const [remoteComponent, setRemoteComponent] = useState<\n React.ReactNode | Error\n >(null);\n\n const { shadowRoot, shadowRootContainerRef } = useShadowRoot({\n isolate,\n mode,\n keySuffix,\n });\n\n const htmlRef = useRef<string | null>(\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot?.innerHTML ??\n document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ??\n document.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`)\n ?.innerHTML ??\n document.querySelector('div[data-bundle][data-route]')?.innerHTML)\n : null,\n );\n const endTemplateRef = useRef<HTMLTemplateElement | null>(null);\n // collect initial content that needs to be removed after remote component renders\n const childrenRef = useRef(\n typeof document !== 'undefined'\n ? (() => {\n let el = document.querySelector(`template[id=\"${name}_start\"]`);\n const elements = [];\n while (el && el.id !== `${name}_end`) {\n if (\n el.id !== `${name}_start` &&\n !el.getAttribute('data-remote-component')\n ) {\n elements.push(el);\n }\n el = el.nextElementSibling as HTMLTemplateElement | null;\n }\n return elements;\n })()\n : [],\n );\n const hostStateRef = useRef(createHostState());\n const componentHydrationHtml = useRef<string | null>(null);\n const prevRemoteComponentContainerRef = useRef<HTMLDivElement | null>(null);\n const unmountRef = useRef<Set<MountOrUnmountFunction> | null>(null);\n\n // Clean up the shadow root cache on unmount to prevent memory leaks\n useLayoutEffect(() => {\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n return () => {\n delete (\n globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n >\n )[shadowRootKey];\n };\n }, [keySuffix]);\n\n useLayoutEffect(() => {\n // Clear initial content after remote component renders\n if (childrenRef.current.length > 0 && remoteComponent) {\n childrenRef.current.forEach((el) => {\n el.remove();\n });\n childrenRef.current = [];\n }\n }, [remoteComponent]);\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 (\n index > 0 &&\n style.getAttribute('data-remote-components-reset') !== 'react'\n ) {\n style.remove();\n }\n });\n }\n\n // clear the html ref after hydration\n htmlRef.current = null;\n\n // clear all nodes except links and styles until the start marker\n // the marker gets only rendered on hydration\n let el: ChildNode | null = shadowRoot.childNodes[0] ?? null;\n while (el && (!('id' in el) || el.id !== `${name}_start`)) {\n const nextEl = el.nextSibling;\n if (el.nodeName !== 'LINK' && el.nodeName !== 'STYLE') {\n el.parentNode?.removeChild(el);\n }\n el = nextEl;\n }\n }\n }, [shadowRoot, remoteComponent, name]);\n\n useEffect(() => {\n if (src && src !== hostStateRef.current.prevSrc) {\n const previousSrc = hostStateRef.current.prevSrc;\n const previousName = hostStateRef.current.prevName;\n hostStateRef.current.prevSrc = src;\n\n if (previousSrc !== null) {\n htmlRef.current = null;\n }\n\n // Abort any in-progress load so the latest src always wins.\n hostStateRef.current.abortController?.abort();\n hostStateRef.current.abortController = new AbortController();\n const { signal } = hostStateRef.current.abortController;\n\n onBeforeLoad?.(src);\n hostStateRef.current.stage = 'loading';\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 credentials,\n } as RequestInit;\n\n const resolvedUrl = new URL(\n resolveClientUrl?.(url.href) ?? url.href,\n location.href,\n );\n const res = await fetchWithHooks(resolvedUrl, fetchInit, {\n onRequest,\n onResponse,\n abortController: hostStateRef.current.abortController,\n });\n\n if (!res || !res.ok) {\n throw await errorFromFailedFetch(url.href, resolvedUrl, res);\n }\n\n // get the full HTML content as a string\n const remoteHtml = await res.text();\n if (signal.aborted) return;\n htmlRef.current = remoteHtml;\n html = getRemoteComponentHtml(remoteHtml);\n }\n\n if (signal.aborted) return;\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 const {\n component,\n name: remoteName,\n isRemoteComponent,\n metadata,\n nextData,\n rsc,\n remoteShared,\n links: linkElements,\n scripts: scriptElements,\n } = parseRemoteComponentDocument(doc, name, url);\n\n if (hostStateRef.current.prevIsRemoteComponent) {\n if (shadowRoot) {\n shadowRoot.innerHTML = '';\n }\n const self = globalThis as typeof globalThis &\n RemoteComponentMountUnmount;\n const prevUrl = hostStateRef.current.prevUrl;\n if (\n prevUrl &&\n self.__remote_script_entrypoint_unmount__?.[prevUrl.href]\n ) {\n const unmountPromises = Promise.all(\n Array.from(unmountRef.current ?? []).map(async (unmount) =>\n unmount(\n shadowRoot ?? prevRemoteComponentContainerRef.current,\n ),\n ),\n );\n unmountRef.current = null;\n await unmountPromises;\n }\n }\n hostStateRef.current.prevIsRemoteComponent = isRemoteComponent;\n hostStateRef.current.prevUrl = url;\n hostStateRef.current.prevName = remoteName;\n\n // update all relative URLs to absolute URLs based on the remote component URL\n applyOriginToNodes(doc, url, resolveClientUrl);\n\n const links = linkElements.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 = scriptElements;\n\n // handle inline scripts in the remote component\n const inlineScripts = (\n isRemoteComponent ? component : doc\n ).querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\n\n if (!isRemoteComponent) {\n // Next.js Script support\n const self = globalThis as typeof globalThis & {\n __next_s: [string, Record<string, string>][];\n };\n const prevNextScripts = self.__next_s;\n const nextScripts = [] as [string, Record<string, string>][];\n // eslint-disable-next-line camelcase\n self.__next_s = nextScripts;\n\n // TODO: needs to be cancellable with a singular listener for the abort signal https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\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 // TODO: needs to be cancellable https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n document.body.appendChild(newScript);\n } else {\n resolve(undefined);\n document.body.appendChild(script);\n }\n } else {\n resolve(undefined);\n }\n });\n }),\n );\n // process the remote component Next.js Script container\n nextScripts.forEach(([scriptSrc, props]) => {\n const script = document.createElement('script');\n // when we have a script src, apply it (inline scripts have `0` as src)\n if (scriptSrc) {\n script.src = scriptSrc;\n }\n // apply Script props\n if (typeof props.children === 'string') {\n script.textContent = props.children;\n }\n setAttributesFromProps(script, props);\n document.head.appendChild(script);\n });\n // restore previous Next.js Script container\n // eslint-disable-next-line camelcase\n self.__next_s = prevNextScripts;\n }\n\n let rscName;\n if (rsc) {\n rscName = `__remote_component_rsc_${escapeString(\n id,\n )}_${escapeString(remoteName)}`;\n rsc.textContent =\n rsc.textContent?.replace(\n new RegExp(`self\\\\[\"${remoteName}\"\\\\]`, 'g'),\n `self[\"${rscName}\"]`,\n ) ?? '';\n document.body.appendChild(rsc);\n }\n\n const newData = {\n ...metadata,\n links,\n remoteShared,\n src: typeof src === 'string' ? src : src.href,\n serverUrl: url.href,\n data: rsc\n ? (rsc.textContent || '').split('\\n').filter(Boolean)\n : [],\n };\n\n componentHydrationHtml.current = `${Array.from(\n doc.querySelectorAll('link,style'),\n )\n .map((link) => link.outerHTML)\n .join('')}${\n reset\n ? `<style data-remote-components-reset=\"\">:host { all: initial; }</style>`\n : ''\n }${component.innerHTML}`;\n\n const userShared = await shared;\n\n if ('__remote_components_missing_shared__' in userShared) {\n userShared.__remote_components_missing_shared__().catch((e) => {\n throw e;\n });\n } else if ('__remote_components_missing_shared__' in remoteShared) {\n throw new RemoteComponentsError(\n remoteShared.__remote_components_missing_shared__,\n );\n }\n\n if (isRemoteComponent) {\n // Only call onChange when not on first load (matching HTML implementation)\n if (previousSrc !== undefined) {\n onChange?.({\n previousSrc,\n nextSrc: src,\n previousName,\n nextName: remoteName,\n });\n }\n setData(newData);\n if (shadowRoot) {\n let shadowRootHtml = component.innerHTML;\n if (reset) {\n shadowRootHtml = `<style data-remote-components-reset=\"\">:host { all: initial; }</style>${shadowRootHtml}`;\n }\n shadowRoot.innerHTML = shadowRootHtml;\n htmlRef.current = null;\n setRemoteComponent(null);\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n resolveClientUrl,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n onLoad?.(src);\n } else if (isolate === false) {\n setRemoteComponent(\n // TODO: remove wrapper div by converting HTML to RSC or React tree\n <div\n dangerouslySetInnerHTML={{ __html: component.innerHTML }}\n ref={prevRemoteComponentContainerRef}\n />,\n );\n htmlRef.current = null;\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(component.querySelectorAll('script')),\n url,\n resolveClientUrl,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) =>\n mountFn(prevRemoteComponentContainerRef.current),\n ),\n );\n onLoad?.(src);\n }\n hostStateRef.current.stage = 'loaded';\n } else {\n const result = await loadRemoteComponent({\n url,\n name: remoteName,\n rscName,\n bundle: metadata.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 resolveClientUrl,\n });\n if (rsc) {\n rsc.remove();\n }\n\n setData(newData);\n // Only call onChange when not on first load (matching HTML implementation)\n if (previousSrc !== undefined) {\n onChange?.({\n previousSrc,\n nextSrc: src,\n previousName,\n nextName: remoteName,\n });\n }\n if (result.error) {\n hostStateRef.current.stage = 'error';\n setRemoteComponent(result.error);\n onError?.(result.error);\n } else {\n hostStateRef.current.stage = 'loaded';\n setRemoteComponent(result.component);\n onLoad?.(src);\n }\n }\n } catch (error) {\n // AbortError is expected when loading is cancelled - exit cleanly\n if (isAbortError(error)) {\n hostStateRef.current.stage = 'idle';\n return;\n }\n hostStateRef.current.stage = 'error';\n setRemoteComponent(error as Error);\n onError?.(error);\n }\n });\n }\n }, [\n url,\n src,\n isolate,\n credentials,\n name,\n shared,\n shadowRoot,\n reset,\n id,\n onBeforeLoad,\n onLoad,\n onError,\n onChange,\n onRequest,\n onResponse,\n resolveClientUrl,\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: hostStateRef.current.prevIsRemoteComponent\n ? RUNTIME_SCRIPT\n : data?.runtime || RUNTIME_WEBPACK,\n })}\n </script>\n );\n const resetStyle = reset ? (\n <style data-remote-components-reset=\"react\">{`:host { all: initial; }`}</style>\n ) : null;\n const linksToRender: React.ReactNode[] | null =\n data?.links?.map((link) => (\n <link\n {...link}\n href={new URL(link.href as string, url).href}\n key={JSON.stringify(link)}\n />\n )) || null;\n const componentToRender = (\n <>\n {resetStyle}\n {linksToRender}\n {remoteComponent ?? children}\n </>\n );\n\n if (componentHydrationHtml.current && shadowRoot && !shadowRoot.innerHTML) {\n shadowRoot.innerHTML = componentHydrationHtml.current;\n componentHydrationHtml.current = null;\n\n if (hostStateRef.current.prevIsRemoteComponent) {\n // ensure we load static resources when hydrating a remote component in shadow DOM\n loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n resolveClientUrl,\n )\n .then(({ mount }) => {\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n })\n .then(() => {\n if (src) {\n onLoad?.(src);\n }\n })\n .catch((e) => {\n const error = new RemoteComponentsError(\n `Error mounting remote component from \"${url.href}\"`,\n {\n cause: e,\n },\n );\n setRemoteComponent(error);\n onError?.(error);\n });\n }\n }\n\n if (isolate !== false) {\n const shadowRemoteComponentHtml =\n shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ??\n shadowRoot?.querySelector('div[data-bundle][data-route]');\n if (shadowRemoteComponentHtml) {\n shadowRemoteComponentHtml.remove();\n }\n\n return (\n <>\n {metadataJson}\n <div\n data-remote-component-id={`shadowroot_${keySuffix}`}\n id={`shadowroot_${data?.name ?? name}`}\n ref={shadowRootContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {typeof document === 'undefined' ? (\n <div\n dangerouslySetInnerHTML={{\n __html: `<img\n alt=\"\" decoding=\"async\" style=\"display:none\"\n src=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==\"\n onload=\"(function(el){\n const root = el.getRootNode();\n globalThis.__remote_components_shadowroot_${keySuffix} = root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {resetStyle}\n {linksToRender}\n {children}\n </template>\n ) : null}\n {shadowRoot && remoteComponent\n ? createPortal(\n <>\n <template id={`${name}_start`} />\n {resetStyle}\n {linksToRender}\n {remoteComponent}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>,\n shadowRoot,\n )\n : null}\n </div>\n </>\n );\n }\n htmlRef.current = null;\n\n // render start/end markers for the remote component\n return (\n <>\n <template id={`${name}_start`} />\n {metadataJson}\n {componentToRender}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>\n );\n}\n","import type { InternalResolveClientUrl } from '#internal/shared/ssr/types';\n\nconst tagNames = [\n 'img',\n 'source',\n 'video',\n 'audio',\n 'track',\n 'iframe',\n 'embed',\n 'script',\n 'link',\n];\n\nexport function applyOriginToNodes(\n doc: Document | HTMLElement,\n url: URL,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n if (url.origin !== location.origin) {\n const nodes = doc.querySelectorAll<HTMLImageElement>(\n tagNames\n .map(\n (type) =>\n `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`,\n )\n .join(','),\n );\n nodes.forEach((node) => {\n if (\n node.hasAttribute('src') &&\n /^[./]+\\/?/.test(node.getAttribute('src') ?? '')\n ) {\n const absoluteSrc = new URL(node.getAttribute('src') ?? '/', url).href;\n // Script elements are handled by the loaders (script-loader, static-loader)\n // which apply the callback themselves. Only apply it here for non-script elements.\n const isScript = node.tagName.toLowerCase() === 'script';\n node.src = isScript\n ? absoluteSrc\n : (resolveClientUrl?.(absoluteSrc) ?? absoluteSrc);\n }\n if (\n node.hasAttribute('href') &&\n /^[./]+\\/?/.test(node.getAttribute('href') ?? '')\n ) {\n const absoluteHref = new URL(node.getAttribute('href') ?? '/', url)\n .href;\n node.setAttribute(\n 'href',\n resolveClientUrl?.(absoluteHref) ?? absoluteHref,\n );\n }\n if (node.hasAttribute('srcset')) {\n const srcSet = node\n .getAttribute('srcset')\n ?.split(',')\n .map((entry) => {\n const [urlPart, descriptor] = entry.trim().split(/\\s+/);\n if (!urlPart) return entry;\n\n const absoluteUrl = new URL(urlPart, url).href;\n const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;\n return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;\n })\n .join(', ');\n if (srcSet) {\n node.setAttribute('srcset', srcSet);\n }\n }\n if (node.hasAttribute('imagesrcset')) {\n const srcSet = node\n .getAttribute('imagesrcset')\n ?.split(',')\n .map((entry) => {\n const [urlPart, descriptor] = entry.trim().split(/\\s+/);\n if (!urlPart) return entry;\n\n const absoluteUrl = new URL(urlPart, url).href;\n const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;\n return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;\n })\n .join(', ');\n if (srcSet) {\n node.setAttribute('imagesrcset', srcSet);\n }\n }\n });\n }\n}\n","export const RC_PROTECTED_REMOTE_FETCH_PATHNAME = '/rc-fetch-protected-remote';\n\nexport const CORS_DOCS_URL =\n 'https://vercel.com/docs/remote-components/concepts/cors-external-urls#accessing-cross-site-protected-remote-components';\n","import { RC_PROTECTED_REMOTE_FETCH_PATHNAME } from '#internal/shared/constants';\n\n/**\n * Generates a fallback URL that proxies the request through the host's protected remote fetch endpoint\n */\nexport function generateProtectedRcFallbackSrc(url: string): string {\n return `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${encodeURIComponent(url)}`;\n}\n\nexport function isProxiedUrl(url: string): boolean {\n try {\n return (\n new URL(url, location.href).pathname ===\n RC_PROTECTED_REMOTE_FETCH_PATHNAME\n );\n } catch {\n return false;\n }\n}\n","/**\n * Type guard to check if an error is an AbortError.\n * Handles cross-environment differences (Node.js, browsers, JSDOM).\n */\nexport function isAbortError(error: unknown): error is DOMException {\n if (error instanceof DOMException && error.name === 'AbortError') {\n return true;\n }\n\n // Handle Node.js native AbortError which may not be instanceof global DOMException\n if (\n error !== null &&\n typeof error === 'object' &&\n 'name' in error &&\n error.name === 'AbortError' &&\n 'message' in error &&\n typeof (error as { message: unknown }).message === 'string'\n ) {\n // Additional check: verify it has DOMException-like structure\n const e = error as { code?: unknown; constructor?: { name?: string } };\n return typeof e.code === 'number' || e.constructor?.name === 'DOMException';\n }\n\n return false;\n}\n","import { isProxiedUrl } from '#internal/shared/client/protected-rc-fallback';\nimport {\n CORS_DOCS_URL,\n RC_PROTECTED_REMOTE_FETCH_PATHNAME,\n} from '#internal/shared/constants';\nimport { isAbortError } from '#internal/shared/utils/abort';\n\nexport class RemoteComponentsError extends Error {\n code = 'REMOTE_COMPONENTS_ERROR';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'RemoteComponentsError';\n }\n}\n\nexport function multipleRemoteComponentsError(url: string | undefined) {\n return new RemoteComponentsError(\n `Multiple Remote Components found at \"${url}\". When a page exposes multiple Remote Components you must specify the \"name\" prop to select which one to load.`,\n );\n}\n\nexport function failedToFetchRemoteComponentError(\n url: string,\n { status, statusText }: { status: number; statusText: string },\n help: string = 'Is the URL correct and accessible?',\n) {\n return new RemoteComponentsError(\n `Failed to fetch Remote Component from \"${url}\". ${help}`,\n { cause: new Error(`${status} ${statusText}`) },\n );\n}\n\nexport async function errorFromFailedFetch(\n originalUrl: string,\n resolvedUrl: URL,\n res: Response | null | undefined,\n): Promise<RemoteComponentsError> {\n const isProxied = isProxiedUrl(resolvedUrl.href);\n\n if (isProxied && res) {\n const body = await res.text().catch(() => '');\n return failedProxyFetchError(\n originalUrl,\n resolvedUrl.href,\n res.status,\n body,\n );\n }\n\n const fallback = failedToFetchRemoteComponentError(\n originalUrl,\n res ?? { status: 0, statusText: 'No Response' },\n );\n\n if (!res) return fallback;\n\n try {\n const body = await res.text();\n const parser = new DOMParser();\n const doc = parser.parseFromString(body, 'text/html');\n const errorTemplate = doc.querySelector(\n 'template[data-next-error-message]',\n );\n const errorMessage = errorTemplate?.getAttribute('data-next-error-message');\n if (errorMessage) {\n const error = new RemoteComponentsError(errorMessage);\n const errorStack = errorTemplate?.getAttribute('data-next-error-stack');\n if (errorStack) {\n error.stack = errorStack;\n }\n return error;\n }\n } catch (parseError) {\n // Re-throw abort errors, ignore parse errors\n if (isAbortError(parseError)) throw parseError;\n }\n\n return fallback;\n}\n\nexport function failedProxyFetchError(\n originalUrl: string,\n proxyUrl: string,\n status: number,\n responseBody?: string,\n): RemoteComponentsError {\n if (status === 404) {\n return new RemoteComponentsError(\n `Could not proxy the request to \"${originalUrl}\" — the proxy endpoint \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" returned 404.\\n\\n` +\n `The host server needs middleware or a route that handles \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\".\\n\\n` +\n `Proxying requires two pieces:\\n` +\n ` 1. resolveClientUrl={proxyClientRequestsThroughHost} on <RemoteComponent>\\n` +\n ` 2. Middleware or a route for \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" on the host server\\n\\n` +\n `Docs: ${CORS_DOCS_URL}`,\n );\n }\n if (status === 403) {\n const detail = responseBody ? ` ${responseBody}` : '';\n return new RemoteComponentsError(\n `Proxied request to \"${proxyUrl}\" was forbidden.${detail} ` +\n `See: ${CORS_DOCS_URL}`,\n );\n }\n return new RemoteComponentsError(\n `Proxied request for \"${originalUrl}\" via \"${proxyUrl}\" failed with status ${status}. ` +\n `See: ${CORS_DOCS_URL}`,\n );\n}\n","export function escapeString(str: string) {\n return str.replace(/[^a-z0-9]/g, '_');\n}\n\nexport const attrToProp = {\n fetchpriority: 'fetchPriority',\n crossorigin: 'crossOrigin',\n imagesrcset: 'imageSrcSet',\n imagesizes: 'imageSizes',\n srcset: 'srcSet',\n} as Record<string, string>;\n","import { escapeString } from '../utils';\n\nexport const DEFAULT_ROUTE = '/';\n\nexport const RUNTIME_WEBPACK = 'webpack';\nexport const RUNTIME_TURBOPACK = 'turbopack';\nexport const RUNTIME_SCRIPT = 'script';\n\nexport const REMOTE_COMPONENT_REGEX =\n /(?<prefix>.*?)\\[(?<bundle>[^\\]]+)\\](?:%20| )(?<id>.+)/;\n\nexport function getBundleKey(bundle: string): string {\n return escapeString(bundle);\n}\n\nexport type Runtime =\n | typeof RUNTIME_WEBPACK\n | typeof RUNTIME_TURBOPACK\n | typeof RUNTIME_SCRIPT;\n","import {\n multipleRemoteComponentsError,\n RemoteComponentsError,\n} from '#internal/shared/error';\nimport type { NextData, RemoteComponentMetadata } from '../ssr/types';\nimport { DEFAULT_ROUTE, RUNTIME_SCRIPT } from './const';\n\nexport interface ParsedRemoteComponent {\n /** The DOM element representing the remote component content. */\n component: Element;\n /** Resolved name of the remote component (with _ssr suffix stripped). */\n name: string;\n /** Whether the component is a <remote-component> custom element. */\n isRemoteComponent: boolean;\n /** Component metadata: bundle, route, runtime. */\n metadata: {\n name: string;\n bundle: string;\n route: string;\n runtime: RemoteComponentMetadata['runtime'];\n };\n /** Parsed __NEXT_DATA__ or __REMOTE_NEXT_DATA__, or null. */\n nextData: NextData | null;\n /** The RSC flight data script element, or null. */\n rsc: Element | null;\n /** Shared module map extracted from the component's shared data script. */\n remoteShared: Record<string, string>;\n /** Link elements extracted from the document (outside the component). */\n links: HTMLLinkElement[];\n /** Script elements extracted from the component or document. */\n scripts: HTMLScriptElement[];\n}\n\n/**\n * Validates that the document does not contain multiple unnamed remote components.\n * When multiple components exist, the consumer must specify a name to select one.\n */\nexport function validateSingleComponent(\n doc: Document,\n name: string,\n url: string,\n): void {\n if (\n (doc.querySelectorAll('div[data-bundle][data-route]').length > 1 &&\n !doc.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`)) ||\n (doc.querySelectorAll('remote-component:not([src])').length > 1 &&\n !doc.querySelector(`remote-component[name=\"${name}\"]`))\n ) {\n throw multipleRemoteComponentsError(url);\n }\n}\n\n/**\n * Finds the remote component element in the parsed HTML document using the\n * standard querySelector chain. Returns null if no component is found.\n */\nexport function findComponentElement(\n doc: Document,\n name: string,\n): Element | null {\n return (\n doc.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`) ??\n doc.querySelector('div[data-bundle][data-route]') ??\n doc.querySelector('div#__next') ??\n doc.querySelector(`remote-component[name=\"${name}\"]:not([src])`) ??\n doc.querySelector('remote-component:not([src])')\n );\n}\n\n/**\n * Parses the __NEXT_DATA__ or __REMOTE_NEXT_DATA__ script element from the document.\n */\nexport function parseNextData(doc: Document): NextData | null {\n return JSON.parse(\n (\n doc.querySelector('#__NEXT_DATA__') ??\n doc.querySelector('#__REMOTE_NEXT_DATA__')\n )?.textContent ?? 'null',\n ) as NextData | null;\n}\n\n/**\n * Resolves the component name from the element's id attribute, the name attribute\n * (for <remote-component> elements), nextData, or a fallback value.\n * Strips the _ssr suffix from the id if present.\n */\nexport function resolveComponentName(\n component: Element | null,\n nextData: NextData | null,\n fallbackName: string,\n): { name: string; isRemoteComponent: boolean } {\n const isRemoteComponent =\n component?.tagName.toLowerCase() === 'remote-component';\n\n const name =\n component?.getAttribute('id')?.replace(/_ssr$/, '') ||\n (isRemoteComponent && component?.getAttribute('name')) ||\n (nextData ? '__next' : fallbackName);\n\n return { name, isRemoteComponent };\n}\n\n/**\n * Extracts component metadata (bundle, route, runtime) from the component element\n * and Next.js data.\n */\nexport function extractComponentMetadata(\n component: Element | null,\n nextData: NextData | null,\n name: string,\n url: URL,\n): ParsedRemoteComponent['metadata'] {\n return {\n name,\n bundle:\n component?.getAttribute('data-bundle') ||\n nextData?.props.__REMOTE_COMPONENT__?.bundle ||\n 'default',\n route:\n component?.getAttribute('data-route') ??\n nextData?.page ??\n (url.pathname || DEFAULT_ROUTE),\n runtime: (component?.getAttribute('data-runtime') ??\n (nextData?.props.__REMOTE_COMPONENT__?.runtime ||\n RUNTIME_SCRIPT)) as RemoteComponentMetadata['runtime'],\n };\n}\n\n/**\n * Extracts the shared module map from the document and removes the element.\n * Falls back to nextData's shared modules if available.\n */\nexport function extractRemoteShared(\n doc: Document,\n name: string,\n nextData: NextData | null,\n): Record<string, string> {\n const remoteSharedEl = doc.querySelector(\n `#${name}_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 return remoteShared;\n}\n\n/**\n * Validates that a remote component was found in the document and that it has\n * RSC data, Next.js data, or is a <remote-component> element.\n * Acts as a type assertion - narrows component to non-null on success.\n */\nexport function validateComponentFound(\n component: Element | null,\n rsc: Element | null,\n nextData: NextData | null,\n isRemoteComponent: boolean,\n url: string,\n name: string,\n): asserts component is Element {\n if (!component || !(rsc || nextData || isRemoteComponent)) {\n throw new RemoteComponentsError(\n `Remote Component not found on ${url}.${\n name !== '__vercel_remote_component'\n ? ` The name for the <RemoteComponent> is \"${name}\". Check <RemoteComponent> usage.`\n : ''\n } Did you forget to wrap the content in <RemoteComponent>?`,\n );\n }\n}\n\n/**\n * Extracts link elements from the document that are not inside the component.\n */\nexport function extractLinks(\n doc: Document,\n component: Element,\n): HTMLLinkElement[] {\n return Array.from(doc.querySelectorAll<HTMLLinkElement>('link[href]')).filter(\n (link) => !component.contains(link),\n );\n}\n\n/**\n * Extracts script elements from the component or document, depending on whether\n * the component is a <remote-component> custom element.\n */\nexport function extractScripts(\n doc: Document,\n component: Element,\n isRemoteComponent: boolean,\n): HTMLScriptElement[] {\n return Array.from(\n (isRemoteComponent ? component : doc).querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src]',\n ),\n );\n}\n\n/**\n * Parses a remote component HTML document and extracts all data needed for\n * loading and hydrating the component. This is the main orchestrator that\n * calls the individual extraction functions.\n */\nexport function parseRemoteComponentDocument(\n doc: Document,\n name: string,\n url: URL,\n): ParsedRemoteComponent {\n validateSingleComponent(doc, name, url.href);\n\n const component = findComponentElement(doc, name);\n const nextData = parseNextData(doc);\n\n const { name: resolvedName, isRemoteComponent } = resolveComponentName(\n component,\n nextData,\n name,\n );\n\n const rsc = doc.querySelector(`#${resolvedName}_rsc`);\n const metadata = extractComponentMetadata(\n component,\n nextData,\n resolvedName,\n url,\n );\n const remoteShared = extractRemoteShared(doc, resolvedName, nextData);\n\n validateComponentFound(\n component,\n rsc,\n nextData,\n isRemoteComponent,\n url.href,\n resolvedName,\n );\n\n const links = extractLinks(doc, component);\n const scripts = extractScripts(doc, component, isRemoteComponent);\n\n return {\n component,\n name: resolvedName,\n isRemoteComponent,\n metadata,\n nextData,\n rsc,\n remoteShared,\n links,\n scripts,\n };\n}\n","import { CORS_DOCS_URL } from '#internal/shared/constants';\nimport { RemoteComponentsError } from '#internal/shared/error';\n\ntype LogLocation =\n | 'ChunkLoader'\n | 'ComponentLoader'\n | 'SharedModules'\n | 'WebpackAdapter'\n | 'TurbopackModule'\n | 'StaticLoader'\n | 'ScriptLoader'\n | 'Polyfill'\n | 'HtmlRemote'\n | 'HtmlHost'\n | 'Config'\n | 'NextAppRouter'\n | 'NextAppRouterCompat'\n | 'FetchRemoteComponent';\n\nconst PREFIX = 'remote-components';\nconst DEBUG =\n typeof window !== 'undefined' && localStorage.getItem('RC_DEBUG') === 'true';\n\nexport function logDebug(location: LogLocation, message: string) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.debug(`[${PREFIX}:${location}]: ${message}`);\n }\n}\n\nexport function logInfo(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.info(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logWarn(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.warn(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logError(\n location: LogLocation,\n message: string,\n cause?: unknown,\n) {\n // eslint-disable-next-line no-console\n console.error(\n new RemoteComponentsError(`[${PREFIX}:${location}]: ${message}`, {\n cause,\n }),\n );\n}\n\n/**\n * Logs a warning when a cross-origin asset request fails, guiding users\n * to configure the withRemoteComponentsHost middleware on their host.\n */\nexport function warnCrossOriginFetchError(\n logLocation: LogLocation,\n url: string | URL,\n): void {\n try {\n const parsed = typeof url === 'string' ? new URL(url) : url;\n if (typeof location === 'undefined' || parsed.origin === location.origin) {\n return;\n }\n logWarn(\n logLocation,\n `Failed to fetch cross-origin resource \"${parsed.href}\". ` +\n 'If this is a protected deployment, ensure withRemoteComponentsHost middleware ' +\n 'is configured in your host and that the remote URL is included in allowedProxyUrls. ' +\n `See: ${CORS_DOCS_URL}`,\n );\n } catch {\n // URL parsing failed — skip the warning\n }\n}\n","import type { ImageProps, StaticImageData } from 'next/image';\nimport type { LinkProps } from 'next/link';\nimport { logWarn } from '../utils/logger';\n\nfunction applyBundleUrlToSrc(bundle: string, src: string) {\n const self = globalThis as typeof globalThis & {\n __remote_bundle_url__?: Record<string, URL>;\n };\n\n if (self.__remote_bundle_url__?.[bundle]?.origin === location.origin) {\n return src;\n }\n\n const { assetPrefix, path } =\n /^(?<assetPrefix>.*?)\\/_next\\/(?<path>.*)/.exec(src)?.groups ?? {};\n if (!path) {\n return new URL(src, self.__remote_bundle_url__?.[bundle]?.origin).href;\n }\n return `${self.__remote_bundle_url__?.[bundle]?.origin ?? ''}${assetPrefix}/_next/${path}`;\n}\n\nexport function applyBundleUrlToImagePropsSrc(\n bundle: string,\n src: ImageProps['src'],\n) {\n if (typeof src === 'string') {\n return applyBundleUrlToSrc(bundle, src);\n }\n const propSrc = src as StaticImageData;\n return applyBundleUrlToSrc(bundle, propSrc.src);\n}\n\nconst imageImpl = (bundle: string) =>\n function RemoteImage({\n fill: _fill,\n loader: _loader,\n quality: _quality,\n priority: _priority,\n loading: _loading,\n placeholder: _placeholder,\n blurDataURL: _blurDataURL,\n unoptimized: _unoptimized,\n overrideSrc: _overrideSrc,\n src,\n ...props\n }: ImageProps) {\n const newSrc = applyBundleUrlToImagePropsSrc(\n bundle,\n typeof src === 'string' ? src : (src as StaticImageData).src,\n );\n\n return (\n // eslint-disable-next-line @next/next/no-img-element, jsx-a11y/alt-text\n <img\n decoding=\"async\"\n style={{ color: 'transparent' }}\n {...props}\n src={newSrc}\n suppressHydrationWarning\n />\n );\n };\n\n// polyfill Next.js App Router client API (minimal)\n// implementations are minimal and do not cover all use cases\n// developer can override these shared modules from configuration\nexport function sharedPolyfills(\n shared?: Record<string, () => Promise<unknown>>,\n) {\n const self = globalThis as typeof globalThis & {\n __remote_component_host_shared_modules__?: Record<\n string,\n () => Promise<unknown>\n >;\n };\n const polyfill = {\n 'next/dist/client/components/navigation':\n self.__remote_component_host_shared_modules__?.['next/navigation'] ??\n shared?.['next/navigation'] ??\n (() =>\n Promise.resolve({\n useRouter() {\n return {\n push: (routerUrl: string) => {\n history.pushState({}, '', routerUrl);\n },\n replace: (routerUrl: string) => {\n history.replaceState({}, '', routerUrl);\n },\n back: () => {\n history.back();\n },\n };\n },\n usePathname() {\n return location.pathname;\n },\n useParams() {\n return {};\n },\n useSearchParams() {\n return new URLSearchParams(location.search);\n },\n useSelectedLayoutSegment() {\n return null;\n },\n useSelectedLayoutSegments() {\n return [];\n },\n __esModule: true,\n })),\n 'next/dist/client/app-dir/link':\n self.__remote_component_host_shared_modules__?.['next/link'] ??\n shared?.['next/link'] ??\n (() =>\n Promise.resolve({\n default: ({\n scroll: _,\n replace,\n prefetch,\n onNavigate,\n children,\n ...props\n }: React.PropsWithChildren<LinkProps>) => {\n if (prefetch) {\n logWarn(\n 'Polyfill',\n 'Next.js Link prefetch is not supported in remote components',\n );\n }\n return (\n <a\n {...props}\n href={props.href as string}\n onClick={(e) => {\n e.preventDefault();\n let preventDefaulted = false;\n e.preventDefault = () => {\n preventDefaulted = true;\n e.defaultPrevented = true;\n };\n if (typeof props.onClick === 'function') {\n props.onClick(e);\n }\n onNavigate?.(e);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (preventDefaulted) {\n return;\n }\n if (replace) {\n history.replaceState({}, '', props.href as string);\n } else {\n history.pushState({}, '', props.href as string);\n }\n }}\n suppressHydrationWarning\n >\n {children ?? null}\n </a>\n );\n },\n useLinkStatus() {\n return { pending: false };\n },\n __esModule: true,\n })),\n 'next/dist/client/app-dir/form':\n self.__remote_component_host_shared_modules__?.['next/form'] ??\n shared?.['next/form'] ??\n (() =>\n Promise.resolve({\n default: () => {\n // TODO: implement <Form> component for non-Next.js host applications\n throw new Error('Next.js <Form> component not implemented');\n },\n __esModule: true,\n })),\n 'next/dist/client/image-component':\n self.__remote_component_host_shared_modules__?.['next/image'] ??\n shared?.['next/image'] ??\n ((bundle: string) =>\n Promise.resolve({\n Image: imageImpl(bundle),\n __esModule: true,\n })),\n 'next/image':\n self.__remote_component_host_shared_modules__?.['next/image'] ??\n shared?.['next/image'] ??\n ((bundle: string) =>\n Promise.resolve({\n default: imageImpl(bundle),\n getImageProps: (_imgProps: ImageProps) => {\n throw new Error(\n 'Next.js getImageProps() is not implemented in remote components',\n );\n },\n __esModule: true,\n })),\n 'next/dist/client/script':\n self.__remote_component_host_shared_modules__?.['next/script'] ??\n shared?.['next/script'] ??\n (() =>\n Promise.resolve({\n // TODO: implement <Script> component for non-Next.js host applications\n // do not throw an error for now\n default: () => null,\n __esModule: true,\n })),\n 'next/router':\n self.__remote_component_host_shared_modules__?.['next/router'] ??\n shared?.['next/router'] ??\n (() =>\n // TODO: incomplete implementation\n Promise.resolve({\n useRouter() {\n return {\n push: (routerUrl: string) => {\n history.pushState({}, '', routerUrl);\n },\n replace: (routerUrl: string) => {\n history.replaceState({}, '', routerUrl);\n },\n back: () => {\n history.back();\n },\n };\n },\n __esModule: true,\n })),\n 'next/dist/build/polyfills/process': () =>\n Promise.resolve({\n default: {\n env: {\n NODE_ENV: 'production',\n },\n },\n __esModule: true,\n }),\n } as Record<string, () => Promise<unknown>>;\n\n polyfill['next/navigation'] = polyfill[\n 'next/dist/client/components/navigation'\n ] as () => Promise<unknown>;\n polyfill['next/link'] = polyfill[\n 'next/dist/client/app-dir/link'\n ] as () => Promise<unknown>;\n polyfill['next/form'] = polyfill[\n 'next/dist/client/app-dir/form'\n ] as () => Promise<unknown>;\n polyfill['next/dist/api/image'] = polyfill[\n 'next/dist/client/image-component'\n ] as () => Promise<unknown>;\n polyfill['next/script'] = polyfill[\n 'next/dist/client/script'\n ] as () => Promise<unknown>;\n\n return polyfill;\n}\n","import * as React from 'react';\nimport * as JSXDevRuntime from 'react/jsx-dev-runtime';\nimport * as JSXRuntime from 'react/jsx-runtime';\nimport * as ReactDOM from 'react-dom';\nimport * as ReactDOMClient from 'react-dom/client';\nimport type { InternalResolveClientUrl } from '#internal/shared/ssr/types';\nimport { RemoteComponentsError } from '../error';\nimport { logDebug, logWarn } from '../utils/logger';\nimport { nextClientPagesLoader } from '../webpack/next-client-pages-loader';\nimport { applySharedModules } from '../webpack/shared-modules';\nimport { createRSCStream } from './rsc';\nimport { loadScripts } from './script-loader';\nimport type {\n GlobalScope,\n LoaderResult,\n RemoteComponentPayload,\n} from './types';\nimport { setupWebpackRuntime } from './webpack-adapter';\n\n/**\n * Props accepted by {@link loadRemoteComponent}.\n *\n * Extends {@link RemoteComponentPayload} (the SSR-resolved fields needed for\n * hydration) with loader-specific fields (`url`, `shared`, `container`, etc.).\n * `remoteShared` is narrowed from optional to required (defaults to `{}` at\n * the call site).\n */\nexport interface LoadRemoteComponentProps extends RemoteComponentPayload {\n url: URL;\n shared:\n | Promise<Record<string, (bundle?: string) => Promise<unknown>>>\n | Record<string, (bundle?: string) => Promise<unknown>>;\n remoteShared: Record<string, string>;\n container?: HTMLHeadElement | ShadowRoot | null;\n rscName?: string;\n resolveClientUrl?: InternalResolveClientUrl;\n}\n\n/**\n * Main loader function that orchestrates the component loading process\n */\nexport async function loadRemoteComponent({\n url,\n name,\n rscName,\n bundle,\n route = '/',\n runtime = 'webpack',\n data,\n nextData,\n scripts = [],\n shared = Promise.resolve({}),\n remoteShared = {},\n container,\n resolveClientUrl,\n}: LoadRemoteComponentProps): Promise<LoaderResult> {\n try {\n // Load scripts if using webpack runtime\n if (runtime === 'webpack') {\n const self = globalThis as GlobalScope;\n // disable webpack entrypoint execution for the remote\n if (!self.__DISABLE_WEBPACK_EXEC__) {\n self.__DISABLE_WEBPACK_EXEC__ = {};\n }\n // disable webpack entrypoint execution for the current remote bundle\n self.__DISABLE_WEBPACK_EXEC__[bundle] = true;\n await loadScripts(scripts, resolveClientUrl);\n }\n\n const hostShared = await shared;\n logDebug(\n 'ComponentLoader',\n `loadRemoteComponent: bundle=\"${bundle}\", name=\"${name}\"`,\n );\n logDebug(\n 'ComponentLoader',\n `Host shared modules available: ${Object.keys(hostShared)}`,\n );\n logDebug(\n 'ComponentLoader',\n `Remote shared modules requested: ${JSON.stringify(remoteShared)}`,\n );\n\n // Setup webpack runtime environment\n await setupWebpackRuntime(\n runtime,\n scripts,\n url,\n bundle,\n hostShared,\n remoteShared,\n resolveClientUrl,\n );\n\n // Setup shared modules\n if (bundle) {\n const resolve = {\n '/react/index.js': React,\n '/react/jsx-dev-runtime.js': JSXDevRuntime,\n '/react/jsx-runtime.js': JSXRuntime,\n '/react-dom/index.js': ReactDOM,\n '/react-dom/client.js': ReactDOMClient,\n ...Object.entries(remoteShared).reduce<Record<string, unknown>>(\n (acc, [key, value]) => {\n if (typeof hostShared[value] !== 'undefined') {\n acc[key.replace(/^\\(ssr\\)\\/(?<relative>\\.\\/)?/, '')] =\n hostShared[value];\n } else {\n logDebug(\n 'ComponentLoader',\n `Remote requests \"${value}\" but host doesn't provide it`,\n );\n }\n return acc;\n },\n {},\n ),\n } as Record<string, unknown>;\n await Promise.all(\n Object.entries(resolve).map(async ([key, value]) => {\n if (typeof value === 'function') {\n resolve[key] = await value(bundle);\n }\n return Promise.resolve(value);\n }),\n );\n applySharedModules(bundle, resolve);\n } else {\n logWarn(\n 'ComponentLoader',\n 'No bundle specified, skipping shared module setup',\n );\n }\n\n // Load component based on data type\n if (data.length > 0) {\n return await loadRSCComponent(rscName ?? name, data);\n } else if (nextData) {\n return loadNextPagesComponent(bundle, route, nextData, name, container);\n }\n\n return loadRSCComponent(rscName ?? name, [`0:[null]\\n`]); // Fallback to empty RSC payload\n } catch (error) {\n return {\n component: null,\n error: new RemoteComponentsError(\n `Failed to load remote component \"${name}\".`,\n {\n cause: error instanceof Error ? error : new Error(String(error)),\n },\n ),\n };\n }\n}\n\n/**\n * Loads RSC (React Server Components) based component\n */\nasync function loadRSCComponent(\n rscName: string,\n data: string[],\n): Promise<LoaderResult> {\n // try to import react-server-dom-webpack from Next.js with a fallback\n let createFromReadableStream;\n try {\n const { createFromReadableStream: _createFromReadableStream } =\n await import(\n 'next/dist/compiled/react-server-dom-webpack/client.browser'\n );\n createFromReadableStream = _createFromReadableStream;\n } catch {\n const {\n default: { createFromReadableStream: _createFromReadableStream },\n } = await import('react-server-dom-webpack/client.browser');\n createFromReadableStream = _createFromReadableStream;\n }\n // remote components with RSC requires react-server-dom-webpack\n if (typeof createFromReadableStream !== 'function') {\n throw new RemoteComponentsError(\n 'Failed to import \"react-server-dom-webpack\". Is Next.js installed correctly?',\n );\n }\n\n const stream = createRSCStream(rscName, data);\n const component = createFromReadableStream(stream);\n\n return { component };\n}\n\n/**\n * Loads Next.js Pages Router based component\n */\nfunction loadNextPagesComponent(\n bundle: string,\n route: string,\n nextData: NonNullable<RemoteComponentPayload['nextData']>,\n name: string,\n container?: HTMLHeadElement | ShadowRoot | null,\n): LoaderResult {\n const { Component, App } = nextClientPagesLoader(bundle, route, container);\n\n if (!Component) {\n throw new RemoteComponentsError(\n `Remote Component \"${name}\" is trying to load the component for route \"${route}\" but it is not available.`,\n );\n }\n\n // error tolerance when app component is not found\n const component = App\n ? React.createElement(App, { Component, ...nextData.props })\n : React.createElement(Component, nextData.props);\n\n return { component };\n}\n","import { RemoteComponentsError } from '../error';\n\n// module loader for Next.js Pages Router\nexport function nextClientPagesLoader(\n bundle: string,\n route: string,\n styleContainer: HTMLHeadElement | ShadowRoot | null = document.head,\n) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string | number) => unknown) & {\n c?: Record<\n string | number,\n { id: string; parents: string[]; children: string[] }\n >;\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n type?: 'turbopack' | 'webpack';\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n // Next.js client pages loader reference storage\n __NEXT_P?: [\n (\n | [\n string,\n () => { default?: React.ComponentType<Record<string, unknown>> },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n ];\n // Next.js Pages Router CSS cache\n __remote_next_css__?: Record<string, ChildNode[]>;\n };\n\n // temporarily remove the original Next.js CSS loader\n const nextCssOriginal = document.querySelector(\n `[id=\"__next_css__DO_NOT_USE__\"]:not([data-bundle=\"${bundle}\"][data-route=\"${route}\"])`,\n );\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.removeChild(nextCssOriginal);\n }\n\n // create a new Next.js CSS loader element\n const nextCss = document.createElement('noscript');\n nextCss.id = '__next_css__DO_NOT_USE__';\n nextCss.setAttribute('data-bundle', bundle);\n nextCss.setAttribute('data-route', route);\n const nextCssEnd = document.createElement('noscript');\n nextCssEnd.id = '__next_css__DO_NOT_USE_END__';\n nextCssEnd.setAttribute('data-bundle', bundle);\n nextCssEnd.setAttribute('data-route', route);\n document.head.appendChild(nextCssEnd);\n document.head.appendChild(nextCss);\n\n // find the page component loader chunk\n const componentLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}!`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}!`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // find the app loader chunk\n const appLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // if we didn't find the component loader or app loader, throw an error\n if (!(componentLoaderChunk && appLoaderChunk)) {\n throw new RemoteComponentsError(\n `Next.js client pages loader not found in bundle \"${bundle}\".`,\n );\n }\n\n // temporarily store the original __NEXT_P reference\n // this is required to avoid conflicts with the Next.js client pages loader\n // which uses the same global variable to store the page components\n const __NEXT_P_ORIGINAL = self.__NEXT_P;\n const selfOriginal = self;\n delete selfOriginal.__NEXT_P;\n\n // load the component and app loader chunks\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? componentLoaderChunk\n : `[${bundle}] ${componentLoaderChunk}`,\n );\n if (\n typeof appLoaderChunk === 'string' ||\n (typeof appLoaderChunk === 'number' && appLoaderChunk !== -1)\n ) {\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? appLoaderChunk\n : `[${bundle}] ${appLoaderChunk}`,\n );\n }\n\n // if we have the __NEXT_P global variable, we can extract the component and app\n if (self.__NEXT_P) {\n const [, componentLoader] = self.__NEXT_P[0] ?? [\n undefined,\n () => ({ default: null }),\n ];\n const [, appLoader] = self.__NEXT_P[2] ?? [\n undefined,\n () => ({\n default: null,\n }),\n ];\n const { default: Component } = componentLoader();\n const { default: App } = appLoader();\n\n if (!self.__remote_next_css__) {\n // eslint-disable-next-line camelcase\n self.__remote_next_css__ = {};\n }\n\n if (!self.__remote_next_css__[bundle]) {\n // load the CSS files from the remote bundle\n const cssRE = /\\.s?css$/;\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {})\n .filter((id) => cssRE.test(id))\n .forEach((id) => {\n self.__remote_webpack_require__?.[bundle]?.(id);\n });\n\n Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {})\n .filter((path) => cssRE.test(path))\n .forEach((path) => {\n const id = self.__remote_webpack_module_map__?.[bundle]?.[path];\n if (id) {\n self.__remote_webpack_require__?.[bundle]?.(id);\n }\n });\n\n const elements = [];\n let node = nextCss.previousSibling;\n while (node && node !== nextCssEnd) {\n elements.push(node);\n node.remove();\n node = nextCss.previousSibling;\n }\n self.__remote_next_css__[bundle] = elements;\n }\n\n // if the styleContainer is provided, we need to move the styles to it\n if (styleContainer) {\n const elements = self.__remote_next_css__[bundle];\n elements.forEach((el) => {\n styleContainer.appendChild(el.cloneNode(true));\n });\n } else {\n // if no styleContainer is provided, we need to move the styles back to the head\n const elements = self.__remote_next_css__[bundle];\n elements.forEach((el) => {\n document.head.appendChild(el);\n });\n }\n\n // restore the original __NEXT_P reference\n delete self.__NEXT_P;\n self.__NEXT_P = __NEXT_P_ORIGINAL;\n\n // restore the original Next.js CSS loader\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.appendChild(nextCssOriginal);\n }\n\n nextCss.remove();\n nextCssEnd.remove();\n\n return { Component, App };\n }\n\n return { Component: null, App: null };\n}\n","// Webpack shared module patching\n// used in multiple remote component host types\n// multiple host types includes: HTML custom element for remote components and Next.js host application\n// we are using this shared function to patch a Webpack module map\n// to use shared modules between the host application and the remote component\n\nimport { logDebug, logWarn } from '../utils/logger';\n\nexport function applySharedModules(\n bundle: string,\n resolve: Record<string, unknown>,\n) {\n logDebug(\n 'SharedModules',\n `applySharedModules called for bundle: \"${bundle}\"`,\n );\n logDebug(\n 'SharedModules',\n `Shared modules to resolve: ${Object.keys(resolve)}`,\n );\n\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string) => unknown) & {\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n } & Record<string, string[]>;\n\n // if we have the bundle\n if (self.__remote_webpack_require__?.[bundle]) {\n const modulePaths = Object.keys(\n self.__remote_webpack_module_map__?.[bundle] ??\n self.__remote_webpack_require__[bundle].m ??\n {},\n );\n logDebug(\n 'SharedModules',\n `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`,\n );\n\n // patch all modules in the bundle to use the shared modules\n for (const [key, value] of Object.entries(resolve)) {\n let ids = modulePaths.filter((p) => p === key);\n if (ids.length === 0) {\n ids = modulePaths.filter((p) => p.includes(key));\n }\n\n if (ids.length === 0) {\n logDebug(\n 'SharedModules',\n `No matching module path found for shared module \"${key}\"`,\n );\n }\n\n for (let id of ids) {\n const webpackBundle = self.__remote_webpack_require__[bundle];\n if (webpackBundle.m) {\n // if we have a module map, we need to use the mapped id\n // this is required for production builds where the module ids are module id numbers\n if (self.__remote_webpack_module_map__?.[bundle]?.[id]) {\n const mappedId = `${self.__remote_webpack_module_map__[bundle][id]}`;\n logDebug(\n 'SharedModules',\n `Mapped module id: \"${id}\" -> \"${mappedId}\"`,\n );\n id = mappedId;\n }\n // create a mock module which exports the shared module\n webpackBundle.m[id] = (module) => {\n module.exports = value;\n };\n } else {\n logWarn(\n 'SharedModules',\n `webpackBundle.m is not available for bundle \"${bundle}\"`,\n );\n }\n }\n }\n } else {\n logWarn('SharedModules', `No webpack require found for bundle \"${bundle}\"`);\n logDebug(\n 'SharedModules',\n `Available bundles: ${Object.keys(self.__remote_webpack_require__ ?? {})}`,\n );\n }\n}\n","import { ReadableStream } from 'web-streams-polyfill';\n\n/**\n * Fixes RSC payload to make it compatible with React JSX development runtime\n */\nexport function fixPayload(payload: unknown): void {\n if (Array.isArray(payload)) {\n // if the current node is a React element, we need to fix the payload\n if (payload[0] === '$') {\n // fix the props (children or other React elements)\n fixPayload(payload[3]);\n if (payload.length === 4) {\n // add placeholder for the missing debug info\n payload.push(null, null, 1);\n }\n } else {\n // we are in an array, continue with visiting each item\n for (const item of payload) {\n fixPayload(item);\n }\n }\n } else if (typeof payload === 'object' && payload !== null) {\n // we are in an object, continue with visiting each property\n for (const key in payload) {\n fixPayload((payload as Record<string, unknown>)[key]);\n }\n }\n}\n\n/**\n * Processes RSC flight data and creates a ReadableStream\n */\nexport function createRSCStream(\n rscName: string,\n data: string[],\n): ReadableStream<Uint8Array> {\n return new ReadableStream({\n type: 'bytes',\n start(controller) {\n const encoder = new TextEncoder();\n const self = globalThis as typeof globalThis &\n Record<string, string[] | null>;\n\n // when the remote component RSC scripts are not found or loaded\n // we need to load the RSC flight data parsing the chunks\n if (data.length > 0) {\n data.forEach((chunk) => {\n const lines = chunk.split('\\n');\n for (const line of lines) {\n const match = /\\.push\\(\"(?<rsc>.*)\"\\);$/.exec(line);\n if (match?.groups?.rsc) {\n self[rscName] = self[rscName] ?? [];\n self[rscName].push(JSON.parse(`\"${match.groups.rsc}\"`) as string);\n }\n }\n });\n }\n\n // get the RSC flight data from the global scope\n // the RSC flight data is stored in an array\n // fallback to an empty RSC payload if the data is not found\n const allChunks = (self[rscName] ?? [`0:[null]\\n`]).join('');\n\n // clear the RSC flight data from the global scope\n self[rscName] = null;\n\n // process each line in the RSC flight data\n allChunks.split('\\n').forEach((chunk) => {\n if (chunk.length > 0) {\n // parse the chunk to get the id, prefix and payload\n const { before, id, prefix, payload } =\n /^(?<before>[^:]*?)?(?<id>[0-9a-zA-Z]+):(?<prefix>[A-Z])?(?<payload>\\[.*\\])/.exec(\n chunk,\n )?.groups ?? {};\n\n if (payload) {\n // parse the payload to a JSON object\n const jsonPayload = JSON.parse(payload) as unknown[];\n // fix the payload to make it compatible with React JSX development runtime\n fixPayload(jsonPayload);\n // reconstruct the chunk to a string\n const reconstruct = `${before ?? ''}${id}:${prefix ?? ''}${JSON.stringify(jsonPayload)}`;\n // encode the chunk to a byte buffer\n controller.enqueue(encoder.encode(`${reconstruct}\\n`));\n } else {\n // add empty line before closing the stream\n controller.enqueue(encoder.encode(`${chunk}\\n`));\n }\n } else {\n // add empty line before closing the stream\n controller.enqueue(encoder.encode(`${chunk}\\n`));\n }\n });\n // close the stream when all chunks are enqueued\n controller.close();\n },\n });\n}\n","export const NEXT_BUNDLE_PATH_RE = /\\/_next\\/\\[.+\\](?:%20| )/;\n","import {\n CORS_DOCS_URL,\n RC_PROTECTED_REMOTE_FETCH_PATHNAME,\n} from '#internal/shared/constants';\nimport type { InternalResolveClientUrl } from '#internal/shared/ssr/types';\nimport { RemoteComponentsError } from '../error';\nimport { warnCrossOriginFetchError } from '../utils/logger';\nimport { isProxiedUrl } from './protected-rc-fallback';\nimport { NEXT_BUNDLE_PATH_RE } from './webpack-patterns';\n\n/**\n * Loads external scripts for remote components\n */\nexport async function loadScripts(\n scripts: { src: string }[],\n resolveClientUrl?: InternalResolveClientUrl,\n): Promise<void> {\n await Promise.all(\n scripts.map((script) => {\n return new Promise<void>((resolve, reject) => {\n const newSrc = new URL(\n // remove the remote component bundle name identifier from the script src\n script.src.replace(NEXT_BUNDLE_PATH_RE, '/_next/'),\n location.origin,\n ).href;\n\n const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;\n\n const newScript = document.createElement('script');\n newScript.onload = () => resolve();\n newScript.onerror = () => {\n const isProxied = isProxiedUrl(resolvedSrc);\n if (isProxied) {\n reject(\n new RemoteComponentsError(\n `Failed to load script \"${newSrc}\" via proxy \"${resolvedSrc}\". ` +\n `Ensure withRemoteComponentsHost middleware is configured and \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" is in the matcher. ` +\n `See: ${CORS_DOCS_URL}`,\n ),\n );\n } else {\n warnCrossOriginFetchError('ScriptLoader', newSrc);\n reject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${newSrc}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n }\n };\n newScript.src = resolvedSrc;\n newScript.async = true;\n document.head.appendChild(newScript);\n });\n }),\n );\n}\n","/**\n * Regex patterns for parsing Turbopack's minified and development code.\n *\n * Turbopack outputs different variable names in dev vs production builds:\n * - Development: __turbopack_context__, parentImport, chunk, self\n * - Minified: e, t, etc.\n *\n * These patterns use named capture groups and backreferences to ensure\n * consistency within a single match (e.g., if ctx is 'e', all uses of ctx must be 'e').\n */\n\n/**\n * Matches: self.TURBOPACK_REMOTE_SHARED or e.TURBOPACK_REMOTE_SHARED\n *\n * @example\n * // Development:\n * \"self.TURBOPACK_REMOTE_SHARED=await __turbopack_context__.A(984803)\"\n *\n * // Minified:\n * \"e.TURBOPACK_REMOTE_SHARED=await e.A(984803)\"\n */\nexport const REMOTE_SHARED_MARKER_RE =\n /(?:self|[a-z])\\.TURBOPACK_REMOTE_SHARED/;\n\n/**\n * Extracts the module ID from a TURBOPACK_REMOTE_SHARED assignment.\n *\n * Captures:\n * - `sharedModuleId`: The numeric module ID\n *\n * @example\n * // Development:\n * \"self.TURBOPACK_REMOTE_SHARED=await __turbopack_context__.A(984803)\"\n * // -> { sharedModuleId: \"984803\" }\n *\n * // Minified:\n * \"e.TURBOPACK_REMOTE_SHARED=await e.A(123456)\"\n * // -> { sharedModuleId: \"123456\" }\n */\nexport const REMOTE_SHARED_ASSIGNMENT_RE =\n /\\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|e)\\.A\\((?<sharedModuleId>[0-9]+)\\)/;\n\n/**\n * Matches async module loader calls: ctx.A(moduleId)\n *\n * Captures:\n * - `asyncSharedModuleId`: The numeric module ID being loaded asynchronously\n *\n * @example\n * // Development:\n * \"() => __turbopack_context__.A(460400)\"\n * // -> { asyncSharedModuleId: \"460400\" }\n *\n * // Minified:\n * \"() => e.A(460400)\"\n * // -> { asyncSharedModuleId: \"460400\" }\n */\nexport const ASYNC_MODULE_LOADER_RE =\n /(?:__turbopack_context__|e)\\.A\\((?<asyncSharedModuleId>[0-9]+)\\)/;\n\n/**\n * Matches async module with Promise.resolve pattern.\n * Used for modules that can be loaded immediately without chunk loading.\n *\n * Captures:\n * - `ctx`: The context variable (__turbopack_context__ or e)\n * - `inner`: The inner callback variable (parentImport or e)\n * - `sharedModuleId`: The numeric module ID\n *\n * @example\n * // Development:\n * \"__turbopack_context__=>{__turbopack_context__.v(parentImport=>Promise.resolve().then(()=>parentImport(633334)))}\"\n * // -> { ctx: \"__turbopack_context__\", inner: \"parentImport\", sharedModuleId: \"633334\" }\n *\n * // Minified:\n * \"e=>{e.v(e=>Promise.resolve().then(()=>e(633334)))}\"\n * // -> { ctx: \"e\", inner: \"e\", sharedModuleId: \"633334\" }\n */\nexport const ASYNC_MODULE_RESOLVE_RE =\n /(?<ctx>__turbopack_context__|e)=>\\{\\k<ctx>\\.v\\((?<inner>parentImport|e)=>Promise\\.resolve\\(\\)\\.then\\(\\(\\)=>\\k<inner>\\((?<sharedModuleId>[0-9]+)\\)\\)\\)\\}/;\n\n/**\n * Matches async module with Promise.all pattern.\n * Used for modules that require loading additional chunks first.\n *\n * Captures:\n * - `ctx`: The context variable (__turbopack_context__ or e)\n * - `vCb`: The callback passed to .v() (parentImport or t)\n * - `mapCb`: The callback passed to .map() (chunk or t)\n * - `sharedModuleId`: The numeric module ID\n *\n * @example\n * // Development:\n * \"__turbopack_context__=>{__turbopack_context__.v(parentImport=>Promise.all([\\\"static/chunks/82dcf883b4ba22f0.js\\\"].map(chunk=>__turbopack_context__.l(chunk))).then(()=>parentImport(657407)))}\"\n * // -> { ctx: \"__turbopack_context__\", vCb: \"parentImport\", mapCb: \"chunk\", sharedModuleId: \"657407\" }\n *\n * // Minified:\n * \"e=>{e.v(t=>Promise.all([\\\"chunk.js\\\"].map(t=>e.l(t))).then(()=>t(633334)))}\"\n * // -> { ctx: \"e\", vCb: \"t\", mapCb: \"t\", sharedModuleId: \"633334\" }\n */\nexport const ASYNC_MODULE_ALL_RE =\n /(?<ctx>__turbopack_context__|e)=>\\{\\k<ctx>\\.v\\((?<vCb>parentImport|t)=>Promise\\.all\\(\\[\"[^\"]+\"\\]\\.map\\((?<mapCb>chunk|t)=>\\k<ctx>\\.l\\(\\k<mapCb>\\)\\)\\)\\.then\\(\\(\\)=>\\k<vCb>\\((?<sharedModuleId>[0-9]+)\\)\\)\\)\\}/;\n\n/**\n * Detects Turbopack runtime global usage in a chunk.\n *\n * Matches either dot-notation or bracket-notation access off `globalThis` or `self`:\n * - globalThis.TURBOPACK / self.TURBOPACK\n * - globalThis[\"TURBOPACK\"] / self['TURBOPACK'] (whitespace tolerated)\n */\nexport const TURBOPACK_GLOBAL_RE =\n /(?:globalThis|self)\\s*(?:\\.TURBOPACK|\\[\\s*[\"']TURBOPACK[\"']\\s*\\])/;\n","import {\n CORS_DOCS_URL,\n RC_PROTECTED_REMOTE_FETCH_PATHNAME,\n} from '#internal/shared/constants';\nimport type { InternalResolveClientUrl } from '#internal/shared/ssr/types';\nimport { RemoteComponentsError } from '../error';\nimport { logDebug, warnCrossOriginFetchError } from '../utils/logger';\nimport {\n getBundleKey,\n REMOTE_COMPONENT_REGEX,\n RUNTIME_WEBPACK,\n type Runtime,\n} from './const';\nimport { isProxiedUrl } from './protected-rc-fallback';\nimport { TURBOPACK_GLOBAL_RE } from './turbopack-patterns';\nimport type { GlobalScope } from './types';\n\n/**\n * Creates chunk loader function for webpack runtime.\n * This function is responsible for loading JavaScript chunks from remote applications\n * and transforming Turbopack-specific code to work in the host environment.\n */\nexport function createChunkLoader(\n runtime: Runtime,\n resolveClientUrl?: InternalResolveClientUrl,\n): (chunkId: string, scriptBundle?: string) => Promise<unknown> | undefined {\n return function __turbopack_chunk_load__(\n chunkId: string,\n scriptBundle?: string,\n ) {\n logDebug('ChunkLoader', `Loading chunk: \"${chunkId}\"`);\n const self = globalThis as GlobalScope;\n const {\n bundle,\n id: path,\n prefix,\n } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {\n bundle: scriptBundle ?? '',\n id: chunkId,\n };\n logDebug(\n 'ChunkLoader',\n `Parsed chunk - bundle: \"${bundle}\", path: \"${path}\", prefix: \"${prefix}\"`,\n );\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : runtime;\n logDebug('ChunkLoader', `Remote runtime: \"${remoteRuntime}\"`);\n if (remoteRuntime === RUNTIME_WEBPACK) {\n logDebug('ChunkLoader', 'Skipping chunk load - webpack runtime detected');\n return Promise.resolve(undefined);\n }\n\n const url = new URL(\n path\n ? `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n )\n : '/',\n self.__remote_bundle_url__?.[bundle ?? 'default'] ??\n new URL(location.origin),\n ).href;\n if (url.endsWith('.css')) {\n logDebug('ChunkLoader', `Skipping CSS file: \"${url}\"`);\n return;\n }\n\n if (!self.__remote_components_turbopack_chunk_loader_promise__) {\n self.__remote_components_turbopack_chunk_loader_promise__ = {};\n }\n if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {\n logDebug('ChunkLoader', `Returning cached promise for: \"${url}\"`);\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n }\n\n const resolvedUrl = resolveClientUrl?.(url) ?? url;\n logDebug('ChunkLoader', `Fetching chunk from: \"${resolvedUrl}\"`);\n self.__remote_components_turbopack_chunk_loader_promise__[url] =\n new Promise((resolve, reject) => {\n fetch(resolvedUrl)\n .then((res) => res.text())\n .then((code) => {\n // Turbopack runtime uses either dot-notation or bracket-notation globals.\n const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);\n if (hasTurbopack) {\n return handleTurbopackChunk(code, bundle ?? '', url);\n }\n logDebug(\n 'ChunkLoader',\n `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: \"${url}\"`,\n );\n logDebug(\n 'ChunkLoader',\n `First 500 chars of chunk: ${code.slice(0, 500)}`,\n );\n })\n .then(resolve)\n .catch((error) => {\n const isProxied = isProxiedUrl(resolvedUrl);\n if (isProxied) {\n reject(\n new RemoteComponentsError(\n `Failed to load chunk \"${url}\" via proxy \"${resolvedUrl}\". ` +\n `Ensure withRemoteComponentsHost middleware is configured and \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" is in the matcher. ` +\n `See: ${CORS_DOCS_URL}`,\n ),\n );\n } else {\n warnCrossOriginFetchError('ChunkLoader', url);\n reject(error);\n }\n });\n });\n\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n };\n}\n\n/**\n * Handles Turbopack chunk loading by transforming the chunk code to isolate\n * global variables per bundle and dynamically loading the transformed script.\n */\nasync function handleTurbopackChunk(\n code: string,\n bundle: string,\n url: string,\n): Promise<void> {\n logDebug(\n 'ChunkLoader',\n `Handling Turbopack chunk - bundle: \"${bundle}\", url: \"${url}\"`,\n );\n // skip this chunk as it is not needed for remote components\n if (/importScripts\\(\\.\\.\\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {\n logDebug('ChunkLoader', `Skipping worker chunk: \"${url}\"`);\n // remove preload links for this chunk\n const preloadLinks = document.querySelectorAll(\n `link[rel=\"preload\"][href=\"${new URL(url).pathname}\"]`,\n );\n preloadLinks.forEach((preloadLink) => preloadLink.remove());\n return;\n }\n\n const self = globalThis as GlobalScope;\n const bundleKey = getBundleKey(bundle);\n logDebug('ChunkLoader', `Bundle key: \"${bundleKey}\"`);\n\n // replace global variables with bundle-specific ones to prevent collisions\n // between multiple remote component bundles\n const transformedCode = code\n // Turbopack runtime can reference TURBOPACK via bracket-notation (common in newer Next.js)\n // e.g. globalThis[\"TURBOPACK\"] / self['TURBOPACK']\n .replace(\n /globalThis\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `globalThis[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(\n /self\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `self[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(/globalThis\\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`)\n .replace(/self\\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`)\n .replace(\n /TURBOPACK_WORKER_LOCATION/g,\n `TURBOPACK_WORKER_LOCATION_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_NEXT_CHUNK_URLS/g,\n `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,\n `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`,\n )\n .replace(/__next_require__/g, `__${bundleKey}_next_require__`)\n .replace(\n /\\/\\/# sourceMappingURL=(?<name>.+)(?<optional>\\._)?\\.js\\.map/g,\n `//# sourceMappingURL=${\n new URL(\n '.',\n new URL(\n url,\n self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin),\n ),\n ).href\n }$1$2.js.map`,\n );\n\n // Initialize TURBOPACK bundle with push interceptor for Next.js 16.2.0-canary\n // Use webpack-style chunk loading pattern\n if (!self[`TURBOPACK_${bundleKey}`]) {\n const chunkData: unknown[][] = [];\n const turbopackObject = {\n push: (item: unknown) => {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? 'array' : typeof item}`,\n );\n if (Array.isArray(item)) {\n chunkData.push(item);\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`,\n );\n } else {\n chunkData.push([item]);\n }\n return chunkData.length;\n },\n // Store chunks for later access\n __chunks__: chunkData,\n };\n self[`TURBOPACK_${bundleKey}`] = turbopackObject as unknown as Record<\n string,\n unknown\n >;\n }\n\n // load the script dynamically using a Blob URL\n logDebug('ChunkLoader', `Creating blob script for: \"${url}\"`);\n await new Promise<void>((scriptResolve, scriptReject) => {\n const blob = new Blob([transformedCode], {\n type: 'application/javascript; charset=UTF-8',\n });\n const scriptUrl = URL.createObjectURL(blob);\n const script = document.createElement('script');\n script.setAttribute('data-turbopack-src', url);\n script.src = scriptUrl;\n script.async = true;\n script.onload = () => {\n URL.revokeObjectURL(scriptUrl);\n logDebug(\n 'ChunkLoader',\n `Script loaded successfully for bundle \"${bundle}\"`,\n );\n const turbopackBundle = self[`TURBOPACK_${bundleKey}`];\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${\n turbopackBundle\n ? Object.keys(turbopackBundle as object)\n .slice(0, 10)\n .join(', ')\n : 'none'\n }`,\n );\n if (turbopackBundle && typeof turbopackBundle === 'object') {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle as object).length}`,\n );\n }\n scriptResolve(undefined);\n script.remove();\n };\n script.onerror = () => {\n URL.revokeObjectURL(scriptUrl);\n scriptReject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${script.src}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n script.remove();\n };\n document.head.appendChild(script);\n });\n\n // process any additional chunks that were registered during script execution\n const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`] as\n | { chunks: string[] }[]\n | undefined;\n logDebug(\n 'ChunkLoader',\n `Processing chunk lists for bundle \"${bundle}\": ${chunkLists?.length ?? 0} lists`,\n );\n const loadChunkLists = [] as (Promise<unknown> | undefined)[];\n while (chunkLists?.length) {\n const { chunks } = chunkLists.shift() ?? { chunks: [] };\n if (chunks.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Loading ${chunks.length} additional chunks for bundle \"${bundle}\": [${chunks.join(', ')}]`,\n );\n chunks.forEach((id: string) => {\n const chunkLoadResult = self.__webpack_chunk_load__?.(\n `[${bundle}] ${url.slice(0, url.indexOf('/_next'))}/_next/${id}`,\n );\n if (chunkLoadResult) {\n loadChunkLists.push(chunkLoadResult);\n }\n });\n }\n }\n if (loadChunkLists.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Waiting for ${loadChunkLists.length} additional chunks to load`,\n );\n await Promise.all(loadChunkLists);\n }\n}\n","import { logError } from '../utils/logger';\nimport { getBundleKey } from './const';\nimport type { GlobalScope } from './types';\n\n/**\n * Function signature for Turbopack module initializers.\n * These functions are generated by Turbopack and initialize module exports.\n */\nexport type TurbopackModuleInit = (\n turbopackContext: TurbopackContext,\n module: { exports: Record<string, unknown> },\n exports: Record<string, unknown>,\n) => void;\n\n/**\n * The context object passed to Turbopack module initializers.\n * This provides the runtime API that modules use for imports, exports, and HMR.\n */\ninterface TurbopackContext {\n /** HMR (Hot Module Replacement) - not implemented for remote components */\n k: {\n register(): void;\n registerExports(): void;\n signature(): (fn: unknown) => unknown;\n };\n /** ESM exports setup */\n s: (\n bindings:\n | Record<string, () => unknown>\n | [...([string, () => unknown] | [string, number, () => unknown])],\n esmId?: string | number,\n ) => void;\n /** Import module */\n i: (importId: string | number) => Record<string, unknown> | undefined;\n /** Require module */\n r: (requireId: string) => unknown;\n /** Value exports */\n v: (value: unknown) => void;\n /** Async module initializer */\n a: (\n mod: (\n handleDeps: unknown,\n setResult: (value: unknown) => void,\n ) => Promise<void>,\n ) => Promise<void>;\n /** Async module loader */\n A: (Aid: string) => Promise<unknown>;\n /**\n * Dynamic import tracking. Called in production chunks after ctx.s() to\n * register async/dynamic module relationships. e.g. t.j(importedMod, 58790)\n */\n j: (module: unknown, esmId?: string | number) => void;\n /** Chunk loader */\n l: (url: string) => Promise<unknown> | undefined;\n /** Global object for this bundle */\n g: unknown;\n /** Module object */\n m: { exports: Record<string, unknown> };\n /** Exports object */\n e: Record<string, unknown>;\n}\n\n/**\n * Turbopack pushes chunks as flat arrays in one of two shapes:\n *\n * Module chunk (common case):\n * [scriptElement, id1, factory1, id2, factory2, ...]\n * - index 0: the script Element (document.currentScript) or undefined\n * - alternating pairs: numeric ID (prod) or path string (dev), then factory function\n *\n * Runtime manifest (bootstrapper only, no module factories):\n * [scriptElement, { otherChunks: [...], runtimeModuleIds: [...] }]\n *\n * Newer Next.js canary versions may also store modules as a plain object\n * { [moduleId]: factory } rather than as an array.\n */\ntype BundleModules =\n | (\n | Element\n | string\n | number\n | TurbopackModuleInit\n | Record<string, TurbopackModuleInit>\n | null\n | undefined\n )[]\n | Record<string, TurbopackModuleInit>\n | undefined;\n\n/**\n * Handles Turbopack module resolution and execution.\n * This function finds a module in the Turbopack bundle, executes its initializer,\n * and returns the module exports.\n *\n * The Turbopack bundle stores modules as arrays where each entry is either:\n * - A module ID (string or number)\n * - A module initializer function\n *\n * This function provides a custom runtime context that implements the Turbopack\n * module system API, enabling remote modules to resolve their dependencies.\n */\nexport function handleTurbopackModule(\n bundle: string,\n moduleId: string,\n id: string,\n): unknown {\n const self = globalThis as GlobalScope;\n const bundleKey = getBundleKey(bundle);\n const raw = self[`TURBOPACK_${bundleKey}`];\n\n // Normalize the bundle global to a flat entry list. The chunk-loader push\n // interceptor stores modules as { __chunks__: [[Element, id, fn, ...], ...] }.\n let modules: BundleModules;\n if (raw && typeof raw === 'object' && '__chunks__' in raw) {\n modules = (\n raw as { __chunks__: unknown[][] }\n ).__chunks__.flat() as unknown as BundleModules;\n } else if (Array.isArray(raw)) {\n modules = (raw as unknown[]).flat() as unknown as BundleModules;\n } else {\n modules = raw as BundleModules;\n }\n\n // prepare module cache to handle circular dependencies\n if (!self.__remote_components_turbopack_modules__) {\n self.__remote_components_turbopack_modules__ = {};\n }\n if (!self.__remote_components_turbopack_modules__[bundle]) {\n self.__remote_components_turbopack_modules__[bundle] = {};\n }\n // return cached module if already loaded (CRITICAL: check this FIRST)\n if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {\n return self.__remote_components_turbopack_modules__[bundle][moduleId];\n }\n\n // Log only if bundle is completely missing (critical error)\n if (!modules) {\n logError('TurbopackModule', `TURBOPACK_${bundleKey} is undefined`);\n }\n\n const moduleInit = findModuleInit(modules, moduleId);\n const exports = {} as Record<string, unknown>;\n const moduleExports = { exports };\n\n if (typeof moduleInit !== 'function') {\n throw new Error(\n `Module ${id} not found in bundle ${bundle} with id ${moduleId}`,\n );\n }\n\n // store a reference to the module exports in the cache before execution\n // to handle circular dependencies\n self.__remote_components_turbopack_modules__[bundle][moduleId] =\n moduleExports.exports;\n\n // prepare global object for the bundle\n if (!self.__remote_components_turbopack_global__) {\n self.__remote_components_turbopack_global__ = {};\n }\n if (!self.__remote_components_turbopack_global__[bundle]) {\n self.__remote_components_turbopack_global__[bundle] = {};\n }\n\n // execute the module initializer with our custom Turbopack context\n moduleInit(\n createTurbopackContext(\n bundle,\n exports,\n moduleExports,\n modules,\n moduleInit,\n id,\n self,\n ),\n moduleExports,\n exports,\n );\n\n // update the cache with the final exports (may have changed during execution)\n if (\n self.__remote_components_turbopack_modules__[bundle][moduleId] !==\n moduleExports.exports\n ) {\n self.__remote_components_turbopack_modules__[bundle][moduleId] =\n moduleExports.exports;\n }\n\n return moduleExports.exports;\n}\n\n/**\n * Finds the module initializer function in the Turbopack bundle.\n */\nfunction findModuleInit(\n modules: BundleModules,\n\n moduleId: string,\n): TurbopackModuleInit | undefined {\n if (!modules || typeof modules !== 'object') return;\n\n // Object format: { [id]: factory } (newer Next.js canary builds)\n if (!Array.isArray(modules)) {\n const key =\n moduleId in modules\n ? moduleId\n : Object.keys(modules).find((k) => k.startsWith(moduleId));\n return key !== undefined ? modules[key] : undefined;\n }\n\n const flat = modules.flat();\n\n // Two-pass ID search: exact match first to avoid prefix false positives.\n // The startsWith fallback handles dev-mode IDs with appended qualifiers\n // such as \"[project]/path.tsx [app-client] (ecmascript, async loader)\".\n let idx = flat.findIndex((e) => String(e) === String(moduleId));\n if (idx < 0) {\n idx = flat.findIndex(\n (e) => typeof e === 'string' && e.startsWith(moduleId),\n );\n }\n if (idx >= 0) {\n // Factory is the first function entry that follows the module ID\n return flat\n .slice(idx + 1)\n .find((e): e is TurbopackModuleInit => typeof e === 'function');\n }\n\n // Embedded object map: entries of the form { [moduleId]: factory }\n return flat.find((e): e is Record<string, TurbopackModuleInit> =>\n Boolean(e && typeof e === 'object' && moduleId in (e as object)),\n )?.[moduleId];\n}\n\n/**\n * Creates the Turbopack context object that provides the runtime API for modules.\n */\nfunction createTurbopackContext(\n bundle: string,\n exports: Record<string, unknown>,\n moduleExports: { exports: Record<string, unknown> },\n modules: BundleModules,\n moduleInit: TurbopackModuleInit,\n id: string,\n self: GlobalScope,\n): TurbopackContext {\n return {\n // HMR not implemented for Remote Components\n k: {\n register() {\n // omit\n },\n registerExports() {\n // omit\n },\n signature() {\n return (fn: unknown) => fn;\n },\n },\n\n // ESM exports setup\n s(\n bindings:\n | Record<string, () => unknown>\n | [...([string, () => unknown] | [string, number, () => unknown])],\n esmId?: string | number,\n ) {\n let mod = exports;\n if (typeof esmId === 'string' || typeof esmId === 'number') {\n if (!self.__remote_components_turbopack_modules__) {\n self.__remote_components_turbopack_modules__ = {};\n }\n if (!self.__remote_components_turbopack_modules__[bundle]) {\n self.__remote_components_turbopack_modules__[bundle] = {};\n }\n if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {\n self.__remote_components_turbopack_modules__[bundle][esmId] =\n {} as Record<string, unknown>;\n }\n mod = self.__remote_components_turbopack_modules__[bundle][\n esmId\n ] as Record<string, unknown>;\n }\n\n Object.defineProperty(mod, '__esModule', { value: true });\n if (Array.isArray(bindings)) {\n let i = 0;\n while (i < bindings.length) {\n const propName = bindings[i++] as string;\n const tagOrFunc = bindings[i++];\n if (typeof tagOrFunc === 'number') {\n Object.defineProperty(mod, propName, {\n value: bindings[i++],\n enumerable: true,\n writable: false,\n });\n } else {\n const getterFn = tagOrFunc as () => unknown;\n if (typeof bindings[i] === 'function') {\n const setterFn = bindings[i++] as (v: unknown) => unknown;\n Object.defineProperty(mod, propName, {\n get: getterFn,\n set: setterFn,\n enumerable: true,\n });\n } else {\n Object.defineProperty(mod, propName, {\n get: getterFn,\n enumerable: true,\n });\n }\n }\n }\n }\n },\n\n // import\n i(importId: string | number) {\n let mod: Record<string, unknown> | undefined;\n if (typeof importId === 'string') {\n // parse export syntax if present (e.g., \"module <export foo as bar>\")\n const { exportSource, exportName } =\n /\\s+<export (?<exportSource>.*?) as (?<exportName>.*?)>$/.exec(\n importId,\n )?.groups ?? {};\n const normalizedId = importId.replace(\n /\\s+<export(?<specifier>.*)>$/,\n '',\n );\n mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`) as\n | Record<string, unknown>\n | undefined;\n // map the requested export to the module exports\n if (\n mod &&\n exportSource &&\n exportName &&\n (exportSource === '*' || typeof mod[exportSource] !== 'undefined') &&\n typeof mod[exportName] === 'undefined'\n ) {\n if (exportSource === '*') {\n mod[exportName] = mod;\n } else {\n mod[exportName] = mod[exportSource];\n }\n }\n } else {\n mod = self.__webpack_require__?.(`[${bundle}] ${importId}`) as\n | Record<string, unknown>\n | undefined;\n }\n\n if (typeof mod !== 'object' || mod === null) {\n mod = { default: mod };\n } else if (!('default' in mod) && mod.toString() !== '[object Module]') {\n try {\n mod.default = mod;\n } catch {\n // ignore if mod is not extensible\n }\n }\n return mod;\n },\n\n // require\n r(requireId: string) {\n return self.__webpack_require__?.(`[${bundle}] ${requireId}`);\n },\n\n // value exports\n v(value: unknown) {\n if (typeof value === 'function') {\n exports.default = value((vid: string | number) => {\n return self.__webpack_require__?.(`[${bundle}] ${vid}`);\n });\n } else {\n moduleExports.exports = value as Record<string, unknown>;\n }\n },\n\n // async module initializer\n async a(\n mod: (\n handleDeps: unknown,\n setResult: (value: unknown) => void,\n ) => Promise<void>,\n ) {\n let result;\n await mod(\n () => {\n // not implemented\n },\n (value) => (result = value),\n );\n exports.default = result;\n },\n\n // async module loader\n async A(Aid: string) {\n const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`) as {\n default: (\n parentImport: (parentId: string) => unknown,\n ) => Promise<unknown>;\n };\n return mod.default((parentId: string) =>\n self.__webpack_require__?.(`[${bundle}] ${parentId}`),\n );\n },\n\n // dynamic import tracking — no-op for remote components\n j() {\n // omit\n },\n\n // chunk loader\n l(url: string) {\n // find the script tag that loaded the current module to determine base URL\n const flatModules = Array.isArray(modules) ? modules : [];\n const moduleInitIndex = flatModules.indexOf(moduleInit);\n if (moduleInitIndex !== -1) {\n const scriptIndex = flatModules\n .slice(0, moduleInitIndex)\n .findLastIndex((bundleEntry) => bundleEntry instanceof Element);\n if (scriptIndex !== -1) {\n const script = flatModules[scriptIndex] as HTMLScriptElement;\n const scriptSrc = script.getAttribute('data-turbopack-src') || '';\n const nextIndex = scriptSrc.indexOf('/_next');\n const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : '';\n const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;\n return self.__webpack_chunk_load__?.(bundleUrl, bundle);\n }\n }\n throw new Error(\n `Failed to load Turbopack chunk \"${url}\" for module \"${id}\". Check the URL is correct.`,\n );\n },\n\n // global object for this bundle\n g: self.__remote_components_turbopack_global__?.[bundle],\n m: moduleExports,\n e: exports,\n };\n}\n","import { logError } from '../utils/logger';\nimport { getBundleKey } from './const';\nimport { handleTurbopackModule } from './turbopack-module';\nimport {\n ASYNC_MODULE_ALL_RE,\n ASYNC_MODULE_LOADER_RE,\n ASYNC_MODULE_RESOLVE_RE,\n REMOTE_SHARED_ASSIGNMENT_RE,\n REMOTE_SHARED_MARKER_RE,\n} from './turbopack-patterns';\nimport type { GlobalScope } from './types';\n\n/**\n * Initializes shared modules between the host application and remote components.\n * This enables sharing of common dependencies like React to avoid duplicate instances.\n *\n * The function works by:\n * 1. Looking for a shared module initializer in the Turbopack bundle\n * 2. Extracting module IDs from the initializer\n * 3. Loading the corresponding host modules and mapping them to the remote's expected IDs\n */\nexport async function initializeSharedModules(\n bundle: string,\n hostShared: Record<string, (bundle?: string) => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n // biome-ignore lint/suspicious/noConfusingVoidType: Runtime is undefined but in TS land service it is void\n): Promise<void[]> {\n const self = globalThis as GlobalScope & {\n __next_f?: unknown[];\n };\n self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};\n\n if (!self.__remote_shared_modules__[bundle]) {\n self.__remote_shared_modules__[bundle] = {};\n }\n\n // prepare to load shared module initializers from the Turbopack bundle\n const bundleKey = getBundleKey(bundle);\n let modules = self[`TURBOPACK_${bundleKey}`] as\n | [unknown, Record<string, unknown>][]\n | Record<string, unknown>\n | undefined;\n\n // Check for new push-based format with __chunks__\n if (modules && typeof modules === 'object' && '__chunks__' in modules) {\n const chunks = (modules as { __chunks__: unknown[][] }).__chunks__;\n // Flatten chunks into module array format\n modules = chunks.flat() as [unknown, Record<string, unknown>][];\n }\n let sharedModuleInitializer: Promise<{\n shared: Record<string, string | (() => Promise<unknown>)>;\n }> | null = null;\n\n // find the shared module initializer in the Turbopack bundle\n if (modules) {\n // Handle both array and object formats for modules\n const allModules = Array.isArray(modules)\n ? modules.flat()\n : Object.entries(modules).flat();\n // find the shared module initializer module id by looking for\n // a function that contains the TURBOPACK_REMOTE_SHARED pattern\n const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {\n if (typeof idOrFunc !== 'function') {\n return false;\n }\n const funcCode = idOrFunc.toString();\n return REMOTE_SHARED_MARKER_RE.test(funcCode);\n });\n\n // if found, extract the shared module initializer\n // first element in the array is always the source script element\n if (sharedModuleInitializerIndex > 0) {\n const sharedModuleInitializerCode = (\n allModules[sharedModuleInitializerIndex] as () => unknown\n ).toString();\n const sharedModuleInitializerId = allModules[\n sharedModuleInitializerIndex - 1\n ] as string | number;\n // extract the shared module id from the function code\n const { sharedModuleId } =\n REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ??\n {};\n // load the shared module initializer using the extracted module id\n if (sharedModuleId) {\n const { default: sharedModuleInitializerInstance } =\n handleTurbopackModule(\n bundle,\n sharedModuleId,\n `[${bundle}] ${sharedModuleInitializerId}`,\n ) as {\n default: Promise<{\n shared: Record<string, string | (() => Promise<unknown>)>;\n }>;\n };\n sharedModuleInitializer = sharedModuleInitializerInstance;\n }\n }\n\n // if we have a shared module initializer, load the shared modules from the host application\n if (sharedModuleInitializer) {\n const { shared } = await sharedModuleInitializer;\n // map shared module ids to their initializer functions\n const sharedModuleIds = extractSharedModuleIds(\n shared,\n bundleKey,\n self as GlobalScope,\n );\n\n // load shared modules from the host application\n return Promise.all(\n Object.entries(sharedModuleIds).map(async ([id, module]) => {\n if (self.__remote_shared_modules__?.[bundle]) {\n if (hostShared[module]) {\n self.__remote_shared_modules__[bundle][id] =\n await hostShared[module](bundle);\n } else {\n logError(\n 'SharedModules',\n `Host shared module \"${module}\" not found for ID ${id}`,\n );\n }\n }\n }),\n );\n }\n }\n\n // fallback: ensure that the shared modules are initialized using remoteShared mapping\n return Promise.all(\n Object.entries(remoteShared).map(async ([id, module]) => {\n if (self.__remote_shared_modules__?.[bundle]) {\n if (hostShared[module]) {\n const normalizedId = id.replace('[app-ssr]', '[app-client]');\n self.__remote_shared_modules__[bundle][normalizedId] =\n await hostShared[module](bundle);\n } else {\n logError(\n 'SharedModules',\n `Shared module \"${module}\" not found for \"${bundle}\"`,\n );\n }\n }\n }),\n );\n}\n\n/**\n * Extracts shared module IDs from the shared module initializer functions.\n * This parses the minified Turbopack code to find the module ID mappings.\n */\nfunction extractSharedModuleIds(\n shared: Record<string, string | (() => Promise<unknown>)>,\n bundleKey: string,\n self: GlobalScope,\n): Record<string, string> {\n return Object.entries(shared)\n .filter(([, value]) => typeof value === 'function')\n .reduce<Record<string, string>>((acc, [key, value]) => {\n const { asyncSharedModuleId } =\n ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};\n\n if (asyncSharedModuleId) {\n const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);\n\n let asyncSharedModule;\n let turbopackModules = self[`TURBOPACK_${bundleKey}`] as\n | unknown[]\n | Record<string, unknown>\n | undefined;\n\n // Check for new push-based format with __chunks__\n if (\n turbopackModules &&\n typeof turbopackModules === 'object' &&\n '__chunks__' in turbopackModules\n ) {\n const chunks = (turbopackModules as { __chunks__: unknown[][] })\n .__chunks__;\n turbopackModules = chunks.flat() as unknown[];\n }\n\n const newAllModules = Array.isArray(turbopackModules)\n ? turbopackModules.flat()\n : turbopackModules\n ? Object.entries(turbopackModules).flatMap(([key, value]) => [\n key,\n value,\n ])\n : [];\n const asyncSharedModuleIdIndex = newAllModules.indexOf(\n asyncSharedModuleIdNumber,\n );\n if (\n asyncSharedModuleIdIndex !== -1 &&\n typeof newAllModules[asyncSharedModuleIdIndex + 1] === 'function'\n ) {\n asyncSharedModule = newAllModules[\n asyncSharedModuleIdIndex + 1\n ] as () => unknown;\n }\n if (asyncSharedModule) {\n const asyncSharedModuleCode = asyncSharedModule.toString();\n // Try both Promise.resolve and Promise.all patterns\n const { sharedModuleId } =\n ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ??\n ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ??\n {};\n // map the shared module id to the actual module name\n acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(\n '__remote_shared_module_',\n '',\n );\n }\n }\n return acc;\n }, {});\n}\n\n/**\n * Returns a shared module for the given bundle and module ID.\n * Shared modules are common dependencies like React that are provided by the host.\n */\nexport function getSharedModule(bundle: string, id: string | number): unknown {\n const self = globalThis as {\n __remote_shared_modules__?: Record<string, Record<string, unknown>>;\n };\n\n for (const [key, value] of Object.entries(\n self.__remote_shared_modules__?.[bundle] ?? {},\n )) {\n if (\n typeof value !== 'undefined' &&\n ((typeof id === 'string' && id.includes(key)) || id === key)\n ) {\n return value;\n }\n }\n return null;\n}\n","import type { InternalResolveClientUrl } from '#internal/shared/ssr/types';\nimport { RemoteComponentsError } from '../error';\nimport { logDebug, logWarn } from '../utils/logger';\nimport { createChunkLoader } from './chunk-loader';\nimport {\n REMOTE_COMPONENT_REGEX,\n RUNTIME_TURBOPACK,\n RUNTIME_WEBPACK,\n type Runtime,\n} from './const';\nimport { getSharedModule, initializeSharedModules } from './shared-modules';\nimport { handleTurbopackModule } from './turbopack-module';\nimport type { GlobalScope } from './types';\n\n/**\n * Sets up webpack runtime environment for remote components.\n * This function initializes the global webpack require and chunk loading functions\n * to support loading and executing remote component bundles.\n *\n * @param runtime - The bundler runtime type ('webpack' or 'turbopack')\n * @param scripts - Initial script chunks to load for Turbopack runtime\n * @param url - Base URL for the remote component bundle\n * @param bundle - Bundle identifier (defaults to 'default')\n * @param shared - Host-provided shared modules (e.g., React)\n * @param remoteShared - Mapping of remote module IDs to shared module names\n */\nexport async function setupWebpackRuntime(\n runtime: Runtime,\n scripts: { src: string | null }[] = [],\n url: URL = new URL(location.href),\n bundle?: string,\n shared: Record<string, () => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n resolveClientUrl?: InternalResolveClientUrl,\n): Promise<void> {\n const self = globalThis as GlobalScope;\n\n if (!self.__remote_bundle_url__) {\n self.__remote_bundle_url__ = {};\n }\n self.__remote_bundle_url__[bundle ?? 'default'] = url;\n self.__webpack_get_script_filename__ = () => null;\n\n if (\n typeof self.__webpack_require__ !== 'function' ||\n self.__webpack_require_type__ !== 'turbopack'\n ) {\n // preserve original webpack functions for fallback\n if (\n !self.__original_webpack_require__ &&\n !self.__original_webpack_chunk_load__\n ) {\n self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;\n self.__original_webpack_require__ = self.__webpack_require__;\n }\n\n self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);\n self.__webpack_require__ = createModuleRequire(runtime);\n self.__webpack_require_type__ = runtime;\n\n if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {\n const remoteBundle = bundle ?? 'default';\n self.__remote_webpack_require__[remoteBundle] =\n self.__webpack_require__ as (remoteId: string | number) => unknown;\n self.__remote_webpack_require__[remoteBundle].type = 'turbopack';\n }\n }\n\n // load all initial chunks when using Turbopack runtime\n if (runtime === RUNTIME_TURBOPACK) {\n await Promise.all(\n scripts.map((script) => {\n if (script.src) {\n return self.__webpack_chunk_load__?.(script.src, bundle);\n }\n return Promise.resolve(undefined);\n }),\n );\n }\n\n // initialize shared modules with core React dependencies\n const coreShared = {\n react: async () => (await import('react')).default,\n 'react-dom': async () => (await import('react-dom')).default,\n 'react/jsx-dev-runtime': async () =>\n (await import('react/jsx-dev-runtime')).default,\n 'react/jsx-runtime': async () =>\n (await import('react/jsx-runtime')).default,\n 'react-dom/client': async () => (await import('react-dom/client')).default,\n ...shared,\n };\n await initializeSharedModules(\n bundle ?? 'default',\n // include all core modules as shared\n coreShared,\n remoteShared,\n );\n}\n\n/**\n * Creates module require function for webpack runtime.\n * This function resolves module IDs to their exports, handling:\n * - Webpack remotes (pre-loaded bundles)\n * - Shared modules (React, etc.)\n * - Turbopack modules (dynamically loaded)\n */\nfunction createModuleRequire(runtime: Runtime): (id: string) => unknown {\n return (id: string) => {\n const self = globalThis as GlobalScope;\n const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)\n ?.groups ?? {\n bundle: 'default',\n id,\n };\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : runtime;\n\n logDebug('WebpackAdapter', `remoteRuntime: \"${remoteRuntime}\"`);\n\n try {\n // for webpack remotes, use the pre-loaded require function\n if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {\n return self.__remote_webpack_require__?.[bundle]?.(moduleId);\n }\n const sharedModuleId = moduleId ?? id;\n const sharedModule = getSharedModule(bundle ?? 'default', sharedModuleId);\n if (sharedModule) {\n return sharedModule;\n }\n if (bundle && moduleId) {\n return handleTurbopackModule(bundle, moduleId, id);\n }\n throw new Error(`Module \"${id}\" not found.`);\n } catch (requireError) {\n logWarn(\n 'WebpackAdapter',\n `Module require failed: ${String(requireError)}`,\n );\n if (typeof self.__original_webpack_require__ !== 'function') {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundle}\".`,\n {\n cause: requireError instanceof Error ? requireError : undefined,\n },\n );\n }\n try {\n logDebug('WebpackAdapter', 'Falling back to original webpack require');\n return self.__original_webpack_require__(id);\n } catch (originalError) {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundle}\".`,\n { cause: originalError instanceof Error ? originalError : undefined },\n );\n }\n }\n };\n}\n","import { generateProtectedRcFallbackSrc } from './protected-rc-fallback';\n\n/**\n * Intercepts client-side URL resolution for remote component resources.\n * Called before each asset (script, stylesheet, chunk, module, image) is fetched.\n *\n * Return a new URL string to redirect the fetch (e.g., through a proxy),\n * or undefined to use the original URL.\n *\n * @param remoteSrc - The `src` of the remote component being loaded\n * @param url - The asset URL about to be fetched\n *\n * @example\n * // Proxy all assets from the remote's origin through the host\n * const resolveClientUrl = (remoteSrc, url) => {\n * const remoteOrigin = new URL(remoteSrc).origin;\n * const parsed = new URL(url);\n * if (parsed.origin !== location.origin && parsed.origin === remoteOrigin) {\n * return `/rc-fetch-protected-remote?url=${encodeURIComponent(url)}`;\n * }\n * };\n */\nexport type ResolveClientUrl = (\n remoteSrc: string,\n url: string,\n) => string | undefined;\n\n/**\n * Internal bound resolver — `ResolveClientUrl` with `remoteSrc` already applied.\n * Used by internal loaders that don't need to know the remote src.\n */\nexport type InternalResolveClientUrl = (url: string) => string | undefined;\n\n/**\n * Binds a `ResolveClientUrl` to a specific `remoteSrc`, producing an\n * `InternalResolveClientUrl` that only needs the asset URL.\n *\n * Only invokes the callback for URLs whose origin matches the remote\n * component's origin. Third-party scripts (e.g. `vercel.live` toolbar)\n * are left untouched. To proxy additional domains in the future, a\n * field or flag can be added to the host configuration.\n */\nexport function withRemoteSrc(\n resolveClientUrl: ResolveClientUrl,\n remoteSrc: string,\n): InternalResolveClientUrl {\n const remoteOrigin = parseOrigin(remoteSrc);\n return (url) => {\n const urlOrigin = parseOrigin(url);\n if (remoteOrigin && urlOrigin && urlOrigin !== remoteOrigin) {\n return undefined;\n }\n return resolveClientUrl(remoteSrc, url);\n };\n}\n\nfunction parseOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * A `ResolveClientUrl` that proxies cross-origin asset URLs\n * through the host's protected remote fetch endpoint (`/rc-fetch-protected-remote`).\n * Same-origin URLs are left unchanged.\n *\n * On Vercel preview deployments, deployment protection blocks direct cross-origin\n * asset fetches. This function proxies those requests through the host so they\n * inherit the host's authentication cookies.\n *\n * Requires `withRemoteComponentsHost` middleware on the host to handle the\n * proxied requests. Configure `allowedProxyUrls` to restrict which URLs can\n * be proxied.\n *\n * @example\n * ```tsx\n * import { RemoteComponent, proxyClientRequestsThroughHost } from 'remote-components/react';\n *\n * <RemoteComponent\n * src=\"https://remote-app.com/components/header\"\n * resolveClientUrl={proxyClientRequestsThroughHost}\n * />\n * ```\n */\nexport const proxyClientRequestsThroughHost: ResolveClientUrl = (\n remoteSrc,\n url,\n) => {\n if (typeof location === 'undefined') {\n return undefined;\n }\n const remoteOrigin = new URL(remoteSrc, location.href).origin;\n if (remoteOrigin === location.origin) {\n return undefined;\n }\n try {\n const parsed = new URL(url, location.href);\n if (parsed.origin === remoteOrigin) {\n return generateProtectedRcFallbackSrc(url);\n }\n } catch {\n // If URL parsing fails, return undefined to use the original\n }\n return undefined;\n};\n","// extracted from Next.js source at https://github.com/vercel/next.js/blob/canary/packages/next/src/client/set-attributes-from-props.ts\n\nconst DOMAttributeNames: Record<string, string> = {\n acceptCharset: 'accept-charset',\n className: 'class',\n htmlFor: 'for',\n httpEquiv: 'http-equiv',\n noModule: 'noModule',\n};\n\nconst ignoreProps = [\n 'onLoad',\n 'onReady',\n 'dangerouslySetInnerHTML',\n 'children',\n 'onError',\n 'strategy',\n 'stylesheets',\n];\n\nfunction isBooleanScriptAttribute(\n attr: string,\n): attr is 'async' | 'defer' | 'noModule' {\n return ['async', 'defer', 'noModule'].includes(attr);\n}\n\nexport function setAttributesFromProps(el: HTMLElement, props: object) {\n for (const [p, value] of Object.entries(props)) {\n if (!Object.hasOwn(props, p)) continue;\n if (ignoreProps.includes(p)) continue;\n\n // we don't render undefined props to the DOM\n if (value === undefined) {\n continue;\n }\n\n const attr = DOMAttributeNames[p] || p.toLowerCase();\n\n if (el.tagName === 'SCRIPT' && isBooleanScriptAttribute(attr)) {\n // Correctly assign boolean script attributes\n // https://github.com/vercel/next.js/pull/20748\n (el as HTMLScriptElement)[attr] = Boolean(value);\n } else {\n el.setAttribute(attr, String(value));\n }\n\n // Remove falsy non-zero boolean attributes so they are correctly interpreted\n // (e.g. if we set them to false, this coerces to the string \"false\", which the browser interprets as true)\n if (\n value === false ||\n (el.tagName === 'SCRIPT' &&\n isBooleanScriptAttribute(attr) &&\n (!value || value === 'false'))\n ) {\n // Call setAttribute before, as we need to set and unset the attribute to override force async:\n // https://html.spec.whatwg.org/multipage/scripting.html#script-force-async\n el.setAttribute(attr, '');\n el.removeAttribute(attr);\n }\n }\n}\n","import type { InternalResolveClientUrl } from '#internal/shared/ssr/types';\nimport { logError, warnCrossOriginFetchError } from '../utils/logger';\nimport type {\n MountOrUnmountFunction,\n RemoteComponentMountUnmount,\n} from './types';\n\ntype ScriptMod = {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n default?: {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n };\n};\n\n/**\n * Fetches an ES module via the resolveClientUrl callback, rewrites its\n * relative imports to also go through the callback, then loads it by injecting a\n * wrapper <script type=\"module\"> tag. The module's namespace is captured via\n * a temporary global and returned.\n *\n * This is needed when a direct import() of a cross-origin module fails due to\n * CORS restrictions or Vercel preview-deployment auth. A simple URL rewrite\n * doesn't work for import() because relative imports inside the module would\n * resolve against the rewritten URL instead of the original remote origin.\n */\nasync function importViaCallback<T>(\n absoluteSrc: string,\n resolveClientUrl: InternalResolveClientUrl,\n): Promise<T> {\n const resolvedUrl = resolveClientUrl(absoluteSrc) ?? absoluteSrc;\n const fetchUrl = new URL(resolvedUrl, location.href).href;\n const response = await fetch(fetchUrl);\n if (!response.ok) throw new Error(`Proxied fetch failed: ${response.status}`);\n\n // Restore import.meta.url to the original module URL so any code that\n // relies on it (e.g. for asset resolution) gets the right value.\n // Rewrite relative imports to absolute URLs resolved through the callback so\n // that transitive dependencies also bypass CORS/auth.\n const content = (await response.text())\n .replace(/import\\.meta\\.url/g, JSON.stringify(absoluteSrc))\n .replace(\n /\\b(from|import)\\s*([\"'])(\\.\\.?\\/[^\"']+)\\2/g,\n (_, keyword, quote, relativePath) => {\n const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;\n const resolvedImportUrl = new URL(\n resolveClientUrl(absoluteImportUrl) ?? absoluteImportUrl,\n location.href,\n ).href;\n return `${keyword} ${quote}${resolvedImportUrl}${quote}`;\n },\n );\n const moduleBlobUrl = URL.createObjectURL(\n new Blob([content], { type: 'text/javascript' }),\n );\n const wrapperContent = [\n `import*as m from${JSON.stringify(moduleBlobUrl)};`,\n `globalThis.__rc_module_registry__=globalThis.__rc_module_registry__||{};`,\n `globalThis.__rc_module_registry__[${JSON.stringify(absoluteSrc)}]=m;`,\n ].join('');\n const wrapperBlobUrl = URL.createObjectURL(\n new Blob([wrapperContent], { type: 'text/javascript' }),\n );\n const scriptEl = document.createElement('script');\n scriptEl.type = 'module';\n scriptEl.src = wrapperBlobUrl;\n try {\n await new Promise<void>((resolve, reject) => {\n scriptEl.onload = () => resolve();\n scriptEl.onerror = () =>\n reject(new Error(`Failed to load module for ${absoluteSrc}`));\n document.head.appendChild(scriptEl);\n });\n } finally {\n scriptEl.remove();\n URL.revokeObjectURL(moduleBlobUrl);\n URL.revokeObjectURL(wrapperBlobUrl);\n }\n const registry = (\n globalThis as unknown as { __rc_module_registry__?: Record<string, T> }\n ).__rc_module_registry__;\n const mod = registry?.[absoluteSrc] ?? ({} as T);\n if (registry) delete registry[absoluteSrc];\n return mod;\n}\n\nasync function importDirectly<T>(absoluteSrc: string): Promise<T> {\n try {\n return (await import(\n /* @vite-ignore */\n /* webpackIgnore: true */ absoluteSrc\n )) as T;\n } catch (importError) {\n if (!absoluteSrc.startsWith('blob:')) {\n warnCrossOriginFetchError('StaticLoader', absoluteSrc);\n }\n throw importError;\n }\n}\n\nfunction resolveScriptSrc(script: HTMLScriptElement, url: URL): string {\n const rawSrc =\n typeof script.getAttribute === 'function'\n ? (script.getAttribute('src') ?? script.src)\n : script.src;\n if (!rawSrc && script.textContent) {\n return URL.createObjectURL(\n new Blob(\n [script.textContent.replace(/import\\.meta\\.url/g, JSON.stringify(url))],\n { type: 'text/javascript' },\n ),\n );\n }\n return rawSrc;\n}\n\nexport async function loadStaticRemoteComponent(\n scripts: HTMLScriptElement[],\n url: URL,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n const self = globalThis as typeof globalThis & RemoteComponentMountUnmount;\n if (self.__remote_script_entrypoint_mount__?.[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n if (self.__remote_script_entrypoint_unmount__?.[url.href]) {\n self.__remote_script_entrypoint_unmount__[url.href] = new Set();\n }\n const mountUnmountSets = await Promise.all(\n scripts.map(async (script) => {\n try {\n const src = resolveScriptSrc(script, url);\n const absoluteSrc = new URL(src, url).href;\n const mod: ScriptMod = resolveClientUrl\n ? await importViaCallback<ScriptMod>(absoluteSrc, resolveClientUrl)\n : await importDirectly<ScriptMod>(absoluteSrc);\n // revoke the object URL if we created one for inline script content\n if (src.startsWith('blob:')) {\n URL.revokeObjectURL(src);\n }\n if (\n typeof mod.mount === 'function' ||\n typeof mod.default?.mount === 'function'\n ) {\n if (!self.__remote_script_entrypoint_mount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_mount__ = {};\n }\n if (!self.__remote_script_entrypoint_mount__[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_mount__[url.href]?.add(\n mod.mount ||\n mod.default?.mount ||\n (() => {\n // noop\n }),\n );\n }\n if (\n typeof mod.unmount === 'function' ||\n typeof mod.default?.unmount === 'function'\n ) {\n if (!self.__remote_script_entrypoint_unmount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_unmount__ = {};\n }\n if (!self.__remote_script_entrypoint_unmount__[url.href]) {\n self.__remote_script_entrypoint_unmount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_unmount__[url.href]?.add(\n mod.unmount ||\n mod.default?.unmount ||\n (() => {\n // noop\n }),\n );\n }\n return {\n mount: mod.mount || mod.default?.mount,\n unmount: mod.unmount || mod.default?.unmount,\n };\n } catch (e) {\n logError(\n 'StaticLoader',\n `Error loading remote component script from \"${script.src || url.href}\".`,\n e,\n );\n return {\n mount: undefined,\n unmount: undefined,\n };\n }\n }),\n );\n return mountUnmountSets.reduce(\n (acc, { mount, unmount }) => {\n if (typeof mount === 'function') {\n acc.mount.add(mount);\n }\n if (typeof unmount === 'function') {\n acc.unmount.add(unmount);\n }\n return acc;\n },\n {\n mount: new Set<MountOrUnmountFunction>(),\n unmount: new Set<MountOrUnmountFunction>(),\n },\n );\n}\n","/**\n * The lifecycle stages a host progresses through during a load cycle.\n *\n * ```\n * ┌─────────────────────────┐\n * │ (new load) │\n * ▼ │\n * idle ──▶ loading ──▶ loaded ─────────┘\n * ▲ │ │\n * │ ▼ │ (new load)\n * │ error ─────────┘\n * │\n * └── loading (abandoned / aborted)\n * ```\n *\n * - `idle` — No load has started, or a previous load was abandoned.\n * - `loading` — A fetch or hydration is in progress.\n * - `loaded` — The remote component rendered successfully.\n * - `error` — The load failed (the error itself is surfaced separately).\n *\n * Any non-idle stage transitions directly to `loading` when a new load starts.\n */\nexport type HostStage = 'idle' | 'loading' | 'loaded' | 'error';\n\n/**\n * Mutable state shared by every host implementation (HTML, React, Next.js\n * App Router).\n *\n * Each host stores a single `HostState` instance rather than scattering\n * individual properties/refs. This keeps the \"what changed since the last\n * load?\" tracking consistent across frameworks and makes it easy to test\n * state transitions in isolation.\n */\nexport interface HostState {\n /** Current lifecycle stage. */\n stage: HostStage;\n\n /** Source from the most-recent load. `undefined` before the first load. */\n prevSrc: string | URL | undefined;\n\n /** Resolved URL from the most-recent load. `undefined` before the first load. */\n prevUrl: URL | undefined;\n\n /** Component name from the most-recent load. `undefined` before the first load. */\n prevName: string | undefined;\n\n /** Whether the most-recent load was a remote component (vs. a plain page). */\n prevIsRemoteComponent: boolean;\n\n /**\n * `AbortController` for the in-flight load. Abort it to cancel a\n * superseded fetch. `undefined` when no load is active.\n */\n abortController: AbortController | undefined;\n}\n\n/** Creates a fresh `HostState` with all fields at their initial values. */\nexport function createHostState(): HostState {\n return {\n stage: 'idle',\n prevSrc: undefined,\n prevUrl: undefined,\n prevName: undefined,\n prevIsRemoteComponent: false,\n abortController: undefined,\n };\n}\n","/**\n * Extracts a component name from the URL hash of `src`, falling back to\n * `defaultName` when no hash is present.\n *\n * Both the HTML and React hosts use this to derive the component name\n * from patterns like `/components/header#my-component`.\n *\n * Parses the hash directly from the string rather than constructing a\n * full `URL`, so no SSR fallback base is needed.\n */\nexport function resolveNameFromSrc(\n src: string | URL | undefined,\n defaultName: string,\n): string {\n if (!src) {\n return defaultName;\n }\n\n const hash = typeof src === 'string' ? src : src.hash;\n const hashIndex = hash.indexOf('#');\n if (hashIndex < 0) {\n return defaultName;\n }\n\n const name = hash.slice(hashIndex + 1);\n return name || defaultName;\n}\n","/**\n * The headers to use when fetching the remote component.\n */\nexport function remoteFetchHeaders() {\n return {\n /**\n * Authenticates deployment protection for the remote. Needed for SSR and SSG clients.\n * If the remote component uses vercel deployment protection, ensure the host and remote vercel\n * projects share a common automation bypass secret, and the shared secret is used as the\n * VERCEL_AUTOMATION_BYPASS_SECRET env var in the host project.\n */\n ...(typeof process === 'object' &&\n typeof process.env === 'object' &&\n typeof process.env.VERCEL_AUTOMATION_BYPASS_SECRET === 'string'\n ? {\n 'x-vercel-protection-bypass':\n process.env.VERCEL_AUTOMATION_BYPASS_SECRET,\n }\n : {}),\n Accept: 'text/html',\n };\n}\n","import { warnCrossOriginFetchError } from '#internal/shared/utils/logger';\nimport { remoteFetchHeaders } from './fetch-headers';\nimport type { HookOptions, OnRequestHook, OnResponseHook } from './types';\n\n/**\n * Options for fetching with request/response hooks.\n */\nexport interface FetchWithHooksOptions {\n /** Hook to intercept the request before fetching */\n onRequest?: OnRequestHook;\n /** Hook to process the response after fetching */\n onResponse?: OnResponseHook;\n /** AbortController to cancel loading - aborts will throw AbortError */\n abortController?: AbortController;\n}\n\n/**\n * Performs a fetch with optional request and response lifecycle hooks.\n *\n * This utility centralizes the logic for:\n * 1. Calling onRequest hook - if it returns a Response, use it instead of fetching\n * 2. Performing the actual fetch if onRequest didn't provide a response\n * 3. Calling onResponse hook - if it returns a Response, use that transformed response\n *\n * Hooks receive an AbortSignal and abort function to cancel loading at any point.\n * When aborted, throws AbortError (DOMException with name 'AbortError').\n *\n * @param url - The URL to fetch\n * @param init - The fetch init options\n * @param options - Optional hooks for request/response interception and AbortController\n * @returns The response (never null - throws on abort)\n * @throws DOMException with name 'AbortError' if loading is aborted\n *\n * @example\n * const controller = new AbortController();\n * try {\n * const response = await fetchWithHooks(url, fetchInit, {\n * abortController: controller,\n * onResponse: async (url, response, { abort }) => {\n * if (response.redirected) {\n * abort(); // Throws AbortError\n * }\n * },\n * });\n * } catch (error) {\n * if (error.name === 'AbortError') {\n * console.log('Loading was aborted');\n * }\n * }\n */\nexport async function fetchWithHooks(\n url: URL,\n additionalInit: {\n credentials?: RequestCredentials;\n next?: {\n tags?: string[];\n };\n },\n options: FetchWithHooksOptions = {},\n): Promise<Response> {\n const {\n onRequest,\n onResponse,\n abortController = new AbortController(),\n } = options;\n const signal = abortController.signal;\n\n const hookOptions: HookOptions = {\n signal,\n abort: (reason?: unknown) => abortController.abort(reason),\n };\n\n // Include signal in fetch init for reactive abort support\n const init: RequestInit = {\n method: 'GET',\n headers: remoteFetchHeaders(),\n signal,\n ...additionalInit,\n };\n\n // Call onRequest hook if provided - may return a Response to skip fetching\n let res = await onRequest?.(url, init, hookOptions);\n\n if (!res) {\n try {\n res = await fetch(url, init);\n } catch (error) {\n warnCrossOriginFetchError('FetchRemoteComponent', url);\n throw error;\n }\n }\n\n // Call onResponse hook if provided - may return a transformed Response\n const transformedRes = await onResponse?.(url, res, hookOptions);\n\n if (transformedRes) {\n res = transformedRes;\n }\n\n return res;\n}\n","export function getClientOrServerUrl(\n src: string | URL | undefined,\n serverFallback: string,\n): URL {\n const fallback =\n typeof location !== 'undefined' ? location.href : serverFallback;\n\n if (!src) {\n return new URL(fallback);\n }\n\n return typeof src === 'string' ? new URL(src, fallback) : src;\n}\n","import { useMemo } from 'react';\nimport { useRemoteComponentsContext } from '#internal/react/context';\nimport { bindResolveClientUrl } from '#internal/shared/client/default-resolve-client-url';\nimport type { ResolveClientUrl } from '#internal/shared/client/proxy-through-host';\n\nexport function useResolveClientUrl(\n prop: ResolveClientUrl | undefined,\n urlHref: string,\n) {\n const { resolveClientUrl: contextValue } = useRemoteComponentsContext();\n const resolveClientUrl = prop ?? contextValue;\n return useMemo(\n () => bindResolveClientUrl(resolveClientUrl, urlHref),\n [resolveClientUrl, urlHref],\n );\n}\n","import {\n type InternalResolveClientUrl,\n type ResolveClientUrl,\n withRemoteSrc,\n} from './proxy-through-host';\n\nexport function bindResolveClientUrl(\n prop: ResolveClientUrl | undefined,\n remoteSrc: string,\n): InternalResolveClientUrl | undefined {\n return prop ? withRemoteSrc(prop, remoteSrc) : undefined;\n}\n","import { useLayoutEffect, useRef, useState } from 'react';\n\nexport interface GlobalThis {\n [key: `__remote_components_shadowroot_${string}`]: ShadowRoot | null;\n}\n\ninterface UseShadowRootOptions {\n /** Whether CSS isolation is enabled */\n isolate: boolean | undefined;\n /** Shadow DOM mode */\n mode: 'open' | 'closed';\n /** Unique key suffix for identifying this shadow root */\n keySuffix: string;\n}\n\ninterface UseShadowRootResult {\n /** The shadow root element, or null if not isolated */\n shadowRoot: ShadowRoot | null;\n /** Ref to attach to the shadow host container element */\n shadowRootContainerRef: React.RefObject<HTMLDivElement | null>;\n}\n\n/**\n * Manages shadow root lifecycle for CSS isolation.\n *\n * Handles:\n * - Initial shadow root discovery from SSR or declarative shadow DOM\n * - Creating shadow root as fallback for browsers without declarative shadow DOM support\n * - Cleanup when isolation is disabled\n * - Re-attachment when isolation is re-enabled\n */\nexport function useShadowRoot({\n isolate,\n mode,\n keySuffix,\n}: UseShadowRootOptions): UseShadowRootResult {\n const shadowRootContainerRef = useRef<HTMLDivElement | null>(null);\n\n const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(() => {\n const self = globalThis as unknown as GlobalThis;\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n const ssrShadowRoot =\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot ??\n self[shadowRootKey] ??\n null)\n : null;\n // Clear the global reference after reading it\n self[shadowRootKey] = null;\n return ssrShadowRoot;\n });\n\n useLayoutEffect(() => {\n if (\n isolate !== false &&\n typeof document !== 'undefined' &&\n (!shadowRoot || !shadowRoot.isConnected)\n ) {\n const self: GlobalThis = globalThis;\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n\n let shadowRootElement: ShadowRoot | null = null;\n const element = document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n );\n shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;\n\n if (!shadowRootElement && element) {\n // Create a shadow root if it doesn't exist.\n // This is a fallback for browsers that don't support declarative shadow DOM.\n try {\n shadowRootElement = element.attachShadow({ mode });\n self[shadowRootKey] = shadowRootElement;\n } catch {\n // Do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n // Remove all nodes from the shadow root except links (preserves stylesheets)\n shadowRootElement.querySelectorAll('*:not(link)').forEach((node) => {\n node.remove();\n });\n setShadowRoot(shadowRootElement);\n }\n } else if (isolate === false && shadowRoot) {\n // Clear the global cache when disabling isolation (only when explicitly false)\n const self: GlobalThis = globalThis;\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n self[shadowRootKey] = null;\n setShadowRoot(null);\n }\n }, [isolate, shadowRoot, mode, keySuffix]);\n\n return { shadowRoot, shadowRootContainerRef };\n}\n","/**\n * Dummy URL used as a fallback base for URL parsing when no real base URL is available.\n * This is used during SSR or when location is not defined.\n */\nexport const DUMMY_FALLBACK = 'http://remote-components-dummy-fallback';\n\n/**\n * Extracts the relevant HTML content from a remote component response.\n *\n * Handles multiple remote component formats:\n * - Next.js Pages Router SSR wrapper (`div[id^=\"__REMOTE_COMPONENT\"]`)\n * - App Router remote components (`div[data-bundle][data-route]`)\n * - Next.js pages (`div#__next`)\n * - Web component format (`remote-component:not([src])`)\n *\n * @param html - Raw HTML string from the remote component response\n * @returns Extracted HTML content with links and scripts, or empty string if not found\n */\nexport function getRemoteComponentHtml(html: string): string {\n if (typeof document === 'undefined') return html;\n\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 from various sources\n const remoteComponentContainer = temp.querySelectorAll(\n `div[data-bundle][data-route][data-runtime][id^=\"__vercel_remote_component\"],div[data-bundle][data-route],div#__next,remote-component:not([src])`,\n );\n if (remoteComponentContainer.length > 0) {\n return `${Array.from(temp.querySelectorAll('link,script'))\n .map((link) => link.outerHTML)\n .join('')}${Array.from(remoteComponentContainer)\n .map((container) => container.outerHTML)\n .join('')}`;\n }\n\n return '';\n}\n","import type { NavigateOptions } from 'next/dist/shared/lib/app-router-context.shared-runtime';\nimport type { default as ImageComponentType, ImageProps } from 'next/image';\nimport { usePathname, useSearchParams } from 'next/navigation';\nimport { applyBundleUrlToImagePropsSrc } from '#internal/shared/client/polyfill';\nimport { logWarn } from '../../shared/utils/logger';\n\nexport function imageImpl(\n ImageComponent: typeof ImageComponentType,\n bundle: string,\n) {\n const component = function RemoteImage(props: ImageProps) {\n return (\n <ImageComponent\n {...props}\n src={applyBundleUrlToImagePropsSrc(bundle, props.src)}\n />\n );\n };\n component.default = component;\n return component;\n}\n\nexport const routerImpl = async () => {\n const { useRouter } = await import('next/navigation');\n return Promise.resolve({\n useRouter: () => {\n const router = useRouter();\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const query = Object.fromEntries(searchParams.entries());\n return {\n pathname,\n query,\n asPath: searchParams.toString()\n ? `${pathname}?${searchParams.toString()}`\n : pathname,\n push: (href: string, _: string, options?: NavigateOptions) => {\n router.push(href, options);\n return Promise.resolve(true);\n },\n replace: (href: string, _: string, options?: NavigateOptions) => {\n router.replace(href, options);\n return Promise.resolve(true);\n },\n refresh: () => Promise.resolve(router.refresh()),\n prefetch: async () => {\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.prefetch() in a remote component loaded in the Next.js App Router. prefetch() is a no-op in the App Router.',\n );\n return Promise.resolve();\n },\n back: () => {\n // there's no back() in the App Router\n if (typeof window !== 'undefined') {\n window.history.back();\n }\n },\n reload: () => {\n router.refresh();\n },\n beforePopState: () => {\n // there's no beforePopState() in the App Router\n },\n events: {\n on: () => {\n // there's no router.events in the App Router\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.events.on() in a remote component loaded in the Next.js App Router. events.on() is a no-op in the App Router.',\n );\n },\n off: () => {\n // there's no router.events in the App Router\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.events.off() in a remote component loaded in the Next.js App Router. events.off() is a no-op in the App Router.',\n );\n },\n emit: () => {\n // there's no router.events in the App Router\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.events.emit() in a remote component loaded in the Next.js App Router. events.emit() is a no-op in the App Router.',\n );\n },\n },\n };\n },\n });\n};\n"],"mapp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EtB;AAAA,QACA,QAAQ;AAAA,UACN,IAAI,MAAM;AAER;AAAA,cACE;AAAA,cACA;AAAA,YACF;AAAA,UACF;AAAA,UACA,KAAK,MAAM;AAET;AAAA,cACE;AAAA,cACA;AAAA,YACF;AAAA,UACF;AAAA,UACA,MAAM,MAAM;AAEV;AAAA,cACE;AAAA,cACA;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;;;AnCrCI,IAAAC,sBAAA;AAzCJ,eAAe,kBAAkB;AAC/B,MAAI;AACF,UAAM,EAAE,OAAO,IAAI,MAAM,OAAO,mCAAmC;AACnE,WAAO;AAAA,EACT,QAAE;AACA,WAAO,CAAC;AAAA,EACV;AACF;AAEA,IAAM,gBAAgB,OAAO,eAAgD;AAC3E,QAAM,CAAC,gBAAgB,kBAAkB,IAAI,MAAM,QAAQ,IAAI;AAAA,IAC7D,gBAAgB;AAAA,IAChB,cAAc,QAAQ,QAAQ,CAAC,CAAC;AAAA,EAClC,CAAC;AAED,SAAO;AAAA,IACL,GAAG;AAAA,IACH,eAAe;AAAA,IACf,cAAc,CAAC,WACb,QAAQ,QAAQC,WAAgB,eAAS,UAAU,SAAS,CAAC;AAAA,IAC/D,oCAAoC,CAAC,WACnC,QAAQ,QAAQ,EAAE,OAAOA,WAAgB,eAAS,UAAU,SAAS,EAAE,CAAC;AAAA,IAC1E,GAAG;AAAA,EACL;AACF;AAWO,SAASC,iBAAgB,OAA6B;AAC3D,MAAI,OAAO,MAAM,QAAQ,YAAY,EAAE,MAAM,eAAe,MAAM;AAChE,WAAO,MAAM,YAAY;AAAA,EAC3B;AAEA,SACE,6CAAC,mBAAsB,GAAG,OAAO,QAAQ,cAAc,MAAM,MAAM,GAAG;AAE1E;","names":["RemoteComponent","import_react","location","location","module","module","key","value","import_react","import_context","import_jsx_runtime","import_react","import_context","import_jsx_runtime","imageImpl","import_jsx_runtime","imageImpl","RemoteComponent"]}
|