remote-components 0.0.34 → 0.0.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/html/host.cjs +127 -117
  2. package/dist/html/host.cjs.map +1 -1
  3. package/dist/html/host.js +127 -117
  4. package/dist/html/host.js.map +1 -1
  5. package/dist/html/remote.cjs +4 -3
  6. package/dist/html/remote.cjs.map +1 -1
  7. package/dist/html/remote.js +4 -3
  8. package/dist/html/remote.js.map +1 -1
  9. package/dist/internal/next/host/app-router-client.cjs +4 -15
  10. package/dist/internal/next/host/app-router-client.cjs.map +1 -1
  11. package/dist/internal/next/host/app-router-client.js +10 -21
  12. package/dist/internal/next/host/app-router-client.js.map +1 -1
  13. package/dist/internal/next/host/app-router-compat.cjs.map +1 -1
  14. package/dist/internal/next/host/app-router-compat.d.ts +1 -1
  15. package/dist/internal/next/host/app-router-compat.js.map +1 -1
  16. package/dist/internal/next/remote/render-server.cjs +1 -1
  17. package/dist/internal/next/remote/render-server.cjs.map +1 -1
  18. package/dist/internal/next/remote/render-server.js +1 -1
  19. package/dist/internal/next/remote/render-server.js.map +1 -1
  20. package/dist/internal/shared/client/polyfill.cjs.map +1 -1
  21. package/dist/internal/shared/client/polyfill.js.map +1 -1
  22. package/dist/internal/shared/client/remote-component.cjs +179 -174
  23. package/dist/internal/shared/client/remote-component.cjs.map +1 -1
  24. package/dist/internal/shared/client/remote-component.d.ts +23 -23
  25. package/dist/internal/shared/client/remote-component.js +179 -174
  26. package/dist/internal/shared/client/remote-component.js.map +1 -1
  27. package/dist/internal/shared/error.cjs +1 -1
  28. package/dist/internal/shared/error.cjs.map +1 -1
  29. package/dist/internal/shared/error.js +1 -1
  30. package/dist/internal/shared/error.js.map +1 -1
  31. package/dist/internal/shared/ssr/dom-flight.cjs +7 -3
  32. package/dist/internal/shared/ssr/dom-flight.cjs.map +1 -1
  33. package/dist/internal/shared/ssr/dom-flight.js +7 -3
  34. package/dist/internal/shared/ssr/dom-flight.js.map +1 -1
  35. package/dist/internal/shared/ssr/fetch-remote-component.cjs +4 -4
  36. package/dist/internal/shared/ssr/fetch-remote-component.cjs.map +1 -1
  37. package/dist/internal/shared/ssr/fetch-remote-component.js +5 -5
  38. package/dist/internal/shared/ssr/fetch-remote-component.js.map +1 -1
  39. package/dist/next/config.cjs +100 -86
  40. package/dist/next/config.cjs.map +1 -1
  41. package/dist/next/config.js +100 -86
  42. package/dist/next/config.js.map +1 -1
  43. package/dist/next/host/app-router-server.cjs.map +1 -1
  44. package/dist/next/host/app-router-server.js +1 -1
  45. package/dist/next/host/app-router-server.js.map +1 -1
  46. package/dist/next/host/client/index.cjs +723 -718
  47. package/dist/next/host/client/index.cjs.map +1 -1
  48. package/dist/next/host/client/index.js +727 -722
  49. package/dist/next/host/client/index.js.map +1 -1
  50. package/dist/next/host/pages-router-server.cjs +4 -4
  51. package/dist/next/host/pages-router-server.cjs.map +1 -1
  52. package/dist/next/host/pages-router-server.js +4 -4
  53. package/dist/next/host/pages-router-server.js.map +1 -1
  54. package/dist/next/{middleware.cjs → proxy.cjs} +24 -14
  55. package/dist/next/proxy.cjs.map +1 -0
  56. package/dist/next/proxy.d.ts +29 -0
  57. package/dist/next/{middleware.js → proxy.js} +21 -11
  58. package/dist/next/proxy.js.map +1 -0
  59. package/dist/react/index.cjs +4 -4
  60. package/dist/react/index.cjs.map +1 -1
  61. package/dist/react/index.js +11 -11
  62. package/dist/react/index.js.map +1 -1
  63. package/package.json +15 -9
  64. package/dist/next/middleware.cjs.map +0 -1
  65. package/dist/next/middleware.d.ts +0 -29
  66. package/dist/next/middleware.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/shared/ssr/dom-flight.ts"],"sourcesContent":["import { isCustomAttribute, possibleStandardNames } from 'react-property';\nimport styleToJs from 'style-to-js';\nimport type {\n ChildNode,\n Element,\n Node,\n TextNode,\n} from 'parse5/dist/tree-adapters/default';\nimport { serializeOuter } from 'parse5';\nimport type { RemoteComponentMetadata } from './types';\n\n// add fetch-priority to the possible standard names\npossibleStandardNames.fetchpriority = 'fetchPriority';\npossibleStandardNames['data-precedence'] = 'precedence';\n\nexport interface Context {\n name?: string;\n url: URL;\n origin?: string;\n defer?: boolean;\n active?: boolean;\n visitedRSCNodes?: Set<Node>;\n visitedNonActiveNodes?: Set<Node>;\n onMetadata?: (metadata: RemoteComponentMetadata) => void;\n onScript?: (attrs: Record<string, string | boolean>) => void;\n onLink?: (attrs: Record<string, string | boolean>) => void;\n onRSC?: (rsc: string) => void;\n onNextData?: (data: {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: string;\n };\n };\n page?: string;\n }) => void;\n onHTML?: (html: string) => void;\n onShared?: (shared: Record<string, string>) => void;\n onError?: (message: string, stack?: string) => void;\n}\n\ntype RSC =\n | ['$', string, null, Record<string, unknown>, null, null, number]\n | (\n | ['$', string, null, Record<string, unknown>, null, null, number]\n | string\n | null\n )[]\n | string\n | null;\n\nconst applyOriginToNodes = [\n 'img',\n 'source',\n 'video',\n 'audio',\n 'track',\n 'iframe',\n 'embed',\n 'script',\n 'link',\n];\n\nexport function visit(\n node: (Node | ChildNode) & {\n attrsObj?: Record<string, string>;\n attrsObjToArray?: Record<string, { name: string; value: string }>;\n },\n context: Context = {\n url: new URL('http://localhost'),\n active: false,\n },\n): RSC | RSC[] | string | null {\n if ('attrs' in node && typeof node.attrsObj === 'undefined') {\n node.attrsObjToArray = {};\n node.attrsObj = node.attrs.reduce<Record<string, string>>((acc, attr) => {\n acc[attr.name] = attr.value;\n if (node.attrsObjToArray) {\n node.attrsObjToArray[attr.name] = attr;\n }\n return acc;\n }, {});\n }\n\n if (\n node.nodeName === 'template' &&\n node.attrsObj?.['data-next-error-message']\n ) {\n context.onError?.(\n node.attrsObj['data-next-error-message'],\n node.attrsObj['data-next-error-stack'],\n );\n }\n\n // apply origin to src and srcset attributes\n if (\n applyOriginToNodes.includes(node.nodeName.toLowerCase()) &&\n 'attrs' in node\n ) {\n const origin = context.origin ?? context.url.origin;\n const src = node.attrsObj?.src;\n if (src) {\n const url = new URL(src, origin);\n if (node.attrsObjToArray && 'src' in node.attrsObjToArray) {\n node.attrsObjToArray.src.value = url.href;\n }\n }\n const href = node.attrsObj?.href;\n if (href) {\n const url = new URL(href, origin);\n if (node.attrsObjToArray && 'href' in node.attrsObjToArray) {\n node.attrsObjToArray.href.value = url.href;\n }\n }\n\n const srcSet = node.attrsObj?.srcset;\n if (srcSet) {\n const srcSetValue = srcSet\n .split(',')\n .map((entry) => {\n const [url, descriptor] = entry.trim().split(/\\s+/);\n if (!url) return entry;\n\n const absoluteUrl = new URL(url, origin).href;\n return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;\n })\n .join(', ');\n if (node.attrsObjToArray && 'srcset' in node.attrsObjToArray) {\n node.attrsObjToArray.srcset.value = srcSetValue;\n }\n }\n const imageSrcSet = node.attrsObj?.imagesrcset;\n if (imageSrcSet) {\n const srcSetValue = imageSrcSet\n .split(',')\n .map((entry) => {\n const [url, descriptor] = entry.trim().split(/\\s+/);\n if (!url) return entry;\n\n const absoluteUrl = new URL(url, origin).href;\n return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;\n })\n .join(', ');\n if (node.attrsObjToArray && 'imagesrcset' in node.attrsObjToArray) {\n node.attrsObjToArray.imagesrcset.value = srcSetValue;\n }\n }\n }\n\n if (node.nodeName === 'script' || node.nodeName === 'link') {\n const nodeId = node.attrsObj?.id;\n if (nodeId?.endsWith('_shared')) {\n context.onShared?.(\n JSON.parse((node.childNodes[0] as TextNode).value) as Record<\n string,\n string\n >,\n );\n return null;\n } else if (nodeId?.endsWith('_rsc') && 'childNodes' in node) {\n if (!context.visitedRSCNodes) {\n context.visitedRSCNodes = new Set();\n }\n if (\n !context.visitedRSCNodes.has(node) &&\n (context.name ? nodeId.startsWith(context.name) : true)\n ) {\n context.visitedRSCNodes.add(node);\n context.onRSC?.((node.childNodes[0] as TextNode).value);\n }\n } else if (nodeId === '__NEXT_DATA__' && 'childNodes' in node) {\n context.onHTML?.(\n `<script id=\"__REMOTE_NEXT_DATA__\" type=\"application/json\">${(node.childNodes[0] as TextNode).value}</script>`,\n );\n context.onNextData?.(\n JSON.parse((node.childNodes[0] as TextNode).value) as {\n props: { pageProps: Record<string, unknown> };\n },\n );\n } else if (node.childNodes.length === 0) {\n if (\n node.nodeName === 'script' &&\n node.attrsObj &&\n !('src' in node.attrsObj)\n ) {\n return [\n '$',\n node.nodeName,\n null,\n node.attrs.reduce<Record<string, string>>((props, attr) => {\n props[possibleStandardNames[attr.name] ?? attr.name] = attr.value;\n return props;\n }, {}),\n null,\n null,\n 1,\n ] as RSC;\n }\n if (node.nodeName === 'script') {\n context.onScript?.(\n node.attrs.reduce<Record<string, string | boolean>>((props, attr) => {\n props[attr.name] = attr.value || true;\n return props;\n }, {}),\n );\n const src = node.attrsObj?.src;\n if (src) {\n node.attrs = node.attrs.filter((attr) => attr.name !== 'src');\n node.attrs.push({\n name: 'data-src',\n value: src,\n });\n if (node.attrsObj) {\n delete node.attrsObj.src;\n node.attrsObj['data-src'] = src;\n }\n }\n context.onHTML?.(serializeOuter(node));\n } else {\n context.onLink?.(\n node.attrs.reduce<Record<string, string | boolean>>((props, attr) => {\n if (attr.name === 'href') {\n attr.value = new URL(attr.value, context.url.origin).href;\n }\n props[possibleStandardNames[attr.name] ?? attr.name] =\n attr.value || true;\n return props;\n }, {}),\n );\n context.onHTML?.(serializeOuter(node));\n }\n return null;\n } else if (\n context.active &&\n node.nodeName === 'script' &&\n 'childNodes' in node &&\n node.childNodes.length > 0\n ) {\n // inline script\n context.onScript?.({\n ...node.attrs.reduce<Record<string, string | boolean>>(\n (props, attr) => {\n props[attr.name] = attr.value || true;\n return props;\n },\n {},\n ),\n textContent: (node.childNodes[0] as TextNode).value,\n });\n return null;\n }\n }\n\n if (!context.active) {\n if (!context.visitedNonActiveNodes) {\n context.visitedNonActiveNodes = new Set();\n }\n\n if (\n 'childNodes' in node &&\n !(\n node.nodeName === 'remote-component' &&\n !node.attrsObj?.src &&\n (context.name ? node.attrsObj?.name !== context.name : false)\n )\n ) {\n if (!context.visitedNonActiveNodes.has(node)) {\n context.visitedNonActiveNodes.add(node);\n (node as Element).childNodes.forEach((childNode) => {\n visit(childNode, context);\n });\n }\n } else return null;\n }\n\n switch (node.nodeName) {\n case '#document-fragment':\n return node.childNodes.reduce<RSC[]>((acc, childNode) => {\n const result = visit(childNode, context);\n if (result !== null) {\n acc.push(result as unknown as RSC);\n }\n return acc;\n }, []);\n case '#text':\n return (node as TextNode).value;\n case '#comment':\n case 'head':\n case 'meta':\n case 'title':\n case 'noscript':\n return null;\n default: {\n const nodeId = node.attrsObj?.id;\n\n if (\n (node.nodeName === 'remote-component' &&\n !node.attrsObj?.src &&\n (!context.name || node.attrsObj?.name === context.name)) ||\n (node.nodeName === 'div' &&\n (nodeId === '__next' ||\n (context.name\n ? nodeId?.startsWith(context.name)\n : node.attrsObj &&\n 'data-bundle' in node.attrsObj &&\n node.attrsObj['data-bundle'] &&\n 'data-route' in node.attrsObj &&\n nodeId?.endsWith('_ssr'))))\n ) {\n context.onMetadata?.({\n bundle: node.attrsObj?.['data-bundle'] ?? 'default',\n route: node.attrsObj?.['data-route'] ?? context.url.pathname,\n runtime: (node.attrsObj?.['data-runtime'] ??\n (node.nodeName === 'remote-component'\n ? 'script'\n : 'webpack')) as RemoteComponentMetadata['runtime'],\n id: nodeId?.endsWith('_ssr') ? nodeId : '__vercel_remote_component',\n type: (node.nodeName === 'remote-component'\n ? 'remote-component'\n : node.attrsObj?.['data-type'] ||\n 'unknown') as RemoteComponentMetadata['type'],\n });\n context.onHTML?.(serializeOuter(node));\n return node.childNodes.reduce<RSC[]>((acc, childNode) => {\n const result = visit(childNode, {\n ...context,\n active: true,\n });\n if (result !== null) {\n acc.push(result as unknown as RSC);\n }\n return acc;\n }, []);\n }\n const childNodes = (node as Element).childNodes.reduce<unknown[]>(\n (acc, childNode) => {\n const result = visit(childNode, context);\n if (result !== null) {\n acc.push(result as unknown);\n }\n return acc;\n },\n [],\n );\n const children = childNodes.length > 1 ? childNodes : childNodes[0];\n const nodeProps = (node as Element).attrs.reduce<\n Record<string, string | ReturnType<typeof styleToJs>> & {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n children?: any;\n }\n >((props, attr) => {\n if (attr.name === 'style') {\n props.style = styleToJs(attr.value, {\n reactCompat: true,\n });\n return props;\n }\n if (node.nodeName === 'input' && attr.name === 'value') {\n props.defaultValue = attr.value;\n return props;\n }\n if (isCustomAttribute(attr.name)) {\n props[attr.name] = attr.value;\n return props;\n }\n props[possibleStandardNames[attr.name] ?? attr.name] = attr.value;\n return props;\n }, {});\n if (typeof children !== 'undefined') {\n if (\n node.nodeName === 'script' &&\n typeof children === 'string' &&\n children.startsWith('$')\n ) {\n nodeProps.children = `$${children}`;\n } else {\n nodeProps.children = children;\n }\n }\n if (!context.active) {\n if (childNodes.length > 0) {\n return childNodes as RSC;\n }\n return null;\n }\n return ['$', node.nodeName, null, nodeProps, null, null, 1] as RSC;\n }\n }\n}\n"],"mappings":"AAAA,SAAS,mBAAmB,6BAA6B;AACzD,OAAO,eAAe;AAOtB,SAAS,sBAAsB;AAI/B,sBAAsB,gBAAgB;AACtC,sBAAsB,iBAAiB,IAAI;AAuC3C,MAAM,qBAAqB;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,MACd,MAIA,UAAmB;AAAA,EACjB,KAAK,IAAI,IAAI,kBAAkB;AAAA,EAC/B,QAAQ;AACV,GAC6B;AAC7B,MAAI,WAAW,QAAQ,OAAO,KAAK,aAAa,aAAa;AAC3D,SAAK,kBAAkB,CAAC;AACxB,SAAK,WAAW,KAAK,MAAM,OAA+B,CAAC,KAAK,SAAS;AACvE,UAAI,KAAK,IAAI,IAAI,KAAK;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ClC,aAAa;AAAA,UACf,CAAC;AACD,iBAAO;AAAA,QACT;AACA,YAAI,KAAK,aAAa,WAAW,KAAK,SAAS,SAAS;AACtD,gBAAM,eAAe,KAAK;AAC1B,iBAAO;AAAA,QACT;AACA,YAAI,kBAAkB,KAAK,IAAI,GAAG;AAChC,gBAAM,KAAK,IAAI,IAAI,KAAK;AACxB,iBAAO;AAAA,QACT;AACA,cAAM,sBAAsB,KAAK,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK;AAC5D,eAAO;AAAA,MACT,GAAG,CAAC,CAAC;AACL,UAAI,OAAO,aAAa,aAAa;AACnC,YACE,KAAK,aAAa,YAClB,OAAO,aAAa,YACpB,SAAS,WAAW,GAAG,GACvB;AACA,oBAAU,WAAW,IAAI;AAAA,QAC3B,OAAO;AACL,oBAAU,WAAW;AAAA,QACvB;AAAA,MACF;AACA,UAAI,CAAC,QAAQ,QAAQ;AACnB,YAAI,WAAW,SAAS,GAAG;AACzB,iBAAO;AAAA,QACT;AACA,eAAO;AAAA,MACT;AACA,aAAO,CAAC,KAAK,KAAK,UAAU,MAAM,WAAW,MAAM,MAAM,CAAC;AAAA,IAC5D;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../../src/shared/ssr/dom-flight.ts"],"sourcesContent":["import { serializeOuter } from 'parse5';\nimport type {\n ChildNode,\n Element,\n Node,\n TextNode,\n} from 'parse5/dist/tree-adapters/default';\nimport { isCustomAttribute, possibleStandardNames } from 'react-property';\nimport styleToJs from 'style-to-js';\nimport type { RemoteComponentMetadata } from './types';\n\n// add fetch-priority to the possible standard names\npossibleStandardNames.fetchpriority = 'fetchPriority';\npossibleStandardNames['data-precedence'] = 'precedence';\n\nexport interface Context {\n name?: string;\n url: URL;\n origin?: string;\n defer?: boolean;\n active?: boolean;\n visitedRSCNodes?: Set<Node>;\n visitedNonActiveNodes?: Set<Node>;\n onMetadata?: (metadata: RemoteComponentMetadata) => void;\n onScript?: (attrs: Record<string, string | boolean>) => void;\n onLink?: (attrs: Record<string, string | boolean>) => void;\n onRSC?: (rsc: string) => void;\n onNextData?: (data: {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: string;\n };\n };\n page?: string;\n }) => void;\n onHTML?: (html: string) => void;\n onShared?: (shared: Record<string, string>) => void;\n onError?: (message: string, stack?: string) => void;\n}\n\ntype RSC =\n | ['$', string, null, Record<string, unknown>, null, null, number]\n | (\n | ['$', string, null, Record<string, unknown>, null, null, number]\n | string\n | null\n )[]\n | string\n | null;\n\nconst applyOriginToNodes = [\n 'img',\n 'source',\n 'video',\n 'audio',\n 'track',\n 'iframe',\n 'embed',\n 'script',\n 'link',\n];\n\nexport function visit(\n node: (Node | ChildNode) & {\n attrsObj?: Record<string, string>;\n attrsObjToArray?: Record<string, { name: string; value: string }>;\n },\n context: Context = {\n url: new URL('http://localhost'),\n active: false,\n },\n): RSC | RSC[] | string | null {\n if ('attrs' in node && typeof node.attrsObj === 'undefined') {\n node.attrsObjToArray = {};\n node.attrsObj = node.attrs.reduce<Record<string, string>>((acc, attr) => {\n acc[attr.name] = attr.value;\n if (node.attrsObjToArray) {\n node.attrsObjToArray[attr.name] = attr;\n }\n return acc;\n }, {});\n }\n\n if (\n node.nodeName === 'template' &&\n node.attrsObj?.['data-next-error-message']\n ) {\n context.onError?.(\n node.attrsObj['data-next-error-message'],\n node.attrsObj['data-next-error-stack'],\n );\n }\n\n // apply origin to src and srcset attributes\n if (\n applyOriginToNodes.includes(node.nodeName.toLowerCase()) &&\n 'attrs' in node\n ) {\n const origin = context.origin ?? context.url.origin;\n const src = node.attrsObj?.src;\n if (src) {\n const url = new URL(src, origin);\n if (node.attrsObjToArray && 'src' in node.attrsObjToArray) {\n node.attrsObjToArray.src.value = url.href;\n }\n }\n const href = node.attrsObj?.href;\n if (href) {\n const url = new URL(href, origin);\n if (node.attrsObjToArray && 'href' in node.attrsObjToArray) {\n node.attrsObjToArray.href.value = url.href;\n }\n }\n\n const srcSet = node.attrsObj?.srcset;\n if (srcSet) {\n const srcSetValue = srcSet\n .split(',')\n .map((entry) => {\n const [url, descriptor] = entry.trim().split(/\\s+/);\n if (!url) return entry;\n\n const absoluteUrl = new URL(url, origin).href;\n return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;\n })\n .join(', ');\n if (node.attrsObjToArray && 'srcset' in node.attrsObjToArray) {\n node.attrsObjToArray.srcset.value = srcSetValue;\n }\n }\n const imageSrcSet = node.attrsObj?.imagesrcset;\n if (imageSrcSet) {\n const srcSetValue = imageSrcSet\n .split(',')\n .map((entry) => {\n const [url, descriptor] = entry.trim().split(/\\s+/);\n if (!url) return entry;\n\n const absoluteUrl = new URL(url, origin).href;\n return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;\n })\n .join(', ');\n if (node.attrsObjToArray && 'imagesrcset' in node.attrsObjToArray) {\n node.attrsObjToArray.imagesrcset.value = srcSetValue;\n }\n }\n }\n\n if (node.nodeName === 'script' || node.nodeName === 'link') {\n const nodeId = node.attrsObj?.id;\n if (nodeId?.endsWith('_shared')) {\n context.onShared?.(\n JSON.parse((node.childNodes[0] as TextNode).value) as Record<\n string,\n string\n >,\n );\n return null;\n } else if (nodeId?.endsWith('_rsc') && 'childNodes' in node) {\n if (!context.visitedRSCNodes) {\n context.visitedRSCNodes = new Set();\n }\n if (\n !context.visitedRSCNodes.has(node) &&\n (context.name ? nodeId.startsWith(context.name) : true)\n ) {\n context.visitedRSCNodes.add(node);\n context.onRSC?.((node.childNodes[0] as TextNode).value);\n }\n } else if (nodeId === '__NEXT_DATA__' && 'childNodes' in node) {\n context.onHTML?.(\n `<script id=\"__REMOTE_NEXT_DATA__\" type=\"application/json\">${(node.childNodes[0] as TextNode).value}</script>`,\n );\n context.onNextData?.(\n JSON.parse((node.childNodes[0] as TextNode).value) as {\n props: { pageProps: Record<string, unknown> };\n },\n );\n } else if (node.childNodes.length === 0) {\n if (\n node.nodeName === 'script' &&\n node.attrsObj &&\n !('src' in node.attrsObj) &&\n !('data-src' in node.attrsObj)\n ) {\n return [\n '$',\n node.nodeName,\n null,\n node.attrs.reduce<Record<string, string>>((props, attr) => {\n props[possibleStandardNames[attr.name] ?? attr.name] = attr.value;\n return props;\n }, {}),\n null,\n null,\n 1,\n ] as RSC;\n }\n if (node.nodeName === 'script') {\n context.onScript?.(\n node.attrs.reduce<Record<string, string | boolean>>((props, attr) => {\n if (attr.name === 'data-src') {\n props.src = attr.value;\n } else {\n props[attr.name] = attr.value || true;\n }\n return props;\n }, {}),\n );\n const src = node.attrsObj?.src;\n if (src) {\n node.attrs = node.attrs.filter((attr) => attr.name !== 'src');\n node.attrs.push({\n name: 'data-src',\n value: src,\n });\n if (node.attrsObj) {\n delete node.attrsObj.src;\n node.attrsObj['data-src'] = src;\n }\n }\n context.onHTML?.(serializeOuter(node));\n } else {\n context.onLink?.(\n node.attrs.reduce<Record<string, string | boolean>>((props, attr) => {\n if (attr.name === 'href') {\n attr.value = new URL(attr.value, context.url.origin).href;\n }\n props[possibleStandardNames[attr.name] ?? attr.name] =\n attr.value || true;\n return props;\n }, {}),\n );\n context.onHTML?.(serializeOuter(node));\n }\n return null;\n } else if (\n context.active &&\n node.nodeName === 'script' &&\n 'childNodes' in node &&\n node.childNodes.length > 0\n ) {\n // inline script\n context.onScript?.({\n ...node.attrs.reduce<Record<string, string | boolean>>(\n (props, attr) => {\n props[attr.name] = attr.value || true;\n return props;\n },\n {},\n ),\n textContent: (node.childNodes[0] as TextNode).value,\n });\n return null;\n }\n }\n\n if (!context.active) {\n if (!context.visitedNonActiveNodes) {\n context.visitedNonActiveNodes = new Set();\n }\n\n if (\n 'childNodes' in node &&\n !(\n node.nodeName === 'remote-component' &&\n !node.attrsObj?.src &&\n (context.name ? node.attrsObj?.name !== context.name : false)\n )\n ) {\n if (!context.visitedNonActiveNodes.has(node)) {\n context.visitedNonActiveNodes.add(node);\n (node as Element).childNodes.forEach((childNode) => {\n visit(childNode, context);\n });\n }\n } else return null;\n }\n\n switch (node.nodeName) {\n case '#document-fragment':\n return node.childNodes.reduce<RSC[]>((acc, childNode) => {\n const result = visit(childNode, context);\n if (result !== null) {\n acc.push(result as unknown as RSC);\n }\n return acc;\n }, []);\n case '#text':\n return (node as TextNode).value;\n case '#comment':\n case 'head':\n case 'meta':\n case 'title':\n case 'noscript':\n return null;\n default: {\n const nodeId = node.attrsObj?.id;\n\n if (\n (node.nodeName === 'remote-component' &&\n !node.attrsObj?.src &&\n (!context.name || node.attrsObj?.name === context.name)) ||\n (node.nodeName === 'div' &&\n (nodeId === '__next' ||\n (context.name\n ? nodeId?.startsWith(context.name)\n : node.attrsObj &&\n 'data-bundle' in node.attrsObj &&\n node.attrsObj['data-bundle'] &&\n 'data-route' in node.attrsObj &&\n nodeId?.endsWith('_ssr'))))\n ) {\n context.onMetadata?.({\n bundle: node.attrsObj?.['data-bundle'] ?? 'default',\n route: node.attrsObj?.['data-route'] ?? context.url.pathname,\n runtime: (node.attrsObj?.['data-runtime'] ??\n (node.nodeName === 'remote-component'\n ? 'script'\n : 'webpack')) as RemoteComponentMetadata['runtime'],\n id: nodeId?.endsWith('_ssr') ? nodeId : '__vercel_remote_component',\n type: (node.nodeName === 'remote-component'\n ? 'remote-component'\n : node.attrsObj?.['data-type'] ||\n 'unknown') as RemoteComponentMetadata['type'],\n });\n context.onHTML?.(serializeOuter(node));\n return node.childNodes.reduce<RSC[]>((acc, childNode) => {\n const result = visit(childNode, {\n ...context,\n active: true,\n });\n if (result !== null) {\n acc.push(result as unknown as RSC);\n }\n return acc;\n }, []);\n }\n const childNodes = (node as Element).childNodes.reduce<unknown[]>(\n (acc, childNode) => {\n const result = visit(childNode, context);\n if (result !== null) {\n acc.push(result as unknown);\n }\n return acc;\n },\n [],\n );\n const children = childNodes.length > 1 ? childNodes : childNodes[0];\n const nodeProps = (node as Element).attrs.reduce<\n Record<string, string | ReturnType<typeof styleToJs>> & {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n children?: any;\n }\n >((props, attr) => {\n if (attr.name === 'style') {\n props.style = styleToJs(attr.value, {\n reactCompat: true,\n });\n return props;\n }\n if (node.nodeName === 'input' && attr.name === 'value') {\n props.defaultValue = attr.value;\n return props;\n }\n if (isCustomAttribute(attr.name)) {\n props[attr.name] = attr.value;\n return props;\n }\n props[possibleStandardNames[attr.name] ?? attr.name] = attr.value;\n return props;\n }, {});\n if (typeof children !== 'undefined') {\n if (\n node.nodeName === 'script' &&\n typeof children === 'string' &&\n children.startsWith('$')\n ) {\n nodeProps.children = `$${children}`;\n } else {\n nodeProps.children = children;\n }\n }\n if (!context.active) {\n if (childNodes.length > 0) {\n return childNodes as RSC;\n }\n return null;\n }\n return ['$', node.nodeName, null, nodeProps, null, null, 1] as RSC;\n }\n }\n}\n"],"mappings":"AAAA,SAAS,sBAAsB;AAO/B,SAAS,mBAAmB,6BAA6B;AACzD,OAAO,eAAe;AAItB,sBAAsB,gBAAgB;AACtC,sBAAsB,iBAAiB,IAAI;AAuC3C,MAAM,qBAAqB;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,MACd,MAIA,UAAmB;AAAA,EACjB,KAAK,IAAI,IAAI,kBAAkB;AAAA,EAC/B,QAAQ;AACV,GAC6B;AAC7B,MAAI,WAAW,QAAQ,OAAO,KAAK,aAAa,aAAa;AAC3D,SAAK,kBAAkB,CAAC;AACxB,SAAK,WAAW,KAAK,MAAM,OAA+B,CAAC,KAAK,SAAS;AACvE,UAAI,KAAK,IAAI,IAAI,KAAK;AACtB,UAAI,KAAK,iBAAiB;AACxB,aAAK,gBAAgB,KAAK,IAAI,IAAI;AAAA,MACpC;AACA,aAAO;AAAA,IACT,GAAG,CAAC,CAAC;AAAA,EACP;AAEA,MACE,KAAK,aAAa,cAClB,KAAK,WAAW,yBAAyB,GACzC;AACA,YAAQ;AAAA,MACN,KAAK,SAAS,yBAAyB;AA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K;AAC1B,iBAAO;AAAA,QACT;AACA,YAAI,kBAAkB,KAAK,IAAI,GAAG;AAChC,gBAAM,KAAK,IAAI,IAAI,KAAK;AACxB,iBAAO;AAAA,QACT;AACA,cAAM,sBAAsB,KAAK,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK;AAC5D,eAAO;AAAA,MACT,GAAG,CAAC,CAAC;AACL,UAAI,OAAO,aAAa,aAAa;AACnC,YACE,KAAK,aAAa,YAClB,OAAO,aAAa,YACpB,SAAS,WAAW,GAAG,GACvB;AACA,oBAAU,WAAW,IAAI;AAAA,QAC3B,OAAO;AACL,oBAAU,WAAW;AAAA,QACvB;AAAA,MACF;AACA,UAAI,CAAC,QAAQ,QAAQ;AACnB,YAAI,WAAW,SAAS,GAAG;AACzB,iBAAO;AAAA,QACT;AACA,eAAO;AAAA,MACT;AACA,aAAO,CAAC,KAAK,KAAK,UAAU,MAAM,WAAW,MAAM,MAAM,CAAC;AAAA,IAC5D;AAAA,EACF;AACF;","names":[]}
@@ -33,9 +33,9 @@ __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_error = require("#internal/shared/error");
36
37
  var import_dom_flight = require("#internal/shared/ssr/dom-flight");
37
38
  var import_fetch_headers = require("#internal/shared/ssr/fetch-headers");
38
- var import_error = require("#internal/shared/error");
39
39
  const CURRENT_ZONE = process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION;
40
40
  function getBaseUrl(reqHeaders) {
41
41
  const host = reqHeaders.get("host");
@@ -46,8 +46,8 @@ function getBaseUrl(reqHeaders) {
46
46
  if (forwardedHost) {
47
47
  return `https://${forwardedHost}`;
48
48
  }
49
- if (process.env.VERCEL_PROJECT_PRODUCTION_URL) {
50
- return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
49
+ if (process.env.VERCEL_URL) {
50
+ return `https://${process.env.VERCEL_URL}`;
51
51
  }
52
52
  return `http://localhost:${process.env.MFE_LOCAL_PROXY_PORT || 3024}`;
53
53
  }
@@ -110,7 +110,7 @@ async function fetchRemoteComponent(src, headers = new Headers(), options = {
110
110
  },
111
111
  onScript(attrs) {
112
112
  if (!scripts.find(
113
- (it) => it.src === attrs.src || it.textContent === attrs.textContent
113
+ (it) => it.src === attrs.src || attrs.textContent && it.textContent === attrs.textContent
114
114
  )) {
115
115
  scripts.push({
116
116
  src: typeof attrs.textContent === "string" ? "" : new URL(attrs.src, new URL(url).origin).href,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/shared/ssr/fetch-remote-component.ts"],"sourcesContent":["import { type DefaultTreeAdapterMap, Parser } from 'parse5';\nimport { visit } from '#internal/shared/ssr/dom-flight';\nimport { remoteFetchHeaders } from '#internal/shared/ssr/fetch-headers';\nimport {\n failedToFetchRemoteComponentError,\n multipleRemoteComponentsError,\n RemoteComponentsError,\n} from '#internal/shared/error';\nimport type { RemoteComponentMetadata } from './types';\n\nconst CURRENT_ZONE = process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION;\n\n/**\n * Resolves the base URL that should be used to fetch the remote component.\n * This function must support local development, Vercel environments, and SSG\n * and dynamic rendering.\n */\nexport function getBaseUrl(reqHeaders: Headers): string {\n const host = reqHeaders.get('host');\n if (host) {\n return host.startsWith('localhost') ? `http://${host}` : `https://${host}`;\n }\n const forwardedHost = reqHeaders.get('x-forwarded-host');\n if (forwardedHost) {\n return `https://${forwardedHost}`;\n }\n if (process.env.VERCEL_PROJECT_PRODUCTION_URL) {\n return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;\n }\n // TODO: Resolve the correct URL in local development when the proxy is not running.\n return `http://localhost:${process.env.MFE_LOCAL_PROXY_PORT || 3024}`;\n}\n\nexport async function fetchRemoteComponent(\n src: string | URL,\n headers: Headers = new Headers(),\n options: {\n name?: string;\n rsc?: boolean;\n } = {\n rsc: false,\n },\n) {\n const url = new URL(src, getBaseUrl(headers));\n\n const fetchInit = {\n method: 'GET',\n // pass all headers to the remote component\n headers: remoteFetchHeaders(headers),\n credentials: 'include',\n } as RequestInit;\n\n const res = await fetch(url, fetchInit);\n\n if (!res.ok && !res.body) {\n throw failedToFetchRemoteComponentError(\n url.href,\n new Error(`${res.status} ${res.statusText}`),\n );\n }\n\n // create a parser for the HTML response\n const parser = Parser.getFragmentParser<DefaultTreeAdapterMap>();\n\n if (!res.body) {\n throw new Error(\n `Response is empty for Remote Component \"${url.href}\". Check if you can open it in the browser and you see the Remote Component content.`,\n );\n }\n\n const decoder = new TextDecoder();\n // read the response body as a stream and parse it using the parse5 fragment parser\n for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {\n parser.tokenizer.write(decoder.decode(chunk), false);\n }\n const fragment = parser.getFragment();\n\n let metadata: RemoteComponentMetadata = {\n bundle: CURRENT_ZONE ?? '__vercel_remote_component',\n route: '/',\n runtime: 'webpack',\n id: '__vercel_remote_component',\n type: 'unknown',\n };\n let remoteShared: Record<string, string> = {};\n const scripts: { src: string; textContent?: string }[] = [];\n const links: Record<string, string | boolean>[] = [];\n const hydrationData: string[] = [];\n let nextData:\n | {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: string;\n shared?: Record<string, string>;\n };\n };\n page?: string;\n buildId?: string;\n }\n | undefined;\n let html = '';\n\n const remoteName =\n options.name || url.hash ? url.hash.substring(1) : undefined;\n // convert the parsed HTML fragment into an RSC flight data\n // and extract the metadata, scripts, links and remote component RSC flight data\n let hasRemoteComponent = false;\n let hasRSC = false;\n let hasShared = false;\n let hasMultipleRemoteComponents = false;\n let error: Error | undefined;\n const rsc = visit(fragment, {\n url,\n name: remoteName,\n onMetadata(_metadata) {\n metadata = _metadata;\n if (hasRemoteComponent && metadata.id !== _metadata.id) {\n hasMultipleRemoteComponents = true;\n }\n hasRemoteComponent = true;\n },\n onScript(attrs) {\n if (\n !scripts.find(\n (it) => it.src === attrs.src || it.textContent === attrs.textContent,\n )\n ) {\n scripts.push({\n src:\n typeof attrs.textContent === 'string'\n ? ''\n : new URL(attrs.src as string, new URL(url).origin).href,\n textContent:\n typeof attrs.textContent === 'string'\n ? attrs.textContent\n : undefined,\n });\n }\n },\n onLink(attrs) {\n const relativeAttrs = {\n ...attrs,\n href: new URL(attrs.href as string, new URL(url).origin).href,\n };\n if (\n !links.find(\n (it) => it.href === relativeAttrs.href && it.rel === attrs.rel,\n )\n ) {\n links.push(relativeAttrs);\n }\n },\n onRSC(chunk) {\n hydrationData.push(chunk);\n hasRSC = true;\n },\n onNextData(data) {\n nextData = data;\n\n // use the Next.js Pages Router props data to extract remote component metadata\n if (data.props.__REMOTE_COMPONENT__) {\n Object.assign(metadata, data.props.__REMOTE_COMPONENT__);\n // only a singleton remote component is supported per page when using the Next.js Pages Router\n metadata.id = '__next';\n metadata.route = data.page ?? '/';\n }\n },\n onHTML(_html) {\n if (!html.includes(_html)) {\n html += _html;\n }\n },\n onShared(_shared) {\n remoteShared = _shared;\n hasShared = true;\n },\n onError(message, stack) {\n error = new RemoteComponentsError(message);\n if (stack) {\n error.stack = stack;\n }\n },\n });\n\n if (error) {\n throw error;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!hasRemoteComponent) {\n throw new Error(\n `No Remote Component found at \"${url.href}\". Make sure the remote URL is correct and contains a Remote Component.`,\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (hasMultipleRemoteComponents && !remoteName) {\n throw multipleRemoteComponentsError(url.href);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!hasRSC && !nextData && metadata.type === 'nextjs') {\n throw new Error(\n `The Remote Component at \"${url.href}\" seems to be a Next.js component but it does not contain any RSC flight data or Next.js props data. Make sure the remote URL is correct and contains a Remote Component.`,\n );\n }\n\n if (\n metadata.type === 'nextjs' &&\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n !hasShared &&\n !nextData?.props.__REMOTE_COMPONENT__?.shared\n ) {\n throw new Error(\n `No shared dependencies found for Remote Component at \"${url.href}\". Make sure the remote URL is correct and contains a Remote Component with shared dependencies.`,\n );\n }\n\n let component: React.ReactNode | undefined;\n\n // only create a React component if requested\n if (options.rsc) {\n // RSC flight data for the static HTML in a single RSC line\n const componentRSC = `0:${JSON.stringify(rsc)}\\n`;\n\n const { createFromReadableStream } = await import(\n 'next/dist/compiled/react-server-dom-webpack/client.edge'\n );\n\n // create a React tree from the RSC flight data\n component = await createFromReadableStream(\n new ReadableStream({\n type: 'bytes',\n start(controller) {\n const encoder = new TextEncoder();\n controller.enqueue(encoder.encode(componentRSC));\n controller.close();\n },\n }),\n {\n serverConsumerManifest: {\n moduleLoading: {\n prefix: url.origin,\n crossOrigin: true,\n },\n moduleMap: {},\n },\n },\n );\n }\n\n const name = metadata.id.replace(/_ssr$/, '');\n return {\n name,\n url,\n metadata,\n rsc,\n scripts,\n links,\n hydrationData,\n nextData,\n component,\n html,\n remoteShared: nextData?.props.__REMOTE_COMPONENT__?.shared ?? remoteShared,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAmD;AACnD,wBAAsB;AACtB,2BAAmC;AACnC,mBAIO;AAGP,MAAM,eAAe,QAAQ,IAAI;AAO1B,SAAS,WAAW,YAA6B;AACtD,QAAM,OAAO,WAAW,IAAI,MAAM;AAClC,MAAI,MAAM;AACR,WAAO,KAAK,WAAW,WAAW,IAAI,UAAU,SAAS,WAAW;AAAA,EACtE;AACA,QAAM,gBAAgB,WAAW,IAAI,kBAAkB;AACvD,MAAI,eAAe;AACjB,WAAO,WAAW;AAAA,EACpB;AACA,MAAI,QAAQ,IAAI,+BAA+B;AAC7C,WAAO,WAAW,QAAQ,IAAI;AAAA,EAChC;AAEA,SAAO,oBAAoB,QAAQ,IAAI,wBAAwB;AACjE;AAEA,eAAsB,qBACpB,KACA,UAAmB,IAAI,QAAQ,GAC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Ac,UAAU,MAAM,sBAAsB,UAAU;AAAA,EAChE;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../../src/shared/ssr/fetch-remote-component.ts"],"sourcesContent":["import { type DefaultTreeAdapterMap, Parser } from 'parse5';\nimport {\n failedToFetchRemoteComponentError,\n multipleRemoteComponentsError,\n RemoteComponentsError,\n} from '#internal/shared/error';\nimport { visit } from '#internal/shared/ssr/dom-flight';\nimport { remoteFetchHeaders } from '#internal/shared/ssr/fetch-headers';\nimport type { RemoteComponentMetadata } from './types';\n\nconst CURRENT_ZONE = process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION;\n\n/**\n * Resolves the base URL that should be used to fetch the remote component.\n * This function must support local development, Vercel environments, and SSG\n * and dynamic rendering.\n */\nexport function getBaseUrl(reqHeaders: Headers): string {\n const host = reqHeaders.get('host');\n if (host) {\n return host.startsWith('localhost') ? `http://${host}` : `https://${host}`;\n }\n const forwardedHost = reqHeaders.get('x-forwarded-host');\n if (forwardedHost) {\n return `https://${forwardedHost}`;\n }\n // This is the deployment URL. When using deployment protection the\n // automation bypass header can be provided using additionalHeaders.\n if (process.env.VERCEL_URL) {\n return `https://${process.env.VERCEL_URL}`;\n }\n // TODO: Resolve the correct URL in local development when the proxy is not running.\n return `http://localhost:${process.env.MFE_LOCAL_PROXY_PORT || 3024}`;\n}\n\nexport async function fetchRemoteComponent(\n src: string | URL,\n headers: Headers = new Headers(),\n options: {\n name?: string;\n rsc?: boolean;\n } = {\n rsc: false,\n },\n) {\n const url = new URL(src, getBaseUrl(headers));\n\n const fetchInit = {\n method: 'GET',\n // pass all headers to the remote component\n headers: remoteFetchHeaders(headers),\n credentials: 'include',\n } as RequestInit;\n\n const res = await fetch(url, fetchInit);\n\n if (!res.ok && !res.body) {\n throw failedToFetchRemoteComponentError(\n url.href,\n new Error(`${res.status} ${res.statusText}`),\n );\n }\n\n // create a parser for the HTML response\n const parser = Parser.getFragmentParser<DefaultTreeAdapterMap>();\n\n if (!res.body) {\n throw new Error(\n `Response is empty for Remote Component \"${url.href}\". Check if you can open it in the browser and you see the Remote Component content.`,\n );\n }\n\n const decoder = new TextDecoder();\n // read the response body as a stream and parse it using the parse5 fragment parser\n for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {\n parser.tokenizer.write(decoder.decode(chunk), false);\n }\n const fragment = parser.getFragment();\n\n let metadata: RemoteComponentMetadata = {\n bundle: CURRENT_ZONE ?? '__vercel_remote_component',\n route: '/',\n runtime: 'webpack',\n id: '__vercel_remote_component',\n type: 'unknown',\n };\n let remoteShared: Record<string, string> = {};\n const scripts: { src: string; textContent?: string }[] = [];\n const links: Record<string, string | boolean>[] = [];\n const hydrationData: string[] = [];\n let nextData:\n | {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: string;\n shared?: Record<string, string>;\n };\n };\n page?: string;\n buildId?: string;\n }\n | undefined;\n let html = '';\n\n const remoteName =\n options.name || url.hash ? url.hash.substring(1) : undefined;\n // convert the parsed HTML fragment into an RSC flight data\n // and extract the metadata, scripts, links and remote component RSC flight data\n let hasRemoteComponent = false;\n let hasRSC = false;\n let hasShared = false;\n let hasMultipleRemoteComponents = false;\n let error: Error | undefined;\n const rsc = visit(fragment, {\n url,\n name: remoteName,\n onMetadata(_metadata) {\n metadata = _metadata;\n if (hasRemoteComponent && metadata.id !== _metadata.id) {\n hasMultipleRemoteComponents = true;\n }\n hasRemoteComponent = true;\n },\n onScript(attrs) {\n if (\n !scripts.find(\n (it) =>\n it.src === attrs.src ||\n (attrs.textContent && it.textContent === attrs.textContent),\n )\n ) {\n scripts.push({\n src:\n typeof attrs.textContent === 'string'\n ? ''\n : new URL(attrs.src as string, new URL(url).origin).href,\n textContent:\n typeof attrs.textContent === 'string'\n ? attrs.textContent\n : undefined,\n });\n }\n },\n onLink(attrs) {\n const relativeAttrs = {\n ...attrs,\n href: new URL(attrs.href as string, new URL(url).origin).href,\n };\n if (\n !links.find(\n (it) => it.href === relativeAttrs.href && it.rel === attrs.rel,\n )\n ) {\n links.push(relativeAttrs);\n }\n },\n onRSC(chunk) {\n hydrationData.push(chunk);\n hasRSC = true;\n },\n onNextData(data) {\n nextData = data;\n\n // use the Next.js Pages Router props data to extract remote component metadata\n if (data.props.__REMOTE_COMPONENT__) {\n Object.assign(metadata, data.props.__REMOTE_COMPONENT__);\n // only a singleton remote component is supported per page when using the Next.js Pages Router\n metadata.id = '__next';\n metadata.route = data.page ?? '/';\n }\n },\n onHTML(_html) {\n if (!html.includes(_html)) {\n html += _html;\n }\n },\n onShared(_shared) {\n remoteShared = _shared;\n hasShared = true;\n },\n onError(message, stack) {\n error = new RemoteComponentsError(message);\n if (stack) {\n error.stack = stack;\n }\n },\n });\n\n if (error) {\n throw error;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!hasRemoteComponent) {\n throw new Error(\n `No Remote Component found at \"${url.href}\". Make sure the remote URL is correct and contains a Remote Component.`,\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (hasMultipleRemoteComponents && !remoteName) {\n throw multipleRemoteComponentsError(url.href);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!hasRSC && !nextData && metadata.type === 'nextjs') {\n throw new Error(\n `The Remote Component at \"${url.href}\" seems to be a Next.js component but it does not contain any RSC flight data or Next.js props data. Make sure the remote URL is correct and contains a Remote Component.`,\n );\n }\n\n if (\n metadata.type === 'nextjs' &&\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n !hasShared &&\n !nextData?.props.__REMOTE_COMPONENT__?.shared\n ) {\n throw new Error(\n `No shared dependencies found for Remote Component at \"${url.href}\". Make sure the remote URL is correct and contains a Remote Component with shared dependencies.`,\n );\n }\n\n let component: React.ReactNode | undefined;\n\n // only create a React component if requested\n if (options.rsc) {\n // RSC flight data for the static HTML in a single RSC line\n const componentRSC = `0:${JSON.stringify(rsc)}\\n`;\n\n const { createFromReadableStream } = await import(\n 'next/dist/compiled/react-server-dom-webpack/client.edge'\n );\n\n // create a React tree from the RSC flight data\n component = await createFromReadableStream(\n new ReadableStream({\n type: 'bytes',\n start(controller) {\n const encoder = new TextEncoder();\n controller.enqueue(encoder.encode(componentRSC));\n controller.close();\n },\n }),\n {\n serverConsumerManifest: {\n moduleLoading: {\n prefix: url.origin,\n crossOrigin: true,\n },\n moduleMap: {},\n },\n },\n );\n }\n\n const name = metadata.id.replace(/_ssr$/, '');\n return {\n name,\n url,\n metadata,\n rsc,\n scripts,\n links,\n hydrationData,\n nextData,\n component,\n html,\n remoteShared: nextData?.props.__REMOTE_COMPONENT__?.shared ?? remoteShared,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAmD;AACnD,mBAIO;AACP,wBAAsB;AACtB,2BAAmC;AAGnC,MAAM,eAAe,QAAQ,IAAI;AAO1B,SAAS,WAAW,YAA6B;AACtD,QAAM,OAAO,WAAW,IAAI,MAAM;AAClC,MAAI,MAAM;AACR,WAAO,KAAK,WAAW,WAAW,IAAI,UAAU,SAAS,WAAW;AAAA,EACtE;AACA,QAAM,gBAAgB,WAAW,IAAI,kBAAkB;AACvD,MAAI,eAAe;AACjB,WAAO,WAAW;AAAA,EACpB;AAGA,MAAI,QAAQ,IAAI,YAAY;AAC1B,WAAO,WAAW,QAAQ,IAAI;AAAA,EAChC;AAEA,SAAO,oBAAoB,QAAQ,IAAI,wBAAwB;AACjE;AAEA,eAAsB,qBACpB,KACA,UAAmB,IAAI,QAAQ,GAC/B,UAGI;AAAA,EACF,KAAK;AACP,GACA;AACA,QAAM,MAAM,IAAI,IAAI,KAAK,WAAW,OAAO,CAAC;AAE5C,QAAM,YAAY;AAAA,IAChB,QAAQ;AAAA;AAAA,IAER,aAAS,yCAAmB,OAAO;AAAA,IACnC,aAAa;AAAA,EACf;AAEA,QAAM,MAAM,MAAM,MAAM,KAAK,SAAS;AAEtC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,4CAA8B,IAAI,IAAI;AAAA,EAC9C;AAGA,MAAI,CAAC,UAAU,CAAC,YAAY,SAAS,SAAS,UAAU;AACtD,UAAM,IAAI;AAAA,MACR,4BAA4B,IAAI;AAAA,IAClC;AAAA,EACF;AAEA,MACE,SAAS,SAAS;AAAA,EAElB,CAAC,aACD,CAAC,UAAU,MAAM,sBAAsB,QACvC;AACA,UAAM,IAAI;AAAA,MACR,yDAAyD,IAAI;AAAA,IAC/D;AAAA,EACF;AAEA,MAAI;AAGJ,MAAI,QAAQ,KAAK;AAEf,UAAM,eAAe,KAAK,KAAK,UAAU,GAAG;AAAA;AAE5C,UAAM,EAAE,yBAAyB,IAAI,MAAM,OACzC,yDACF;AAGA,gBAAY,MAAM;AAAA,MAChB,IAAI,eAAe;AAAA,QACjB,MAAM;AAAA,QACN,MAAM,YAAY;AAChB,gBAAM,UAAU,IAAI,YAAY;AAChC,qBAAW,QAAQ,QAAQ,OAAO,YAAY,CAAC;AAC/C,qBAAW,MAAM;AAAA,QACnB;AAAA,MACF,CAAC;AAAA,MACD;AAAA,QACE,wBAAwB;AAAA,UACtB,eAAe;AAAA,YACb,QAAQ,IAAI;AAAA,YACZ,aAAa;AAAA,UACf;AAAA,UACA,WAAW,CAAC;AAAA,QACd;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,QAAM,OAAO,SAAS,GAAG,QAAQ,SAAS,EAAE;AAC5C,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc,UAAU,MAAM,sBAAsB,UAAU;AAAA,EAChE;AACF;","names":[]}
@@ -1,11 +1,11 @@
1
1
  import { Parser } from "parse5";
2
- import { visit } from "#internal/shared/ssr/dom-flight";
3
- import { remoteFetchHeaders } from "#internal/shared/ssr/fetch-headers";
4
2
  import {
5
3
  failedToFetchRemoteComponentError,
6
4
  multipleRemoteComponentsError,
7
5
  RemoteComponentsError
8
6
  } from "#internal/shared/error";
7
+ import { visit } from "#internal/shared/ssr/dom-flight";
8
+ import { remoteFetchHeaders } from "#internal/shared/ssr/fetch-headers";
9
9
  const CURRENT_ZONE = process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION;
10
10
  function getBaseUrl(reqHeaders) {
11
11
  const host = reqHeaders.get("host");
@@ -16,8 +16,8 @@ function getBaseUrl(reqHeaders) {
16
16
  if (forwardedHost) {
17
17
  return `https://${forwardedHost}`;
18
18
  }
19
- if (process.env.VERCEL_PROJECT_PRODUCTION_URL) {
20
- return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
19
+ if (process.env.VERCEL_URL) {
20
+ return `https://${process.env.VERCEL_URL}`;
21
21
  }
22
22
  return `http://localhost:${process.env.MFE_LOCAL_PROXY_PORT || 3024}`;
23
23
  }
@@ -80,7 +80,7 @@ async function fetchRemoteComponent(src, headers = new Headers(), options = {
80
80
  },
81
81
  onScript(attrs) {
82
82
  if (!scripts.find(
83
- (it) => it.src === attrs.src || it.textContent === attrs.textContent
83
+ (it) => it.src === attrs.src || attrs.textContent && it.textContent === attrs.textContent
84
84
  )) {
85
85
  scripts.push({
86
86
  src: typeof attrs.textContent === "string" ? "" : new URL(attrs.src, new URL(url).origin).href,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/shared/ssr/fetch-remote-component.ts"],"sourcesContent":["import { type DefaultTreeAdapterMap, Parser } from 'parse5';\nimport { visit } from '#internal/shared/ssr/dom-flight';\nimport { remoteFetchHeaders } from '#internal/shared/ssr/fetch-headers';\nimport {\n failedToFetchRemoteComponentError,\n multipleRemoteComponentsError,\n RemoteComponentsError,\n} from '#internal/shared/error';\nimport type { RemoteComponentMetadata } from './types';\n\nconst CURRENT_ZONE = process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION;\n\n/**\n * Resolves the base URL that should be used to fetch the remote component.\n * This function must support local development, Vercel environments, and SSG\n * and dynamic rendering.\n */\nexport function getBaseUrl(reqHeaders: Headers): string {\n const host = reqHeaders.get('host');\n if (host) {\n return host.startsWith('localhost') ? `http://${host}` : `https://${host}`;\n }\n const forwardedHost = reqHeaders.get('x-forwarded-host');\n if (forwardedHost) {\n return `https://${forwardedHost}`;\n }\n if (process.env.VERCEL_PROJECT_PRODUCTION_URL) {\n return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;\n }\n // TODO: Resolve the correct URL in local development when the proxy is not running.\n return `http://localhost:${process.env.MFE_LOCAL_PROXY_PORT || 3024}`;\n}\n\nexport async function fetchRemoteComponent(\n src: string | URL,\n headers: Headers = new Headers(),\n options: {\n name?: string;\n rsc?: boolean;\n } = {\n rsc: false,\n },\n) {\n const url = new URL(src, getBaseUrl(headers));\n\n const fetchInit = {\n method: 'GET',\n // pass all headers to the remote component\n headers: remoteFetchHeaders(headers),\n credentials: 'include',\n } as RequestInit;\n\n const res = await fetch(url, fetchInit);\n\n if (!res.ok && !res.body) {\n throw failedToFetchRemoteComponentError(\n url.href,\n new Error(`${res.status} ${res.statusText}`),\n );\n }\n\n // create a parser for the HTML response\n const parser = Parser.getFragmentParser<DefaultTreeAdapterMap>();\n\n if (!res.body) {\n throw new Error(\n `Response is empty for Remote Component \"${url.href}\". Check if you can open it in the browser and you see the Remote Component content.`,\n );\n }\n\n const decoder = new TextDecoder();\n // read the response body as a stream and parse it using the parse5 fragment parser\n for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {\n parser.tokenizer.write(decoder.decode(chunk), false);\n }\n const fragment = parser.getFragment();\n\n let metadata: RemoteComponentMetadata = {\n bundle: CURRENT_ZONE ?? '__vercel_remote_component',\n route: '/',\n runtime: 'webpack',\n id: '__vercel_remote_component',\n type: 'unknown',\n };\n let remoteShared: Record<string, string> = {};\n const scripts: { src: string; textContent?: string }[] = [];\n const links: Record<string, string | boolean>[] = [];\n const hydrationData: string[] = [];\n let nextData:\n | {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: string;\n shared?: Record<string, string>;\n };\n };\n page?: string;\n buildId?: string;\n }\n | undefined;\n let html = '';\n\n const remoteName =\n options.name || url.hash ? url.hash.substring(1) : undefined;\n // convert the parsed HTML fragment into an RSC flight data\n // and extract the metadata, scripts, links and remote component RSC flight data\n let hasRemoteComponent = false;\n let hasRSC = false;\n let hasShared = false;\n let hasMultipleRemoteComponents = false;\n let error: Error | undefined;\n const rsc = visit(fragment, {\n url,\n name: remoteName,\n onMetadata(_metadata) {\n metadata = _metadata;\n if (hasRemoteComponent && metadata.id !== _metadata.id) {\n hasMultipleRemoteComponents = true;\n }\n hasRemoteComponent = true;\n },\n onScript(attrs) {\n if (\n !scripts.find(\n (it) => it.src === attrs.src || it.textContent === attrs.textContent,\n )\n ) {\n scripts.push({\n src:\n typeof attrs.textContent === 'string'\n ? ''\n : new URL(attrs.src as string, new URL(url).origin).href,\n textContent:\n typeof attrs.textContent === 'string'\n ? attrs.textContent\n : undefined,\n });\n }\n },\n onLink(attrs) {\n const relativeAttrs = {\n ...attrs,\n href: new URL(attrs.href as string, new URL(url).origin).href,\n };\n if (\n !links.find(\n (it) => it.href === relativeAttrs.href && it.rel === attrs.rel,\n )\n ) {\n links.push(relativeAttrs);\n }\n },\n onRSC(chunk) {\n hydrationData.push(chunk);\n hasRSC = true;\n },\n onNextData(data) {\n nextData = data;\n\n // use the Next.js Pages Router props data to extract remote component metadata\n if (data.props.__REMOTE_COMPONENT__) {\n Object.assign(metadata, data.props.__REMOTE_COMPONENT__);\n // only a singleton remote component is supported per page when using the Next.js Pages Router\n metadata.id = '__next';\n metadata.route = data.page ?? '/';\n }\n },\n onHTML(_html) {\n if (!html.includes(_html)) {\n html += _html;\n }\n },\n onShared(_shared) {\n remoteShared = _shared;\n hasShared = true;\n },\n onError(message, stack) {\n error = new RemoteComponentsError(message);\n if (stack) {\n error.stack = stack;\n }\n },\n });\n\n if (error) {\n throw error;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!hasRemoteComponent) {\n throw new Error(\n `No Remote Component found at \"${url.href}\". Make sure the remote URL is correct and contains a Remote Component.`,\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (hasMultipleRemoteComponents && !remoteName) {\n throw multipleRemoteComponentsError(url.href);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!hasRSC && !nextData && metadata.type === 'nextjs') {\n throw new Error(\n `The Remote Component at \"${url.href}\" seems to be a Next.js component but it does not contain any RSC flight data or Next.js props data. Make sure the remote URL is correct and contains a Remote Component.`,\n );\n }\n\n if (\n metadata.type === 'nextjs' &&\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n !hasShared &&\n !nextData?.props.__REMOTE_COMPONENT__?.shared\n ) {\n throw new Error(\n `No shared dependencies found for Remote Component at \"${url.href}\". Make sure the remote URL is correct and contains a Remote Component with shared dependencies.`,\n );\n }\n\n let component: React.ReactNode | undefined;\n\n // only create a React component if requested\n if (options.rsc) {\n // RSC flight data for the static HTML in a single RSC line\n const componentRSC = `0:${JSON.stringify(rsc)}\\n`;\n\n const { createFromReadableStream } = await import(\n 'next/dist/compiled/react-server-dom-webpack/client.edge'\n );\n\n // create a React tree from the RSC flight data\n component = await createFromReadableStream(\n new ReadableStream({\n type: 'bytes',\n start(controller) {\n const encoder = new TextEncoder();\n controller.enqueue(encoder.encode(componentRSC));\n controller.close();\n },\n }),\n {\n serverConsumerManifest: {\n moduleLoading: {\n prefix: url.origin,\n crossOrigin: true,\n },\n moduleMap: {},\n },\n },\n );\n }\n\n const name = metadata.id.replace(/_ssr$/, '');\n return {\n name,\n url,\n metadata,\n rsc,\n scripts,\n links,\n hydrationData,\n nextData,\n component,\n html,\n remoteShared: nextData?.props.__REMOTE_COMPONENT__?.shared ?? remoteShared,\n };\n}\n"],"mappings":"AAAA,SAAqC,cAAc;AACnD,SAAS,aAAa;AACtB,SAAS,0BAA0B;AACnC;AAAA,EACE;AAA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,UAAU,IAAI,YAAY;AAChC,qBAAW,QAAQ,QAAQ,OAAO,YAAY,CAAC;AAC/C,qBAAW,MAAM;AAAA,QACnB;AAAA,MACF,CAAC;AAAA,MACD;AAAA,QACE,wBAAwB;AAAA,UACtB,eAAe;AAAA,YACb,QAAQ,IAAI;AAAA,YACZ,aAAa;AAAA,UACf;AAAA,UACA,WAAW,CAAC;AAAA,QACd;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,QAAM,OAAO,SAAS,GAAG,QAAQ,SAAS,EAAE;AAC5C,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc,UAAU,MAAM,sBAAsB,UAAU;AAAA,EAChE;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../../src/shared/ssr/fetch-remote-component.ts"],"sourcesContent":["import { type DefaultTreeAdapterMap, Parser } from 'parse5';\nimport {\n failedToFetchRemoteComponentError,\n multipleRemoteComponentsError,\n RemoteComponentsError,\n} from '#internal/shared/error';\nimport { visit } from '#internal/shared/ssr/dom-flight';\nimport { remoteFetchHeaders } from '#internal/shared/ssr/fetch-headers';\nimport type { RemoteComponentMetadata } from './types';\n\nconst CURRENT_ZONE = process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION;\n\n/**\n * Resolves the base URL that should be used to fetch the remote component.\n * This function must support local development, Vercel environments, and SSG\n * and dynamic rendering.\n */\nexport function getBaseUrl(reqHeaders: Headers): string {\n const host = reqHeaders.get('host');\n if (host) {\n return host.startsWith('localhost') ? `http://${host}` : `https://${host}`;\n }\n const forwardedHost = reqHeaders.get('x-forwarded-host');\n if (forwardedHost) {\n return `https://${forwardedHost}`;\n }\n // This is the deployment URL. When using deployment protection the\n // automation bypass header can be provided using additionalHeaders.\n if (process.env.VERCEL_URL) {\n return `https://${process.env.VERCEL_URL}`;\n }\n // TODO: Resolve the correct URL in local development when the proxy is not running.\n return `http://localhost:${process.env.MFE_LOCAL_PROXY_PORT || 3024}`;\n}\n\nexport async function fetchRemoteComponent(\n src: string | URL,\n headers: Headers = new Headers(),\n options: {\n name?: string;\n rsc?: boolean;\n } = {\n rsc: false,\n },\n) {\n const url = new URL(src, getBaseUrl(headers));\n\n const fetchInit = {\n method: 'GET',\n // pass all headers to the remote component\n headers: remoteFetchHeaders(headers),\n credentials: 'include',\n } as RequestInit;\n\n const res = await fetch(url, fetchInit);\n\n if (!res.ok && !res.body) {\n throw failedToFetchRemoteComponentError(\n url.href,\n new Error(`${res.status} ${res.statusText}`),\n );\n }\n\n // create a parser for the HTML response\n const parser = Parser.getFragmentParser<DefaultTreeAdapterMap>();\n\n if (!res.body) {\n throw new Error(\n `Response is empty for Remote Component \"${url.href}\". Check if you can open it in the browser and you see the Remote Component content.`,\n );\n }\n\n const decoder = new TextDecoder();\n // read the response body as a stream and parse it using the parse5 fragment parser\n for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {\n parser.tokenizer.write(decoder.decode(chunk), false);\n }\n const fragment = parser.getFragment();\n\n let metadata: RemoteComponentMetadata = {\n bundle: CURRENT_ZONE ?? '__vercel_remote_component',\n route: '/',\n runtime: 'webpack',\n id: '__vercel_remote_component',\n type: 'unknown',\n };\n let remoteShared: Record<string, string> = {};\n const scripts: { src: string; textContent?: string }[] = [];\n const links: Record<string, string | boolean>[] = [];\n const hydrationData: string[] = [];\n let nextData:\n | {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: string;\n shared?: Record<string, string>;\n };\n };\n page?: string;\n buildId?: string;\n }\n | undefined;\n let html = '';\n\n const remoteName =\n options.name || url.hash ? url.hash.substring(1) : undefined;\n // convert the parsed HTML fragment into an RSC flight data\n // and extract the metadata, scripts, links and remote component RSC flight data\n let hasRemoteComponent = false;\n let hasRSC = false;\n let hasShared = false;\n let hasMultipleRemoteComponents = false;\n let error: Error | undefined;\n const rsc = visit(fragment, {\n url,\n name: remoteName,\n onMetadata(_metadata) {\n metadata = _metadata;\n if (hasRemoteComponent && metadata.id !== _metadata.id) {\n hasMultipleRemoteComponents = true;\n }\n hasRemoteComponent = true;\n },\n onScript(attrs) {\n if (\n !scripts.find(\n (it) =>\n it.src === attrs.src ||\n (attrs.textContent && it.textContent === attrs.textContent),\n )\n ) {\n scripts.push({\n src:\n typeof attrs.textContent === 'string'\n ? ''\n : new URL(attrs.src as string, new URL(url).origin).href,\n textContent:\n typeof attrs.textContent === 'string'\n ? attrs.textContent\n : undefined,\n });\n }\n },\n onLink(attrs) {\n const relativeAttrs = {\n ...attrs,\n href: new URL(attrs.href as string, new URL(url).origin).href,\n };\n if (\n !links.find(\n (it) => it.href === relativeAttrs.href && it.rel === attrs.rel,\n )\n ) {\n links.push(relativeAttrs);\n }\n },\n onRSC(chunk) {\n hydrationData.push(chunk);\n hasRSC = true;\n },\n onNextData(data) {\n nextData = data;\n\n // use the Next.js Pages Router props data to extract remote component metadata\n if (data.props.__REMOTE_COMPONENT__) {\n Object.assign(metadata, data.props.__REMOTE_COMPONENT__);\n // only a singleton remote component is supported per page when using the Next.js Pages Router\n metadata.id = '__next';\n metadata.route = data.page ?? '/';\n }\n },\n onHTML(_html) {\n if (!html.includes(_html)) {\n html += _html;\n }\n },\n onShared(_shared) {\n remoteShared = _shared;\n hasShared = true;\n },\n onError(message, stack) {\n error = new RemoteComponentsError(message);\n if (stack) {\n error.stack = stack;\n }\n },\n });\n\n if (error) {\n throw error;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!hasRemoteComponent) {\n throw new Error(\n `No Remote Component found at \"${url.href}\". Make sure the remote URL is correct and contains a Remote Component.`,\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (hasMultipleRemoteComponents && !remoteName) {\n throw multipleRemoteComponentsError(url.href);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!hasRSC && !nextData && metadata.type === 'nextjs') {\n throw new Error(\n `The Remote Component at \"${url.href}\" seems to be a Next.js component but it does not contain any RSC flight data or Next.js props data. Make sure the remote URL is correct and contains a Remote Component.`,\n );\n }\n\n if (\n metadata.type === 'nextjs' &&\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n !hasShared &&\n !nextData?.props.__REMOTE_COMPONENT__?.shared\n ) {\n throw new Error(\n `No shared dependencies found for Remote Component at \"${url.href}\". Make sure the remote URL is correct and contains a Remote Component with shared dependencies.`,\n );\n }\n\n let component: React.ReactNode | undefined;\n\n // only create a React component if requested\n if (options.rsc) {\n // RSC flight data for the static HTML in a single RSC line\n const componentRSC = `0:${JSON.stringify(rsc)}\\n`;\n\n const { createFromReadableStream } = await import(\n 'next/dist/compiled/react-server-dom-webpack/client.edge'\n );\n\n // create a React tree from the RSC flight data\n component = await createFromReadableStream(\n new ReadableStream({\n type: 'bytes',\n start(controller) {\n const encoder = new TextEncoder();\n controller.enqueue(encoder.encode(componentRSC));\n controller.close();\n },\n }),\n {\n serverConsumerManifest: {\n moduleLoading: {\n prefix: url.origin,\n crossOrigin: true,\n },\n moduleMap: {},\n },\n },\n );\n }\n\n const name = metadata.id.replace(/_ssr$/, '');\n return {\n name,\n url,\n metadata,\n rsc,\n scripts,\n links,\n hydrationData,\n nextData,\n component,\n html,\n remoteShared: nextData?.props.__REMOTE_COMPONENT__?.shared ?? remoteShared,\n };\n}\n"],"mappings":"AAAA,SAAqC,cAAc;AACnD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa;AACtB,SAAS,0BAA0B;AAGnC,MAAM,eAAe,QAAQ,IAAI;AAO1B,SAAS,WAAW,YAA6B;AACtD,QAAM,OAAO,WAAW,IAAI,MAAM;AAClC,MAAI,MAAM;AACR,WAAO,KAAK,WAAW,WAAW,IAAI,UAAU,SAAS,WAAW;AAAA,EACtE;AACA,QAAM,gBAAgB,WAAW,IAAI,kBAAkB;AACvD,MAAI,eAA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A,MACF;AAAA,IACF;AAAA,EACF;AAEA,QAAM,OAAO,SAAS,GAAG,QAAQ,SAAS,EAAE;AAC5C,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc,UAAU,MAAM,sBAAsB,UAAU;AAAA,EAChE;AACF;","names":[]}
@@ -33,8 +33,8 @@ __export(config_exports, {
33
33
  withRemoteComponents: () => withRemoteComponents
34
34
  });
35
35
  module.exports = __toCommonJS(config_exports);
36
- var import_node_path3 = require("path");
37
36
  var import_node_fs = require("fs");
37
+ var import_node_path3 = require("path");
38
38
  var import_enhanced_resolve = __toESM(require("enhanced-resolve"), 1);
39
39
  var import_find_up = require("find-up");
40
40
  var import_config_schema = require("next/dist/server/config-schema.js");
@@ -43,37 +43,37 @@ var import_tsconfig_paths_webpack_plugin = __toESM(require("tsconfig-paths-webpa
43
43
  // src/next/config/webpack/index.ts
44
44
  var import_node_path2 = require("path");
45
45
 
46
- // src/next/config/webpack/plugins/remote-webpack-require-runtime-module.ts
47
- function createRemoteWebpackRequireRuntimeModule(webpack) {
48
- return class RemoteWebpackRequireRuntimeModule extends webpack.RuntimeModule {
49
- constructor(appName) {
50
- super("remote-webpack-require");
51
- this.appName = appName;
52
- }
53
- generate() {
54
- return `globalThis.__remote_webpack_require__ = globalThis.__remote_webpack_require__ || {}; globalThis.__remote_webpack_require__["${this.appName}"] = __webpack_require__;`;
55
- }
56
- };
57
- }
58
-
59
- // src/next/config/webpack/plugins/remote-webpack-require.ts
60
- var RemoteWebpackRequirePlugin = class {
46
+ // src/next/config/webpack/plugins/conditional-exec.ts
47
+ var ConditionalExecPlugin = class {
48
+ appName;
61
49
  constructor(appName) {
62
50
  this.appName = appName;
63
51
  }
64
52
  apply(compiler) {
65
- const RemoteWebpackRequireRuntimeModule = createRemoteWebpackRequireRuntimeModule(compiler.webpack);
53
+ const { Compilation, sources } = compiler.webpack;
66
54
  compiler.hooks.thisCompilation.tap(
67
- "RemoteWebpackRequirePlugin",
55
+ "ConditionalExecPlugin",
68
56
  (compilation) => {
69
- compilation.hooks.runtimeRequirementInTree.for("__webpack_require__").tap("RemoteWebpackRequirePlugin", (chunk) => {
70
- compilation.addRuntimeModule(
71
- chunk,
72
- new RemoteWebpackRequireRuntimeModule(
73
- this.appName
74
- )
75
- );
76
- });
57
+ compilation.hooks.processAssets.tap(
58
+ {
59
+ name: "ConditionalExecPlugin",
60
+ stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
61
+ },
62
+ (assets) => {
63
+ for (const [name, source] of Object.entries(assets)) {
64
+ if (name.endsWith(".js")) {
65
+ const patchedSource = source.source().toString().replace(
66
+ `var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))`,
67
+ `var __webpack_exec__ = (moduleId) => { if (globalThis.__DISABLE_WEBPACK_EXEC__ && globalThis.__DISABLE_WEBPACK_EXEC__["${this.appName}"]) return; return __webpack_require__(__webpack_require__.s = moduleId); }`
68
+ );
69
+ compilation.updateAsset(
70
+ name,
71
+ new sources.RawSource(patchedSource)
72
+ );
73
+ }
74
+ }
75
+ }
76
+ );
77
77
  }
78
78
  );
79
79
  }
@@ -85,6 +85,8 @@ var import_node_path = require("path");
85
85
  // src/next/config/webpack/plugins/module-id-embed-runtime-module.ts
86
86
  function createModuleIdEmbedRuntimeModule(webpack) {
87
87
  return class ModuleIdEmbedRuntimeModule extends webpack.RuntimeModule {
88
+ appName;
89
+ moduleMap;
88
90
  constructor(appName, moduleMap) {
89
91
  super("remote-webpack-module-id-embed");
90
92
  this.appName = appName;
@@ -99,6 +101,7 @@ function createModuleIdEmbedRuntimeModule(webpack) {
99
101
  // src/next/config/webpack/plugins/module-id-embed.ts
100
102
  var cwd = process.cwd();
101
103
  var ModuleIdEmbedPlugin = class {
104
+ appName;
102
105
  constructor(appName) {
103
106
  this.appName = appName;
104
107
  }
@@ -151,43 +154,9 @@ var ModuleIdEmbedPlugin = class {
151
154
  }
152
155
  };
153
156
 
154
- // src/next/config/webpack/plugins/conditional-exec.ts
155
- var ConditionalExecPlugin = class {
156
- constructor(appName) {
157
- this.appName = appName;
158
- }
159
- apply(compiler) {
160
- const { Compilation, sources } = compiler.webpack;
161
- compiler.hooks.thisCompilation.tap(
162
- "ConditionalExecPlugin",
163
- (compilation) => {
164
- compilation.hooks.processAssets.tap(
165
- {
166
- name: "ConditionalExecPlugin",
167
- stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
168
- },
169
- (assets) => {
170
- for (const [name, source] of Object.entries(assets)) {
171
- if (name.endsWith(".js")) {
172
- const patchedSource = source.source().toString().replace(
173
- `var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))`,
174
- `var __webpack_exec__ = (moduleId) => { if (globalThis.__DISABLE_WEBPACK_EXEC__ && globalThis.__DISABLE_WEBPACK_EXEC__["${this.appName}"]) return; return __webpack_require__(__webpack_require__.s = moduleId); }`
175
- );
176
- compilation.updateAsset(
177
- name,
178
- new sources.RawSource(patchedSource)
179
- );
180
- }
181
- }
182
- }
183
- );
184
- }
185
- );
186
- }
187
- };
188
-
189
157
  // src/next/config/webpack/plugins/patch-require.ts
190
158
  var PatchRequirePlugin = class {
159
+ appName;
191
160
  constructor(appName) {
192
161
  this.appName = appName;
193
162
  }
@@ -254,6 +223,44 @@ __webpack_require__.e = function __remote_webpack_require_e__(chunkId) {
254
223
  }
255
224
  };
256
225
 
226
+ // src/next/config/webpack/plugins/remote-webpack-require-runtime-module.ts
227
+ function createRemoteWebpackRequireRuntimeModule(webpack) {
228
+ return class RemoteWebpackRequireRuntimeModule extends webpack.RuntimeModule {
229
+ appName;
230
+ constructor(appName) {
231
+ super("remote-webpack-require");
232
+ this.appName = appName;
233
+ }
234
+ generate() {
235
+ return `globalThis.__remote_webpack_require__ = globalThis.__remote_webpack_require__ || {}; globalThis.__remote_webpack_require__["${this.appName}"] = __webpack_require__;`;
236
+ }
237
+ };
238
+ }
239
+
240
+ // src/next/config/webpack/plugins/remote-webpack-require.ts
241
+ var RemoteWebpackRequirePlugin = class {
242
+ appName;
243
+ constructor(appName) {
244
+ this.appName = appName;
245
+ }
246
+ apply(compiler) {
247
+ const RemoteWebpackRequireRuntimeModule = createRemoteWebpackRequireRuntimeModule(compiler.webpack);
248
+ compiler.hooks.thisCompilation.tap(
249
+ "RemoteWebpackRequirePlugin",
250
+ (compilation) => {
251
+ compilation.hooks.runtimeRequirementInTree.for("__webpack_require__").tap("RemoteWebpackRequirePlugin", (chunk) => {
252
+ compilation.addRuntimeModule(
253
+ chunk,
254
+ new RemoteWebpackRequireRuntimeModule(
255
+ this.appName
256
+ )
257
+ );
258
+ });
259
+ }
260
+ );
261
+ }
262
+ };
263
+
257
264
  // src/next/config/webpack/index.ts
258
265
  function transform(nextConfig, {
259
266
  app,
@@ -295,28 +302,23 @@ function transform(nextConfig, {
295
302
  function withRemoteComponents(nextConfig, options) {
296
303
  const virtualRemoteComponentAppSharedRemote = (0, import_node_path3.join)(
297
304
  process.cwd(),
298
- nextConfig.distDir ?? ".next",
299
- "remote-components/shared/app-remote.tsx"
305
+ ".remote-components/shared/app-remote.tsx"
300
306
  );
301
307
  const virtualRemoteComponentPagesSharedRemote = (0, import_node_path3.join)(
302
308
  process.cwd(),
303
- nextConfig.distDir ?? ".next",
304
- "remote-components/shared/pages-remote.tsx"
309
+ ".remote-components/shared/pages-remote.tsx"
305
310
  );
306
311
  const virtualRemoteComponentConfigWrapper = (0, import_node_path3.join)(
307
312
  process.cwd(),
308
- nextConfig.distDir ?? ".next",
309
- "remote-components/shared/config-wrapper.ts"
313
+ ".remote-components/shared/config-wrapper.ts"
310
314
  );
311
315
  const virtualRemoteComponentAppSharedHost = (0, import_node_path3.join)(
312
316
  process.cwd(),
313
- nextConfig.distDir ?? ".next",
314
- "remote-components/shared/app-host.tsx"
317
+ ".remote-components/shared/app-host.tsx"
315
318
  );
316
319
  const virtualRemoteComponentPagesSharedHost = (0, import_node_path3.join)(
317
320
  process.cwd(),
318
- nextConfig.distDir ?? ".next",
319
- "remote-components/shared/pages-host.tsx"
321
+ ".remote-components/shared/pages-host.tsx"
320
322
  );
321
323
  const appShared = /* @__PURE__ */ new Set([
322
324
  ...[
@@ -372,8 +374,30 @@ function withRemoteComponents(nextConfig, options) {
372
374
  ]
373
375
  } : {}
374
376
  });
377
+ let packageJson = {
378
+ name: (0, import_node_path3.basename)(process.cwd()),
379
+ type: "module"
380
+ };
381
+ try {
382
+ const packageJsonPath = (0, import_find_up.findUpSync)("package.json", {
383
+ cwd: process.cwd()
384
+ });
385
+ if (packageJsonPath) {
386
+ packageJson = {
387
+ ...packageJson,
388
+ ...JSON.parse((0, import_node_fs.readFileSync)(packageJsonPath, "utf8"))
389
+ };
390
+ }
391
+ } catch {
392
+ }
393
+ let exportPre = "export const shared = { ";
394
+ let exportPost = "};\n";
395
+ if (packageJson.type !== "module") {
396
+ exportPre = "module.exports = { shared: { ";
397
+ exportPost = "} };\n";
398
+ }
375
399
  const generateSharedRemote = (sharedRemote) => `'use client';
376
- module.exports = { shared: { ${Array.from(sharedRemote).reduce((acc, curr) => {
400
+ ${exportPre}${Array.from(sharedRemote).reduce((acc, curr) => {
377
401
  let path;
378
402
  try {
379
403
  path = resolve(process.cwd(), curr);
@@ -392,14 +416,12 @@ module.exports = { shared: { ${Array.from(sharedRemote).reduce((acc, curr) => {
392
416
  `['__remote_shared_module_${curr}']: () => import('${curr}'),`
393
417
  );
394
418
  return acc;
395
- }, []).join("\n")} } };
396
- `;
419
+ }, []).join("\n")}${exportPost}`;
397
420
  const generateSharedHost = (sharedHost) => `'use client';
398
- module.exports = { shared: { ${Array.from(sharedHost).reduce((acc, curr) => {
421
+ ${exportPre}${Array.from(sharedHost).reduce((acc, curr) => {
399
422
  acc.push(`['${curr}']: () => import('${curr}'),`);
400
423
  return acc;
401
- }, []).join("\n")} } };
402
- `;
424
+ }, []).join("\n")}${exportPost}`;
403
425
  const appSharedRemote = generateSharedRemote(appShared);
404
426
  const pagesSharedRemote = generateSharedRemote(pagesShared);
405
427
  const appSharedHost = generateSharedHost(appShared);
@@ -477,15 +499,7 @@ module.exports = { shared: { ${Array.from(sharedHost).reduce((acc, curr) => {
477
499
  }
478
500
  }
479
501
  if (!projectId) {
480
- const packageJsonPath = (0, import_find_up.findUpSync)("package.json", {
481
- cwd: process.cwd()
482
- });
483
- if (packageJsonPath) {
484
- const packageJson = JSON.parse((0, import_node_fs.readFileSync)(packageJsonPath, "utf8"));
485
- projectId = packageJson.name || (0, import_node_path3.basename)(process.cwd());
486
- } else {
487
- projectId = (0, import_node_path3.basename)(process.cwd());
488
- }
502
+ projectId = packageJson.name;
489
503
  }
490
504
  process.env.REMOTE_COMPONENTS_PROJECT_ID = projectId;
491
505
  if (process.env.TURBOPACK) {