remote-components 0.0.37 → 0.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/html/host.cjs +78 -0
- package/dist/html/host.cjs.map +1 -1
- package/dist/html/host.js +78 -0
- package/dist/html/host.js.map +1 -1
- package/dist/internal/next/host/app-router-client.cjs +5 -1
- package/dist/internal/next/host/app-router-client.cjs.map +1 -1
- package/dist/internal/next/host/app-router-client.js +5 -1
- 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 -0
- package/dist/internal/next/remote/render-server.js.map +1 -1
- package/dist/internal/shared/client/get-client-src.cjs +39 -0
- package/dist/internal/shared/client/get-client-src.cjs.map +1 -0
- package/dist/internal/shared/client/get-client-src.d.ts +7 -0
- package/dist/internal/shared/client/get-client-src.js +15 -0
- package/dist/internal/shared/client/get-client-src.js.map +1 -0
- package/dist/internal/shared/ssr/fetch-remote-component.cjs +14 -10
- package/dist/internal/shared/ssr/fetch-remote-component.cjs.map +1 -1
- package/dist/internal/shared/ssr/fetch-remote-component.js +14 -10
- package/dist/internal/shared/ssr/fetch-remote-component.js.map +1 -1
- package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.cjs +34 -0
- package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.cjs.map +1 -0
- package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.d.ts +10 -0
- package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.js +10 -0
- package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.js.map +1 -0
- package/dist/next/host/client/index.cjs +41 -2
- package/dist/next/host/client/index.cjs.map +1 -1
- package/dist/next/host/client/index.d.ts +13 -0
- package/dist/next/host/client/index.js +41 -2
- package/dist/next/host/client/index.js.map +1 -1
- package/dist/react/index.cjs +41 -2
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.ts +14 -1
- package/dist/react/index.js +41 -2
- package/dist/react/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -37,6 +37,7 @@ var Image = __toESM(require("next/image"), 1);
|
|
|
37
37
|
var import_react = require("react");
|
|
38
38
|
var import_react_dom = require("react-dom");
|
|
39
39
|
var import_app_router_compat = require("#internal/next/host/app-router-compat");
|
|
40
|
+
var import_get_client_src = require("#internal/shared/client/get-client-src");
|
|
40
41
|
var import_remote_component = require("#internal/shared/client/remote-component");
|
|
41
42
|
var import_get_client_or_server_url = require("#internal/shared/ssr/get-client-or-server-url");
|
|
42
43
|
var import_utils = require("#internal/shared/utils");
|
|
@@ -290,6 +291,7 @@ function RemoteComponentClient({
|
|
|
290
291
|
{
|
|
291
292
|
link,
|
|
292
293
|
url,
|
|
294
|
+
serverUrl,
|
|
293
295
|
"data-wait": link.rel === "stylesheet" && link.href ? "" : void 0
|
|
294
296
|
},
|
|
295
297
|
JSON.stringify(link)
|
|
@@ -298,6 +300,7 @@ function RemoteComponentClient({
|
|
|
298
300
|
RenderLink,
|
|
299
301
|
{
|
|
300
302
|
link,
|
|
303
|
+
serverUrl,
|
|
301
304
|
url,
|
|
302
305
|
as: "style",
|
|
303
306
|
fetchPriority: "high",
|
|
@@ -378,6 +381,7 @@ function RemoteComponentClient({
|
|
|
378
381
|
function RenderLink({
|
|
379
382
|
link,
|
|
380
383
|
url,
|
|
384
|
+
serverUrl,
|
|
381
385
|
...rest
|
|
382
386
|
}) {
|
|
383
387
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
@@ -392,7 +396,7 @@ function RenderLink({
|
|
|
392
396
|
},
|
|
393
397
|
{}
|
|
394
398
|
),
|
|
395
|
-
href:
|
|
399
|
+
href: (0, import_get_client_src.getClientSrc)(link.href, serverUrl),
|
|
396
400
|
...rest
|
|
397
401
|
}
|
|
398
402
|
);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/next/host/app-router-client.tsx"],"sourcesContent":["'use client';\n\nimport * as Image from 'next/image';\nimport {\n startTransition,\n useEffect,\n useId,\n useLayoutEffect,\n useRef,\n useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { imageImpl, routerImpl } from '#internal/next/host/app-router-compat';\nimport type { RemoteComponentProps } from '#internal/shared/client/remote-component';\nimport {\n DEFAULT_ROUTE,\n loadRemoteComponent,\n loadStaticRemoteComponent,\n RUNTIME_WEBPACK,\n} from '#internal/shared/client/remote-component';\nimport type { MountOrUnmountFunction } from '#internal/shared/client/types';\nimport { getClientOrServerUrl } from '#internal/shared/ssr/get-client-or-server-url';\nimport { attrToProp, escapeString } from '#internal/shared/utils';\n\n// patch react/jsx-runtime to support the shadowrootmode attribute on template elements\ndeclare module 'react/jsx-runtime' {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace JSX {\n interface IntrinsicElements {\n template: {\n shadowrootmode?: 'open' | 'closed';\n id?: string;\n ref?: React.Ref<HTMLTemplateElement>;\n dangerouslySetInnerHTML?: {\n __html: string;\n };\n children?: React.ReactNode;\n };\n }\n }\n}\n\n// import { shared } from 'remote-components/shared/host';\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\n/**\n * RemoteComponentClient - Main component for rendering remote components\n *\n * This component handles the loading and rendering of remote microfrontends.\n * It supports both RSC (React Server Components) and Next.js Pages Router based components.\n */\nexport function RemoteComponentClient({\n src,\n serverUrl,\n name,\n bundle,\n route = DEFAULT_ROUTE,\n runtime = RUNTIME_WEBPACK,\n data,\n nextData,\n scripts = [],\n links = [],\n remoteShared = {},\n isolate,\n mode = 'open',\n reset,\n type,\n children,\n}: RemoteComponentProps) {\n const remoteComponentId = useId();\n const [component, setComponent] = useState<React.ReactNode | Error>(null);\n const url = getClientOrServerUrl(src, serverUrl);\n const metadataRef = useRef<{\n name: string;\n bundle: string;\n route: string;\n url: string;\n loading: boolean;\n }>({\n name,\n bundle,\n route,\n url: url.href,\n loading: false,\n });\n const startRef = useRef<HTMLTemplateElement | null>(null);\n const endRef = useRef<HTMLTemplateElement | null>(null);\n const prevRemoteComponentUnmountRef = useRef<{\n unmount: Set<MountOrUnmountFunction>;\n root: ShadowRoot | DocumentFragment | null;\n } | null>(null);\n\n // Handle errors by re-throwing them\n if (component instanceof Error) {\n throw component;\n }\n\n // determine whether to use children or loaded component\n const shouldUseChildren =\n (!component ||\n (component &&\n !nextData &&\n type !== 'remote-component' &&\n typeof (component as unknown as Promise<unknown>).then !==\n 'function')) &&\n // if the remote Next.js Pages Router application is in development mode\n // we don't use the provided static HTML\n // to mitigate layout shift when loading CSS using JavaScript on the client\n nextData?.buildId !== 'development';\n\n // The pathname is used so this URL is the same across server and client requests for relative src's\n const keySuffix = `${escapeString(bundle)}_${escapeString(\n url.pathname,\n )}_${escapeString(name)}`;\n\n const self = globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n > &\n Record<`__remote_components_container_${string}`, HTMLDivElement | null>;\n const shadowRootKey = `__remote_components_shadowroot_${keySuffix}` as const;\n const shadowContainerRef = useRef<HTMLDivElement | null>(\n typeof document === 'undefined'\n ? null\n : document.querySelector(\n `[data-remote-component-id=\"shadowroot_${remoteComponentId}\"]`,\n ),\n );\n const shadowRootRef = useRef<ShadowRoot | null>(\n self[shadowRootKey] ?? shadowContainerRef.current?.shadowRoot ?? null,\n );\n const ssrShadowRootContentRef = useRef<NodeListOf<ChildNode> | null>(\n shadowRootRef.current?.querySelectorAll('*') ?? null,\n );\n const ssrLinksStylesRef = useRef<(HTMLLinkElement | HTMLStyleElement)[]>([]);\n\n if (self[shadowRootKey] && shadowRootRef.current) {\n self[shadowRootKey] = null;\n }\n\n useLayoutEffect(() => {\n if (\n !shadowContainerRef.current ||\n shadowContainerRef.current !== shadowRootRef.current?.host\n ) {\n shadowRootRef.current = null;\n }\n\n if (\n isolate !== false &&\n typeof document !== 'undefined' &&\n !shadowRootRef.current\n ) {\n let shadowRootElement: ShadowRoot | null = null;\n const element = shadowContainerRef.current;\n\n shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;\n self[shadowRootKey] = 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 } catch {\n // do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n shadowRootRef.current = shadowRootElement;\n }\n }\n\n if (\n shadowRootRef.current &&\n ssrShadowRootContentRef.current &&\n !shouldUseChildren\n ) {\n // remove all nodes from the shadow root except links\n ssrShadowRootContentRef.current.forEach((node) => {\n if (node.nodeName !== 'LINK' && node.nodeName !== 'STYLE') {\n node.parentNode?.removeChild(node);\n } else {\n ssrLinksStylesRef.current.push(\n node as HTMLLinkElement | HTMLStyleElement,\n );\n }\n });\n ssrShadowRootContentRef.current = null;\n }\n\n if (ssrLinksStylesRef.current.length > 0 && shadowRootRef.current) {\n const waitForLoad =\n shadowRootRef.current.querySelectorAll('link[data-wait]');\n if (waitForLoad.length > 0) {\n Promise.all(\n Array.from(waitForLoad).map(\n (link) =>\n new Promise<void>((resolve) => {\n link.addEventListener('load', () => resolve());\n link.addEventListener('error', () => resolve());\n }),\n ),\n )\n .then(() => {\n waitForLoad.forEach((el) => {\n el.removeAttribute('data-wait');\n });\n\n // remove SSR injected styles and links\n ssrLinksStylesRef.current.forEach((el) => {\n el.parentNode?.removeChild(el);\n });\n ssrLinksStylesRef.current = [];\n })\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n });\n }\n }\n }, [isolate, mode, self, shadowRootKey, shouldUseChildren]);\n\n useEffect(() => {\n // run unmount functions when the component changes or unmounts\n if (prevRemoteComponentUnmountRef.current && component !== children) {\n const { unmount, root } = prevRemoteComponentUnmountRef.current;\n prevRemoteComponentUnmountRef.current = null;\n Promise.all(\n Array.from(unmount).map(async (unmountFn) => {\n try {\n await unmountFn(root);\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(e);\n }\n }),\n ).catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n });\n }\n }, [component, children]);\n\n useEffect(() => {\n startTransition(async () => {\n try {\n // if we have a component, we don't need to load it again\n if (\n (!metadataRef.current.loading &&\n !component &&\n (isolate === false || shadowRootRef.current)) ||\n metadataRef.current.url !== url.href ||\n metadataRef.current.name !== name ||\n metadataRef.current.bundle !== bundle ||\n metadataRef.current.route !== route\n ) {\n metadataRef.current = {\n name,\n bundle,\n route,\n url: url.href,\n loading: true,\n };\n\n // use the children as the component when type is remote-component\n if (type === 'remote-component') {\n setComponent(children);\n // load static scripts and execute mount functions\n // run this async but don't await it as we render children immediately\n loadStaticRemoteComponent(scripts as HTMLScriptElement[], url)\n .then(({ mount, unmount }) => {\n if (mount.size > 0) {\n let root: ShadowRoot | DocumentFragment | null =\n shadowRootRef.current;\n try {\n if (!root && startRef.current && endRef.current) {\n root = document.querySelectorAll(\n `#${startRef.current.id} ~ *:not(#${endRef.current.id}):has(~ #${endRef.current.id})`,\n ) as unknown as DocumentFragment;\n }\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(e);\n }\n if (unmount.size > 0) {\n prevRemoteComponentUnmountRef.current = { unmount, root };\n }\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(root)),\n );\n }\n })\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n setComponent(e as Error);\n });\n return;\n }\n\n const rscName = `__remote_components_rsc_${keySuffix}`;\n const result = await loadRemoteComponent({\n url,\n name,\n bundle,\n route,\n runtime,\n rscName,\n data,\n nextData,\n scripts,\n shared: (async () => {\n const shared = await tryImportShared();\n\n if ('__remote_components_missing_shared__' in shared) {\n await shared.__remote_components_missing_shared__();\n }\n\n return {\n 'next/router': routerImpl,\n ...shared,\n 'next/image': () =>\n Promise.resolve(imageImpl(Image.default, bundle)),\n 'next/dist/client/image-component': () =>\n Promise.resolve({ Image: imageImpl(Image.default, bundle) }),\n };\n })(),\n remoteShared,\n container: shadowRootRef.current,\n });\n metadataRef.current.loading = false;\n if (result.error) {\n setComponent(result.error);\n } else {\n setComponent(result.component);\n }\n }\n } catch (error: unknown) {\n metadataRef.current.loading = false;\n setComponent(error as Error);\n }\n });\n }, [\n component,\n name,\n bundle,\n route,\n runtime,\n scripts,\n data,\n nextData,\n remoteShared,\n children,\n isolate,\n type,\n keySuffix,\n url,\n ]);\n\n if (\n nextData?.buildId === 'development' &&\n shadowRootRef.current &&\n isolate !== false &&\n reset &&\n !shadowRootRef.current.querySelector('[data-remote-components-reset]')\n ) {\n // inject reset styles into the shadow root\n const style = document.createElement('style');\n style.setAttribute('data-remote-components-reset', '');\n style.textContent = `:host { all: initial; }`;\n shadowRootRef.current.insertBefore(style, shadowRootRef.current.firstChild);\n } else if (\n shadowRootRef.current &&\n isolate !== false &&\n !reset &&\n shadowRootRef.current.querySelector('[data-remote-components-reset]')\n ) {\n // ensure reset styles are the first child in the shadow root\n const style = shadowRootRef.current.querySelector(\n '[data-remote-components-reset]',\n );\n if (style && shadowRootRef.current.firstChild !== style) {\n shadowRootRef.current.removeChild(style);\n }\n }\n\n const linksToRender = (\n <>\n {(!nextData || nextData.buildId !== 'development') &&\n isolate !== false &&\n reset ? (\n <style data-remote-components-reset=\"\">{`:host { all: initial; }`}</style>\n ) : null}\n {links.map((link) => (\n <RenderLink\n key={JSON.stringify(link)}\n link={link}\n url={url}\n data-wait={link.rel === 'stylesheet' && link.href ? '' : undefined}\n />\n ))}\n {links\n .filter((link) => link.rel === 'stylesheet')\n .map((link) => (\n <RenderLink\n key={JSON.stringify(link)}\n link={link}\n url={url}\n as=\"style\"\n fetchPriority=\"high\"\n precedence={bundle}\n rel=\"preload\"\n />\n ))}\n </>\n );\n\n let componentToRender = shouldUseChildren\n ? children\n : (component as React.ReactNode);\n\n if (isolate !== false) {\n componentToRender = (\n <div\n data-remote-component-id={`shadowroot_${remoteComponentId}`}\n data-remote-component-isolation-root=\"\"\n id={`shadowroot_${name}`}\n ref={shadowContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {mode === 'closed' ? (\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.${shadowRootKey} = root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {linksToRender}\n {shouldUseChildren ? children : null}\n </template>\n ) : null}\n {typeof document !== 'undefined' &&\n shadowRootRef.current &&\n !shouldUseChildren\n ? createPortal(\n <>\n {linksToRender}\n {componentToRender}\n </>,\n shadowRootRef.current,\n )\n : null}\n </div>\n );\n }\n\n return (\n <>\n {isolate === false ? (\n <template id={`${name}_start`} ref={startRef} />\n ) : null}\n <script data-remote-component type=\"application/json\">\n {JSON.stringify({\n name,\n bundle,\n route,\n runtime,\n })}\n </script>\n {isolate === false ? linksToRender : null}\n {componentToRender}\n {nextData ? (\n <script\n id={`${bundle}_${route.replace(\n /[^a-zA-Z0-9]+/g,\n '_',\n )}${name}_next_data`}\n type=\"application/json\"\n >\n {JSON.stringify(nextData)}\n </script>\n ) : null}\n {isolate === false ? <template id={`${name}_end`} ref={endRef} /> : null}\n </>\n );\n}\n\nfunction RenderLink({\n link,\n url,\n ...rest\n}: {\n link: Record<string, string | boolean | undefined>;\n url: URL;\n} & React.LinkHTMLAttributes<HTMLLinkElement>) {\n return (\n <link\n {...Object.entries(link).reduce<Record<string, string>>(\n (acc, [key, value]) => {\n if (\n key !== 'href' &&\n key !== 'precedence' &&\n typeof value === 'string'\n ) {\n acc[attrToProp[key] ?? key] = value;\n }\n return acc;\n },\n {},\n )}\n href={\n typeof link.href === 'string' ? new URL(link.href, url).href : undefined\n }\n {...rest}\n />\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;A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,YAAO,yBAAqB,MAAC,MAAK,oBAChC,eAAK,UAAU;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC,GACH;AAAA,IACC,YAAY,QAAQ,gBAAgB;AAAA,IACpC;AAAA,IACA,WACC;AAAA,MAAC;AAAA;AAAA,QACC,IAAI,GAAG,UAAU,MAAM;AAAA,UACrB;AAAA,UACA;AAAA,QACF,IAAI;AAAA,QACJ,MAAK;AAAA,QAEJ,eAAK,UAAU,QAAQ;AAAA;AAAA,IAC1B,IACE;AAAA,IACH,YAAY,QAAQ,4CAAC,cAAS,IAAI,GAAG,YAAY,KAAK,QAAQ,IAAK;AAAA,KACtE;AAEJ;AAEA,SAAS,WAAW;AAAA,EAClB;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAG+C;AAC7C,SACE;AAAA,IAAC;AAAA;AAAA,MACE,GAAG,OAAO,QAAQ,IAAI,EAAE;AAAA,QACvB,CAAC,KAAK,CAAC,KAAK,KAAK,MAAM;AACrB,cACE,QAAQ,UACR,QAAQ,gBACR,OAAO,UAAU,UACjB;AACA,gBAAI,wBAAW,GAAG,KAAK,GAAG,IAAI;AAAA,UAChC;AACA,iBAAO;AAAA,QACT;AAAA,QACA,CAAC;AAAA,MACH;AAAA,MACA,MACE,OAAO,KAAK,SAAS,WAAW,IAAI,IAAI,KAAK,MAAM,GAAG,EAAE,OAAO;AAAA,MAEhE,GAAG;AAAA;AAAA,EACN;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/next/host/app-router-client.tsx"],"sourcesContent":["'use client';\n\nimport * as Image from 'next/image';\nimport {\n startTransition,\n useEffect,\n useId,\n useLayoutEffect,\n useRef,\n useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { imageImpl, routerImpl } from '#internal/next/host/app-router-compat';\nimport { getClientSrc } from '#internal/shared/client/get-client-src';\nimport type { RemoteComponentProps } from '#internal/shared/client/remote-component';\nimport {\n DEFAULT_ROUTE,\n loadRemoteComponent,\n loadStaticRemoteComponent,\n RUNTIME_WEBPACK,\n} from '#internal/shared/client/remote-component';\nimport type { MountOrUnmountFunction } from '#internal/shared/client/types';\nimport { getClientOrServerUrl } from '#internal/shared/ssr/get-client-or-server-url';\nimport { attrToProp, escapeString } from '#internal/shared/utils';\n\n// patch react/jsx-runtime to support the shadowrootmode attribute on template elements\ndeclare module 'react/jsx-runtime' {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace JSX {\n interface IntrinsicElements {\n template: {\n shadowrootmode?: 'open' | 'closed';\n id?: string;\n ref?: React.Ref<HTMLTemplateElement>;\n dangerouslySetInnerHTML?: {\n __html: string;\n };\n children?: React.ReactNode;\n };\n }\n }\n}\n\n// import { shared } from 'remote-components/shared/host';\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\n/**\n * RemoteComponentClient - Main component for rendering remote components\n *\n * This component handles the loading and rendering of remote microfrontends.\n * It supports both RSC (React Server Components) and Next.js Pages Router based components.\n */\nexport function RemoteComponentClient({\n src,\n serverUrl,\n name,\n bundle,\n route = DEFAULT_ROUTE,\n runtime = RUNTIME_WEBPACK,\n data,\n nextData,\n scripts = [],\n links = [],\n remoteShared = {},\n isolate,\n mode = 'open',\n reset,\n type,\n children,\n}: RemoteComponentProps) {\n const remoteComponentId = useId();\n const [component, setComponent] = useState<React.ReactNode | Error>(null);\n const url = getClientOrServerUrl(src, serverUrl);\n const metadataRef = useRef<{\n name: string;\n bundle: string;\n route: string;\n url: string;\n loading: boolean;\n }>({\n name,\n bundle,\n route,\n url: url.href,\n loading: false,\n });\n const startRef = useRef<HTMLTemplateElement | null>(null);\n const endRef = useRef<HTMLTemplateElement | null>(null);\n const prevRemoteComponentUnmountRef = useRef<{\n unmount: Set<MountOrUnmountFunction>;\n root: ShadowRoot | DocumentFragment | null;\n } | null>(null);\n\n // Handle errors by re-throwing them\n if (component instanceof Error) {\n throw component;\n }\n\n // determine whether to use children or loaded component\n const shouldUseChildren =\n (!component ||\n (component &&\n !nextData &&\n type !== 'remote-component' &&\n typeof (component as unknown as Promise<unknown>).then !==\n 'function')) &&\n // if the remote Next.js Pages Router application is in development mode\n // we don't use the provided static HTML\n // to mitigate layout shift when loading CSS using JavaScript on the client\n nextData?.buildId !== 'development';\n\n // The pathname is used so this URL is the same across server and client requests for relative src's\n const keySuffix = `${escapeString(bundle)}_${escapeString(\n url.pathname,\n )}_${escapeString(name)}`;\n\n const self = globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n > &\n Record<`__remote_components_container_${string}`, HTMLDivElement | null>;\n const shadowRootKey = `__remote_components_shadowroot_${keySuffix}` as const;\n const shadowContainerRef = useRef<HTMLDivElement | null>(\n typeof document === 'undefined'\n ? null\n : document.querySelector(\n `[data-remote-component-id=\"shadowroot_${remoteComponentId}\"]`,\n ),\n );\n const shadowRootRef = useRef<ShadowRoot | null>(\n self[shadowRootKey] ?? shadowContainerRef.current?.shadowRoot ?? null,\n );\n const ssrShadowRootContentRef = useRef<NodeListOf<ChildNode> | null>(\n shadowRootRef.current?.querySelectorAll('*') ?? null,\n );\n const ssrLinksStylesRef = useRef<(HTMLLinkElement | HTMLStyleElement)[]>([]);\n\n if (self[shadowRootKey] && shadowRootRef.current) {\n self[shadowRootKey] = null;\n }\n\n useLayoutEffect(() => {\n if (\n !shadowContainerRef.current ||\n shadowContainerRef.current !== shadowRootRef.current?.host\n ) {\n shadowRootRef.current = null;\n }\n\n if (\n isolate !== false &&\n typeof document !== 'undefined' &&\n !shadowRootRef.current\n ) {\n let shadowRootElement: ShadowRoot | null = null;\n const element = shadowContainerRef.current;\n\n shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;\n self[shadowRootKey] = 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 } catch {\n // do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n shadowRootRef.current = shadowRootElement;\n }\n }\n\n if (\n shadowRootRef.current &&\n ssrShadowRootContentRef.current &&\n !shouldUseChildren\n ) {\n // remove all nodes from the shadow root except links\n ssrShadowRootContentRef.current.forEach((node) => {\n if (node.nodeName !== 'LINK' && node.nodeName !== 'STYLE') {\n node.parentNode?.removeChild(node);\n } else {\n ssrLinksStylesRef.current.push(\n node as HTMLLinkElement | HTMLStyleElement,\n );\n }\n });\n ssrShadowRootContentRef.current = null;\n }\n\n if (ssrLinksStylesRef.current.length > 0 && shadowRootRef.current) {\n const waitForLoad =\n shadowRootRef.current.querySelectorAll('link[data-wait]');\n if (waitForLoad.length > 0) {\n Promise.all(\n Array.from(waitForLoad).map(\n (link) =>\n new Promise<void>((resolve) => {\n link.addEventListener('load', () => resolve());\n link.addEventListener('error', () => resolve());\n }),\n ),\n )\n .then(() => {\n waitForLoad.forEach((el) => {\n el.removeAttribute('data-wait');\n });\n\n // remove SSR injected styles and links\n ssrLinksStylesRef.current.forEach((el) => {\n el.parentNode?.removeChild(el);\n });\n ssrLinksStylesRef.current = [];\n })\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n });\n }\n }\n }, [isolate, mode, self, shadowRootKey, shouldUseChildren]);\n\n useEffect(() => {\n // run unmount functions when the component changes or unmounts\n if (prevRemoteComponentUnmountRef.current && component !== children) {\n const { unmount, root } = prevRemoteComponentUnmountRef.current;\n prevRemoteComponentUnmountRef.current = null;\n Promise.all(\n Array.from(unmount).map(async (unmountFn) => {\n try {\n await unmountFn(root);\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(e);\n }\n }),\n ).catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n });\n }\n }, [component, children]);\n\n useEffect(() => {\n startTransition(async () => {\n try {\n // if we have a component, we don't need to load it again\n if (\n (!metadataRef.current.loading &&\n !component &&\n (isolate === false || shadowRootRef.current)) ||\n metadataRef.current.url !== url.href ||\n metadataRef.current.name !== name ||\n metadataRef.current.bundle !== bundle ||\n metadataRef.current.route !== route\n ) {\n metadataRef.current = {\n name,\n bundle,\n route,\n url: url.href,\n loading: true,\n };\n\n // use the children as the component when type is remote-component\n if (type === 'remote-component') {\n setComponent(children);\n // load static scripts and execute mount functions\n // run this async but don't await it as we render children immediately\n loadStaticRemoteComponent(scripts as HTMLScriptElement[], url)\n .then(({ mount, unmount }) => {\n if (mount.size > 0) {\n let root: ShadowRoot | DocumentFragment | null =\n shadowRootRef.current;\n try {\n if (!root && startRef.current && endRef.current) {\n root = document.querySelectorAll(\n `#${startRef.current.id} ~ *:not(#${endRef.current.id}):has(~ #${endRef.current.id})`,\n ) as unknown as DocumentFragment;\n }\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(e);\n }\n if (unmount.size > 0) {\n prevRemoteComponentUnmountRef.current = { unmount, root };\n }\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(root)),\n );\n }\n })\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n setComponent(e as Error);\n });\n return;\n }\n\n const rscName = `__remote_components_rsc_${keySuffix}`;\n const result = await loadRemoteComponent({\n url,\n name,\n bundle,\n route,\n runtime,\n rscName,\n data,\n nextData,\n scripts,\n shared: (async () => {\n const shared = await tryImportShared();\n\n if ('__remote_components_missing_shared__' in shared) {\n await shared.__remote_components_missing_shared__();\n }\n\n return {\n 'next/router': routerImpl,\n ...shared,\n 'next/image': () =>\n Promise.resolve(imageImpl(Image.default, bundle)),\n 'next/dist/client/image-component': () =>\n Promise.resolve({ Image: imageImpl(Image.default, bundle) }),\n };\n })(),\n remoteShared,\n container: shadowRootRef.current,\n });\n metadataRef.current.loading = false;\n if (result.error) {\n setComponent(result.error);\n } else {\n setComponent(result.component);\n }\n }\n } catch (error: unknown) {\n metadataRef.current.loading = false;\n setComponent(error as Error);\n }\n });\n }, [\n component,\n name,\n bundle,\n route,\n runtime,\n scripts,\n data,\n nextData,\n remoteShared,\n children,\n isolate,\n type,\n keySuffix,\n url,\n ]);\n\n if (\n nextData?.buildId === 'development' &&\n shadowRootRef.current &&\n isolate !== false &&\n reset &&\n !shadowRootRef.current.querySelector('[data-remote-components-reset]')\n ) {\n // inject reset styles into the shadow root\n const style = document.createElement('style');\n style.setAttribute('data-remote-components-reset', '');\n style.textContent = `:host { all: initial; }`;\n shadowRootRef.current.insertBefore(style, shadowRootRef.current.firstChild);\n } else if (\n shadowRootRef.current &&\n isolate !== false &&\n !reset &&\n shadowRootRef.current.querySelector('[data-remote-components-reset]')\n ) {\n // ensure reset styles are the first child in the shadow root\n const style = shadowRootRef.current.querySelector(\n '[data-remote-components-reset]',\n );\n if (style && shadowRootRef.current.firstChild !== style) {\n shadowRootRef.current.removeChild(style);\n }\n }\n\n const linksToRender = (\n <>\n {(!nextData || nextData.buildId !== 'development') &&\n isolate !== false &&\n reset ? (\n <style data-remote-components-reset=\"\">{`:host { all: initial; }`}</style>\n ) : null}\n {links.map((link) => (\n <RenderLink\n key={JSON.stringify(link)}\n link={link}\n url={url}\n serverUrl={serverUrl}\n data-wait={link.rel === 'stylesheet' && link.href ? '' : undefined}\n />\n ))}\n {links\n .filter((link) => link.rel === 'stylesheet')\n .map((link) => (\n <RenderLink\n key={JSON.stringify(link)}\n link={link}\n serverUrl={serverUrl}\n url={url}\n as=\"style\"\n fetchPriority=\"high\"\n precedence={bundle}\n rel=\"preload\"\n />\n ))}\n </>\n );\n\n let componentToRender = shouldUseChildren\n ? children\n : (component as React.ReactNode);\n\n if (isolate !== false) {\n componentToRender = (\n <div\n data-remote-component-id={`shadowroot_${remoteComponentId}`}\n data-remote-component-isolation-root=\"\"\n id={`shadowroot_${name}`}\n ref={shadowContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {mode === 'closed' ? (\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.${shadowRootKey} = root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {linksToRender}\n {shouldUseChildren ? children : null}\n </template>\n ) : null}\n {typeof document !== 'undefined' &&\n shadowRootRef.current &&\n !shouldUseChildren\n ? createPortal(\n <>\n {linksToRender}\n {componentToRender}\n </>,\n shadowRootRef.current,\n )\n : null}\n </div>\n );\n }\n\n return (\n <>\n {isolate === false ? (\n <template id={`${name}_start`} ref={startRef} />\n ) : null}\n <script data-remote-component type=\"application/json\">\n {JSON.stringify({\n name,\n bundle,\n route,\n runtime,\n })}\n </script>\n {isolate === false ? linksToRender : null}\n {componentToRender}\n {nextData ? (\n <script\n id={`${bundle}_${route.replace(\n /[^a-zA-Z0-9]+/g,\n '_',\n )}${name}_next_data`}\n type=\"application/json\"\n >\n {JSON.stringify(nextData)}\n </script>\n ) : null}\n {isolate === false ? <template id={`${name}_end`} ref={endRef} /> : null}\n </>\n );\n}\n\nfunction RenderLink({\n link,\n url,\n serverUrl,\n ...rest\n}: {\n link: Record<string, string | boolean | undefined>;\n url: URL;\n serverUrl: string;\n} & React.LinkHTMLAttributes<HTMLLinkElement>) {\n return (\n <link\n {...Object.entries(link).reduce<Record<string, string>>(\n (acc, [key, value]) => {\n if (\n key !== 'href' &&\n key !== 'precedence' &&\n typeof value === 'string'\n ) {\n acc[attrToProp[key] ?? key] = value;\n }\n return acc;\n },\n {},\n )}\n href={getClientSrc(link.href, serverUrl)}\n {...rest}\n />\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA6YI;AA3YJ,YAAuB;AACvB,mBAOO;AACP,uBAA6B;AAC7B,+BAAsC;AACtC,4BAA6B;AAE7B,8BAKO;AAEP,sCAAqC;AACrC,mBAAyC;AAqBzC,eAAe,kBAAkB;A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AQ,gBAAgB;AAAA,IACpC;AAAA,IACA,WACC;AAAA,MAAC;AAAA;AAAA,QACC,IAAI,GAAG,UAAU,MAAM;AAAA,UACrB;AAAA,UACA;AAAA,QACF,IAAI;AAAA,QACJ,MAAK;AAAA,QAEJ,eAAK,UAAU,QAAQ;AAAA;AAAA,IAC1B,IACE;AAAA,IACH,YAAY,QAAQ,4CAAC,cAAS,IAAI,GAAG,YAAY,KAAK,QAAQ,IAAK;AAAA,KACtE;AAEJ;AAEA,SAAS,WAAW;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAI+C;AAC7C,SACE;AAAA,IAAC;AAAA;AAAA,MACE,GAAG,OAAO,QAAQ,IAAI,EAAE;AAAA,QACvB,CAAC,KAAK,CAAC,KAAK,KAAK,MAAM;AACrB,cACE,QAAQ,UACR,QAAQ,gBACR,OAAO,UAAU,UACjB;AACA,gBAAI,wBAAW,GAAG,KAAK,GAAG,IAAI;AAAA,UAChC;AACA,iBAAO;AAAA,QACT;AAAA,QACA,CAAC;AAAA,MACH;AAAA,MACA,UAAM,oCAAa,KAAK,MAAM,SAAS;AAAA,MACtC,GAAG;AAAA;AAAA,EACN;AAEJ;","names":[]}
|
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
} from "react";
|
|
12
12
|
import { createPortal } from "react-dom";
|
|
13
13
|
import { imageImpl, routerImpl } from "#internal/next/host/app-router-compat";
|
|
14
|
+
import { getClientSrc } from "#internal/shared/client/get-client-src";
|
|
14
15
|
import {
|
|
15
16
|
DEFAULT_ROUTE,
|
|
16
17
|
loadRemoteComponent,
|
|
@@ -269,6 +270,7 @@ function RemoteComponentClient({
|
|
|
269
270
|
{
|
|
270
271
|
link,
|
|
271
272
|
url,
|
|
273
|
+
serverUrl,
|
|
272
274
|
"data-wait": link.rel === "stylesheet" && link.href ? "" : void 0
|
|
273
275
|
},
|
|
274
276
|
JSON.stringify(link)
|
|
@@ -277,6 +279,7 @@ function RemoteComponentClient({
|
|
|
277
279
|
RenderLink,
|
|
278
280
|
{
|
|
279
281
|
link,
|
|
282
|
+
serverUrl,
|
|
280
283
|
url,
|
|
281
284
|
as: "style",
|
|
282
285
|
fetchPriority: "high",
|
|
@@ -357,6 +360,7 @@ function RemoteComponentClient({
|
|
|
357
360
|
function RenderLink({
|
|
358
361
|
link,
|
|
359
362
|
url,
|
|
363
|
+
serverUrl,
|
|
360
364
|
...rest
|
|
361
365
|
}) {
|
|
362
366
|
return /* @__PURE__ */ jsx(
|
|
@@ -371,7 +375,7 @@ function RenderLink({
|
|
|
371
375
|
},
|
|
372
376
|
{}
|
|
373
377
|
),
|
|
374
|
-
href:
|
|
378
|
+
href: getClientSrc(link.href, serverUrl),
|
|
375
379
|
...rest
|
|
376
380
|
}
|
|
377
381
|
);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/next/host/app-router-client.tsx"],"sourcesContent":["'use client';\n\nimport * as Image from 'next/image';\nimport {\n startTransition,\n useEffect,\n useId,\n useLayoutEffect,\n useRef,\n useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { imageImpl, routerImpl } from '#internal/next/host/app-router-compat';\nimport type { RemoteComponentProps } from '#internal/shared/client/remote-component';\nimport {\n DEFAULT_ROUTE,\n loadRemoteComponent,\n loadStaticRemoteComponent,\n RUNTIME_WEBPACK,\n} from '#internal/shared/client/remote-component';\nimport type { MountOrUnmountFunction } from '#internal/shared/client/types';\nimport { getClientOrServerUrl } from '#internal/shared/ssr/get-client-or-server-url';\nimport { attrToProp, escapeString } from '#internal/shared/utils';\n\n// patch react/jsx-runtime to support the shadowrootmode attribute on template elements\ndeclare module 'react/jsx-runtime' {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace JSX {\n interface IntrinsicElements {\n template: {\n shadowrootmode?: 'open' | 'closed';\n id?: string;\n ref?: React.Ref<HTMLTemplateElement>;\n dangerouslySetInnerHTML?: {\n __html: string;\n };\n children?: React.ReactNode;\n };\n }\n }\n}\n\n// import { shared } from 'remote-components/shared/host';\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\n/**\n * RemoteComponentClient - Main component for rendering remote components\n *\n * This component handles the loading and rendering of remote microfrontends.\n * It supports both RSC (React Server Components) and Next.js Pages Router based components.\n */\nexport function RemoteComponentClient({\n src,\n serverUrl,\n name,\n bundle,\n route = DEFAULT_ROUTE,\n runtime = RUNTIME_WEBPACK,\n data,\n nextData,\n scripts = [],\n links = [],\n remoteShared = {},\n isolate,\n mode = 'open',\n reset,\n type,\n children,\n}: RemoteComponentProps) {\n const remoteComponentId = useId();\n const [component, setComponent] = useState<React.ReactNode | Error>(null);\n const url = getClientOrServerUrl(src, serverUrl);\n const metadataRef = useRef<{\n name: string;\n bundle: string;\n route: string;\n url: string;\n loading: boolean;\n }>({\n name,\n bundle,\n route,\n url: url.href,\n loading: false,\n });\n const startRef = useRef<HTMLTemplateElement | null>(null);\n const endRef = useRef<HTMLTemplateElement | null>(null);\n const prevRemoteComponentUnmountRef = useRef<{\n unmount: Set<MountOrUnmountFunction>;\n root: ShadowRoot | DocumentFragment | null;\n } | null>(null);\n\n // Handle errors by re-throwing them\n if (component instanceof Error) {\n throw component;\n }\n\n // determine whether to use children or loaded component\n const shouldUseChildren =\n (!component ||\n (component &&\n !nextData &&\n type !== 'remote-component' &&\n typeof (component as unknown as Promise<unknown>).then !==\n 'function')) &&\n // if the remote Next.js Pages Router application is in development mode\n // we don't use the provided static HTML\n // to mitigate layout shift when loading CSS using JavaScript on the client\n nextData?.buildId !== 'development';\n\n // The pathname is used so this URL is the same across server and client requests for relative src's\n const keySuffix = `${escapeString(bundle)}_${escapeString(\n url.pathname,\n )}_${escapeString(name)}`;\n\n const self = globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n > &\n Record<`__remote_components_container_${string}`, HTMLDivElement | null>;\n const shadowRootKey = `__remote_components_shadowroot_${keySuffix}` as const;\n const shadowContainerRef = useRef<HTMLDivElement | null>(\n typeof document === 'undefined'\n ? null\n : document.querySelector(\n `[data-remote-component-id=\"shadowroot_${remoteComponentId}\"]`,\n ),\n );\n const shadowRootRef = useRef<ShadowRoot | null>(\n self[shadowRootKey] ?? shadowContainerRef.current?.shadowRoot ?? null,\n );\n const ssrShadowRootContentRef = useRef<NodeListOf<ChildNode> | null>(\n shadowRootRef.current?.querySelectorAll('*') ?? null,\n );\n const ssrLinksStylesRef = useRef<(HTMLLinkElement | HTMLStyleElement)[]>([]);\n\n if (self[shadowRootKey] && shadowRootRef.current) {\n self[shadowRootKey] = null;\n }\n\n useLayoutEffect(() => {\n if (\n !shadowContainerRef.current ||\n shadowContainerRef.current !== shadowRootRef.current?.host\n ) {\n shadowRootRef.current = null;\n }\n\n if (\n isolate !== false &&\n typeof document !== 'undefined' &&\n !shadowRootRef.current\n ) {\n let shadowRootElement: ShadowRoot | null = null;\n const element = shadowContainerRef.current;\n\n shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;\n self[shadowRootKey] = 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 } catch {\n // do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n shadowRootRef.current = shadowRootElement;\n }\n }\n\n if (\n shadowRootRef.current &&\n ssrShadowRootContentRef.current &&\n !shouldUseChildren\n ) {\n // remove all nodes from the shadow root except links\n ssrShadowRootContentRef.current.forEach((node) => {\n if (node.nodeName !== 'LINK' && node.nodeName !== 'STYLE') {\n node.parentNode?.removeChild(node);\n } else {\n ssrLinksStylesRef.current.push(\n node as HTMLLinkElement | HTMLStyleElement,\n );\n }\n });\n ssrShadowRootContentRef.current = null;\n }\n\n if (ssrLinksStylesRef.current.length > 0 && shadowRootRef.current) {\n const waitForLoad =\n shadowRootRef.current.querySelectorAll('link[data-wait]');\n if (waitForLoad.length > 0) {\n Promise.all(\n Array.from(waitForLoad).map(\n (link) =>\n new Promise<void>((resolve) => {\n link.addEventListener('load', () => resolve());\n link.addEventListener('error', () => resolve());\n }),\n ),\n )\n .then(() => {\n waitForLoad.forEach((el) => {\n el.removeAttribute('data-wait');\n });\n\n // remove SSR injected styles and links\n ssrLinksStylesRef.current.forEach((el) => {\n el.parentNode?.removeChild(el);\n });\n ssrLinksStylesRef.current = [];\n })\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n });\n }\n }\n }, [isolate, mode, self, shadowRootKey, shouldUseChildren]);\n\n useEffect(() => {\n // run unmount functions when the component changes or unmounts\n if (prevRemoteComponentUnmountRef.current && component !== children) {\n const { unmount, root } = prevRemoteComponentUnmountRef.current;\n prevRemoteComponentUnmountRef.current = null;\n Promise.all(\n Array.from(unmount).map(async (unmountFn) => {\n try {\n await unmountFn(root);\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(e);\n }\n }),\n ).catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n });\n }\n }, [component, children]);\n\n useEffect(() => {\n startTransition(async () => {\n try {\n // if we have a component, we don't need to load it again\n if (\n (!metadataRef.current.loading &&\n !component &&\n (isolate === false || shadowRootRef.current)) ||\n metadataRef.current.url !== url.href ||\n metadataRef.current.name !== name ||\n metadataRef.current.bundle !== bundle ||\n metadataRef.current.route !== route\n ) {\n metadataRef.current = {\n name,\n bundle,\n route,\n url: url.href,\n loading: true,\n };\n\n // use the children as the component when type is remote-component\n if (type === 'remote-component') {\n setComponent(children);\n // load static scripts and execute mount functions\n // run this async but don't await it as we render children immediately\n loadStaticRemoteComponent(scripts as HTMLScriptElement[], url)\n .then(({ mount, unmount }) => {\n if (mount.size > 0) {\n let root: ShadowRoot | DocumentFragment | null =\n shadowRootRef.current;\n try {\n if (!root && startRef.current && endRef.current) {\n root = document.querySelectorAll(\n `#${startRef.current.id} ~ *:not(#${endRef.current.id}):has(~ #${endRef.current.id})`,\n ) as unknown as DocumentFragment;\n }\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(e);\n }\n if (unmount.size > 0) {\n prevRemoteComponentUnmountRef.current = { unmount, root };\n }\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(root)),\n );\n }\n })\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n setComponent(e as Error);\n });\n return;\n }\n\n const rscName = `__remote_components_rsc_${keySuffix}`;\n const result = await loadRemoteComponent({\n url,\n name,\n bundle,\n route,\n runtime,\n rscName,\n data,\n nextData,\n scripts,\n shared: (async () => {\n const shared = await tryImportShared();\n\n if ('__remote_components_missing_shared__' in shared) {\n await shared.__remote_components_missing_shared__();\n }\n\n return {\n 'next/router': routerImpl,\n ...shared,\n 'next/image': () =>\n Promise.resolve(imageImpl(Image.default, bundle)),\n 'next/dist/client/image-component': () =>\n Promise.resolve({ Image: imageImpl(Image.default, bundle) }),\n };\n })(),\n remoteShared,\n container: shadowRootRef.current,\n });\n metadataRef.current.loading = false;\n if (result.error) {\n setComponent(result.error);\n } else {\n setComponent(result.component);\n }\n }\n } catch (error: unknown) {\n metadataRef.current.loading = false;\n setComponent(error as Error);\n }\n });\n }, [\n component,\n name,\n bundle,\n route,\n runtime,\n scripts,\n data,\n nextData,\n remoteShared,\n children,\n isolate,\n type,\n keySuffix,\n url,\n ]);\n\n if (\n nextData?.buildId === 'development' &&\n shadowRootRef.current &&\n isolate !== false &&\n reset &&\n !shadowRootRef.current.querySelector('[data-remote-components-reset]')\n ) {\n // inject reset styles into the shadow root\n const style = document.createElement('style');\n style.setAttribute('data-remote-components-reset', '');\n style.textContent = `:host { all: initial; }`;\n shadowRootRef.current.insertBefore(style, shadowRootRef.current.firstChild);\n } else if (\n shadowRootRef.current &&\n isolate !== false &&\n !reset &&\n shadowRootRef.current.querySelector('[data-remote-components-reset]')\n ) {\n // ensure reset styles are the first child in the shadow root\n const style = shadowRootRef.current.querySelector(\n '[data-remote-components-reset]',\n );\n if (style && shadowRootRef.current.firstChild !== style) {\n shadowRootRef.current.removeChild(style);\n }\n }\n\n const linksToRender = (\n <>\n {(!nextData || nextData.buildId !== 'development') &&\n isolate !== false &&\n reset ? (\n <style data-remote-components-reset=\"\">{`:host { all: initial; }`}</style>\n ) : null}\n {links.map((link) => (\n <RenderLink\n key={JSON.stringify(link)}\n link={link}\n url={url}\n data-wait={link.rel === 'stylesheet' && link.href ? '' : undefined}\n />\n ))}\n {links\n .filter((link) => link.rel === 'stylesheet')\n .map((link) => (\n <RenderLink\n key={JSON.stringify(link)}\n link={link}\n url={url}\n as=\"style\"\n fetchPriority=\"high\"\n precedence={bundle}\n rel=\"preload\"\n />\n ))}\n </>\n );\n\n let componentToRender = shouldUseChildren\n ? children\n : (component as React.ReactNode);\n\n if (isolate !== false) {\n componentToRender = (\n <div\n data-remote-component-id={`shadowroot_${remoteComponentId}`}\n data-remote-component-isolation-root=\"\"\n id={`shadowroot_${name}`}\n ref={shadowContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {mode === 'closed' ? (\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.${shadowRootKey} = root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {linksToRender}\n {shouldUseChildren ? children : null}\n </template>\n ) : null}\n {typeof document !== 'undefined' &&\n shadowRootRef.current &&\n !shouldUseChildren\n ? createPortal(\n <>\n {linksToRender}\n {componentToRender}\n </>,\n shadowRootRef.current,\n )\n : null}\n </div>\n );\n }\n\n return (\n <>\n {isolate === false ? (\n <template id={`${name}_start`} ref={startRef} />\n ) : null}\n <script data-remote-component type=\"application/json\">\n {JSON.stringify({\n name,\n bundle,\n route,\n runtime,\n })}\n </script>\n {isolate === false ? linksToRender : null}\n {componentToRender}\n {nextData ? (\n <script\n id={`${bundle}_${route.replace(\n /[^a-zA-Z0-9]+/g,\n '_',\n )}${name}_next_data`}\n type=\"application/json\"\n >\n {JSON.stringify(nextData)}\n </script>\n ) : null}\n {isolate === false ? <template id={`${name}_end`} ref={endRef} /> : null}\n </>\n );\n}\n\nfunction RenderLink({\n link,\n url,\n ...rest\n}: {\n link: Record<string, string | boolean | undefined>;\n url: URL;\n} & React.LinkHTMLAttributes<HTMLLinkElement>) {\n return (\n <link\n {...Object.entries(link).reduce<Record<string, string>>(\n (acc, [key, value]) => {\n if (\n key !== 'href' &&\n key !== 'precedence' &&\n typeof value === 'string'\n ) {\n acc[attrToProp[key] ?? key] = value;\n }\n return acc;\n },\n {},\n )}\n href={\n typeof link.href === 'string' ? new URL(link.href, url).href : undefined\n }\n {...rest}\n />\n );\n}\n"],"mappings":";AA4YI,mBAII,KAJJ;AA1YJ,YAAY,WAAW;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,WAAW,kBAAkB;AAEtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,4BAA4B;AACrC,SAAS,YAAY,oBAAoB;AAqBzC,eAAe,kBAAkB;AAC/B,MAAI;AACF,UAAM,EAAE,OAAO,IAAI,MAAM,OAAO,mCAAmC;AACnE,WAAO;AAAA,EACT,QAAE;AACA,WAAO,CAAC;AAAA,EACV;AACF;AAQO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,QAAQ;AAAA,EACR,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA,UAAU,CAAC;AAAA,EACX,QAAQ,CAAC;AAAA,EACT,eAAe,CAAC;AAAA,EAChB;AAAA,EACA,OAAO;AAAA,EACP;AAAA,EACA;AAAA,EACA;AACF,G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O,QAAQ,IAAI,EAAE;AAAA,QACvB,CAAC,KAAK,CAAC,KAAK,KAAK,MAAM;AACrB,cACE,QAAQ,UACR,QAAQ,gBACR,OAAO,UAAU,UACjB;AACA,gBAAI,WAAW,GAAG,KAAK,GAAG,IAAI;AAAA,UAChC;AACA,iBAAO;AAAA,QACT;AAAA,QACA,CAAC;AAAA,MACH;AAAA,MACA,MACE,OAAO,KAAK,SAAS,WAAW,IAAI,IAAI,KAAK,MAAM,GAAG,EAAE,OAAO;AAAA,MAEhE,GAAG;AAAA;AAAA,EACN;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/next/host/app-router-client.tsx"],"sourcesContent":["'use client';\n\nimport * as Image from 'next/image';\nimport {\n startTransition,\n useEffect,\n useId,\n useLayoutEffect,\n useRef,\n useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { imageImpl, routerImpl } from '#internal/next/host/app-router-compat';\nimport { getClientSrc } from '#internal/shared/client/get-client-src';\nimport type { RemoteComponentProps } from '#internal/shared/client/remote-component';\nimport {\n DEFAULT_ROUTE,\n loadRemoteComponent,\n loadStaticRemoteComponent,\n RUNTIME_WEBPACK,\n} from '#internal/shared/client/remote-component';\nimport type { MountOrUnmountFunction } from '#internal/shared/client/types';\nimport { getClientOrServerUrl } from '#internal/shared/ssr/get-client-or-server-url';\nimport { attrToProp, escapeString } from '#internal/shared/utils';\n\n// patch react/jsx-runtime to support the shadowrootmode attribute on template elements\ndeclare module 'react/jsx-runtime' {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace JSX {\n interface IntrinsicElements {\n template: {\n shadowrootmode?: 'open' | 'closed';\n id?: string;\n ref?: React.Ref<HTMLTemplateElement>;\n dangerouslySetInnerHTML?: {\n __html: string;\n };\n children?: React.ReactNode;\n };\n }\n }\n}\n\n// import { shared } from 'remote-components/shared/host';\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\n/**\n * RemoteComponentClient - Main component for rendering remote components\n *\n * This component handles the loading and rendering of remote microfrontends.\n * It supports both RSC (React Server Components) and Next.js Pages Router based components.\n */\nexport function RemoteComponentClient({\n src,\n serverUrl,\n name,\n bundle,\n route = DEFAULT_ROUTE,\n runtime = RUNTIME_WEBPACK,\n data,\n nextData,\n scripts = [],\n links = [],\n remoteShared = {},\n isolate,\n mode = 'open',\n reset,\n type,\n children,\n}: RemoteComponentProps) {\n const remoteComponentId = useId();\n const [component, setComponent] = useState<React.ReactNode | Error>(null);\n const url = getClientOrServerUrl(src, serverUrl);\n const metadataRef = useRef<{\n name: string;\n bundle: string;\n route: string;\n url: string;\n loading: boolean;\n }>({\n name,\n bundle,\n route,\n url: url.href,\n loading: false,\n });\n const startRef = useRef<HTMLTemplateElement | null>(null);\n const endRef = useRef<HTMLTemplateElement | null>(null);\n const prevRemoteComponentUnmountRef = useRef<{\n unmount: Set<MountOrUnmountFunction>;\n root: ShadowRoot | DocumentFragment | null;\n } | null>(null);\n\n // Handle errors by re-throwing them\n if (component instanceof Error) {\n throw component;\n }\n\n // determine whether to use children or loaded component\n const shouldUseChildren =\n (!component ||\n (component &&\n !nextData &&\n type !== 'remote-component' &&\n typeof (component as unknown as Promise<unknown>).then !==\n 'function')) &&\n // if the remote Next.js Pages Router application is in development mode\n // we don't use the provided static HTML\n // to mitigate layout shift when loading CSS using JavaScript on the client\n nextData?.buildId !== 'development';\n\n // The pathname is used so this URL is the same across server and client requests for relative src's\n const keySuffix = `${escapeString(bundle)}_${escapeString(\n url.pathname,\n )}_${escapeString(name)}`;\n\n const self = globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n > &\n Record<`__remote_components_container_${string}`, HTMLDivElement | null>;\n const shadowRootKey = `__remote_components_shadowroot_${keySuffix}` as const;\n const shadowContainerRef = useRef<HTMLDivElement | null>(\n typeof document === 'undefined'\n ? null\n : document.querySelector(\n `[data-remote-component-id=\"shadowroot_${remoteComponentId}\"]`,\n ),\n );\n const shadowRootRef = useRef<ShadowRoot | null>(\n self[shadowRootKey] ?? shadowContainerRef.current?.shadowRoot ?? null,\n );\n const ssrShadowRootContentRef = useRef<NodeListOf<ChildNode> | null>(\n shadowRootRef.current?.querySelectorAll('*') ?? null,\n );\n const ssrLinksStylesRef = useRef<(HTMLLinkElement | HTMLStyleElement)[]>([]);\n\n if (self[shadowRootKey] && shadowRootRef.current) {\n self[shadowRootKey] = null;\n }\n\n useLayoutEffect(() => {\n if (\n !shadowContainerRef.current ||\n shadowContainerRef.current !== shadowRootRef.current?.host\n ) {\n shadowRootRef.current = null;\n }\n\n if (\n isolate !== false &&\n typeof document !== 'undefined' &&\n !shadowRootRef.current\n ) {\n let shadowRootElement: ShadowRoot | null = null;\n const element = shadowContainerRef.current;\n\n shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;\n self[shadowRootKey] = 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 } catch {\n // do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n shadowRootRef.current = shadowRootElement;\n }\n }\n\n if (\n shadowRootRef.current &&\n ssrShadowRootContentRef.current &&\n !shouldUseChildren\n ) {\n // remove all nodes from the shadow root except links\n ssrShadowRootContentRef.current.forEach((node) => {\n if (node.nodeName !== 'LINK' && node.nodeName !== 'STYLE') {\n node.parentNode?.removeChild(node);\n } else {\n ssrLinksStylesRef.current.push(\n node as HTMLLinkElement | HTMLStyleElement,\n );\n }\n });\n ssrShadowRootContentRef.current = null;\n }\n\n if (ssrLinksStylesRef.current.length > 0 && shadowRootRef.current) {\n const waitForLoad =\n shadowRootRef.current.querySelectorAll('link[data-wait]');\n if (waitForLoad.length > 0) {\n Promise.all(\n Array.from(waitForLoad).map(\n (link) =>\n new Promise<void>((resolve) => {\n link.addEventListener('load', () => resolve());\n link.addEventListener('error', () => resolve());\n }),\n ),\n )\n .then(() => {\n waitForLoad.forEach((el) => {\n el.removeAttribute('data-wait');\n });\n\n // remove SSR injected styles and links\n ssrLinksStylesRef.current.forEach((el) => {\n el.parentNode?.removeChild(el);\n });\n ssrLinksStylesRef.current = [];\n })\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n });\n }\n }\n }, [isolate, mode, self, shadowRootKey, shouldUseChildren]);\n\n useEffect(() => {\n // run unmount functions when the component changes or unmounts\n if (prevRemoteComponentUnmountRef.current && component !== children) {\n const { unmount, root } = prevRemoteComponentUnmountRef.current;\n prevRemoteComponentUnmountRef.current = null;\n Promise.all(\n Array.from(unmount).map(async (unmountFn) => {\n try {\n await unmountFn(root);\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(e);\n }\n }),\n ).catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n });\n }\n }, [component, children]);\n\n useEffect(() => {\n startTransition(async () => {\n try {\n // if we have a component, we don't need to load it again\n if (\n (!metadataRef.current.loading &&\n !component &&\n (isolate === false || shadowRootRef.current)) ||\n metadataRef.current.url !== url.href ||\n metadataRef.current.name !== name ||\n metadataRef.current.bundle !== bundle ||\n metadataRef.current.route !== route\n ) {\n metadataRef.current = {\n name,\n bundle,\n route,\n url: url.href,\n loading: true,\n };\n\n // use the children as the component when type is remote-component\n if (type === 'remote-component') {\n setComponent(children);\n // load static scripts and execute mount functions\n // run this async but don't await it as we render children immediately\n loadStaticRemoteComponent(scripts as HTMLScriptElement[], url)\n .then(({ mount, unmount }) => {\n if (mount.size > 0) {\n let root: ShadowRoot | DocumentFragment | null =\n shadowRootRef.current;\n try {\n if (!root && startRef.current && endRef.current) {\n root = document.querySelectorAll(\n `#${startRef.current.id} ~ *:not(#${endRef.current.id}):has(~ #${endRef.current.id})`,\n ) as unknown as DocumentFragment;\n }\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(e);\n }\n if (unmount.size > 0) {\n prevRemoteComponentUnmountRef.current = { unmount, root };\n }\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(root)),\n );\n }\n })\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n setComponent(e as Error);\n });\n return;\n }\n\n const rscName = `__remote_components_rsc_${keySuffix}`;\n const result = await loadRemoteComponent({\n url,\n name,\n bundle,\n route,\n runtime,\n rscName,\n data,\n nextData,\n scripts,\n shared: (async () => {\n const shared = await tryImportShared();\n\n if ('__remote_components_missing_shared__' in shared) {\n await shared.__remote_components_missing_shared__();\n }\n\n return {\n 'next/router': routerImpl,\n ...shared,\n 'next/image': () =>\n Promise.resolve(imageImpl(Image.default, bundle)),\n 'next/dist/client/image-component': () =>\n Promise.resolve({ Image: imageImpl(Image.default, bundle) }),\n };\n })(),\n remoteShared,\n container: shadowRootRef.current,\n });\n metadataRef.current.loading = false;\n if (result.error) {\n setComponent(result.error);\n } else {\n setComponent(result.component);\n }\n }\n } catch (error: unknown) {\n metadataRef.current.loading = false;\n setComponent(error as Error);\n }\n });\n }, [\n component,\n name,\n bundle,\n route,\n runtime,\n scripts,\n data,\n nextData,\n remoteShared,\n children,\n isolate,\n type,\n keySuffix,\n url,\n ]);\n\n if (\n nextData?.buildId === 'development' &&\n shadowRootRef.current &&\n isolate !== false &&\n reset &&\n !shadowRootRef.current.querySelector('[data-remote-components-reset]')\n ) {\n // inject reset styles into the shadow root\n const style = document.createElement('style');\n style.setAttribute('data-remote-components-reset', '');\n style.textContent = `:host { all: initial; }`;\n shadowRootRef.current.insertBefore(style, shadowRootRef.current.firstChild);\n } else if (\n shadowRootRef.current &&\n isolate !== false &&\n !reset &&\n shadowRootRef.current.querySelector('[data-remote-components-reset]')\n ) {\n // ensure reset styles are the first child in the shadow root\n const style = shadowRootRef.current.querySelector(\n '[data-remote-components-reset]',\n );\n if (style && shadowRootRef.current.firstChild !== style) {\n shadowRootRef.current.removeChild(style);\n }\n }\n\n const linksToRender = (\n <>\n {(!nextData || nextData.buildId !== 'development') &&\n isolate !== false &&\n reset ? (\n <style data-remote-components-reset=\"\">{`:host { all: initial; }`}</style>\n ) : null}\n {links.map((link) => (\n <RenderLink\n key={JSON.stringify(link)}\n link={link}\n url={url}\n serverUrl={serverUrl}\n data-wait={link.rel === 'stylesheet' && link.href ? '' : undefined}\n />\n ))}\n {links\n .filter((link) => link.rel === 'stylesheet')\n .map((link) => (\n <RenderLink\n key={JSON.stringify(link)}\n link={link}\n serverUrl={serverUrl}\n url={url}\n as=\"style\"\n fetchPriority=\"high\"\n precedence={bundle}\n rel=\"preload\"\n />\n ))}\n </>\n );\n\n let componentToRender = shouldUseChildren\n ? children\n : (component as React.ReactNode);\n\n if (isolate !== false) {\n componentToRender = (\n <div\n data-remote-component-id={`shadowroot_${remoteComponentId}`}\n data-remote-component-isolation-root=\"\"\n id={`shadowroot_${name}`}\n ref={shadowContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {mode === 'closed' ? (\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.${shadowRootKey} = root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {linksToRender}\n {shouldUseChildren ? children : null}\n </template>\n ) : null}\n {typeof document !== 'undefined' &&\n shadowRootRef.current &&\n !shouldUseChildren\n ? createPortal(\n <>\n {linksToRender}\n {componentToRender}\n </>,\n shadowRootRef.current,\n )\n : null}\n </div>\n );\n }\n\n return (\n <>\n {isolate === false ? (\n <template id={`${name}_start`} ref={startRef} />\n ) : null}\n <script data-remote-component type=\"application/json\">\n {JSON.stringify({\n name,\n bundle,\n route,\n runtime,\n })}\n </script>\n {isolate === false ? linksToRender : null}\n {componentToRender}\n {nextData ? (\n <script\n id={`${bundle}_${route.replace(\n /[^a-zA-Z0-9]+/g,\n '_',\n )}${name}_next_data`}\n type=\"application/json\"\n >\n {JSON.stringify(nextData)}\n </script>\n ) : null}\n {isolate === false ? <template id={`${name}_end`} ref={endRef} /> : null}\n </>\n );\n}\n\nfunction RenderLink({\n link,\n url,\n serverUrl,\n ...rest\n}: {\n link: Record<string, string | boolean | undefined>;\n url: URL;\n serverUrl: string;\n} & React.LinkHTMLAttributes<HTMLLinkElement>) {\n return (\n <link\n {...Object.entries(link).reduce<Record<string, string>>(\n (acc, [key, value]) => {\n if (\n key !== 'href' &&\n key !== 'precedence' &&\n typeof value === 'string'\n ) {\n acc[attrToProp[key] ?? key] = value;\n }\n return acc;\n },\n {},\n )}\n href={getClientSrc(link.href, serverUrl)}\n {...rest}\n />\n );\n}\n"],"mappings":";AA6YI,mBAII,KAJJ;AA3YJ,YAAY,WAAW;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,WAAW,kBAAkB;AACtC,SAAS,oBAAoB;AAE7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,4BAA4B;AACrC,SAAS,YAAY,oBAAoB;AAqBzC,eAAe,kBAAkB;AAC/B,MAAI;AACF,UAAM,EAAE,OAAO,IAAI,MAAM,OAAO,mCAAmC;AACnE,WAAO;AAAA,EACT,QAAE;AACA,WAAO,CAAC;AAAA,EACV;AACF;AAQO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,QAAQ;AAAA,EACR,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA,UAAU,CAAC;AAAA,EACX,QAAQ,CAAC;AAAA,EACT,eAAe,CAAC;AAAA,EAChB;AAAA,EACA,OAAO;AAAA,EACP;AAAA,EACA;AAAA,EACA;AACF,GAAyB;AACvB,QAAM,oBAAoB,MAAM;AAChC,QAAM,CAAC,WAAW,YAAY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,QACvB,CAAC,KAAK,CAAC,KAAK,KAAK,MAAM;AACrB,cACE,QAAQ,UACR,QAAQ,gBACR,OAAO,UAAU,UACjB;AACA,gBAAI,WAAW,GAAG,KAAK,GAAG,IAAI;AAAA,UAChC;AACA,iBAAO;AAAA,QACT;AAAA,QACA,CAAC;AAAA,MACH;AAAA,MACA,MAAM,aAAa,KAAK,MAAM,SAAS;AAAA,MACtC,GAAG;AAAA;AAAA,EACN;AAEJ;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/next/remote/render-server.tsx"],"sourcesContent":["import { workAsyncStorage } from 'next/dist/server/app-render/work-async-storage.external';\nimport { Suspense } from 'react';\nimport { RemoteComponentSharedRemote } from '#internal/next/remote/render-client';\nimport { RemoteComponentsError } from '#internal/shared/error';\nimport type { Manifest } from './types';\n\n// internal Next.js symbol to access the manifest which is stored in the global scope\nconst SERVER_ACTION_MANIFESTS_SINGLETON = Symbol.for(\n 'next.server.action-manifests',\n);\n\nconst PROJECT_ID =\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID;\n\nasync function tryImport<T>(importer: () => Promise<T>) {\n try {\n return (await importer()) as T;\n } catch {\n return {} as T;\n }\n}\n\n// inject the RSC flight data into the HTML response using <script>\n// the RSC flight data is used to hydrate the remote component on the host\n// this approach is similar to an island architecture on the host\n// the remote component is static HTML until it is hydrated using this RSC flight data\nfunction RemoteComponentData({ name, data }: { name: string; data: string[] }) {\n return (\n <script id={`${name}_rsc`}>\n {data\n .map(\n (chunk, i) =>\n // make the data handling somewhat safe\n `${i === 0 ? `self[\"${name}\"]=self[\"${name}\"]||[];` : ''}self[\"${name}\"].push(${JSON.stringify(\n chunk,\n )});`,\n )\n .join('\\n')}\n </script>\n );\n}\n\nexport interface RemoteComponentProps {\n /** The name of the remote component. Use a unique name to expose multiple remote components from the same page. */\n name?: string;\n /** The content of the remote component. This is the content that will be rendered as the remote component. */\n children: React.ReactNode;\n}\n\n/**\n * RemoteComponent is a Next.js component that exposes a remote component\n * that can be used in a host application.\n *\n * @param name - The name of the remote component. Use a unique name to expose multiple remote components from the same page.\n * @param children - The content of the remote component. This is the content that will be rendered as the remote component.\n * @returns A React component that renders the remote component.\n *\n * @example\n *\n * Use the `<RemoteComponent>` in your Next.js App Router application to expose the children as a remote component:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/next';\n *\n * export default function MyPage() {\n * return (\n * <RemoteComponent>\n * <h1>Hello from the remote component!</h1>\n * <p>This is a remote component that can be used in a host application.</p>\n * </RemoteComponent>\n * );\n * }\n * ```\n */\nexport async function RemoteComponent({\n name = '__vercel_remote_component',\n children,\n}: RemoteComponentProps): Promise<React.ReactElement> {\n // access the internal Next.js work store to get the active page and route\n const { page, route } = workAsyncStorage.getStore() ?? {\n page: '/',\n route: '/',\n };\n\n // get reference to the manifests from the global scope\n const manifests = (\n globalThis as typeof globalThis & {\n [SERVER_ACTION_MANIFESTS_SINGLETON]: {\n clientReferenceManifestsPerPage?: Record<string, Manifest>;\n };\n }\n )[SERVER_ACTION_MANIFESTS_SINGLETON];\n const manifest = manifests.clientReferenceManifestsPerPage?.[route];\n\n const self = globalThis as typeof globalThis & {\n [SERVER_ACTION_MANIFESTS_SINGLETON]?: {\n clientReferenceManifestsPerPage?: Record<string, Manifest>;\n };\n __RSC_MANIFEST?: Record<string, unknown>;\n };\n\n // manually handle the internal Next.js manifest\n self.__RSC_MANIFEST = self.__RSC_MANIFEST || {};\n self.__RSC_MANIFEST[page] = self.__RSC_MANIFEST[page] || manifest;\n\n // get the client and SSR module mapping to be able to use client components in the remote component\n let clientModules = manifest?.clientModules ?? {};\n const ssrModuleMapping = { ...manifest?.ssrModuleMapping };\n\n // if the remote component is used in a hosting application, we need to mutate the module map to include the zone\n clientModules = Object.fromEntries(\n Object.entries(clientModules).map(([key, value]) => {\n // append a prefix to each entry in the module map to include the zone of the remote component\n const remoteId = `[${PROJECT_ID}] ${value.id}`;\n ssrModuleMapping[remoteId] = ssrModuleMapping[value.id];\n // override the original id with the new remote id\n return [\n key,\n {\n ...value,\n id: remoteId,\n // prepend the current zone to the chunks to handle remote component chunk loading in Webpack\n // this is required to avoid loading the wrong chunk in the host application\n chunks: value.chunks.map((chunk) => `[${PROJECT_ID}] ${chunk}`),\n },\n ];\n }),\n );\n\n // dynamically import the runtime specific RSC rendering functions and client component\n const [\n { renderToReadableStream: nextRenderToReadableStream },\n { renderToReadableStream: legacyRenderToReadableStream },\n ] = await Promise.all(\n process.env.TURBOPACK\n ? [\n tryImport<RSDWServer>(\n () => import('react-server-dom-turbopack/server'),\n ),\n tryImport<RSDWServer>(\n () => import('react-server-dom-turbopack/server.edge'),\n ),\n ]\n : [\n tryImport<RSDWServer>(\n () => import('react-server-dom-webpack/server'),\n ),\n tryImport<RSDWServer>(\n () => import('react-server-dom-webpack/server.edge'),\n ),\n ],\n );\n const renderToReadableStream =\n nextRenderToReadableStream ?? legacyRenderToReadableStream;\n\n if (typeof renderToReadableStream !== 'function') {\n throw new RemoteComponentsError(\n 'No valid `renderToReadableStream()` function found. Do you have Next.js installed?',\n );\n }\n\n let error: Error | undefined;\n // render the wrapped content of this component (children) into an RSC stream\n const stream = renderToReadableStream(children, clientModules, {\n onError(e) {\n error = e;\n },\n });\n\n const data = [];\n const decoder = new TextDecoder();\n\n // convert the stream to an array for safe passing to the client\n for await (const chunk of stream as unknown as AsyncIterable<Uint8Array>) {\n data.push(decoder.decode(chunk));\n }\n\n const runtime = process.env.TURBOPACK ? 'turbopack' : 'webpack';\n const remoteComponentName = `${name}_${route.replace(/[/[\\].]/g, '_')}`;\n\n return (\n // wrap the remote component content into a div to know which part of the HTML belongs to the remote component\n <div\n data-bundle={PROJECT_ID}\n data-route={route}\n data-runtime={runtime}\n data-type=\"nextjs\"\n id={`${remoteComponentName}_ssr`}\n >\n <RemoteComponentSharedRemote name={remoteComponentName} />\n {typeof error !== 'undefined' ? (\n <>\n <template\n data-next-error-message={\n error instanceof Error ? error.message : String(error)\n }\n data-next-error-stack={\n error instanceof Error ? (error.stack ?? '') : ''\n }\n />\n <Suspense fallback={null}>{children}</Suspense>\n </>\n ) : (\n children\n )}\n {/* inject RSC flight data as <script> */}\n <RemoteComponentData data={data} name={remoteComponentName} />\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA8BI;AA9BJ,gCAAiC;AACjC,mBAAyB;AACzB,2BAA4C;AAC5C,mBAAsC;AAItC,MAAM,oCAAoC,OAAO;AAAA,EAC/C;AACF;AAEA,MAAM,aACJ,QAAQ,IAAI,gCACZ,QAAQ,IAAI,uCACZ,QAAQ,IAAI;AAEd,eAAe,UAAa,UAA4B;AACtD,MAAI;AACF,WAAQ,MAAM,SAAS;AAAA,EACzB,QAAE;AACA,WAAO,CAAC;AAAA,EACV;AACF;AAMA,SAAS,oBAAoB,EAAE,MAAM,KAAK,GAAqC;AAC7E,SACE,4CAAC,YAAO,IAAI,GAAG,YACZ,eACE;AAAA,IACC,CAAC,OAAO;AAAA;AAAA,MAEN,GAAG,MAAM,IAAI,SAAS,gBAAgB,gBAAgB,WAAW,eAAe,KAAK;AAAA,QACnF;AAAA,MACF;AAAA;AAAA,EACJ,EACC,KAAK,IAAI,GACd;AAEJ;AAkCA,eAAsB,gBAAgB;AAAA,EACpC,OAAO;AAAA,EACP;AACF,GAAsD;AAEpD,QAAM,EAAE,MAAM,MAAM,IAAI,2CAAiB,SAAS,KAAK;AAAA,IACrD,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAGA,QAAM,YACJ,WAKA,iCAAiC;AACnC,QAAM,WAAW,UAAU,kCAAkC,KAAK;AAElE,QAAM,OAAO;AAQb,OAAK,iBAAiB,KAAK,kBAAkB,CAAC;AAC9C,OAAK,eAAe,IAAI,IAAI,KAAK,eAAe,IAAI,KAAK;AAGzD,MAAI,gBAAg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AQ,IAAI,YAAY,cAAc;AACtD,QAAM,sBAAsB,GAAG,QAAQ,MAAM,QAAQ,YAAY,GAAG;AAEpE;AAAA;AAAA,IAEE;AAAA,MAAC;AAAA;AAAA,QACC,eAAa;AAAA,QACb,cAAY;AAAA,QACZ,gBAAc;AAAA,QACd,aAAU;AAAA,QACV,IAAI,GAAG;AAAA,QAEP;AAAA,sDAAC,oDAA4B,MAAM,qBAAqB;AAAA,UACvD,OAAO,UAAU,cAChB,4EACE;AAAA;AAAA,cAAC;AAAA;AAAA,gBACC,2BACE,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,gBAEvD,yBACE,iBAAiB,QAAS,MAAM,SAAS,KAAM;AAAA;AAAA,YAEnD;AAAA,YACA,4CAAC,yBAAS,UAAU,MAAO,UAAS;AAAA,aACtC,IAEA;AAAA,UAGF,4CAAC,uBAAoB,MAAY,MAAM,qBAAqB;AAAA;AAAA;AAAA,IAC9D;AAAA;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/next/remote/render-server.tsx"],"sourcesContent":["import { workAsyncStorage } from 'next/dist/server/app-render/work-async-storage.external';\nimport { Suspense } from 'react';\nimport { RemoteComponentSharedRemote } from '#internal/next/remote/render-client';\nimport { RemoteComponentsError } from '#internal/shared/error';\nimport type { Manifest } from './types';\n\n// internal Next.js symbol to access the manifest which is stored in the global scope\nconst SERVER_ACTION_MANIFESTS_SINGLETON = Symbol.for(\n 'next.server.action-manifests',\n);\n\nconst PROJECT_ID =\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID;\n\nasync function tryImport<T>(importer: () => Promise<T>) {\n try {\n return (await importer()) as T;\n } catch {\n return {} as T;\n }\n}\n\n// inject the RSC flight data into the HTML response using <script>\n// the RSC flight data is used to hydrate the remote component on the host\n// this approach is similar to an island architecture on the host\n// the remote component is static HTML until it is hydrated using this RSC flight data\nfunction RemoteComponentData({ name, data }: { name: string; data: string[] }) {\n return (\n <script id={`${name}_rsc`}>\n {data\n .map(\n (chunk, i) =>\n // make the data handling somewhat safe\n `${i === 0 ? `self[\"${name}\"]=self[\"${name}\"]||[];` : ''}self[\"${name}\"].push(${JSON.stringify(\n chunk,\n )});`,\n )\n .join('\\n')}\n </script>\n );\n}\n\nexport interface RemoteComponentProps {\n /** The name of the remote component. Use a unique name to expose multiple remote components from the same page. */\n name?: string;\n /** The content of the remote component. This is the content that will be rendered as the remote component. */\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\n/**\n * RemoteComponent is a Next.js component that exposes a remote component\n * that can be used in a host application.\n *\n * @param name - The name of the remote component. Use a unique name to expose multiple remote components from the same page.\n * @param children - The content of the remote component. This is the content that will be rendered as the remote component.\n * @returns A React component that renders the remote component.\n *\n * @example\n *\n * Use the `<RemoteComponent>` in your Next.js App Router application to expose the children as a remote component:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/next';\n *\n * export default function MyPage() {\n * return (\n * <RemoteComponent>\n * <h1>Hello from the remote component!</h1>\n * <p>This is a remote component that can be used in a host application.</p>\n * </RemoteComponent>\n * );\n * }\n * ```\n */\nexport async function RemoteComponent({\n name = '__vercel_remote_component',\n children,\n}: RemoteComponentProps): Promise<React.ReactElement> {\n // access the internal Next.js work store to get the active page and route\n const { page, route } = workAsyncStorage.getStore() ?? {\n page: '/',\n route: '/',\n };\n\n // get reference to the manifests from the global scope\n const manifests = (\n globalThis as typeof globalThis & {\n [SERVER_ACTION_MANIFESTS_SINGLETON]: {\n clientReferenceManifestsPerPage?: Record<string, Manifest>;\n };\n }\n )[SERVER_ACTION_MANIFESTS_SINGLETON];\n const manifest = manifests.clientReferenceManifestsPerPage?.[route];\n\n const self = globalThis as typeof globalThis & {\n [SERVER_ACTION_MANIFESTS_SINGLETON]?: {\n clientReferenceManifestsPerPage?: Record<string, Manifest>;\n };\n __RSC_MANIFEST?: Record<string, unknown>;\n };\n\n // manually handle the internal Next.js manifest\n self.__RSC_MANIFEST = self.__RSC_MANIFEST || {};\n self.__RSC_MANIFEST[page] = self.__RSC_MANIFEST[page] || manifest;\n\n // get the client and SSR module mapping to be able to use client components in the remote component\n let clientModules = manifest?.clientModules ?? {};\n const ssrModuleMapping = { ...manifest?.ssrModuleMapping };\n\n // if the remote component is used in a hosting application, we need to mutate the module map to include the zone\n clientModules = Object.fromEntries(\n Object.entries(clientModules).map(([key, value]) => {\n // append a prefix to each entry in the module map to include the zone of the remote component\n const remoteId = `[${PROJECT_ID}] ${value.id}`;\n ssrModuleMapping[remoteId] = ssrModuleMapping[value.id];\n // override the original id with the new remote id\n return [\n key,\n {\n ...value,\n id: remoteId,\n // prepend the current zone to the chunks to handle remote component chunk loading in Webpack\n // this is required to avoid loading the wrong chunk in the host application\n chunks: value.chunks.map((chunk) => `[${PROJECT_ID}] ${chunk}`),\n },\n ];\n }),\n );\n\n // dynamically import the runtime specific RSC rendering functions and client component\n const [\n { renderToReadableStream: nextRenderToReadableStream },\n { renderToReadableStream: legacyRenderToReadableStream },\n ] = await Promise.all(\n process.env.TURBOPACK\n ? [\n tryImport<RSDWServer>(\n () => import('react-server-dom-turbopack/server'),\n ),\n tryImport<RSDWServer>(\n () => import('react-server-dom-turbopack/server.edge'),\n ),\n ]\n : [\n tryImport<RSDWServer>(\n () => import('react-server-dom-webpack/server'),\n ),\n tryImport<RSDWServer>(\n () => import('react-server-dom-webpack/server.edge'),\n ),\n ],\n );\n const renderToReadableStream =\n nextRenderToReadableStream ?? legacyRenderToReadableStream;\n\n if (typeof renderToReadableStream !== 'function') {\n throw new RemoteComponentsError(\n 'No valid `renderToReadableStream()` function found. Do you have Next.js installed?',\n );\n }\n\n let error: Error | undefined;\n // render the wrapped content of this component (children) into an RSC stream\n const stream = renderToReadableStream(children, clientModules, {\n onError(e) {\n error = e;\n },\n });\n\n const data = [];\n const decoder = new TextDecoder();\n\n // convert the stream to an array for safe passing to the client\n for await (const chunk of stream as unknown as AsyncIterable<Uint8Array>) {\n data.push(decoder.decode(chunk));\n }\n\n const runtime = process.env.TURBOPACK ? 'turbopack' : 'webpack';\n const remoteComponentName = `${name}_${route.replace(/[/[\\].]/g, '_')}`;\n\n return (\n // wrap the remote component content into a div to know which part of the HTML belongs to the remote component\n <div\n data-bundle={PROJECT_ID}\n data-route={route}\n data-runtime={runtime}\n data-type=\"nextjs\"\n id={`${remoteComponentName}_ssr`}\n >\n <RemoteComponentSharedRemote name={remoteComponentName} />\n {typeof error !== 'undefined' ? (\n <>\n <template\n data-next-error-message={\n error instanceof Error ? error.message : String(error)\n }\n data-next-error-stack={\n error instanceof Error ? (error.stack ?? '') : ''\n }\n />\n <Suspense fallback={null}>{children}</Suspense>\n </>\n ) : (\n children\n )}\n {/* inject RSC flight data as <script> */}\n <RemoteComponentData data={data} name={remoteComponentName} />\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA8BI;AA9BJ,gCAAiC;AACjC,mBAAyB;AACzB,2BAA4C;AAC5C,mBAAsC;AAItC,MAAM,oCAAoC,OAAO;AAAA,EAC/C;AACF;AAEA,MAAM,aACJ,QAAQ,IAAI,gCACZ,QAAQ,IAAI,uCACZ,QAAQ,IAAI;AAEd,eAAe,UAAa,UAA4B;AACtD,MAAI;AACF,WAAQ,MAAM,SAAS;AAAA,EACzB,QAAE;AACA,WAAO,CAAC;AAAA,EACV;AACF;AAMA,SAAS,oBAAoB,EAAE,MAAM,KAAK,GAAqC;AAC7E,SACE,4CAAC,YAAO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name?: string;
|
|
4
4
|
/** The content of the remote component. This is the content that will be rendered as the remote component. */
|
|
5
5
|
children: React.ReactNode;
|
|
6
|
+
/** Called right before a new remote component load starts. */
|
|
7
|
+
onBeforeLoad?: (src: string | URL) => void;
|
|
8
|
+
/** Called when the remote component has been successfully loaded and mounted. */
|
|
9
|
+
onLoad?: (src: string | URL) => void;
|
|
10
|
+
/** Called when an error occurs while loading or mounting the remote component. */
|
|
11
|
+
onError?: (error: unknown) => void;
|
|
12
|
+
/** Called when a different remote component is loaded into the same wrapper. */
|
|
13
|
+
onChange?: (info: {
|
|
14
|
+
previousSrc: string | URL | null;
|
|
15
|
+
nextSrc: string | URL | null;
|
|
16
|
+
previousName: string | undefined;
|
|
17
|
+
nextName: string | undefined;
|
|
18
|
+
}) => void;
|
|
6
19
|
}
|
|
7
20
|
/**
|
|
8
21
|
* RemoteComponent is a Next.js component that exposes a remote component
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/next/remote/render-server.tsx"],"sourcesContent":["import { workAsyncStorage } from 'next/dist/server/app-render/work-async-storage.external';\nimport { Suspense } from 'react';\nimport { RemoteComponentSharedRemote } from '#internal/next/remote/render-client';\nimport { RemoteComponentsError } from '#internal/shared/error';\nimport type { Manifest } from './types';\n\n// internal Next.js symbol to access the manifest which is stored in the global scope\nconst SERVER_ACTION_MANIFESTS_SINGLETON = Symbol.for(\n 'next.server.action-manifests',\n);\n\nconst PROJECT_ID =\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID;\n\nasync function tryImport<T>(importer: () => Promise<T>) {\n try {\n return (await importer()) as T;\n } catch {\n return {} as T;\n }\n}\n\n// inject the RSC flight data into the HTML response using <script>\n// the RSC flight data is used to hydrate the remote component on the host\n// this approach is similar to an island architecture on the host\n// the remote component is static HTML until it is hydrated using this RSC flight data\nfunction RemoteComponentData({ name, data }: { name: string; data: string[] }) {\n return (\n <script id={`${name}_rsc`}>\n {data\n .map(\n (chunk, i) =>\n // make the data handling somewhat safe\n `${i === 0 ? `self[\"${name}\"]=self[\"${name}\"]||[];` : ''}self[\"${name}\"].push(${JSON.stringify(\n chunk,\n )});`,\n )\n .join('\\n')}\n </script>\n );\n}\n\nexport interface RemoteComponentProps {\n /** The name of the remote component. Use a unique name to expose multiple remote components from the same page. */\n name?: string;\n /** The content of the remote component. This is the content that will be rendered as the remote component. */\n children: React.ReactNode;\n}\n\n/**\n * RemoteComponent is a Next.js component that exposes a remote component\n * that can be used in a host application.\n *\n * @param name - The name of the remote component. Use a unique name to expose multiple remote components from the same page.\n * @param children - The content of the remote component. This is the content that will be rendered as the remote component.\n * @returns A React component that renders the remote component.\n *\n * @example\n *\n * Use the `<RemoteComponent>` in your Next.js App Router application to expose the children as a remote component:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/next';\n *\n * export default function MyPage() {\n * return (\n * <RemoteComponent>\n * <h1>Hello from the remote component!</h1>\n * <p>This is a remote component that can be used in a host application.</p>\n * </RemoteComponent>\n * );\n * }\n * ```\n */\nexport async function RemoteComponent({\n name = '__vercel_remote_component',\n children,\n}: RemoteComponentProps): Promise<React.ReactElement> {\n // access the internal Next.js work store to get the active page and route\n const { page, route } = workAsyncStorage.getStore() ?? {\n page: '/',\n route: '/',\n };\n\n // get reference to the manifests from the global scope\n const manifests = (\n globalThis as typeof globalThis & {\n [SERVER_ACTION_MANIFESTS_SINGLETON]: {\n clientReferenceManifestsPerPage?: Record<string, Manifest>;\n };\n }\n )[SERVER_ACTION_MANIFESTS_SINGLETON];\n const manifest = manifests.clientReferenceManifestsPerPage?.[route];\n\n const self = globalThis as typeof globalThis & {\n [SERVER_ACTION_MANIFESTS_SINGLETON]?: {\n clientReferenceManifestsPerPage?: Record<string, Manifest>;\n };\n __RSC_MANIFEST?: Record<string, unknown>;\n };\n\n // manually handle the internal Next.js manifest\n self.__RSC_MANIFEST = self.__RSC_MANIFEST || {};\n self.__RSC_MANIFEST[page] = self.__RSC_MANIFEST[page] || manifest;\n\n // get the client and SSR module mapping to be able to use client components in the remote component\n let clientModules = manifest?.clientModules ?? {};\n const ssrModuleMapping = { ...manifest?.ssrModuleMapping };\n\n // if the remote component is used in a hosting application, we need to mutate the module map to include the zone\n clientModules = Object.fromEntries(\n Object.entries(clientModules).map(([key, value]) => {\n // append a prefix to each entry in the module map to include the zone of the remote component\n const remoteId = `[${PROJECT_ID}] ${value.id}`;\n ssrModuleMapping[remoteId] = ssrModuleMapping[value.id];\n // override the original id with the new remote id\n return [\n key,\n {\n ...value,\n id: remoteId,\n // prepend the current zone to the chunks to handle remote component chunk loading in Webpack\n // this is required to avoid loading the wrong chunk in the host application\n chunks: value.chunks.map((chunk) => `[${PROJECT_ID}] ${chunk}`),\n },\n ];\n }),\n );\n\n // dynamically import the runtime specific RSC rendering functions and client component\n const [\n { renderToReadableStream: nextRenderToReadableStream },\n { renderToReadableStream: legacyRenderToReadableStream },\n ] = await Promise.all(\n process.env.TURBOPACK\n ? [\n tryImport<RSDWServer>(\n () => import('react-server-dom-turbopack/server'),\n ),\n tryImport<RSDWServer>(\n () => import('react-server-dom-turbopack/server.edge'),\n ),\n ]\n : [\n tryImport<RSDWServer>(\n () => import('react-server-dom-webpack/server'),\n ),\n tryImport<RSDWServer>(\n () => import('react-server-dom-webpack/server.edge'),\n ),\n ],\n );\n const renderToReadableStream =\n nextRenderToReadableStream ?? legacyRenderToReadableStream;\n\n if (typeof renderToReadableStream !== 'function') {\n throw new RemoteComponentsError(\n 'No valid `renderToReadableStream()` function found. Do you have Next.js installed?',\n );\n }\n\n let error: Error | undefined;\n // render the wrapped content of this component (children) into an RSC stream\n const stream = renderToReadableStream(children, clientModules, {\n onError(e) {\n error = e;\n },\n });\n\n const data = [];\n const decoder = new TextDecoder();\n\n // convert the stream to an array for safe passing to the client\n for await (const chunk of stream as unknown as AsyncIterable<Uint8Array>) {\n data.push(decoder.decode(chunk));\n }\n\n const runtime = process.env.TURBOPACK ? 'turbopack' : 'webpack';\n const remoteComponentName = `${name}_${route.replace(/[/[\\].]/g, '_')}`;\n\n return (\n // wrap the remote component content into a div to know which part of the HTML belongs to the remote component\n <div\n data-bundle={PROJECT_ID}\n data-route={route}\n data-runtime={runtime}\n data-type=\"nextjs\"\n id={`${remoteComponentName}_ssr`}\n >\n <RemoteComponentSharedRemote name={remoteComponentName} />\n {typeof error !== 'undefined' ? (\n <>\n <template\n data-next-error-message={\n error instanceof Error ? error.message : String(error)\n }\n data-next-error-stack={\n error instanceof Error ? (error.stack ?? '') : ''\n }\n />\n <Suspense fallback={null}>{children}</Suspense>\n </>\n ) : (\n children\n )}\n {/* inject RSC flight data as <script> */}\n <RemoteComponentData data={data} name={remoteComponentName} />\n </div>\n );\n}\n"],"mappings":"AA8BI,SAmKI,UAnKJ,KAmKI,YAnKJ;AA9BJ,SAAS,wBAAwB;AACjC,SAAS,gBAAgB;AACzB,SAAS,mCAAmC;AAC5C,SAAS,6BAA6B;AAItC,MAAM,oCAAoC,OAAO;AAAA,EAC/C;AACF;AAEA,MAAM,aACJ,QAAQ,IAAI,gCACZ,QAAQ,IAAI,uCACZ,QAAQ,IAAI;AAEd,eAAe,UAAa,UAA4B;AACtD,MAAI;AACF,WAAQ,MAAM,SAAS;AAAA,EACzB,QAAE;AACA,WAAO,CAAC;AAAA,EACV;AACF;AAMA,SAAS,oBAAoB,EAAE,MAAM,KAAK,GAAqC;AAC7E,SACE,oBAAC,YAAO,IAAI,GAAG,YACZ,eACE;AAAA,IACC,CAAC,OAAO;AAAA;AAAA,MAEN,GAAG,MAAM,IAAI,SAAS,gBAAgB,gBAAgB,WAAW,eAAe,KAAK;AAAA,QACnF;AAAA,MACF;AAAA;AAAA,EACJ,EACC,KAAK,IAAI,GACd;AAEJ;AAkCA,eAAsB,gBAAgB;AAAA,EACpC,OAAO;AAAA,EACP;AACF,GAAsD;AAEpD,QAAM,EAAE,MAAM,MAAM,IAAI,iBAAiB,SAAS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,QAAM,SAAS,uBAAuB,UAAU,eAAe;AAAA,IAC7D,QAAQ,GAAG;AACT,cAAQ;AAAA,IACV;AAAA,EACF,CAAC;AAED,QAAM,OAAO,CAAC;AACd,QAAM,UAAU,IAAI,YAAY;AAGhC,mBAAiB,SAAS,QAAgD;AACxE,SAAK,KAAK,QAAQ,OAAO,KAAK,CAAC;AAAA,EACjC;AAEA,QAAM,UAAU,QAAQ,IAAI,YAAY,cAAc;AACtD,QAAM,sBAAsB,GAAG,QAAQ,MAAM,QAAQ,YAAY,GAAG;AAEpE;AAAA;AAAA,IAEE;AAAA,MAAC;AAAA;AAAA,QACC,eAAa;AAAA,QACb,cAAY;AAAA,QACZ,gBAAc;AAAA,QACd,aAAU;AAAA,QACV,IAAI,GAAG;AAAA,QAEP;AAAA,8BAAC,+BAA4B,MAAM,qBAAqB;AAAA,UACvD,OAAO,UAAU,cAChB,iCACE;AAAA;AAAA,cAAC;AAAA;AAAA,gBACC,2BACE,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,gBAEvD,yBACE,iBAAiB,QAAS,MAAM,SAAS,KAAM;AAAA;AAAA,YAEnD;AAAA,YACA,oBAAC,YAAS,UAAU,MAAO,UAAS;AAAA,aACtC,IAEA;AAAA,UAGF,oBAAC,uBAAoB,MAAY,MAAM,qBAAqB;AAAA;AAAA;AAAA,IAC9D;AAAA;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/next/remote/render-server.tsx"],"sourcesContent":["import { workAsyncStorage } from 'next/dist/server/app-render/work-async-storage.external';\nimport { Suspense } from 'react';\nimport { RemoteComponentSharedRemote } from '#internal/next/remote/render-client';\nimport { RemoteComponentsError } from '#internal/shared/error';\nimport type { Manifest } from './types';\n\n// internal Next.js symbol to access the manifest which is stored in the global scope\nconst SERVER_ACTION_MANIFESTS_SINGLETON = Symbol.for(\n 'next.server.action-manifests',\n);\n\nconst PROJECT_ID =\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID;\n\nasync function tryImport<T>(importer: () => Promise<T>) {\n try {\n return (await importer()) as T;\n } catch {\n return {} as T;\n }\n}\n\n// inject the RSC flight data into the HTML response using <script>\n// the RSC flight data is used to hydrate the remote component on the host\n// this approach is similar to an island architecture on the host\n// the remote component is static HTML until it is hydrated using this RSC flight data\nfunction RemoteComponentData({ name, data }: { name: string; data: string[] }) {\n return (\n <script id={`${name}_rsc`}>\n {data\n .map(\n (chunk, i) =>\n // make the data handling somewhat safe\n `${i === 0 ? `self[\"${name}\"]=self[\"${name}\"]||[];` : ''}self[\"${name}\"].push(${JSON.stringify(\n chunk,\n )});`,\n )\n .join('\\n')}\n </script>\n );\n}\n\nexport interface RemoteComponentProps {\n /** The name of the remote component. Use a unique name to expose multiple remote components from the same page. */\n name?: string;\n /** The content of the remote component. This is the content that will be rendered as the remote component. */\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\n/**\n * RemoteComponent is a Next.js component that exposes a remote component\n * that can be used in a host application.\n *\n * @param name - The name of the remote component. Use a unique name to expose multiple remote components from the same page.\n * @param children - The content of the remote component. This is the content that will be rendered as the remote component.\n * @returns A React component that renders the remote component.\n *\n * @example\n *\n * Use the `<RemoteComponent>` in your Next.js App Router application to expose the children as a remote component:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/next';\n *\n * export default function MyPage() {\n * return (\n * <RemoteComponent>\n * <h1>Hello from the remote component!</h1>\n * <p>This is a remote component that can be used in a host application.</p>\n * </RemoteComponent>\n * );\n * }\n * ```\n */\nexport async function RemoteComponent({\n name = '__vercel_remote_component',\n children,\n}: RemoteComponentProps): Promise<React.ReactElement> {\n // access the internal Next.js work store to get the active page and route\n const { page, route } = workAsyncStorage.getStore() ?? {\n page: '/',\n route: '/',\n };\n\n // get reference to the manifests from the global scope\n const manifests = (\n globalThis as typeof globalThis & {\n [SERVER_ACTION_MANIFESTS_SINGLETON]: {\n clientReferenceManifestsPerPage?: Record<string, Manifest>;\n };\n }\n )[SERVER_ACTION_MANIFESTS_SINGLETON];\n const manifest = manifests.clientReferenceManifestsPerPage?.[route];\n\n const self = globalThis as typeof globalThis & {\n [SERVER_ACTION_MANIFESTS_SINGLETON]?: {\n clientReferenceManifestsPerPage?: Record<string, Manifest>;\n };\n __RSC_MANIFEST?: Record<string, unknown>;\n };\n\n // manually handle the internal Next.js manifest\n self.__RSC_MANIFEST = self.__RSC_MANIFEST || {};\n self.__RSC_MANIFEST[page] = self.__RSC_MANIFEST[page] || manifest;\n\n // get the client and SSR module mapping to be able to use client components in the remote component\n let clientModules = manifest?.clientModules ?? {};\n const ssrModuleMapping = { ...manifest?.ssrModuleMapping };\n\n // if the remote component is used in a hosting application, we need to mutate the module map to include the zone\n clientModules = Object.fromEntries(\n Object.entries(clientModules).map(([key, value]) => {\n // append a prefix to each entry in the module map to include the zone of the remote component\n const remoteId = `[${PROJECT_ID}] ${value.id}`;\n ssrModuleMapping[remoteId] = ssrModuleMapping[value.id];\n // override the original id with the new remote id\n return [\n key,\n {\n ...value,\n id: remoteId,\n // prepend the current zone to the chunks to handle remote component chunk loading in Webpack\n // this is required to avoid loading the wrong chunk in the host application\n chunks: value.chunks.map((chunk) => `[${PROJECT_ID}] ${chunk}`),\n },\n ];\n }),\n );\n\n // dynamically import the runtime specific RSC rendering functions and client component\n const [\n { renderToReadableStream: nextRenderToReadableStream },\n { renderToReadableStream: legacyRenderToReadableStream },\n ] = await Promise.all(\n process.env.TURBOPACK\n ? [\n tryImport<RSDWServer>(\n () => import('react-server-dom-turbopack/server'),\n ),\n tryImport<RSDWServer>(\n () => import('react-server-dom-turbopack/server.edge'),\n ),\n ]\n : [\n tryImport<RSDWServer>(\n () => import('react-server-dom-webpack/server'),\n ),\n tryImport<RSDWServer>(\n () => import('react-server-dom-webpack/server.edge'),\n ),\n ],\n );\n const renderToReadableStream =\n nextRenderToReadableStream ?? legacyRenderToReadableStream;\n\n if (typeof renderToReadableStream !== 'function') {\n throw new RemoteComponentsError(\n 'No valid `renderToReadableStream()` function found. Do you have Next.js installed?',\n );\n }\n\n let error: Error | undefined;\n // render the wrapped content of this component (children) into an RSC stream\n const stream = renderToReadableStream(children, clientModules, {\n onError(e) {\n error = e;\n },\n });\n\n const data = [];\n const decoder = new TextDecoder();\n\n // convert the stream to an array for safe passing to the client\n for await (const chunk of stream as unknown as AsyncIterable<Uint8Array>) {\n data.push(decoder.decode(chunk));\n }\n\n const runtime = process.env.TURBOPACK ? 'turbopack' : 'webpack';\n const remoteComponentName = `${name}_${route.replace(/[/[\\].]/g, '_')}`;\n\n return (\n // wrap the remote component content into a div to know which part of the HTML belongs to the remote component\n <div\n data-bundle={PROJECT_ID}\n data-route={route}\n data-runtime={runtime}\n data-type=\"nextjs\"\n id={`${remoteComponentName}_ssr`}\n >\n <RemoteComponentSharedRemote name={remoteComponentName} />\n {typeof error !== 'undefined' ? (\n <>\n <template\n data-next-error-message={\n error instanceof Error ? error.message : String(error)\n }\n data-next-error-stack={\n error instanceof Error ? (error.stack ?? '') : ''\n }\n />\n <Suspense fallback={null}>{children}</Suspense>\n </>\n ) : (\n children\n )}\n {/* inject RSC flight data as <script> */}\n <RemoteComponentData data={data} name={remoteComponentName} />\n </div>\n );\n}\n"],"mappings":"AA8BI,SAgLI,UAhLJ,KAgLI,YAhLJ;AA9BJ,SAAS,wBAAwB;AACjC,SAAS,gBAAgB;AACzB,SAAS,mCAAmC;AAC5C,SAAS,6BAA6B;AAItC,MAAM,oCAAoC,OAAO;AAAA,EAC/C;AACF;AAEA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,MAAM,SAAS,KAAM;AAAA;AAAA,YAEnD;AAAA,YACA,oBAAC,YAAS,UAAU,MAAO,UAAS;AAAA,aACtC,IAEA;AAAA,UAGF,oBAAC,uBAAoB,MAAY,MAAM,qBAAqB;AAAA;AAAA;AAAA,IAC9D;AAAA;AAEJ;","names":[]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var get_client_src_exports = {};
|
|
20
|
+
__export(get_client_src_exports, {
|
|
21
|
+
getClientSrc: () => getClientSrc
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(get_client_src_exports);
|
|
24
|
+
var import_get_ssr_relative_path_base_url = require("#internal/shared/ssr/get-ssr-relative-path-base-url");
|
|
25
|
+
function getClientSrc(src, serverUrl) {
|
|
26
|
+
if (typeof src !== "string") {
|
|
27
|
+
return "";
|
|
28
|
+
}
|
|
29
|
+
const url = new URL(src, serverUrl);
|
|
30
|
+
if (url.origin === (0, import_get_ssr_relative_path_base_url.getSSRRelativePathBaseUrl)()) {
|
|
31
|
+
return `${url.pathname}${url.search}`;
|
|
32
|
+
}
|
|
33
|
+
return url.href;
|
|
34
|
+
}
|
|
35
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
36
|
+
0 && (module.exports = {
|
|
37
|
+
getClientSrc
|
|
38
|
+
});
|
|
39
|
+
//# sourceMappingURL=get-client-src.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/shared/client/get-client-src.ts"],"sourcesContent":["import { getSSRRelativePathBaseUrl } from '#internal/shared/ssr/get-ssr-relative-path-base-url';\n\n/**\n * If a relative src was provided, but the server url base was used for SSR,\n * use the relative path as the src.\n */\nexport function getClientSrc(\n src: string | boolean | undefined,\n serverUrl: string,\n): string {\n if (typeof src !== 'string') {\n return '';\n }\n\n const url = new URL(src, serverUrl);\n\n if (url.origin === getSSRRelativePathBaseUrl()) {\n return `${url.pathname}${url.search}`;\n }\n\n return url.href;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4CAA0C;AAMnC,SAAS,aACd,KACA,WACQ;AACR,MAAI,OAAO,QAAQ,UAAU;AAC3B,WAAO;AAAA,EACT;AAEA,QAAM,MAAM,IAAI,IAAI,KAAK,SAAS;AAElC,MAAI,IAAI,eAAW,iEAA0B,GAAG;AAC9C,WAAO,GAAG,IAAI,WAAW,IAAI;AAAA,EAC/B;AAEA,SAAO,IAAI;AACb;","names":[]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { getSSRRelativePathBaseUrl } from "#internal/shared/ssr/get-ssr-relative-path-base-url";
|
|
2
|
+
function getClientSrc(src, serverUrl) {
|
|
3
|
+
if (typeof src !== "string") {
|
|
4
|
+
return "";
|
|
5
|
+
}
|
|
6
|
+
const url = new URL(src, serverUrl);
|
|
7
|
+
if (url.origin === getSSRRelativePathBaseUrl()) {
|
|
8
|
+
return `${url.pathname}${url.search}`;
|
|
9
|
+
}
|
|
10
|
+
return url.href;
|
|
11
|
+
}
|
|
12
|
+
export {
|
|
13
|
+
getClientSrc
|
|
14
|
+
};
|
|
15
|
+
//# sourceMappingURL=get-client-src.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/shared/client/get-client-src.ts"],"sourcesContent":["import { getSSRRelativePathBaseUrl } from '#internal/shared/ssr/get-ssr-relative-path-base-url';\n\n/**\n * If a relative src was provided, but the server url base was used for SSR,\n * use the relative path as the src.\n */\nexport function getClientSrc(\n src: string | boolean | undefined,\n serverUrl: string,\n): string {\n if (typeof src !== 'string') {\n return '';\n }\n\n const url = new URL(src, serverUrl);\n\n if (url.origin === getSSRRelativePathBaseUrl()) {\n return `${url.pathname}${url.search}`;\n }\n\n return url.href;\n}\n"],"mappings":"AAAA,SAAS,iCAAiC;AAMnC,SAAS,aACd,KACA,WACQ;AACR,MAAI,OAAO,QAAQ,UAAU;AAC3B,WAAO;AAAA,EACT;AAEA,QAAM,MAAM,IAAI,IAAI,KAAK,SAAS;AAElC,MAAI,IAAI,WAAW,0BAA0B,GAAG;AAC9C,WAAO,GAAG,IAAI,WAAW,IAAI;AAAA,EAC/B;AAEA,SAAO,IAAI;AACb;","names":[]}
|
|
@@ -33,9 +33,11 @@ __export(fetch_remote_component_exports, {
|
|
|
33
33
|
});
|
|
34
34
|
module.exports = __toCommonJS(fetch_remote_component_exports);
|
|
35
35
|
var import_parse5 = require("parse5");
|
|
36
|
+
var import_get_client_src = require("#internal/shared/client/get-client-src");
|
|
36
37
|
var import_error = require("#internal/shared/error");
|
|
37
38
|
var import_dom_flight = require("#internal/shared/ssr/dom-flight");
|
|
38
39
|
var import_fetch_headers = require("#internal/shared/ssr/fetch-headers");
|
|
40
|
+
var import_get_ssr_relative_path_base_url = require("#internal/shared/ssr/get-ssr-relative-path-base-url");
|
|
39
41
|
const CURRENT_ZONE = process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION;
|
|
40
42
|
function getBaseUrl(reqHeaders) {
|
|
41
43
|
const host = reqHeaders.get("host");
|
|
@@ -46,10 +48,7 @@ function getBaseUrl(reqHeaders) {
|
|
|
46
48
|
if (forwardedHost) {
|
|
47
49
|
return `https://${forwardedHost}`;
|
|
48
50
|
}
|
|
49
|
-
|
|
50
|
-
return `https://${process.env.VERCEL_URL}`;
|
|
51
|
-
}
|
|
52
|
-
return `http://localhost:${process.env.MFE_LOCAL_PROXY_PORT || 3024}`;
|
|
51
|
+
return (0, import_get_ssr_relative_path_base_url.getSSRRelativePathBaseUrl)();
|
|
53
52
|
}
|
|
54
53
|
async function fetchRemoteComponent(src, headers = new Headers(), options = {
|
|
55
54
|
rsc: false
|
|
@@ -109,19 +108,24 @@ async function fetchRemoteComponent(src, headers = new Headers(), options = {
|
|
|
109
108
|
hasRemoteComponent = true;
|
|
110
109
|
},
|
|
111
110
|
onScript(attrs) {
|
|
111
|
+
const clientSrc = (0, import_get_client_src.getClientSrc)(attrs.src, serverUrl.href);
|
|
112
112
|
if (!scripts.find(
|
|
113
|
-
(it) => it.src ===
|
|
113
|
+
(it) => it.src === clientSrc || attrs.textContent && it.textContent === attrs.textContent
|
|
114
114
|
)) {
|
|
115
|
-
scripts.push(
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
115
|
+
scripts.push(
|
|
116
|
+
typeof attrs.textContent === "string" ? {
|
|
117
|
+
src: "",
|
|
118
|
+
textContent: attrs.textContent
|
|
119
|
+
} : {
|
|
120
|
+
src: clientSrc
|
|
121
|
+
}
|
|
122
|
+
);
|
|
119
123
|
}
|
|
120
124
|
},
|
|
121
125
|
onLink(attrs) {
|
|
122
126
|
const relativeAttrs = {
|
|
123
127
|
...attrs,
|
|
124
|
-
href:
|
|
128
|
+
href: (0, import_get_client_src.getClientSrc)(attrs.href, serverUrl.href)
|
|
125
129
|
};
|
|
126
130
|
if (!links.find(
|
|
127
131
|
(it) => it.href === relativeAttrs.href && it.rel === attrs.rel
|