remote-components 0.3.0 → 0.3.1
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/host/html.cjs +88 -53
- package/dist/host/html.cjs.map +1 -1
- package/dist/host/html.js +88 -53
- package/dist/host/html.js.map +1 -1
- package/dist/host/nextjs/app/client-only.cjs +64 -22
- package/dist/host/nextjs/app/client-only.cjs.map +1 -1
- package/dist/host/nextjs/app/client-only.js +64 -22
- package/dist/host/nextjs/app/client-only.js.map +1 -1
- package/dist/host/nextjs/app.cjs +5 -6
- package/dist/host/nextjs/app.cjs.map +1 -1
- package/dist/host/nextjs/app.js +5 -6
- package/dist/host/nextjs/app.js.map +1 -1
- package/dist/host/nextjs/pages.cjs +6 -11
- package/dist/host/nextjs/pages.cjs.map +1 -1
- package/dist/host/nextjs/pages.js +9 -11
- package/dist/host/nextjs/pages.js.map +1 -1
- package/dist/host/react.cjs +64 -22
- package/dist/host/react.cjs.map +1 -1
- package/dist/host/react.js +64 -22
- package/dist/host/react.js.map +1 -1
- package/dist/internal/host/nextjs/dom-flight.cjs +16 -7
- package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
- package/dist/internal/host/nextjs/dom-flight.d.ts +2 -2
- package/dist/internal/host/nextjs/dom-flight.js +16 -7
- package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
- package/dist/internal/host/server/fetch-remote-component.cjs +164 -149
- package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
- package/dist/internal/host/server/fetch-remote-component.js +166 -149
- package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
- package/dist/internal/runtime/constants.cjs +6 -6
- package/dist/internal/runtime/constants.cjs.map +1 -1
- package/dist/internal/runtime/constants.d.ts +3 -3
- package/dist/internal/runtime/constants.js +4 -4
- package/dist/internal/runtime/constants.js.map +1 -1
- package/dist/internal/runtime/html/parse-remote-html.cjs +11 -15
- package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
- package/dist/internal/runtime/html/parse-remote-html.d.ts +2 -12
- package/dist/internal/runtime/html/parse-remote-html.js +17 -15
- package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
- package/dist/internal/runtime/loaders/script-loader.cjs +2 -2
- package/dist/internal/runtime/loaders/script-loader.cjs.map +1 -1
- package/dist/internal/runtime/loaders/script-loader.js +1 -1
- package/dist/internal/runtime/loaders/script-loader.js.map +1 -1
- package/dist/internal/runtime/metadata.cjs +42 -0
- package/dist/internal/runtime/metadata.cjs.map +1 -1
- package/dist/internal/runtime/metadata.d.ts +21 -1
- package/dist/internal/runtime/metadata.js +38 -0
- package/dist/internal/runtime/metadata.js.map +1 -1
- package/dist/internal/runtime/patterns.cjs +38 -0
- package/dist/internal/runtime/patterns.cjs.map +1 -0
- package/dist/internal/runtime/patterns.d.ts +5 -0
- package/dist/internal/runtime/patterns.js +12 -0
- package/dist/internal/runtime/patterns.js.map +1 -0
- package/dist/internal/runtime/turbopack/chunk-loader.cjs +4 -3
- package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
- package/dist/internal/runtime/turbopack/chunk-loader.js +1 -1
- package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
- package/dist/internal/runtime/turbopack/webpack-runtime.cjs +11 -2
- package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +1 -1
- package/dist/internal/runtime/turbopack/webpack-runtime.js +10 -2
- package/dist/internal/runtime/turbopack/webpack-runtime.js.map +1 -1
- package/dist/remote/nextjs/app.cjs +2 -1
- package/dist/remote/nextjs/app.cjs.map +1 -1
- package/dist/remote/nextjs/app.js +2 -1
- package/dist/remote/nextjs/app.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/runtime/turbopack/chunk-loader.ts"],"sourcesContent":["import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n getBundleKey,\n REMOTE_COMPONENT_REGEX,\n RUNTIME_WEBPACK,\n type Runtime,\n} from '#internal/runtime/constants';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport {\n failedProxiedAssetError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport { logDebug, warnCrossOriginFetchError } from '#internal/utils/logger';\nimport { TURBOPACK_GLOBAL_RE } from './patterns';\n\n/**\n * Creates chunk loader function for webpack runtime.\n * This function is responsible for loading JavaScript chunks from remote applications\n * and transforming Turbopack-specific code to work in the host environment.\n */\nexport function createChunkLoader(\n runtime: Runtime,\n resolveClientUrl?: InternalResolveClientUrl,\n): (chunkId: string, scriptBundle?: string) => Promise<unknown> | undefined {\n return function __turbopack_chunk_load__(\n chunkId: string,\n scriptBundle?: string,\n ) {\n logDebug('ChunkLoader', `Loading chunk: \"${chunkId}\"`);\n const self = globalThis as GlobalScope;\n const {\n bundle,\n id: path,\n prefix,\n } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {\n bundle: scriptBundle ?? '',\n id: chunkId,\n };\n logDebug(\n 'ChunkLoader',\n `Parsed chunk - bundle: \"${bundle}\", path: \"${path}\", prefix: \"${prefix}\"`,\n );\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : runtime;\n logDebug('ChunkLoader', `Remote runtime: \"${remoteRuntime}\"`);\n if (remoteRuntime === RUNTIME_WEBPACK) {\n logDebug('ChunkLoader', 'Skipping chunk load - webpack runtime detected');\n return Promise.resolve(undefined);\n }\n\n const url = new URL(\n path\n ? `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n )\n : '/',\n self.__remote_bundle_url__?.[bundle ?? 'default'] ??\n new URL(location.origin),\n ).href;\n if (url.endsWith('.css')) {\n logDebug('ChunkLoader', `Skipping CSS file: \"${url}\"`);\n return;\n }\n\n if (!self.__remote_components_turbopack_chunk_loader_promise__) {\n self.__remote_components_turbopack_chunk_loader_promise__ = {};\n }\n if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {\n logDebug('ChunkLoader', `Returning cached promise for: \"${url}\"`);\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n }\n\n const resolvedUrl = resolveClientUrl?.(url) ?? url;\n logDebug('ChunkLoader', `Fetching chunk from: \"${resolvedUrl}\"`);\n self.__remote_components_turbopack_chunk_loader_promise__[url] =\n new Promise((resolve, reject) => {\n fetch(resolvedUrl)\n .then((res) => res.text())\n .then((code) => {\n // Turbopack runtime uses either dot-notation or bracket-notation globals.\n const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);\n if (hasTurbopack) {\n return handleTurbopackChunk(code, bundle ?? '', url);\n }\n logDebug(\n 'ChunkLoader',\n `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: \"${url}\"`,\n );\n logDebug(\n 'ChunkLoader',\n `First 500 chars of chunk: ${code.slice(0, 500)}`,\n );\n })\n .then(resolve)\n .catch((error) => {\n const isProxied = isProxiedUrl(resolvedUrl);\n if (isProxied) {\n reject(failedProxiedAssetError('chunk', url, resolvedUrl));\n } else {\n warnCrossOriginFetchError('ChunkLoader', url);\n reject(error);\n }\n });\n });\n\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n };\n}\n\n/**\n * Handles Turbopack chunk loading by transforming the chunk code to isolate\n * global variables per bundle and dynamically loading the transformed script.\n */\nasync function handleTurbopackChunk(\n code: string,\n bundle: string,\n url: string,\n): Promise<void> {\n logDebug(\n 'ChunkLoader',\n `Handling Turbopack chunk - bundle: \"${bundle}\", url: \"${url}\"`,\n );\n // skip this chunk as it is not needed for remote components\n if (/importScripts\\(\\.\\.\\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {\n logDebug('ChunkLoader', `Skipping worker chunk: \"${url}\"`);\n // remove preload links for this chunk\n const preloadLinks = document.querySelectorAll(\n `link[rel=\"preload\"][href=\"${new URL(url).pathname}\"]`,\n );\n preloadLinks.forEach((preloadLink) => preloadLink.remove());\n return;\n }\n\n const self = globalThis as GlobalScope;\n const bundleKey = getBundleKey(bundle);\n logDebug('ChunkLoader', `Bundle key: \"${bundleKey}\"`);\n\n // replace global variables with bundle-specific ones to prevent collisions\n // between multiple remote component bundles\n const transformedCode = code\n // Turbopack runtime can reference TURBOPACK via bracket-notation (common in newer Next.js)\n // e.g. globalThis[\"TURBOPACK\"] / self['TURBOPACK']\n .replace(\n /globalThis\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `globalThis[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(\n /self\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `self[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(/globalThis\\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`)\n .replace(/self\\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`)\n .replace(\n /TURBOPACK_WORKER_LOCATION/g,\n `TURBOPACK_WORKER_LOCATION_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_NEXT_CHUNK_URLS/g,\n `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,\n `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`,\n )\n .replace(/__next_require__/g, `__${bundleKey}_next_require__`)\n .replace(\n /\\/\\/# sourceMappingURL=(?<name>.+)(?<optional>\\._)?\\.js\\.map/g,\n `//# sourceMappingURL=${\n new URL(\n '.',\n new URL(\n url,\n self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin),\n ),\n ).href\n }$1$2.js.map`,\n );\n\n // Initialize TURBOPACK bundle with push interceptor for Next.js 16.2.0-canary\n // Use webpack-style chunk loading pattern\n if (!self[`TURBOPACK_${bundleKey}`]) {\n const chunkData: unknown[][] = [];\n const turbopackObject = {\n push: (item: unknown) => {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? 'array' : typeof item}`,\n );\n if (Array.isArray(item)) {\n chunkData.push(item);\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`,\n );\n } else {\n chunkData.push([item]);\n }\n return chunkData.length;\n },\n // Store chunks for later access\n __chunks__: chunkData,\n };\n self[`TURBOPACK_${bundleKey}`] = turbopackObject as unknown as Record<\n string,\n unknown\n >;\n }\n\n // load the script dynamically using a Blob URL\n logDebug('ChunkLoader', `Creating blob script for: \"${url}\"`);\n await new Promise<void>((scriptResolve, scriptReject) => {\n const blob = new Blob([transformedCode], {\n type: 'application/javascript; charset=UTF-8',\n });\n const scriptUrl = URL.createObjectURL(blob);\n const script = document.createElement('script');\n script.setAttribute('data-turbopack-src', url);\n script.src = scriptUrl;\n script.async = true;\n script.onload = () => {\n URL.revokeObjectURL(scriptUrl);\n logDebug(\n 'ChunkLoader',\n `Script loaded successfully for bundle \"${bundle}\"`,\n );\n const turbopackBundle = self[`TURBOPACK_${bundleKey}`];\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${\n turbopackBundle\n ? Object.keys(turbopackBundle as object)\n .slice(0, 10)\n .join(', ')\n : 'none'\n }`,\n );\n if (turbopackBundle && typeof turbopackBundle === 'object') {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle as object).length}`,\n );\n }\n scriptResolve(undefined);\n script.remove();\n };\n script.onerror = () => {\n URL.revokeObjectURL(scriptUrl);\n scriptReject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${script.src}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n script.remove();\n };\n document.head.appendChild(script);\n });\n\n // process any additional chunks that were registered during script execution\n const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`] as\n | { chunks: string[] }[]\n | undefined;\n logDebug(\n 'ChunkLoader',\n `Processing chunk lists for bundle \"${bundle}\": ${chunkLists?.length ?? 0} lists`,\n );\n const loadChunkLists = [] as (Promise<unknown> | undefined)[];\n while (chunkLists?.length) {\n const { chunks } = chunkLists.shift() ?? { chunks: [] };\n if (chunks.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Loading ${chunks.length} additional chunks for bundle \"${bundle}\": [${chunks.join(', ')}]`,\n );\n chunks.forEach((id: string) => {\n const chunkLoadResult = self.__webpack_chunk_load__?.(\n `[${bundle}] ${url.slice(0, url.indexOf('/_next'))}/_next/${id}`,\n );\n if (chunkLoadResult) {\n loadChunkLists.push(chunkLoadResult);\n }\n });\n }\n }\n if (loadChunkLists.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Waiting for ${loadChunkLists.length} additional chunks to load`,\n );\n await Promise.all(loadChunkLists);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAKO;AAEP,mCAA6B;AAC7B,mBAGO;AACP,oBAAoD;AACpD,sBAAoC;AAO7B,SAAS,kBACd,SACA,kBAC0E;AAC1E,SAAO,SAAS,yBACd,SACA,cACA;AACA,gCAAS,eAAe,mBAAmB,UAAU;AACrD,UAAM,OAAO;AACb,UAAM;AAAA,MACJ;AAAA,MACA,IAAI;AAAA,MACJ;AAAA,IACF,IAAI,wCAAuB,KAAK,OAAO,GAAG,UAAU;AAAA,MAClD,QAAQ,gBAAgB;AAAA,MACxB,IAAI;AAAA,IACN;AACA;AAAA,MACE;AAAA,MACA,2BAA2B,mBAAmB,mBAAmB;AAAA,IACnE;AACA,UAAM,gBAAgB,KAAK,6BAA6B,UAAU,SAAS,IACvE,KAAK,2BAA2B,UAAU,SAAS,GAAG,QAAQ,YAC9D;AACJ,gCAAS,eAAe,oBAAoB,gBAAgB;AAC5D,QAAI,kBAAkB,kCAAiB;AACrC,kCAAS,eAAe,gDAAgD;AACxE,aAAO,QAAQ,QAAQ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,aAAS,KAAK,YAAY,MAAM;AAAA,EAClC,CAAC;AAGD,QAAM,aAAa,KAAK,aAAa,uBAAuB;AAG5D;AAAA,IACE;AAAA,IACA,sCAAsC,YAAY,YAAY,UAAU;AAAA,EAC1E;AACA,QAAM,iBAAiB,CAAC;AACxB,SAAO,YAAY,QAAQ;AACzB,UAAM,EAAE,OAAO,IAAI,WAAW,MAAM,KAAK,EAAE,QAAQ,CAAC,EAAE;AACtD,QAAI,OAAO,SAAS,GAAG;AACrB;AAAA,QACE;AAAA,QACA,WAAW,OAAO,wCAAwC,aAAa,OAAO,KAAK,IAAI;AAAA,MACzF;AACA,aAAO,QAAQ,CAAC,OAAe;AAC7B,cAAM,kBAAkB,KAAK;AAAA,UAC3B,IAAI,WAAW,IAAI,MAAM,GAAG,IAAI,QAAQ,QAAQ,CAAC,WAAW;AAAA,QAC9D;AACA,YAAI,iBAAiB;AACnB,yBAAe,KAAK,eAAe;AAAA,QACrC;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACA,MAAI,eAAe,SAAS,GAAG;AAC7B;AAAA,MACE;AAAA,MACA,eAAe,eAAe;AAAA,IAChC;AACA,UAAM,QAAQ,IAAI,cAAc;AAAA,EAClC;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/runtime/turbopack/chunk-loader.ts"],"sourcesContent":["import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n getBundleKey,\n RUNTIME_WEBPACK,\n type Runtime,\n} from '#internal/runtime/constants';\nimport { REMOTE_COMPONENT_REGEX } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport {\n failedProxiedAssetError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport { logDebug, warnCrossOriginFetchError } from '#internal/utils/logger';\nimport { TURBOPACK_GLOBAL_RE } from './patterns';\n\n/**\n * Creates chunk loader function for webpack runtime.\n * This function is responsible for loading JavaScript chunks from remote applications\n * and transforming Turbopack-specific code to work in the host environment.\n */\nexport function createChunkLoader(\n runtime: Runtime,\n resolveClientUrl?: InternalResolveClientUrl,\n): (chunkId: string, scriptBundle?: string) => Promise<unknown> | undefined {\n return function __turbopack_chunk_load__(\n chunkId: string,\n scriptBundle?: string,\n ) {\n logDebug('ChunkLoader', `Loading chunk: \"${chunkId}\"`);\n const self = globalThis as GlobalScope;\n const {\n bundle,\n id: path,\n prefix,\n } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {\n bundle: scriptBundle ?? '',\n id: chunkId,\n };\n logDebug(\n 'ChunkLoader',\n `Parsed chunk - bundle: \"${bundle}\", path: \"${path}\", prefix: \"${prefix}\"`,\n );\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : runtime;\n logDebug('ChunkLoader', `Remote runtime: \"${remoteRuntime}\"`);\n if (remoteRuntime === RUNTIME_WEBPACK) {\n logDebug('ChunkLoader', 'Skipping chunk load - webpack runtime detected');\n return Promise.resolve(undefined);\n }\n\n const url = new URL(\n path\n ? `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n )\n : '/',\n self.__remote_bundle_url__?.[bundle ?? 'default'] ??\n new URL(location.origin),\n ).href;\n if (url.endsWith('.css')) {\n logDebug('ChunkLoader', `Skipping CSS file: \"${url}\"`);\n return;\n }\n\n if (!self.__remote_components_turbopack_chunk_loader_promise__) {\n self.__remote_components_turbopack_chunk_loader_promise__ = {};\n }\n if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {\n logDebug('ChunkLoader', `Returning cached promise for: \"${url}\"`);\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n }\n\n const resolvedUrl = resolveClientUrl?.(url) ?? url;\n logDebug('ChunkLoader', `Fetching chunk from: \"${resolvedUrl}\"`);\n self.__remote_components_turbopack_chunk_loader_promise__[url] =\n new Promise((resolve, reject) => {\n fetch(resolvedUrl)\n .then((res) => res.text())\n .then((code) => {\n // Turbopack runtime uses either dot-notation or bracket-notation globals.\n const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);\n if (hasTurbopack) {\n return handleTurbopackChunk(code, bundle ?? '', url);\n }\n logDebug(\n 'ChunkLoader',\n `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: \"${url}\"`,\n );\n logDebug(\n 'ChunkLoader',\n `First 500 chars of chunk: ${code.slice(0, 500)}`,\n );\n })\n .then(resolve)\n .catch((error) => {\n const isProxied = isProxiedUrl(resolvedUrl);\n if (isProxied) {\n reject(failedProxiedAssetError('chunk', url, resolvedUrl));\n } else {\n warnCrossOriginFetchError('ChunkLoader', url);\n reject(error);\n }\n });\n });\n\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n };\n}\n\n/**\n * Handles Turbopack chunk loading by transforming the chunk code to isolate\n * global variables per bundle and dynamically loading the transformed script.\n */\nasync function handleTurbopackChunk(\n code: string,\n bundle: string,\n url: string,\n): Promise<void> {\n logDebug(\n 'ChunkLoader',\n `Handling Turbopack chunk - bundle: \"${bundle}\", url: \"${url}\"`,\n );\n // skip this chunk as it is not needed for remote components\n if (/importScripts\\(\\.\\.\\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {\n logDebug('ChunkLoader', `Skipping worker chunk: \"${url}\"`);\n // remove preload links for this chunk\n const preloadLinks = document.querySelectorAll(\n `link[rel=\"preload\"][href=\"${new URL(url).pathname}\"]`,\n );\n preloadLinks.forEach((preloadLink) => preloadLink.remove());\n return;\n }\n\n const self = globalThis as GlobalScope;\n const bundleKey = getBundleKey(bundle);\n logDebug('ChunkLoader', `Bundle key: \"${bundleKey}\"`);\n\n // replace global variables with bundle-specific ones to prevent collisions\n // between multiple remote component bundles\n const transformedCode = code\n // Turbopack runtime can reference TURBOPACK via bracket-notation (common in newer Next.js)\n // e.g. globalThis[\"TURBOPACK\"] / self['TURBOPACK']\n .replace(\n /globalThis\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `globalThis[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(\n /self\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `self[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(/globalThis\\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`)\n .replace(/self\\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`)\n .replace(\n /TURBOPACK_WORKER_LOCATION/g,\n `TURBOPACK_WORKER_LOCATION_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_NEXT_CHUNK_URLS/g,\n `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,\n `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`,\n )\n .replace(/__next_require__/g, `__${bundleKey}_next_require__`)\n .replace(\n /\\/\\/# sourceMappingURL=(?<name>.+)(?<optional>\\._)?\\.js\\.map/g,\n `//# sourceMappingURL=${\n new URL(\n '.',\n new URL(\n url,\n self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin),\n ),\n ).href\n }$1$2.js.map`,\n );\n\n // Initialize TURBOPACK bundle with push interceptor for Next.js 16.2.0-canary\n // Use webpack-style chunk loading pattern\n if (!self[`TURBOPACK_${bundleKey}`]) {\n const chunkData: unknown[][] = [];\n const turbopackObject = {\n push: (item: unknown) => {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? 'array' : typeof item}`,\n );\n if (Array.isArray(item)) {\n chunkData.push(item);\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`,\n );\n } else {\n chunkData.push([item]);\n }\n return chunkData.length;\n },\n // Store chunks for later access\n __chunks__: chunkData,\n };\n self[`TURBOPACK_${bundleKey}`] = turbopackObject as unknown as Record<\n string,\n unknown\n >;\n }\n\n // load the script dynamically using a Blob URL\n logDebug('ChunkLoader', `Creating blob script for: \"${url}\"`);\n await new Promise<void>((scriptResolve, scriptReject) => {\n const blob = new Blob([transformedCode], {\n type: 'application/javascript; charset=UTF-8',\n });\n const scriptUrl = URL.createObjectURL(blob);\n const script = document.createElement('script');\n script.setAttribute('data-turbopack-src', url);\n script.src = scriptUrl;\n script.async = true;\n script.onload = () => {\n URL.revokeObjectURL(scriptUrl);\n logDebug(\n 'ChunkLoader',\n `Script loaded successfully for bundle \"${bundle}\"`,\n );\n const turbopackBundle = self[`TURBOPACK_${bundleKey}`];\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${\n turbopackBundle\n ? Object.keys(turbopackBundle as object)\n .slice(0, 10)\n .join(', ')\n : 'none'\n }`,\n );\n if (turbopackBundle && typeof turbopackBundle === 'object') {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle as object).length}`,\n );\n }\n scriptResolve(undefined);\n script.remove();\n };\n script.onerror = () => {\n URL.revokeObjectURL(scriptUrl);\n scriptReject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${script.src}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n script.remove();\n };\n document.head.appendChild(script);\n });\n\n // process any additional chunks that were registered during script execution\n const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`] as\n | { chunks: string[] }[]\n | undefined;\n logDebug(\n 'ChunkLoader',\n `Processing chunk lists for bundle \"${bundle}\": ${chunkLists?.length ?? 0} lists`,\n );\n const loadChunkLists = [] as (Promise<unknown> | undefined)[];\n while (chunkLists?.length) {\n const { chunks } = chunkLists.shift() ?? { chunks: [] };\n if (chunks.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Loading ${chunks.length} additional chunks for bundle \"${bundle}\": [${chunks.join(', ')}]`,\n );\n chunks.forEach((id: string) => {\n const chunkLoadResult = self.__webpack_chunk_load__?.(\n `[${bundle}] ${url.slice(0, url.indexOf('/_next'))}/_next/${id}`,\n );\n if (chunkLoadResult) {\n loadChunkLists.push(chunkLoadResult);\n }\n });\n }\n }\n if (loadChunkLists.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Waiting for ${loadChunkLists.length} additional chunks to load`,\n );\n await Promise.all(loadChunkLists);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAIO;AACP,sBAAuC;AAEvC,mCAA6B;AAC7B,mBAGO;AACP,oBAAoD;AACpD,IAAAA,mBAAoC;AAO7B,SAAS,kBACd,SACA,kBAC0E;AAC1E,SAAO,SAAS,yBACd,SACA,cACA;AACA,gCAAS,eAAe,mBAAmB,UAAU;AACrD,UAAM,OAAO;AACb,UAAM;AAAA,MACJ;AAAA,MACA,IAAI;AAAA,MACJ;AAAA,IACF,IAAI,uCAAuB,KAAK,OAAO,GAAG,UAAU;AAAA,MAClD,QAAQ,gBAAgB;AAAA,MACxB,IAAI;AAAA,IACN;AACA;AAAA,MACE;AAAA,MACA,2BAA2B,mBAAmB,mBAAmB;AAAA,IACnE;AACA,UAAM,gBAAgB,KAAK,6BAA6B,UAAU,SAAS,IACvE,KAAK,2BAA2B,UAAU,SAAS,GAAG,QAAQ,YAC9D;AACJ,gCAAS,eAAe,oBAAoB,gBAAgB;AAC5D,QAAI,kBAAkB,kCAAiB;AACrC,kCAAS,eAAe,gDAAgD;AACxE,aAAO,QAAQ,QAAQ,MAAS;AAAA,IAClC;AAEA,UAAM,MAAM,IAAI;AAAA,MACd,OACI,GAAG,UAAU,KAAK,OAAO;AAAA,QACvB;AAAA,QACA;AAAA,MACF,IACA;AAAA,MACJ,KAAK,wBAAwB,UAAU,SAAS,KAC9C,IAAI,IAAI,SAAS,MAAM;AAAA,IAC3B,EAAE;AACF,QAAI,IAAI,SAAS,MAAM,GAAG;AACx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AAE,QAAQ,CAAC,EAAE;AACtD,QAAI,OAAO,SAAS,GAAG;AACrB;AAAA,QACE;AAAA,QACA,WAAW,OAAO,wCAAwC,aAAa,OAAO,KAAK,IAAI;AAAA,MACzF;AACA,aAAO,QAAQ,CAAC,OAAe;AAC7B,cAAM,kBAAkB,KAAK;AAAA,UAC3B,IAAI,WAAW,IAAI,MAAM,GAAG,IAAI,QAAQ,QAAQ,CAAC,WAAW;AAAA,QAC9D;AACA,YAAI,iBAAiB;AACnB,yBAAe,KAAK,eAAe;AAAA,QACrC;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACA,MAAI,eAAe,SAAS,GAAG;AAC7B;AAAA,MACE;AAAA,MACA,eAAe,eAAe;AAAA,IAChC;AACA,UAAM,QAAQ,IAAI,cAAc;AAAA,EAClC;AACF;","names":["import_patterns"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getBundleKey,
|
|
3
|
-
REMOTE_COMPONENT_REGEX,
|
|
4
3
|
RUNTIME_WEBPACK
|
|
5
4
|
} from "#internal/runtime/constants";
|
|
5
|
+
import { REMOTE_COMPONENT_REGEX } from "#internal/runtime/patterns";
|
|
6
6
|
import { isProxiedUrl } from "#internal/runtime/url/protected-rc-fallback";
|
|
7
7
|
import {
|
|
8
8
|
failedProxiedAssetError,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/runtime/turbopack/chunk-loader.ts"],"sourcesContent":["import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n getBundleKey,\n REMOTE_COMPONENT_REGEX,\n RUNTIME_WEBPACK,\n type Runtime,\n} from '#internal/runtime/constants';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport {\n failedProxiedAssetError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport { logDebug, warnCrossOriginFetchError } from '#internal/utils/logger';\nimport { TURBOPACK_GLOBAL_RE } from './patterns';\n\n/**\n * Creates chunk loader function for webpack runtime.\n * This function is responsible for loading JavaScript chunks from remote applications\n * and transforming Turbopack-specific code to work in the host environment.\n */\nexport function createChunkLoader(\n runtime: Runtime,\n resolveClientUrl?: InternalResolveClientUrl,\n): (chunkId: string, scriptBundle?: string) => Promise<unknown> | undefined {\n return function __turbopack_chunk_load__(\n chunkId: string,\n scriptBundle?: string,\n ) {\n logDebug('ChunkLoader', `Loading chunk: \"${chunkId}\"`);\n const self = globalThis as GlobalScope;\n const {\n bundle,\n id: path,\n prefix,\n } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {\n bundle: scriptBundle ?? '',\n id: chunkId,\n };\n logDebug(\n 'ChunkLoader',\n `Parsed chunk - bundle: \"${bundle}\", path: \"${path}\", prefix: \"${prefix}\"`,\n );\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : runtime;\n logDebug('ChunkLoader', `Remote runtime: \"${remoteRuntime}\"`);\n if (remoteRuntime === RUNTIME_WEBPACK) {\n logDebug('ChunkLoader', 'Skipping chunk load - webpack runtime detected');\n return Promise.resolve(undefined);\n }\n\n const url = new URL(\n path\n ? `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n )\n : '/',\n self.__remote_bundle_url__?.[bundle ?? 'default'] ??\n new URL(location.origin),\n ).href;\n if (url.endsWith('.css')) {\n logDebug('ChunkLoader', `Skipping CSS file: \"${url}\"`);\n return;\n }\n\n if (!self.__remote_components_turbopack_chunk_loader_promise__) {\n self.__remote_components_turbopack_chunk_loader_promise__ = {};\n }\n if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {\n logDebug('ChunkLoader', `Returning cached promise for: \"${url}\"`);\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n }\n\n const resolvedUrl = resolveClientUrl?.(url) ?? url;\n logDebug('ChunkLoader', `Fetching chunk from: \"${resolvedUrl}\"`);\n self.__remote_components_turbopack_chunk_loader_promise__[url] =\n new Promise((resolve, reject) => {\n fetch(resolvedUrl)\n .then((res) => res.text())\n .then((code) => {\n // Turbopack runtime uses either dot-notation or bracket-notation globals.\n const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);\n if (hasTurbopack) {\n return handleTurbopackChunk(code, bundle ?? '', url);\n }\n logDebug(\n 'ChunkLoader',\n `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: \"${url}\"`,\n );\n logDebug(\n 'ChunkLoader',\n `First 500 chars of chunk: ${code.slice(0, 500)}`,\n );\n })\n .then(resolve)\n .catch((error) => {\n const isProxied = isProxiedUrl(resolvedUrl);\n if (isProxied) {\n reject(failedProxiedAssetError('chunk', url, resolvedUrl));\n } else {\n warnCrossOriginFetchError('ChunkLoader', url);\n reject(error);\n }\n });\n });\n\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n };\n}\n\n/**\n * Handles Turbopack chunk loading by transforming the chunk code to isolate\n * global variables per bundle and dynamically loading the transformed script.\n */\nasync function handleTurbopackChunk(\n code: string,\n bundle: string,\n url: string,\n): Promise<void> {\n logDebug(\n 'ChunkLoader',\n `Handling Turbopack chunk - bundle: \"${bundle}\", url: \"${url}\"`,\n );\n // skip this chunk as it is not needed for remote components\n if (/importScripts\\(\\.\\.\\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {\n logDebug('ChunkLoader', `Skipping worker chunk: \"${url}\"`);\n // remove preload links for this chunk\n const preloadLinks = document.querySelectorAll(\n `link[rel=\"preload\"][href=\"${new URL(url).pathname}\"]`,\n );\n preloadLinks.forEach((preloadLink) => preloadLink.remove());\n return;\n }\n\n const self = globalThis as GlobalScope;\n const bundleKey = getBundleKey(bundle);\n logDebug('ChunkLoader', `Bundle key: \"${bundleKey}\"`);\n\n // replace global variables with bundle-specific ones to prevent collisions\n // between multiple remote component bundles\n const transformedCode = code\n // Turbopack runtime can reference TURBOPACK via bracket-notation (common in newer Next.js)\n // e.g. globalThis[\"TURBOPACK\"] / self['TURBOPACK']\n .replace(\n /globalThis\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `globalThis[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(\n /self\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `self[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(/globalThis\\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`)\n .replace(/self\\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`)\n .replace(\n /TURBOPACK_WORKER_LOCATION/g,\n `TURBOPACK_WORKER_LOCATION_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_NEXT_CHUNK_URLS/g,\n `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,\n `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`,\n )\n .replace(/__next_require__/g, `__${bundleKey}_next_require__`)\n .replace(\n /\\/\\/# sourceMappingURL=(?<name>.+)(?<optional>\\._)?\\.js\\.map/g,\n `//# sourceMappingURL=${\n new URL(\n '.',\n new URL(\n url,\n self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin),\n ),\n ).href\n }$1$2.js.map`,\n );\n\n // Initialize TURBOPACK bundle with push interceptor for Next.js 16.2.0-canary\n // Use webpack-style chunk loading pattern\n if (!self[`TURBOPACK_${bundleKey}`]) {\n const chunkData: unknown[][] = [];\n const turbopackObject = {\n push: (item: unknown) => {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? 'array' : typeof item}`,\n );\n if (Array.isArray(item)) {\n chunkData.push(item);\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`,\n );\n } else {\n chunkData.push([item]);\n }\n return chunkData.length;\n },\n // Store chunks for later access\n __chunks__: chunkData,\n };\n self[`TURBOPACK_${bundleKey}`] = turbopackObject as unknown as Record<\n string,\n unknown\n >;\n }\n\n // load the script dynamically using a Blob URL\n logDebug('ChunkLoader', `Creating blob script for: \"${url}\"`);\n await new Promise<void>((scriptResolve, scriptReject) => {\n const blob = new Blob([transformedCode], {\n type: 'application/javascript; charset=UTF-8',\n });\n const scriptUrl = URL.createObjectURL(blob);\n const script = document.createElement('script');\n script.setAttribute('data-turbopack-src', url);\n script.src = scriptUrl;\n script.async = true;\n script.onload = () => {\n URL.revokeObjectURL(scriptUrl);\n logDebug(\n 'ChunkLoader',\n `Script loaded successfully for bundle \"${bundle}\"`,\n );\n const turbopackBundle = self[`TURBOPACK_${bundleKey}`];\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${\n turbopackBundle\n ? Object.keys(turbopackBundle as object)\n .slice(0, 10)\n .join(', ')\n : 'none'\n }`,\n );\n if (turbopackBundle && typeof turbopackBundle === 'object') {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle as object).length}`,\n );\n }\n scriptResolve(undefined);\n script.remove();\n };\n script.onerror = () => {\n URL.revokeObjectURL(scriptUrl);\n scriptReject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${script.src}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n script.remove();\n };\n document.head.appendChild(script);\n });\n\n // process any additional chunks that were registered during script execution\n const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`] as\n | { chunks: string[] }[]\n | undefined;\n logDebug(\n 'ChunkLoader',\n `Processing chunk lists for bundle \"${bundle}\": ${chunkLists?.length ?? 0} lists`,\n );\n const loadChunkLists = [] as (Promise<unknown> | undefined)[];\n while (chunkLists?.length) {\n const { chunks } = chunkLists.shift() ?? { chunks: [] };\n if (chunks.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Loading ${chunks.length} additional chunks for bundle \"${bundle}\": [${chunks.join(', ')}]`,\n );\n chunks.forEach((id: string) => {\n const chunkLoadResult = self.__webpack_chunk_load__?.(\n `[${bundle}] ${url.slice(0, url.indexOf('/_next'))}/_next/${id}`,\n );\n if (chunkLoadResult) {\n loadChunkLists.push(chunkLoadResult);\n }\n });\n }\n }\n if (loadChunkLists.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Waiting for ${loadChunkLists.length} additional chunks to load`,\n );\n await Promise.all(loadChunkLists);\n }\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,UAAU,iCAAiC;AACpD,SAAS,2BAA2B;AAO7B,SAAS,kBACd,SACA,kBAC0E;AAC1E,SAAO,SAAS,yBACd,SACA,cACA;AACA,aAAS,eAAe,mBAAmB,UAAU;AACrD,UAAM,OAAO;AACb,UAAM;AAAA,MACJ;AAAA,MACA,IAAI;AAAA,MACJ;AAAA,IACF,IAAI,uBAAuB,KAAK,OAAO,GAAG,UAAU;AAAA,MAClD,QAAQ,gBAAgB;AAAA,MACxB,IAAI;AAAA,IACN;AACA;AAAA,MACE;AAAA,MACA,2BAA2B,mBAAmB,mBAAmB;AAAA,IACnE;AACA,UAAM,gBAAgB,KAAK,6BAA6B,UAAU,SAAS,IACvE,KAAK,2BAA2B,UAAU,SAAS,GAAG,QAAQ,YAC9D;AACJ,aAAS,eAAe,oBAAoB,gBAAgB;AAC5D,QAAI,kBAAkB,iBAAiB;AACrC,eAAS,eAAe,gDAAgD;AACxE,aAAO,QAAQ,QAAQ,MAAS;AAAA,IAClC;AAEA,UAAM,MAAM,IAAI;AAAA,MACd,OACI,GAAG,UAAU,KAAK,OAAO;AAAA,QACvB;AAAA,QACA;AAAA,MACF,IACA;AAAA,MACJ,KAAK,wBAAwB,UAAU,SAAS,KAC9C,IAAI,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,YAAY,QAAQ;AACzB,UAAM,EAAE,OAAO,IAAI,WAAW,MAAM,KAAK,EAAE,QAAQ,CAAC,EAAE;AACtD,QAAI,OAAO,SAAS,GAAG;AACrB;AAAA,QACE;AAAA,QACA,WAAW,OAAO,wCAAwC,aAAa,OAAO,KAAK,IAAI;AAAA,MACzF;AACA,aAAO,QAAQ,CAAC,OAAe;AAC7B,cAAM,kBAAkB,KAAK;AAAA,UAC3B,IAAI,WAAW,IAAI,MAAM,GAAG,IAAI,QAAQ,QAAQ,CAAC,WAAW;AAAA,QAC9D;AACA,YAAI,iBAAiB;AACnB,yBAAe,KAAK,eAAe;AAAA,QACrC;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACA,MAAI,eAAe,SAAS,GAAG;AAC7B;AAAA,MACE;AAAA,MACA,eAAe,eAAe;AAAA,IAChC;AACA,UAAM,QAAQ,IAAI,cAAc;AAAA,EAClC;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/runtime/turbopack/chunk-loader.ts"],"sourcesContent":["import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n getBundleKey,\n RUNTIME_WEBPACK,\n type Runtime,\n} from '#internal/runtime/constants';\nimport { REMOTE_COMPONENT_REGEX } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport {\n failedProxiedAssetError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport { logDebug, warnCrossOriginFetchError } from '#internal/utils/logger';\nimport { TURBOPACK_GLOBAL_RE } from './patterns';\n\n/**\n * Creates chunk loader function for webpack runtime.\n * This function is responsible for loading JavaScript chunks from remote applications\n * and transforming Turbopack-specific code to work in the host environment.\n */\nexport function createChunkLoader(\n runtime: Runtime,\n resolveClientUrl?: InternalResolveClientUrl,\n): (chunkId: string, scriptBundle?: string) => Promise<unknown> | undefined {\n return function __turbopack_chunk_load__(\n chunkId: string,\n scriptBundle?: string,\n ) {\n logDebug('ChunkLoader', `Loading chunk: \"${chunkId}\"`);\n const self = globalThis as GlobalScope;\n const {\n bundle,\n id: path,\n prefix,\n } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {\n bundle: scriptBundle ?? '',\n id: chunkId,\n };\n logDebug(\n 'ChunkLoader',\n `Parsed chunk - bundle: \"${bundle}\", path: \"${path}\", prefix: \"${prefix}\"`,\n );\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : runtime;\n logDebug('ChunkLoader', `Remote runtime: \"${remoteRuntime}\"`);\n if (remoteRuntime === RUNTIME_WEBPACK) {\n logDebug('ChunkLoader', 'Skipping chunk load - webpack runtime detected');\n return Promise.resolve(undefined);\n }\n\n const url = new URL(\n path\n ? `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n )\n : '/',\n self.__remote_bundle_url__?.[bundle ?? 'default'] ??\n new URL(location.origin),\n ).href;\n if (url.endsWith('.css')) {\n logDebug('ChunkLoader', `Skipping CSS file: \"${url}\"`);\n return;\n }\n\n if (!self.__remote_components_turbopack_chunk_loader_promise__) {\n self.__remote_components_turbopack_chunk_loader_promise__ = {};\n }\n if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {\n logDebug('ChunkLoader', `Returning cached promise for: \"${url}\"`);\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n }\n\n const resolvedUrl = resolveClientUrl?.(url) ?? url;\n logDebug('ChunkLoader', `Fetching chunk from: \"${resolvedUrl}\"`);\n self.__remote_components_turbopack_chunk_loader_promise__[url] =\n new Promise((resolve, reject) => {\n fetch(resolvedUrl)\n .then((res) => res.text())\n .then((code) => {\n // Turbopack runtime uses either dot-notation or bracket-notation globals.\n const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);\n if (hasTurbopack) {\n return handleTurbopackChunk(code, bundle ?? '', url);\n }\n logDebug(\n 'ChunkLoader',\n `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: \"${url}\"`,\n );\n logDebug(\n 'ChunkLoader',\n `First 500 chars of chunk: ${code.slice(0, 500)}`,\n );\n })\n .then(resolve)\n .catch((error) => {\n const isProxied = isProxiedUrl(resolvedUrl);\n if (isProxied) {\n reject(failedProxiedAssetError('chunk', url, resolvedUrl));\n } else {\n warnCrossOriginFetchError('ChunkLoader', url);\n reject(error);\n }\n });\n });\n\n return self.__remote_components_turbopack_chunk_loader_promise__[url];\n };\n}\n\n/**\n * Handles Turbopack chunk loading by transforming the chunk code to isolate\n * global variables per bundle and dynamically loading the transformed script.\n */\nasync function handleTurbopackChunk(\n code: string,\n bundle: string,\n url: string,\n): Promise<void> {\n logDebug(\n 'ChunkLoader',\n `Handling Turbopack chunk - bundle: \"${bundle}\", url: \"${url}\"`,\n );\n // skip this chunk as it is not needed for remote components\n if (/importScripts\\(\\.\\.\\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {\n logDebug('ChunkLoader', `Skipping worker chunk: \"${url}\"`);\n // remove preload links for this chunk\n const preloadLinks = document.querySelectorAll(\n `link[rel=\"preload\"][href=\"${new URL(url).pathname}\"]`,\n );\n preloadLinks.forEach((preloadLink) => preloadLink.remove());\n return;\n }\n\n const self = globalThis as GlobalScope;\n const bundleKey = getBundleKey(bundle);\n logDebug('ChunkLoader', `Bundle key: \"${bundleKey}\"`);\n\n // replace global variables with bundle-specific ones to prevent collisions\n // between multiple remote component bundles\n const transformedCode = code\n // Turbopack runtime can reference TURBOPACK via bracket-notation (common in newer Next.js)\n // e.g. globalThis[\"TURBOPACK\"] / self['TURBOPACK']\n .replace(\n /globalThis\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `globalThis[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(\n /self\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `self[\"TURBOPACK_${bundleKey}\"]`,\n )\n .replace(/globalThis\\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`)\n .replace(/self\\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`)\n .replace(\n /TURBOPACK_WORKER_LOCATION/g,\n `TURBOPACK_WORKER_LOCATION_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_NEXT_CHUNK_URLS/g,\n `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`,\n )\n .replace(\n /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,\n `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`,\n )\n .replace(/__next_require__/g, `__${bundleKey}_next_require__`)\n .replace(\n /\\/\\/# sourceMappingURL=(?<name>.+)(?<optional>\\._)?\\.js\\.map/g,\n `//# sourceMappingURL=${\n new URL(\n '.',\n new URL(\n url,\n self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin),\n ),\n ).href\n }$1$2.js.map`,\n );\n\n // Initialize TURBOPACK bundle with push interceptor for Next.js 16.2.0-canary\n // Use webpack-style chunk loading pattern\n if (!self[`TURBOPACK_${bundleKey}`]) {\n const chunkData: unknown[][] = [];\n const turbopackObject = {\n push: (item: unknown) => {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? 'array' : typeof item}`,\n );\n if (Array.isArray(item)) {\n chunkData.push(item);\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`,\n );\n } else {\n chunkData.push([item]);\n }\n return chunkData.length;\n },\n // Store chunks for later access\n __chunks__: chunkData,\n };\n self[`TURBOPACK_${bundleKey}`] = turbopackObject as unknown as Record<\n string,\n unknown\n >;\n }\n\n // load the script dynamically using a Blob URL\n logDebug('ChunkLoader', `Creating blob script for: \"${url}\"`);\n await new Promise<void>((scriptResolve, scriptReject) => {\n const blob = new Blob([transformedCode], {\n type: 'application/javascript; charset=UTF-8',\n });\n const scriptUrl = URL.createObjectURL(blob);\n const script = document.createElement('script');\n script.setAttribute('data-turbopack-src', url);\n script.src = scriptUrl;\n script.async = true;\n script.onload = () => {\n URL.revokeObjectURL(scriptUrl);\n logDebug(\n 'ChunkLoader',\n `Script loaded successfully for bundle \"${bundle}\"`,\n );\n const turbopackBundle = self[`TURBOPACK_${bundleKey}`];\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${\n turbopackBundle\n ? Object.keys(turbopackBundle as object)\n .slice(0, 10)\n .join(', ')\n : 'none'\n }`,\n );\n if (turbopackBundle && typeof turbopackBundle === 'object') {\n logDebug(\n 'ChunkLoader',\n `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle as object).length}`,\n );\n }\n scriptResolve(undefined);\n script.remove();\n };\n script.onerror = () => {\n URL.revokeObjectURL(scriptUrl);\n scriptReject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${script.src}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n script.remove();\n };\n document.head.appendChild(script);\n });\n\n // process any additional chunks that were registered during script execution\n const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`] as\n | { chunks: string[] }[]\n | undefined;\n logDebug(\n 'ChunkLoader',\n `Processing chunk lists for bundle \"${bundle}\": ${chunkLists?.length ?? 0} lists`,\n );\n const loadChunkLists = [] as (Promise<unknown> | undefined)[];\n while (chunkLists?.length) {\n const { chunks } = chunkLists.shift() ?? { chunks: [] };\n if (chunks.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Loading ${chunks.length} additional chunks for bundle \"${bundle}\": [${chunks.join(', ')}]`,\n );\n chunks.forEach((id: string) => {\n const chunkLoadResult = self.__webpack_chunk_load__?.(\n `[${bundle}] ${url.slice(0, url.indexOf('/_next'))}/_next/${id}`,\n );\n if (chunkLoadResult) {\n loadChunkLists.push(chunkLoadResult);\n }\n });\n }\n }\n if (loadChunkLists.length > 0) {\n logDebug(\n 'ChunkLoader',\n `Waiting for ${loadChunkLists.length} additional chunks to load`,\n );\n await Promise.all(loadChunkLists);\n }\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,8BAA8B;AAEvC,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,UAAU,iCAAiC;AACpD,SAAS,2BAA2B;AAO7B,SAAS,kBACd,SACA,kBAC0E;AAC1E,SAAO,SAAS,yBACd,SACA,cACA;AACA,aAAS,eAAe,mBAAmB,UAAU;AACrD,UAAM,OAAO;AACb,UAAM;AAAA,MACJ;AAAA,MACA,IAAI;AAAA,MACJ;AAAA,IACF,IAAI,uBAAuB,KAAK,OAAO,GAAG,UAAU;AAAA,MAClD,QAAQ,gBAAgB;AAAA,MACxB,IAAI;AAAA,IACN;AACA;AAAA,MACE;AAAA,MACA,2BAA2B,mBAAmB,mBAAmB;AAAA,IACnE;AACA,UAAM,gBAAgB,KAAK,6BAA6B,UAAU,SAAS,IACvE,KAAK,2BAA2B,UAAU,SAAS,GAAG,QAAQ,YAC9D;AACJ,aAAS,eAAe,oBAAoB,gBAAgB;AAC5D,QAAI,kBAAkB,iBAAiB;AACrC,eAAS,eAAe,gDAAgD;AACxE,aAAO,QAAQ,QAAQ,MAAS;AAAA,IAClC;AAEA,UAAM,MAAM,IAAI;AAAA,MACd,OACI,GAAG,UAAU,KAAK,OAAO;AAAA,QACvB;AAAA,QACA;AAAA,MACF,IACA;AAAA,MACJ,KAAK,wBAAwB,UAAU,SAAS,KAC9C,IAAI,IAAI,SAAS,MAAM;AAAA,IAC3B,EAAE;AACF,QAAI,IAAI,SAAS,MAAM,GAAG;AACxB,eAAS,eAAe,uBAAuB,MAAM;AACrD;AAAA,IACF;AAEA,QAAI,CAAC,KAAK,sDAAsD;AAC9D,WAAK,uDAAuD,CAAC;AAAA,IAC/D;AACA,QAAI,KAAK,qDAAqD,GAAG,GAAG;AAClE,eAA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AM,kBAAkB,KAAK;AAAA,UAC3B,IAAI,WAAW,IAAI,MAAM,GAAG,IAAI,QAAQ,QAAQ,CAAC,WAAW;AAAA,QAC9D;AACA,YAAI,iBAAiB;AACnB,yBAAe,KAAK,eAAe;AAAA,QACrC;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACA,MAAI,eAAe,SAAS,GAAG;AAC7B;AAAA,MACE;AAAA,MACA,eAAe,eAAe;AAAA,IAChC;AACA,UAAM,QAAQ,IAAI,cAAc;AAAA,EAClC;AACF;","names":[]}
|
|
@@ -32,6 +32,7 @@ __export(webpack_runtime_exports, {
|
|
|
32
32
|
});
|
|
33
33
|
module.exports = __toCommonJS(webpack_runtime_exports);
|
|
34
34
|
var import_constants = require("#internal/runtime/constants");
|
|
35
|
+
var import_patterns = require("#internal/runtime/patterns");
|
|
35
36
|
var import_error = require("#internal/utils/error");
|
|
36
37
|
var import_logger = require("#internal/utils/logger");
|
|
37
38
|
var import_chunk_loader = require("./chunk-loader");
|
|
@@ -59,7 +60,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
|
|
|
59
60
|
}
|
|
60
61
|
}
|
|
61
62
|
if (runtime === import_constants.RUNTIME_TURBOPACK) {
|
|
62
|
-
await Promise.
|
|
63
|
+
const results = await Promise.allSettled(
|
|
63
64
|
scripts.map((script) => {
|
|
64
65
|
if (script.src) {
|
|
65
66
|
return self.__webpack_chunk_load__?.(script.src, bundle);
|
|
@@ -67,6 +68,14 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
|
|
|
67
68
|
return Promise.resolve(void 0);
|
|
68
69
|
})
|
|
69
70
|
);
|
|
71
|
+
for (const result of results) {
|
|
72
|
+
if (result.status === "rejected") {
|
|
73
|
+
(0, import_logger.logWarn)(
|
|
74
|
+
"WebpackRuntime",
|
|
75
|
+
`Initial chunk load failed: ${String(result.reason)}`
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
70
79
|
}
|
|
71
80
|
const coreShared = {
|
|
72
81
|
react: async () => (await import("react")).default,
|
|
@@ -86,7 +95,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
|
|
|
86
95
|
function createModuleRequire(runtime) {
|
|
87
96
|
return (id) => {
|
|
88
97
|
const self = globalThis;
|
|
89
|
-
const { bundle, id: moduleId } = id.match(
|
|
98
|
+
const { bundle, id: moduleId } = id.match(import_patterns.REMOTE_COMPONENT_REGEX)?.groups ?? {
|
|
90
99
|
bundle: "default",
|
|
91
100
|
id
|
|
92
101
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/runtime/turbopack/webpack-runtime.ts"],"sourcesContent":["import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n
|
|
1
|
+
{"version":3,"sources":["../../../../src/runtime/turbopack/webpack-runtime.ts"],"sourcesContent":["import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n RUNTIME_TURBOPACK,\n RUNTIME_WEBPACK,\n type Runtime,\n} from '#internal/runtime/constants';\nimport { REMOTE_COMPONENT_REGEX } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { logDebug, logWarn } from '#internal/utils/logger';\nimport { createChunkLoader } from './chunk-loader';\nimport { handleTurbopackModule } from './module';\nimport { getSharedModule, initializeSharedModules } from './shared-modules';\n\n/**\n * Sets up webpack runtime environment for remote components.\n * This function initializes the global webpack require and chunk loading functions\n * to support loading and executing remote component bundles.\n *\n * @param runtime - The bundler runtime type ('webpack' or 'turbopack')\n * @param scripts - Initial script chunks to load for Turbopack runtime\n * @param url - Base URL for the remote component bundle\n * @param bundle - Bundle identifier (defaults to 'default')\n * @param shared - Host-provided shared modules (e.g., React)\n * @param remoteShared - Mapping of remote module IDs to shared module names\n */\nexport async function setupWebpackRuntime(\n runtime: Runtime,\n scripts: { src: string | null }[] = [],\n url: URL = new URL(location.href),\n bundle?: string,\n shared: Record<string, () => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n resolveClientUrl?: InternalResolveClientUrl,\n): Promise<void> {\n const self = globalThis as GlobalScope;\n\n if (!self.__remote_bundle_url__) {\n self.__remote_bundle_url__ = {};\n }\n self.__remote_bundle_url__[bundle ?? 'default'] = url;\n self.__webpack_get_script_filename__ = () => null;\n\n if (\n typeof self.__webpack_require__ !== 'function' ||\n self.__webpack_require_type__ !== 'turbopack'\n ) {\n // preserve original webpack functions for fallback\n if (\n !self.__original_webpack_require__ &&\n !self.__original_webpack_chunk_load__\n ) {\n self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;\n self.__original_webpack_require__ = self.__webpack_require__;\n }\n\n self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);\n self.__webpack_require__ = createModuleRequire(runtime);\n self.__webpack_require_type__ = runtime;\n\n if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {\n const remoteBundle = bundle ?? 'default';\n self.__remote_webpack_require__[remoteBundle] =\n self.__webpack_require__ as (remoteId: string | number) => unknown;\n self.__remote_webpack_require__[remoteBundle].type = 'turbopack';\n }\n }\n\n // load all initial chunks when using Turbopack runtime\n if (runtime === RUNTIME_TURBOPACK) {\n const results = await Promise.allSettled(\n scripts.map((script) => {\n if (script.src) {\n return self.__webpack_chunk_load__?.(script.src, bundle);\n }\n return Promise.resolve(undefined);\n }),\n );\n\n for (const result of results) {\n if (result.status === 'rejected') {\n logWarn(\n 'WebpackRuntime',\n `Initial chunk load failed: ${String(result.reason)}`,\n );\n }\n }\n }\n\n // initialize shared modules with core React dependencies\n const coreShared = {\n react: async () => (await import('react')).default,\n 'react-dom': async () => (await import('react-dom')).default,\n 'react/jsx-dev-runtime': async () =>\n (await import('react/jsx-dev-runtime')).default,\n 'react/jsx-runtime': async () =>\n (await import('react/jsx-runtime')).default,\n 'react-dom/client': async () => (await import('react-dom/client')).default,\n ...shared,\n };\n await initializeSharedModules(\n bundle ?? 'default',\n // include all core modules as shared\n coreShared,\n remoteShared,\n );\n}\n\n/**\n * Creates module require function for webpack runtime.\n * This function resolves module IDs to their exports, handling:\n * - Webpack remotes (pre-loaded bundles)\n * - Shared modules (React, etc.)\n * - Turbopack modules (dynamically loaded)\n */\nfunction createModuleRequire(runtime: Runtime): (id: string) => unknown {\n return (id: string) => {\n const self = globalThis as GlobalScope;\n const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)\n ?.groups ?? {\n bundle: 'default',\n id,\n };\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : runtime;\n\n logDebug('WebpackRuntime', `remoteRuntime: \"${remoteRuntime}\"`);\n\n try {\n // for webpack remotes, use the pre-loaded require function\n if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {\n return self.__remote_webpack_require__?.[bundle]?.(moduleId);\n }\n const sharedModuleId = moduleId ?? id;\n const sharedModule = getSharedModule(bundle ?? 'default', sharedModuleId);\n if (sharedModule) {\n return sharedModule;\n }\n if (bundle && moduleId) {\n return handleTurbopackModule(bundle, moduleId, id);\n }\n throw new Error(`Module \"${id}\" not found.`);\n } catch (requireError) {\n logWarn(\n 'WebpackRuntime',\n `Module require failed: ${String(requireError)}`,\n );\n if (typeof self.__original_webpack_require__ !== 'function') {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundle}\".`,\n {\n cause: requireError instanceof Error ? requireError : undefined,\n },\n );\n }\n try {\n logDebug('WebpackRuntime', 'Falling back to original webpack require');\n return self.__original_webpack_require__(id);\n } catch (originalError) {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundle}\".`,\n { cause: originalError instanceof Error ? originalError : undefined },\n );\n }\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAIO;AACP,sBAAuC;AAEvC,mBAAsC;AACtC,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I;AACF,oCAAS,kBAAkB,0CAA0C;AACrE,eAAO,KAAK,6BAA6B,EAAE;AAAA,MAC7C,SAAS,eAAP;AACA,cAAM,IAAI;AAAA,UACR,WAAW,6CAA6C;AAAA,UACxD,EAAE,OAAO,yBAAyB,QAAQ,gBAAgB,OAAU;AAAA,QACtE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
|
-
REMOTE_COMPONENT_REGEX,
|
|
3
2
|
RUNTIME_TURBOPACK,
|
|
4
3
|
RUNTIME_WEBPACK
|
|
5
4
|
} from "#internal/runtime/constants";
|
|
5
|
+
import { REMOTE_COMPONENT_REGEX } from "#internal/runtime/patterns";
|
|
6
6
|
import { RemoteComponentsError } from "#internal/utils/error";
|
|
7
7
|
import { logDebug, logWarn } from "#internal/utils/logger";
|
|
8
8
|
import { createChunkLoader } from "./chunk-loader";
|
|
@@ -30,7 +30,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
|
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
32
|
if (runtime === RUNTIME_TURBOPACK) {
|
|
33
|
-
await Promise.
|
|
33
|
+
const results = await Promise.allSettled(
|
|
34
34
|
scripts.map((script) => {
|
|
35
35
|
if (script.src) {
|
|
36
36
|
return self.__webpack_chunk_load__?.(script.src, bundle);
|
|
@@ -38,6 +38,14 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
|
|
|
38
38
|
return Promise.resolve(void 0);
|
|
39
39
|
})
|
|
40
40
|
);
|
|
41
|
+
for (const result of results) {
|
|
42
|
+
if (result.status === "rejected") {
|
|
43
|
+
logWarn(
|
|
44
|
+
"WebpackRuntime",
|
|
45
|
+
`Initial chunk load failed: ${String(result.reason)}`
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
41
49
|
}
|
|
42
50
|
const coreShared = {
|
|
43
51
|
react: async () => (await import("react")).default,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/runtime/turbopack/webpack-runtime.ts"],"sourcesContent":["import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n
|
|
1
|
+
{"version":3,"sources":["../../../../src/runtime/turbopack/webpack-runtime.ts"],"sourcesContent":["import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n RUNTIME_TURBOPACK,\n RUNTIME_WEBPACK,\n type Runtime,\n} from '#internal/runtime/constants';\nimport { REMOTE_COMPONENT_REGEX } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { logDebug, logWarn } from '#internal/utils/logger';\nimport { createChunkLoader } from './chunk-loader';\nimport { handleTurbopackModule } from './module';\nimport { getSharedModule, initializeSharedModules } from './shared-modules';\n\n/**\n * Sets up webpack runtime environment for remote components.\n * This function initializes the global webpack require and chunk loading functions\n * to support loading and executing remote component bundles.\n *\n * @param runtime - The bundler runtime type ('webpack' or 'turbopack')\n * @param scripts - Initial script chunks to load for Turbopack runtime\n * @param url - Base URL for the remote component bundle\n * @param bundle - Bundle identifier (defaults to 'default')\n * @param shared - Host-provided shared modules (e.g., React)\n * @param remoteShared - Mapping of remote module IDs to shared module names\n */\nexport async function setupWebpackRuntime(\n runtime: Runtime,\n scripts: { src: string | null }[] = [],\n url: URL = new URL(location.href),\n bundle?: string,\n shared: Record<string, () => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n resolveClientUrl?: InternalResolveClientUrl,\n): Promise<void> {\n const self = globalThis as GlobalScope;\n\n if (!self.__remote_bundle_url__) {\n self.__remote_bundle_url__ = {};\n }\n self.__remote_bundle_url__[bundle ?? 'default'] = url;\n self.__webpack_get_script_filename__ = () => null;\n\n if (\n typeof self.__webpack_require__ !== 'function' ||\n self.__webpack_require_type__ !== 'turbopack'\n ) {\n // preserve original webpack functions for fallback\n if (\n !self.__original_webpack_require__ &&\n !self.__original_webpack_chunk_load__\n ) {\n self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;\n self.__original_webpack_require__ = self.__webpack_require__;\n }\n\n self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);\n self.__webpack_require__ = createModuleRequire(runtime);\n self.__webpack_require_type__ = runtime;\n\n if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {\n const remoteBundle = bundle ?? 'default';\n self.__remote_webpack_require__[remoteBundle] =\n self.__webpack_require__ as (remoteId: string | number) => unknown;\n self.__remote_webpack_require__[remoteBundle].type = 'turbopack';\n }\n }\n\n // load all initial chunks when using Turbopack runtime\n if (runtime === RUNTIME_TURBOPACK) {\n const results = await Promise.allSettled(\n scripts.map((script) => {\n if (script.src) {\n return self.__webpack_chunk_load__?.(script.src, bundle);\n }\n return Promise.resolve(undefined);\n }),\n );\n\n for (const result of results) {\n if (result.status === 'rejected') {\n logWarn(\n 'WebpackRuntime',\n `Initial chunk load failed: ${String(result.reason)}`,\n );\n }\n }\n }\n\n // initialize shared modules with core React dependencies\n const coreShared = {\n react: async () => (await import('react')).default,\n 'react-dom': async () => (await import('react-dom')).default,\n 'react/jsx-dev-runtime': async () =>\n (await import('react/jsx-dev-runtime')).default,\n 'react/jsx-runtime': async () =>\n (await import('react/jsx-runtime')).default,\n 'react-dom/client': async () => (await import('react-dom/client')).default,\n ...shared,\n };\n await initializeSharedModules(\n bundle ?? 'default',\n // include all core modules as shared\n coreShared,\n remoteShared,\n );\n}\n\n/**\n * Creates module require function for webpack runtime.\n * This function resolves module IDs to their exports, handling:\n * - Webpack remotes (pre-loaded bundles)\n * - Shared modules (React, etc.)\n * - Turbopack modules (dynamically loaded)\n */\nfunction createModuleRequire(runtime: Runtime): (id: string) => unknown {\n return (id: string) => {\n const self = globalThis as GlobalScope;\n const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)\n ?.groups ?? {\n bundle: 'default',\n id,\n };\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : runtime;\n\n logDebug('WebpackRuntime', `remoteRuntime: \"${remoteRuntime}\"`);\n\n try {\n // for webpack remotes, use the pre-loaded require function\n if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {\n return self.__remote_webpack_require__?.[bundle]?.(moduleId);\n }\n const sharedModuleId = moduleId ?? id;\n const sharedModule = getSharedModule(bundle ?? 'default', sharedModuleId);\n if (sharedModule) {\n return sharedModule;\n }\n if (bundle && moduleId) {\n return handleTurbopackModule(bundle, moduleId, id);\n }\n throw new Error(`Module \"${id}\" not found.`);\n } catch (requireError) {\n logWarn(\n 'WebpackRuntime',\n `Module require failed: ${String(requireError)}`,\n );\n if (typeof self.__original_webpack_require__ !== 'function') {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundle}\".`,\n {\n cause: requireError instanceof Error ? requireError : undefined,\n },\n );\n }\n try {\n logDebug('WebpackRuntime', 'Falling back to original webpack require');\n return self.__original_webpack_require__(id);\n } catch (originalError) {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundle}\".`,\n { cause: originalError instanceof Error ? originalError : undefined },\n );\n }\n }\n };\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,8BAA8B;AAEvC,SAAS,6BAA6B;AACtC,SAAS,UAAU,eAAe;AAClC,SAAS,yBAAyB;AAClC,SAAS,6BAA6B;AACtC,SAAS,iBAAiB,+BAA+B;AAczD,eAAsB,oBACpB,SACA,UAAoC,CAAC,GACrC,MAAW,IAAI,IAAI,SAAS,IAAI,GAChC,QACA,SAAiD,CAAC,GAClD,eAAuC,CAAC,GACxC,kBACe;AACf,QAAM,OAAO;AAEb,MAAI,CAAC,KAAK,uBAAuB;AAC/B,SAAK,wBAAwB,CAAC;AAAA,EAChC;AACA,OAAK,sBAAsB,UAAU,SAAS,IAAI;AAClD,OAAK,kCAAkC,MAAM;AA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ACtE,SAAO,CAAC,OAAe;AACrB,UAAM,OAAO;AACb,UAAM,EAAE,QAAQ,IAAI,SAAS,IAAI,GAAG,MAAM,sBAAsB,GAC5D,UAAU;AAAA,MACZ,QAAQ;AAAA,MACR;AAAA,IACF;AACA,UAAM,gBAAgB,KAAK,6BAA6B,UAAU,SAAS,IACvE,KAAK,2BAA2B,UAAU,SAAS,GAAG,QAAQ,YAC9D;AAEJ,aAAS,kBAAkB,mBAAmB,gBAAgB;AAE9D,QAAI;AAEF,UAAI,kBAAkB,mBAAmB,UAAU,UAAU;AAC3D,eAAO,KAAK,6BAA6B,MAAM,IAAI,QAAQ;AAAA,MAC7D;AACA,YAAM,iBAAiB,YAAY;AACnC,YAAM,eAAe,gBAAgB,UAAU,WAAW,cAAc;AACxE,UAAI,cAAc;AAChB,eAAO;AAAA,MACT;AACA,UAAI,UAAU,UAAU;AACtB,eAAO,sBAAsB,QAAQ,UAAU,EAAE;AAAA,MACnD;AACA,YAAM,IAAI,MAAM,WAAW,gBAAgB;AAAA,IAC7C,SAAS,cAAP;AACA;AAAA,QACE;AAAA,QACA,0BAA0B,OAAO,YAAY;AAAA,MAC/C;AACA,UAAI,OAAO,KAAK,iCAAiC,YAAY;AAC3D,cAAM,IAAI;AAAA,UACR,WAAW,6CAA6C;AAAA,UACxD;AAAA,YACE,OAAO,wBAAwB,QAAQ,eAAe;AAAA,UACxD;AAAA,QACF;AAAA,MACF;AACA,UAAI;AACF,iBAAS,kBAAkB,0CAA0C;AACrE,eAAO,KAAK,6BAA6B,EAAE;AAAA,MAC7C,SAAS,eAAP;AACA,cAAM,IAAI;AAAA,UACR,WAAW,6CAA6C;AAAA,UACxD,EAAE,OAAO,yBAAyB,QAAQ,gBAAgB,OAAU;AAAA,QACtE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -36,6 +36,7 @@ var import_wrapper = require("remote-components/remote/defaults/wrapper");
|
|
|
36
36
|
var import_work_async_storage = require("next/dist/server/app-render/work-async-storage.external");
|
|
37
37
|
var import_react = require("react");
|
|
38
38
|
var import_app_client = require("#internal/remote/nextjs/app-client");
|
|
39
|
+
var import_constants = require("#internal/runtime/constants");
|
|
39
40
|
var import_error = require("#internal/utils/error");
|
|
40
41
|
const SERVER_ACTION_MANIFESTS_SINGLETON = Symbol.for(
|
|
41
42
|
"next.server.action-manifests"
|
|
@@ -58,7 +59,7 @@ function RemoteComponentData({ name, data }) {
|
|
|
58
59
|
).join("\n") });
|
|
59
60
|
}
|
|
60
61
|
async function ExposeRemoteComponent({
|
|
61
|
-
name =
|
|
62
|
+
name = import_constants.DEFAULT_COMPONENT_NAME,
|
|
62
63
|
children
|
|
63
64
|
}) {
|
|
64
65
|
const { page, route } = import_work_async_storage.workAsyncStorage.getStore() ?? {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/remote/nextjs/app.tsx"],"sourcesContent":["import 'remote-components/remote/defaults/wrapper';\nimport { workAsyncStorage } from 'next/dist/server/app-render/work-async-storage.external';\nimport { Suspense } from 'react';\nimport type { ConsumeLifecycleCallbacks } from '#internal/host/shared/config';\nimport { RemoteComponentSharedRemote } from '#internal/remote/nextjs/app-client';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\ninterface Manifest {\n clientModules?: Record<\n string,\n { id: string; name: string; chunks: string[]; async: boolean }\n >;\n moduleLoading: { prefix?: string; crossOrigin?: boolean | null };\n ssrModuleMapping?: Record<string, unknown>;\n}\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);\nconst MANIFESTS_SINGLETON = Symbol.for('next.server.manifests');\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 `${\n i === 0 ? `self[\"${name}\"]=self[\"${name}\"]||[];` : ''\n }self[\"${name}\"].push(${JSON.stringify(chunk)});`,\n )\n .join('\\n')}\n </script>\n );\n}\n\n/**\n * Props for exposing a Next.js component as a remote component.\n *\n * Extends {@link ConsumeLifecycleCallbacks} so the consuming host can wire up lifecycle\n * events. The `children` prop is the component content to expose (required,\n * unlike host props where children are an optional loading fallback).\n */\nexport interface ExposeRemoteComponentProps extends ConsumeLifecycleCallbacks {\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 * ExposeRemoteComponent 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 `<ExposeRemoteComponent>` in your Next.js App Router application to expose the children as a remote component:\n *\n * ```tsx\n * import { ExposeRemoteComponent } from 'remote-components/remote/nextjs/app';\n *\n * export default function MyPage() {\n * return (\n * <ExposeRemoteComponent>\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 * </ExposeRemoteComponent>\n * );\n * }\n * ```\n */\nexport async function ExposeRemoteComponent({\n name = '__vercel_remote_component',\n children,\n}: ExposeRemoteComponentProps): 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 self = globalThis as typeof globalThis & {\n [SERVER_ACTION_MANIFESTS_SINGLETON]?: {\n clientReferenceManifestsPerPage?: Record<string, Manifest>;\n };\n [MANIFESTS_SINGLETON]?: {\n clientReferenceManifestsPerRoute?: Map<string, Manifest>;\n };\n __RSC_MANIFEST?: Record<string, unknown>;\n __RSC_SERVER_MANIFEST?: Record<string, unknown>;\n };\n const manifests =\n self[MANIFESTS_SINGLETON] ?? self[SERVER_ACTION_MANIFESTS_SINGLETON] ?? {};\n const manifest =\n 'clientReferenceManifestsPerRoute' in manifests\n ? manifests.clientReferenceManifestsPerRoute?.get?.(route)\n : 'clientReferenceManifestsPerPage' in manifests\n ? manifests.clientReferenceManifestsPerPage?.[route]\n : undefined;\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 self.__RSC_SERVER_MANIFEST = self.__RSC_SERVER_MANIFEST || {};\n self.__RSC_SERVER_MANIFEST[page] =\n self.__RSC_SERVER_MANIFEST[page] || manifest;\n\n // get the client and SSR module mapping to be able to use client components in the remote component\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 const clientModules = Object.fromEntries(\n Object.entries(manifest?.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;AAyCI;AAzCJ,qBAAO;AACP,gCAAiC;AACjC,mBAAyB;AAEzB,wBAA4C;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,QACC,eAAa;AAAA,QACb,cAAY;AAAA,QACZ,gBAAc;AAAA,QACd,aAAU;AAAA,QACV,IAAI,GAAG;AAAA,QAEP;AAAA,sDAAC,iDAA4B,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/remote/nextjs/app.tsx"],"sourcesContent":["import 'remote-components/remote/defaults/wrapper';\nimport { workAsyncStorage } from 'next/dist/server/app-render/work-async-storage.external';\nimport { Suspense } from 'react';\nimport type { ConsumeLifecycleCallbacks } from '#internal/host/shared/config';\nimport { RemoteComponentSharedRemote } from '#internal/remote/nextjs/app-client';\nimport { DEFAULT_COMPONENT_NAME } from '#internal/runtime/constants';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\ninterface Manifest {\n clientModules?: Record<\n string,\n { id: string; name: string; chunks: string[]; async: boolean }\n >;\n moduleLoading: { prefix?: string; crossOrigin?: boolean | null };\n ssrModuleMapping?: Record<string, unknown>;\n}\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);\nconst MANIFESTS_SINGLETON = Symbol.for('next.server.manifests');\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 `${\n i === 0 ? `self[\"${name}\"]=self[\"${name}\"]||[];` : ''\n }self[\"${name}\"].push(${JSON.stringify(chunk)});`,\n )\n .join('\\n')}\n </script>\n );\n}\n\n/**\n * Props for exposing a Next.js component as a remote component.\n *\n * Extends {@link ConsumeLifecycleCallbacks} so the consuming host can wire up lifecycle\n * events. The `children` prop is the component content to expose (required,\n * unlike host props where children are an optional loading fallback).\n */\nexport interface ExposeRemoteComponentProps extends ConsumeLifecycleCallbacks {\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 * ExposeRemoteComponent 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 `<ExposeRemoteComponent>` in your Next.js App Router application to expose the children as a remote component:\n *\n * ```tsx\n * import { ExposeRemoteComponent } from 'remote-components/remote/nextjs/app';\n *\n * export default function MyPage() {\n * return (\n * <ExposeRemoteComponent>\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 * </ExposeRemoteComponent>\n * );\n * }\n * ```\n */\nexport async function ExposeRemoteComponent({\n name = DEFAULT_COMPONENT_NAME,\n children,\n}: ExposeRemoteComponentProps): 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 self = globalThis as typeof globalThis & {\n [SERVER_ACTION_MANIFESTS_SINGLETON]?: {\n clientReferenceManifestsPerPage?: Record<string, Manifest>;\n };\n [MANIFESTS_SINGLETON]?: {\n clientReferenceManifestsPerRoute?: Map<string, Manifest>;\n };\n __RSC_MANIFEST?: Record<string, unknown>;\n __RSC_SERVER_MANIFEST?: Record<string, unknown>;\n };\n const manifests =\n self[MANIFESTS_SINGLETON] ?? self[SERVER_ACTION_MANIFESTS_SINGLETON] ?? {};\n const manifest =\n 'clientReferenceManifestsPerRoute' in manifests\n ? manifests.clientReferenceManifestsPerRoute?.get?.(route)\n : 'clientReferenceManifestsPerPage' in manifests\n ? manifests.clientReferenceManifestsPerPage?.[route]\n : undefined;\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 self.__RSC_SERVER_MANIFEST = self.__RSC_SERVER_MANIFEST || {};\n self.__RSC_SERVER_MANIFEST[page] =\n self.__RSC_SERVER_MANIFEST[page] || manifest;\n\n // get the client and SSR module mapping to be able to use client components in the remote component\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 const clientModules = Object.fromEntries(\n Object.entries(manifest?.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;AA0CI;AA1CJ,qBAAO;AACP,gCAAiC;AACjC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AAA;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,iDAA4B,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":[]}
|
|
@@ -3,6 +3,7 @@ import "remote-components/remote/defaults/wrapper";
|
|
|
3
3
|
import { workAsyncStorage } from "next/dist/server/app-render/work-async-storage.external";
|
|
4
4
|
import { Suspense } from "react";
|
|
5
5
|
import { RemoteComponentSharedRemote } from "#internal/remote/nextjs/app-client";
|
|
6
|
+
import { DEFAULT_COMPONENT_NAME } from "#internal/runtime/constants";
|
|
6
7
|
import { RemoteComponentsError } from "#internal/utils/error";
|
|
7
8
|
const SERVER_ACTION_MANIFESTS_SINGLETON = Symbol.for(
|
|
8
9
|
"next.server.action-manifests"
|
|
@@ -25,7 +26,7 @@ function RemoteComponentData({ name, data }) {
|
|
|
25
26
|
).join("\n") });
|
|
26
27
|
}
|
|
27
28
|
async function ExposeRemoteComponent({
|
|
28
|
-
name =
|
|
29
|
+
name = DEFAULT_COMPONENT_NAME,
|
|
29
30
|
children
|
|
30
31
|
}) {
|
|
31
32
|
const { page, route } = workAsyncStorage.getStore() ?? {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/remote/nextjs/app.tsx"],"sourcesContent":["import 'remote-components/remote/defaults/wrapper';\nimport { workAsyncStorage } from 'next/dist/server/app-render/work-async-storage.external';\nimport { Suspense } from 'react';\nimport type { ConsumeLifecycleCallbacks } from '#internal/host/shared/config';\nimport { RemoteComponentSharedRemote } from '#internal/remote/nextjs/app-client';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\ninterface Manifest {\n clientModules?: Record<\n string,\n { id: string; name: string; chunks: string[]; async: boolean }\n >;\n moduleLoading: { prefix?: string; crossOrigin?: boolean | null };\n ssrModuleMapping?: Record<string, unknown>;\n}\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);\nconst MANIFESTS_SINGLETON = Symbol.for('next.server.manifests');\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 `${\n i === 0 ? `self[\"${name}\"]=self[\"${name}\"]||[];` : ''\n }self[\"${name}\"].push(${JSON.stringify(chunk)});`,\n )\n .join('\\n')}\n </script>\n );\n}\n\n/**\n * Props for exposing a Next.js component as a remote component.\n *\n * Extends {@link ConsumeLifecycleCallbacks} so the consuming host can wire up lifecycle\n * events. The `children` prop is the component content to expose (required,\n * unlike host props where children are an optional loading fallback).\n */\nexport interface ExposeRemoteComponentProps extends ConsumeLifecycleCallbacks {\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 * ExposeRemoteComponent 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 `<ExposeRemoteComponent>` in your Next.js App Router application to expose the children as a remote component:\n *\n * ```tsx\n * import { ExposeRemoteComponent } from 'remote-components/remote/nextjs/app';\n *\n * export default function MyPage() {\n * return (\n * <ExposeRemoteComponent>\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 * </ExposeRemoteComponent>\n * );\n * }\n * ```\n */\nexport async function ExposeRemoteComponent({\n name = '__vercel_remote_component',\n children,\n}: ExposeRemoteComponentProps): 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 self = globalThis as typeof globalThis & {\n [SERVER_ACTION_MANIFESTS_SINGLETON]?: {\n clientReferenceManifestsPerPage?: Record<string, Manifest>;\n };\n [MANIFESTS_SINGLETON]?: {\n clientReferenceManifestsPerRoute?: Map<string, Manifest>;\n };\n __RSC_MANIFEST?: Record<string, unknown>;\n __RSC_SERVER_MANIFEST?: Record<string, unknown>;\n };\n const manifests =\n self[MANIFESTS_SINGLETON] ?? self[SERVER_ACTION_MANIFESTS_SINGLETON] ?? {};\n const manifest =\n 'clientReferenceManifestsPerRoute' in manifests\n ? manifests.clientReferenceManifestsPerRoute?.get?.(route)\n : 'clientReferenceManifestsPerPage' in manifests\n ? manifests.clientReferenceManifestsPerPage?.[route]\n : undefined;\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 self.__RSC_SERVER_MANIFEST = self.__RSC_SERVER_MANIFEST || {};\n self.__RSC_SERVER_MANIFEST[page] =\n self.__RSC_SERVER_MANIFEST[page] || manifest;\n\n // get the client and SSR module mapping to be able to use client components in the remote component\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 const clientModules = Object.fromEntries(\n Object.entries(manifest?.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":"AAyCI,SA+KI,UA/KJ,KA+KI,YA/KJ;AAzCJ,OAAO;AACP,SAAS,wBAAwB;AACjC,SAAS,gBAAgB;AAEzB,SAAS,mCAAmC;AAC5C,SAAS,6BAA6B;AAYtC,MAAM,oCAAoC,OAAO;AAAA,EAC/C;AACF;AACA,MAAM,sBAAsB,OAAO,IAAI,uBAAuB;AAE9D,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,GACE,MAAM,IAAI,SAAS,gBAAgB,gBAAgB,WAC5C,eAAe,KAAK,UAAU,KAAK;AAAA;AAAA,EAChD,EACC,KAAK,IAAI,GACd;AAEJ;AAyCA,eAAsB,sBAAsB;AAAA,EAC1C,OAAO;AAAA,EACP;AACF,GAA4D;AAE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,MAAM,OAAO,iCAAiC;AAAA,MAChD;AAAA,MACA;AAAA,QACE,MAAM,OAAO,sCAAsC;AAAA,MACrD;AAAA,IACF;AAAA,EACN;AACA,QAAM,yBACJ,8BAA8B;AAEhC,MAAI,OAAO,2BAA2B,YAAY;AAChD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,MAAI;AAEJ,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/remote/nextjs/app.tsx"],"sourcesContent":["import 'remote-components/remote/defaults/wrapper';\nimport { workAsyncStorage } from 'next/dist/server/app-render/work-async-storage.external';\nimport { Suspense } from 'react';\nimport type { ConsumeLifecycleCallbacks } from '#internal/host/shared/config';\nimport { RemoteComponentSharedRemote } from '#internal/remote/nextjs/app-client';\nimport { DEFAULT_COMPONENT_NAME } from '#internal/runtime/constants';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\ninterface Manifest {\n clientModules?: Record<\n string,\n { id: string; name: string; chunks: string[]; async: boolean }\n >;\n moduleLoading: { prefix?: string; crossOrigin?: boolean | null };\n ssrModuleMapping?: Record<string, unknown>;\n}\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);\nconst MANIFESTS_SINGLETON = Symbol.for('next.server.manifests');\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 `${\n i === 0 ? `self[\"${name}\"]=self[\"${name}\"]||[];` : ''\n }self[\"${name}\"].push(${JSON.stringify(chunk)});`,\n )\n .join('\\n')}\n </script>\n );\n}\n\n/**\n * Props for exposing a Next.js component as a remote component.\n *\n * Extends {@link ConsumeLifecycleCallbacks} so the consuming host can wire up lifecycle\n * events. The `children` prop is the component content to expose (required,\n * unlike host props where children are an optional loading fallback).\n */\nexport interface ExposeRemoteComponentProps extends ConsumeLifecycleCallbacks {\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 * ExposeRemoteComponent 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 `<ExposeRemoteComponent>` in your Next.js App Router application to expose the children as a remote component:\n *\n * ```tsx\n * import { ExposeRemoteComponent } from 'remote-components/remote/nextjs/app';\n *\n * export default function MyPage() {\n * return (\n * <ExposeRemoteComponent>\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 * </ExposeRemoteComponent>\n * );\n * }\n * ```\n */\nexport async function ExposeRemoteComponent({\n name = DEFAULT_COMPONENT_NAME,\n children,\n}: ExposeRemoteComponentProps): 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 self = globalThis as typeof globalThis & {\n [SERVER_ACTION_MANIFESTS_SINGLETON]?: {\n clientReferenceManifestsPerPage?: Record<string, Manifest>;\n };\n [MANIFESTS_SINGLETON]?: {\n clientReferenceManifestsPerRoute?: Map<string, Manifest>;\n };\n __RSC_MANIFEST?: Record<string, unknown>;\n __RSC_SERVER_MANIFEST?: Record<string, unknown>;\n };\n const manifests =\n self[MANIFESTS_SINGLETON] ?? self[SERVER_ACTION_MANIFESTS_SINGLETON] ?? {};\n const manifest =\n 'clientReferenceManifestsPerRoute' in manifests\n ? manifests.clientReferenceManifestsPerRoute?.get?.(route)\n : 'clientReferenceManifestsPerPage' in manifests\n ? manifests.clientReferenceManifestsPerPage?.[route]\n : undefined;\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 self.__RSC_SERVER_MANIFEST = self.__RSC_SERVER_MANIFEST || {};\n self.__RSC_SERVER_MANIFEST[page] =\n self.__RSC_SERVER_MANIFEST[page] || manifest;\n\n // get the client and SSR module mapping to be able to use client components in the remote component\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 const clientModules = Object.fromEntries(\n Object.entries(manifest?.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":"AA0CI,SA+KI,UA/KJ,KA+KI,YA/KJ;AA1CJ,OAAO;AACP,SAAS,wBAAwB;AACjC,SAAS,gBAAgB;AAEzB,SAAS,mCAAmC;AAC5C,SAAS,8BAA8B;AACvC,SAAS,6BAA6B;AAYtC,MAAM,oCAAoC,OAAO;AAAA,EAC/C;AACF;AACA,MAAM,sBAAsB,OAAO,IAAI,uBAAuB;AAE9D,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,GACE,MAAM,IAAI,SAAS,gBAAgB,gBAAgB,WAC5C,eAAe,KAAK,UAAU,KAAK;AAAA;AAAA,EAChD,EACC,KAAK,IAAI,GACd;AAEJ;AAyCA,eAAsB,sBAAsB;AAAA,EAC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