@expo/cli 55.0.3 → 56.0.0-canary-20260128-67ce8d5
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/build/bin/cli +3 -1
- package/build/bin/cli.map +1 -1
- package/build/src/start/interface/interactiveActions.js +2 -1
- package/build/src/start/interface/interactiveActions.js.map +1 -1
- package/build/src/start/server/UrlCreator.js +1 -1
- package/build/src/start/server/UrlCreator.js.map +1 -1
- package/build/src/start/server/metro/DevToolsPluginWebsocketEndpoint.js +1 -1
- package/build/src/start/server/metro/DevToolsPluginWebsocketEndpoint.js.map +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js +4 -4
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/MetroTerminalReporter.js +144 -33
- package/build/src/start/server/metro/MetroTerminalReporter.js.map +1 -1
- package/build/src/start/server/metro/createServerComponentsMiddleware.js +2 -2
- package/build/src/start/server/metro/createServerComponentsMiddleware.js.map +1 -1
- package/build/src/start/server/metro/fetchRouterManifest.js +1 -13
- package/build/src/start/server/metro/fetchRouterManifest.js.map +1 -1
- package/build/src/start/server/metro/instantiateMetro.js +53 -0
- package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
- package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js +3 -1
- package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/ManifestMiddleware.js +14 -9
- package/build/src/start/server/middleware/ManifestMiddleware.js.map +1 -1
- package/build/src/start/server/type-generation/routes.js +2 -62
- package/build/src/start/server/type-generation/routes.js.map +1 -1
- package/build/src/utils/build-cache-providers/index.js +1 -1
- package/build/src/utils/build-cache-providers/index.js.map +1 -1
- package/build/src/utils/env.js +28 -0
- package/build/src/utils/env.js.map +1 -1
- package/build/src/utils/freeport.js +21 -5
- package/build/src/utils/freeport.js.map +1 -1
- package/build/src/utils/interactive.js +1 -1
- package/build/src/utils/interactive.js.map +1 -1
- package/build/src/utils/jsonl.js +243 -0
- package/build/src/utils/jsonl.js.map +1 -0
- package/build/src/utils/port.js +4 -4
- package/build/src/utils/port.js.map +1 -1
- package/build/src/utils/progress.js +5 -0
- package/build/src/utils/progress.js.map +1 -1
- package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
- package/build/src/utils/telemetry/utils/context.js +1 -1
- package/build/src/utils/url.js +4 -8
- package/build/src/utils/url.js.map +1 -1
- package/package.json +19 -20
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/createServerComponentsMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport type { EntriesDev } from '@expo/router-server/build/rsc/server';\nimport assert from 'assert';\nimport { getRscMiddleware } from 'expo-server/private';\nimport path from 'node:path';\nimport url from 'node:url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport type { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n type ExpoMetroOptions,\n getMetroOptionsFromUrl,\n} from '../middleware/metroOptions';\n\nconst debug = require('debug')('expo:rsc') as typeof console.log;\n\ntype SSRLoadModuleArtifactsFunc = (\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>\n) => Promise<{ artifacts: SerialAsset[]; src: string }>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string | null,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\nconst getMetroServerRootMemo = memoize(getMetroServerRoot);\n\nexport function createServerComponentsMiddleware(\n projectRoot: string,\n {\n rscPath,\n instanceMetroOptions,\n ssrLoadModule,\n ssrLoadModuleArtifacts,\n useClientRouter,\n createModuleId,\n routerOptions,\n }: {\n rscPath: string;\n instanceMetroOptions: Partial<ExpoMetroOptions>;\n ssrLoadModule: SSRLoadModuleFunc;\n ssrLoadModuleArtifacts: SSRLoadModuleArtifactsFunc;\n useClientRouter: boolean;\n createModuleId: (\n filePath: string,\n context: { platform: string; environment: string }\n ) => string | number;\n routerOptions: Record<string, any>;\n }\n) {\n const routerModule = useClientRouter\n ? '@expo/router-server/build/rsc/router/noopRouter'\n : '@expo/router-server/build/rsc/router/expo-definedRouter';\n\n const rscMiddleware = getRscMiddleware({\n config: {},\n // Disabled in development\n baseUrl: '',\n rscPath,\n onError: console.error,\n renderRsc: async (args) => {\n // In development we should add simulated versions of common production headers.\n if (args.headers['x-real-ip'] == null) {\n args.headers['x-real-ip'] = getIpAddress();\n }\n if (args.headers['x-forwarded-for'] == null) {\n args.headers['x-forwarded-for'] = args.headers['x-real-ip'];\n }\n if (args.headers['x-forwarded-proto'] == null) {\n args.headers['x-forwarded-proto'] = 'http';\n }\n\n // Dev server-only implementation.\n try {\n return await renderRscToReadableStream({\n ...args,\n headers: new Headers(args.headers),\n body: args.body!,\n routerOptions,\n });\n } catch (error: any) {\n // If you get a codeFrame error during SSR like when using a Class component in React Server Components, then this\n // will throw with:\n // {\n // rawObject: {\n // type: 'TransformError',\n // lineNumber: 0,\n // errors: [ [Object] ],\n // name: 'SyntaxError',\n // message: '...',\n // }\n // }\n\n // TODO: Revisit all error handling now that we do direct metro bundling...\n await logMetroError(projectRoot, { error });\n\n if (error[IS_METRO_BUNDLE_ERROR_SYMBOL]) {\n throw new Response(JSON.stringify(error), {\n status: isPossiblyUnableToResolveError(error) ? 404 : 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n const sanitizedServerMessage = stripAnsi(error.message) ?? error.message;\n throw new Response(sanitizedServerMessage, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n }\n },\n });\n\n let rscPathPrefix = rscPath;\n if (rscPathPrefix !== '/') {\n rscPathPrefix += '/';\n }\n\n async function exportServerActionsAsync(\n {\n platform,\n entryPoints,\n domRoot,\n }: { platform: string; entryPoints: string[]; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n clientBoundaries: string[];\n manifest: Record<string, [string, string]>;\n }> {\n const uniqueEntryPoints = [...new Set(entryPoints)];\n // TODO: Support multiple entry points in a single split server bundle...\n const manifest: Record<string, [string, string]> = {};\n const nestedClientBoundaries: string[] = [];\n const nestedServerBoundaries: string[] = [];\n const processedEntryPoints = new Set<string>();\n async function processEntryPoint(entryPoint: string) {\n processedEntryPoints.add(entryPoint);\n\n const contents = await ssrLoadModuleArtifacts(entryPoint, {\n environment: 'react-server',\n platform,\n // Ignore the metro runtime to avoid overwriting the original in the API route.\n modulesOnly: true,\n // Required\n runModule: true,\n // Required to ensure assets load as client boundaries.\n domRoot,\n });\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactClientReferences) {\n nestedClientBoundaries.push(...reactClientReferences!);\n }\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactServerReferences) {\n nestedServerBoundaries.push(...reactServerReferences!);\n }\n\n // Naive check to ensure the module runtime is not included in the server action bundle.\n if (contents.src.includes('The experimental Metro feature')) {\n throw new Error(\n 'Internal error: module runtime should not be included in server action bundles: ' +\n entryPoint\n );\n }\n\n const relativeName = createModuleId(entryPoint, {\n platform,\n environment: 'react-server',\n });\n const safeName = path.basename(contents.artifacts.find((a) => a.type === 'js')!.filename!);\n\n const outputName = `_expo/rsc/${platform}/${safeName}`;\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(outputName, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n // Match babel plugin.\n const publicModuleId = './' + toPosixPath(path.relative(projectRoot, entryPoint));\n\n // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[publicModuleId] = [String(relativeName), outputName];\n }\n\n async function processEntryPoints(entryPoints: string[], recursions = 0) {\n // Arbitrary recursion limit to prevent infinite loops.\n if (recursions > 10) {\n throw new Error('Recursion limit exceeded while processing server boundaries');\n }\n\n for (const entryPoint of entryPoints) {\n await processEntryPoint(entryPoint);\n }\n\n // When a server action has other server actions inside of it, we need to process those as well to ensure all entry points are in the manifest and accounted for.\n let uniqueNestedServerBoundaries = [...new Set(nestedServerBoundaries)];\n // Filter out values that have already been processed.\n uniqueNestedServerBoundaries = uniqueNestedServerBoundaries.filter(\n (value) => !processedEntryPoints.has(value)\n );\n if (uniqueNestedServerBoundaries.length) {\n debug('bundling nested server action boundaries', uniqueNestedServerBoundaries);\n return processEntryPoints(uniqueNestedServerBoundaries, recursions + 1);\n }\n }\n\n await processEntryPoints(uniqueEntryPoints);\n\n // Save the SSR manifest so we can perform more replacements in the server renderer and with server actions.\n files.set(`_expo/rsc/${platform}/action-manifest.js`, {\n targetDomain: 'server',\n contents: 'module.exports = ' + JSON.stringify(manifest),\n });\n\n return { manifest, clientBoundaries: nestedClientBoundaries };\n }\n\n async function getExpoRouterClientReferencesAsync(\n { platform, domRoot }: { platform: string; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n reactClientReferences: string[];\n reactServerReferences: string[];\n cssModules: SerialAsset[];\n }> {\n const contents = await ssrLoadModuleArtifacts(routerModule, {\n environment: 'react-server',\n platform,\n modulesOnly: true,\n domRoot,\n });\n\n // Extract the global CSS modules that are imported from the router.\n // These will be injected in the head of the HTML document for the website.\n const cssModules = contents.artifacts.filter((a) => a.type.startsWith('css'));\n\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactServerReferences) {\n throw new Error(\n 'Static server action references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactServerReferences);\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactClientReferences) {\n throw new Error(\n 'Static client references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactClientReferences);\n\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(`_expo/rsc/${platform}/router.js`, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n return { reactClientReferences, reactServerReferences, cssModules };\n }\n\n const routerCache = new Map<string, EntriesDev>();\n\n async function getExpoRouterRscEntriesGetterAsync({\n platform,\n routerOptions,\n }: {\n platform: string;\n routerOptions: Record<string, any>;\n }) {\n await ensureMemo();\n // We can only cache this if we're using the client router since it doesn't change or use HMR\n if (routerCache.has(platform) && useClientRouter) {\n return routerCache.get(platform)!;\n }\n\n const router = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/router/expo-definedRouter')\n >(\n routerModule,\n {\n environment: 'react-server',\n modulesOnly: true,\n platform,\n },\n {\n hot: !useClientRouter,\n }\n );\n\n const entries = router.default({\n redirects: routerOptions?.redirects,\n rewrites: routerOptions?.rewrites,\n });\n\n routerCache.set(platform, entries);\n return entries;\n }\n\n function getResolveClientEntry(context: {\n platform: string;\n engine?: 'hermes' | null;\n ssrManifest?: Map<string, string | null>;\n }): (\n file: string,\n isServer: boolean\n ) => {\n id: string;\n chunks: string[];\n } {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n const {\n mode,\n minify = false,\n isExporting,\n baseUrl,\n routerRoot,\n asyncRoutes,\n preserveEnvVars,\n reactCompiler,\n lazy,\n } = instanceMetroOptions;\n\n assert(\n isExporting != null &&\n baseUrl != null &&\n mode != null &&\n routerRoot != null &&\n asyncRoutes != null,\n `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`\n );\n\n return (file: string, isServer: boolean) => {\n const filePath = path.join(\n projectRoot,\n file.startsWith('file://') ? fileURLToFilePath(file) : file\n );\n\n if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n\n const relativeFilePath = toPosixPath(path.relative(serverRoot, filePath));\n\n assert(\n context.ssrManifest.has(relativeFilePath),\n `SSR manifest is missing client boundary \"${relativeFilePath}\"`\n );\n\n const chunk = context.ssrManifest.get(relativeFilePath);\n\n return {\n id: String(\n createModuleId(filePath, { platform: context.platform, environment: 'client' })\n ),\n chunks: chunk != null ? [chunk] : [],\n };\n }\n\n const environment = isServer ? 'react-server' : 'client';\n const searchParams = createBundleUrlSearchParams({\n mainModuleName: '',\n platform: context.platform,\n mode,\n minify,\n lazy,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n reactCompiler: !!reactCompiler,\n engine: context.engine ?? undefined,\n bytecode: false,\n clientBoundaries: [],\n inlineSourceMap: false,\n environment,\n modulesOnly: true,\n runModule: false,\n });\n\n searchParams.set('resolver.clientboundary', String(true));\n\n const clientReferenceUrl = new URL('http://a');\n\n // TICKLE: Handshake 1\n searchParams.set('xRSC', '1');\n\n clientReferenceUrl.search = searchParams.toString();\n\n const relativeFilePath = path.relative(serverRoot, filePath);\n\n clientReferenceUrl.pathname = relativeFilePath;\n\n // Ensure url.pathname ends with '.bundle'\n if (!clientReferenceUrl.pathname.endsWith('.bundle')) {\n clientReferenceUrl.pathname += '.bundle';\n }\n\n // Return relative URLs to help Android fetch from wherever it was loaded from since it doesn't support localhost.\n const chunkName = clientReferenceUrl.pathname + clientReferenceUrl.search;\n\n return {\n id: String(createModuleId(filePath, { platform: context.platform, environment })),\n chunks: [chunkName],\n };\n };\n }\n\n const rscRendererCache = new Map<\n string,\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >();\n\n let ensurePromise: Promise<unknown> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n await ssrLoadModule(null, {\n environment: 'react-server',\n platform: 'web',\n });\n }\n const ensureMemo = () => {\n ensurePromise ??= ensureSSRReady();\n return ensurePromise;\n };\n\n async function getRscRendererAsync(platform: string) {\n await ensureMemo();\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRendererCache.has(platform)) {\n return rscRendererCache.get(platform)!;\n }\n\n // TODO: Extract CSS Modules / Assets from the bundler process\n const renderer = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >('@expo/router-server/build/rsc/rsc-renderer', {\n environment: 'react-server',\n platform,\n });\n\n rscRendererCache.set(platform, renderer);\n return renderer;\n }\n\n const rscRenderContext = new Map<string, any>();\n\n function getRscRenderContext(platform: string) {\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRenderContext.has(platform)) {\n return rscRenderContext.get(platform)!;\n }\n\n const context = {};\n\n rscRenderContext.set(platform, context);\n return context;\n }\n\n async function renderRscToReadableStream(\n {\n input,\n headers,\n method,\n platform,\n body,\n engine,\n contentType,\n ssrManifest,\n decodedBody,\n routerOptions,\n }: {\n input: string;\n headers: Headers;\n method: 'POST' | 'GET';\n platform: string;\n body?: ReadableStream<Uint8Array>;\n engine?: 'hermes' | null;\n contentType?: string;\n ssrManifest?: Map<string, string | null>;\n decodedBody?: unknown;\n routerOptions: Record<string, any>;\n },\n isExporting: boolean | undefined = instanceMetroOptions.isExporting\n ) {\n assert(\n isExporting != null,\n 'The server must be started before calling renderRscToReadableStream.'\n );\n\n if (method === 'POST') {\n assert(body, 'Server request must be provided when method is POST (server actions)');\n }\n\n const context = getRscRenderContext(platform);\n\n context['__expo_requestHeaders'] = headers;\n\n const { renderRsc } = await getRscRendererAsync(platform);\n\n return renderRsc(\n {\n body,\n decodedBody,\n context,\n config: {},\n input,\n contentType,\n },\n {\n isExporting,\n entries: await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions }),\n resolveClientEntry: getResolveClientEntry({ platform, engine, ssrManifest }),\n async loadServerModuleRsc(urlFragment) {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n debug('[SSR] loadServerModuleRsc:', urlFragment);\n\n const options = getMetroOptionsFromUrl(urlFragment);\n\n return ssrLoadModule(\n path.join(serverRoot, options.mainModuleName),\n\n options,\n {\n hot: true,\n }\n );\n },\n }\n );\n }\n\n return {\n // Get the static client boundaries (no dead code elimination allowed) for the production export.\n getExpoRouterClientReferencesAsync,\n exportServerActionsAsync,\n\n async exportRoutesAsync(\n {\n platform,\n ssrManifest,\n routerOptions,\n }: {\n platform: string;\n ssrManifest: Map<string, string | null>;\n routerOptions: Record<string, any>;\n },\n files: ExportAssetMap\n ) {\n // TODO: When we add web SSR support, we need to extract CSS Modules / Assets from the bundler process to prevent FLOUC.\n const { getBuildConfig } = (\n await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions })\n ).default;\n\n // Get all the routes to render.\n const buildConfig = await getBuildConfig!(async () =>\n // TODO: Rework prefetching code to use Metro runtime.\n []\n );\n\n await Promise.all(\n Array.from(buildConfig).map(async ({ entries }) => {\n for (const { input, isStatic } of entries || []) {\n if (!isStatic) {\n debug('Skipping static export for route', { input });\n continue;\n }\n const destRscFile = path.join('_flight', platform, encodeInput(input));\n\n const pipe = await renderRscToReadableStream(\n {\n input,\n method: 'GET',\n platform,\n headers: new Headers(),\n ssrManifest,\n routerOptions,\n },\n true\n );\n\n const rsc = await streamToStringAsync(pipe);\n debug('RSC Payload', { platform, input, rsc });\n\n files.set(destRscFile, {\n contents: rsc,\n targetDomain: 'client',\n rscId: input,\n });\n }\n })\n );\n },\n\n middleware: createBuiltinAPIRequestHandler(\n // Match `/_flight/[platform]/[...path]`\n (req) => {\n return getFullUrl(req.url).pathname.startsWith(rscPathPrefix);\n },\n rscMiddleware\n ),\n onReloadRscEvent: (platform: string) => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n rscRendererCache.delete(platform);\n routerCache.delete(platform);\n },\n };\n}\n\nconst getFullUrl = (url: string) => {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'http://localhost:0');\n }\n};\n\nexport const fileURLToFilePath = (fileURL: string) => {\n try {\n return url.fileURLToPath(fileURL);\n } catch (error) {\n if (error instanceof TypeError) {\n throw Error(`Invalid URL: ${fileURL}`, { cause: error });\n }\n throw error;\n }\n};\n\nconst encodeInput = (input: string) => {\n if (input === '') {\n return 'index.txt';\n }\n if (input === 'index') {\n throw new Error('Input should not be `index`');\n }\n if (input.startsWith('/')) {\n throw new Error('Input should not start with `/`');\n }\n if (input.endsWith('/')) {\n throw new Error('Input should not end with `/`');\n }\n return input + '.txt';\n};\n\nfunction wrapBundle(str: string) {\n // Skip the metro runtime so debugging is a bit easier.\n // Replace the __r() call with an export statement.\n // Use gm to apply to the last require line. This is needed when the bundle has side-effects.\n return str.replace(/^(__r\\(.*\\);)$/gm, 'module.exports = $1');\n}\n"],"names":["createServerComponentsMiddleware","fileURLToFilePath","debug","require","getMetroServerRootMemo","memoize","getMetroServerRoot","projectRoot","rscPath","instanceMetroOptions","ssrLoadModule","ssrLoadModuleArtifacts","useClientRouter","createModuleId","routerOptions","routerModule","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","IS_METRO_BUNDLE_ERROR_SYMBOL","Response","JSON","stringify","status","isPossiblyUnableToResolveError","sanitizedServerMessage","stripAnsi","message","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","nestedServerBoundaries","processedEntryPoints","processEntryPoint","entryPoint","contents","add","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","reactServerReferences","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","publicModuleId","toPosixPath","relative","String","processEntryPoints","recursions","uniqueNestedServerBoundaries","value","has","length","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","routerCache","Map","getExpoRouterRscEntriesGetterAsync","ensureMemo","get","router","hot","entries","default","redirects","rewrites","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","filePath","join","ssrManifest","relativeFilePath","chunk","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","pathname","endsWith","chunkName","rscRendererCache","ensurePromise","ensureSSRReady","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","exportRoutesAsync","getBuildConfig","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","delete","fileURL","fileURLToPath","TypeError","cause","str","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAuCeA,gCAAgC;eAAhCA;;IAkmBHC,iBAAiB;eAAjBA;;;;yBAxoBsB;;;;;;;gEAGhB;;;;;;;yBACc;;;;;;;gEAChB;;;;;;;gEACD;;;;;;qCAE4C;qCACb;sBAErB;0BACE;oBACJ;oBACK;wBACO;gDACW;8BAKxC;;;;;;AAEP,MAAMC,QAAQC,QAAQ,SAAS;AAa/B,MAAMC,yBAAyBC,IAAAA,WAAO,EAACC,2BAAkB;AAElD,SAASN,iCACdO,WAAmB,EACnB,EACEC,OAAO,EACPC,oBAAoB,EACpBC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,EACfC,cAAc,EACdC,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+
{"version":3,"sources":["../../../../../src/start/server/metro/createServerComponentsMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport type { EntriesDev } from '@expo/router-server/build/rsc/server';\nimport assert from 'assert';\nimport { getRscMiddleware } from 'expo-server/private';\nimport path from 'node:path';\nimport url from 'node:url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport type { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n type ExpoMetroOptions,\n getMetroOptionsFromUrl,\n} from '../middleware/metroOptions';\n\nconst debug = require('debug')('expo:rsc') as typeof console.log;\n\ntype SSRLoadModuleArtifactsFunc = (\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>\n) => Promise<{ artifacts: SerialAsset[]; src: string }>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string | null,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\nconst getMetroServerRootMemo = memoize(getMetroServerRoot);\n\nexport function createServerComponentsMiddleware(\n projectRoot: string,\n {\n rscPath,\n instanceMetroOptions,\n ssrLoadModule,\n ssrLoadModuleArtifacts,\n useClientRouter,\n createModuleId,\n routerOptions,\n }: {\n rscPath: string;\n instanceMetroOptions: Partial<ExpoMetroOptions>;\n ssrLoadModule: SSRLoadModuleFunc;\n ssrLoadModuleArtifacts: SSRLoadModuleArtifactsFunc;\n useClientRouter: boolean;\n createModuleId: (\n filePath: string,\n context: { platform: string; environment: string }\n ) => string | number;\n routerOptions: Record<string, any>;\n }\n) {\n const routerModule = useClientRouter\n ? require.resolve('@expo/router-server/build/rsc/router/noopRouter')\n : require.resolve('@expo/router-server/build/rsc/router/expo-definedRouter');\n\n const rscMiddleware = getRscMiddleware({\n config: {},\n // Disabled in development\n baseUrl: '',\n rscPath,\n onError: console.error,\n renderRsc: async (args) => {\n // In development we should add simulated versions of common production headers.\n if (args.headers['x-real-ip'] == null) {\n args.headers['x-real-ip'] = getIpAddress();\n }\n if (args.headers['x-forwarded-for'] == null) {\n args.headers['x-forwarded-for'] = args.headers['x-real-ip'];\n }\n if (args.headers['x-forwarded-proto'] == null) {\n args.headers['x-forwarded-proto'] = 'http';\n }\n\n // Dev server-only implementation.\n try {\n return await renderRscToReadableStream({\n ...args,\n headers: new Headers(args.headers),\n body: args.body!,\n routerOptions,\n });\n } catch (error: any) {\n // If you get a codeFrame error during SSR like when using a Class component in React Server Components, then this\n // will throw with:\n // {\n // rawObject: {\n // type: 'TransformError',\n // lineNumber: 0,\n // errors: [ [Object] ],\n // name: 'SyntaxError',\n // message: '...',\n // }\n // }\n\n // TODO: Revisit all error handling now that we do direct metro bundling...\n await logMetroError(projectRoot, { error });\n\n if (error[IS_METRO_BUNDLE_ERROR_SYMBOL]) {\n throw new Response(JSON.stringify(error), {\n status: isPossiblyUnableToResolveError(error) ? 404 : 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n const sanitizedServerMessage = stripAnsi(error.message) ?? error.message;\n throw new Response(sanitizedServerMessage, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n }\n },\n });\n\n let rscPathPrefix = rscPath;\n if (rscPathPrefix !== '/') {\n rscPathPrefix += '/';\n }\n\n async function exportServerActionsAsync(\n {\n platform,\n entryPoints,\n domRoot,\n }: { platform: string; entryPoints: string[]; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n clientBoundaries: string[];\n manifest: Record<string, [string, string]>;\n }> {\n const uniqueEntryPoints = [...new Set(entryPoints)];\n // TODO: Support multiple entry points in a single split server bundle...\n const manifest: Record<string, [string, string]> = {};\n const nestedClientBoundaries: string[] = [];\n const nestedServerBoundaries: string[] = [];\n const processedEntryPoints = new Set<string>();\n async function processEntryPoint(entryPoint: string) {\n processedEntryPoints.add(entryPoint);\n\n const contents = await ssrLoadModuleArtifacts(entryPoint, {\n environment: 'react-server',\n platform,\n // Ignore the metro runtime to avoid overwriting the original in the API route.\n modulesOnly: true,\n // Required\n runModule: true,\n // Required to ensure assets load as client boundaries.\n domRoot,\n });\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactClientReferences) {\n nestedClientBoundaries.push(...reactClientReferences!);\n }\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactServerReferences) {\n nestedServerBoundaries.push(...reactServerReferences!);\n }\n\n // Naive check to ensure the module runtime is not included in the server action bundle.\n if (contents.src.includes('The experimental Metro feature')) {\n throw new Error(\n 'Internal error: module runtime should not be included in server action bundles: ' +\n entryPoint\n );\n }\n\n const relativeName = createModuleId(entryPoint, {\n platform,\n environment: 'react-server',\n });\n const safeName = path.basename(contents.artifacts.find((a) => a.type === 'js')!.filename!);\n\n const outputName = `_expo/rsc/${platform}/${safeName}`;\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(outputName, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n // Match babel plugin.\n const publicModuleId = './' + toPosixPath(path.relative(projectRoot, entryPoint));\n\n // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[publicModuleId] = [String(relativeName), outputName];\n }\n\n async function processEntryPoints(entryPoints: string[], recursions = 0) {\n // Arbitrary recursion limit to prevent infinite loops.\n if (recursions > 10) {\n throw new Error('Recursion limit exceeded while processing server boundaries');\n }\n\n for (const entryPoint of entryPoints) {\n await processEntryPoint(entryPoint);\n }\n\n // When a server action has other server actions inside of it, we need to process those as well to ensure all entry points are in the manifest and accounted for.\n let uniqueNestedServerBoundaries = [...new Set(nestedServerBoundaries)];\n // Filter out values that have already been processed.\n uniqueNestedServerBoundaries = uniqueNestedServerBoundaries.filter(\n (value) => !processedEntryPoints.has(value)\n );\n if (uniqueNestedServerBoundaries.length) {\n debug('bundling nested server action boundaries', uniqueNestedServerBoundaries);\n return processEntryPoints(uniqueNestedServerBoundaries, recursions + 1);\n }\n }\n\n await processEntryPoints(uniqueEntryPoints);\n\n // Save the SSR manifest so we can perform more replacements in the server renderer and with server actions.\n files.set(`_expo/rsc/${platform}/action-manifest.js`, {\n targetDomain: 'server',\n contents: 'module.exports = ' + JSON.stringify(manifest),\n });\n\n return { manifest, clientBoundaries: nestedClientBoundaries };\n }\n\n async function getExpoRouterClientReferencesAsync(\n { platform, domRoot }: { platform: string; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n reactClientReferences: string[];\n reactServerReferences: string[];\n cssModules: SerialAsset[];\n }> {\n const contents = await ssrLoadModuleArtifacts(routerModule, {\n environment: 'react-server',\n platform,\n modulesOnly: true,\n domRoot,\n });\n\n // Extract the global CSS modules that are imported from the router.\n // These will be injected in the head of the HTML document for the website.\n const cssModules = contents.artifacts.filter((a) => a.type.startsWith('css'));\n\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactServerReferences) {\n throw new Error(\n 'Static server action references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactServerReferences);\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactClientReferences) {\n throw new Error(\n 'Static client references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactClientReferences);\n\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(`_expo/rsc/${platform}/router.js`, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n return { reactClientReferences, reactServerReferences, cssModules };\n }\n\n const routerCache = new Map<string, EntriesDev>();\n\n async function getExpoRouterRscEntriesGetterAsync({\n platform,\n routerOptions,\n }: {\n platform: string;\n routerOptions: Record<string, any>;\n }) {\n await ensureMemo();\n // We can only cache this if we're using the client router since it doesn't change or use HMR\n if (routerCache.has(platform) && useClientRouter) {\n return routerCache.get(platform)!;\n }\n\n const router = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/router/expo-definedRouter')\n >(\n routerModule,\n {\n environment: 'react-server',\n modulesOnly: true,\n platform,\n },\n {\n hot: !useClientRouter,\n }\n );\n\n const entries = router.default({\n redirects: routerOptions?.redirects,\n rewrites: routerOptions?.rewrites,\n });\n\n routerCache.set(platform, entries);\n return entries;\n }\n\n function getResolveClientEntry(context: {\n platform: string;\n engine?: 'hermes' | null;\n ssrManifest?: Map<string, string | null>;\n }): (\n file: string,\n isServer: boolean\n ) => {\n id: string;\n chunks: string[];\n } {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n const {\n mode,\n minify = false,\n isExporting,\n baseUrl,\n routerRoot,\n asyncRoutes,\n preserveEnvVars,\n reactCompiler,\n lazy,\n } = instanceMetroOptions;\n\n assert(\n isExporting != null &&\n baseUrl != null &&\n mode != null &&\n routerRoot != null &&\n asyncRoutes != null,\n `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`\n );\n\n return (file: string, isServer: boolean) => {\n const filePath = path.join(\n projectRoot,\n file.startsWith('file://') ? fileURLToFilePath(file) : file\n );\n\n if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n\n const relativeFilePath = toPosixPath(path.relative(serverRoot, filePath));\n\n assert(\n context.ssrManifest.has(relativeFilePath),\n `SSR manifest is missing client boundary \"${relativeFilePath}\"`\n );\n\n const chunk = context.ssrManifest.get(relativeFilePath);\n\n return {\n id: String(\n createModuleId(filePath, { platform: context.platform, environment: 'client' })\n ),\n chunks: chunk != null ? [chunk] : [],\n };\n }\n\n const environment = isServer ? 'react-server' : 'client';\n const searchParams = createBundleUrlSearchParams({\n mainModuleName: '',\n platform: context.platform,\n mode,\n minify,\n lazy,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n reactCompiler: !!reactCompiler,\n engine: context.engine ?? undefined,\n bytecode: false,\n clientBoundaries: [],\n inlineSourceMap: false,\n environment,\n modulesOnly: true,\n runModule: false,\n });\n\n searchParams.set('resolver.clientboundary', String(true));\n\n const clientReferenceUrl = new URL('http://a');\n\n // TICKLE: Handshake 1\n searchParams.set('xRSC', '1');\n\n clientReferenceUrl.search = searchParams.toString();\n\n const relativeFilePath = path.relative(serverRoot, filePath);\n\n clientReferenceUrl.pathname = relativeFilePath;\n\n // Ensure url.pathname ends with '.bundle'\n if (!clientReferenceUrl.pathname.endsWith('.bundle')) {\n clientReferenceUrl.pathname += '.bundle';\n }\n\n // Return relative URLs to help Android fetch from wherever it was loaded from since it doesn't support localhost.\n const chunkName = clientReferenceUrl.pathname + clientReferenceUrl.search;\n\n return {\n id: String(createModuleId(filePath, { platform: context.platform, environment })),\n chunks: [chunkName],\n };\n };\n }\n\n const rscRendererCache = new Map<\n string,\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >();\n\n let ensurePromise: Promise<unknown> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n await ssrLoadModule(null, {\n environment: 'react-server',\n platform: 'web',\n });\n }\n const ensureMemo = () => {\n ensurePromise ??= ensureSSRReady();\n return ensurePromise;\n };\n\n async function getRscRendererAsync(platform: string) {\n await ensureMemo();\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRendererCache.has(platform)) {\n return rscRendererCache.get(platform)!;\n }\n\n // TODO: Extract CSS Modules / Assets from the bundler process\n const renderer = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >(require.resolve('@expo/router-server/build/rsc/rsc-renderer'), {\n environment: 'react-server',\n platform,\n });\n\n rscRendererCache.set(platform, renderer);\n return renderer;\n }\n\n const rscRenderContext = new Map<string, any>();\n\n function getRscRenderContext(platform: string) {\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRenderContext.has(platform)) {\n return rscRenderContext.get(platform)!;\n }\n\n const context = {};\n\n rscRenderContext.set(platform, context);\n return context;\n }\n\n async function renderRscToReadableStream(\n {\n input,\n headers,\n method,\n platform,\n body,\n engine,\n contentType,\n ssrManifest,\n decodedBody,\n routerOptions,\n }: {\n input: string;\n headers: Headers;\n method: 'POST' | 'GET';\n platform: string;\n body?: ReadableStream<Uint8Array>;\n engine?: 'hermes' | null;\n contentType?: string;\n ssrManifest?: Map<string, string | null>;\n decodedBody?: unknown;\n routerOptions: Record<string, any>;\n },\n isExporting: boolean | undefined = instanceMetroOptions.isExporting\n ) {\n assert(\n isExporting != null,\n 'The server must be started before calling renderRscToReadableStream.'\n );\n\n if (method === 'POST') {\n assert(body, 'Server request must be provided when method is POST (server actions)');\n }\n\n const context = getRscRenderContext(platform);\n\n context['__expo_requestHeaders'] = headers;\n\n const { renderRsc } = await getRscRendererAsync(platform);\n\n return renderRsc(\n {\n body,\n decodedBody,\n context,\n config: {},\n input,\n contentType,\n },\n {\n isExporting,\n entries: await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions }),\n resolveClientEntry: getResolveClientEntry({ platform, engine, ssrManifest }),\n async loadServerModuleRsc(urlFragment) {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n debug('[SSR] loadServerModuleRsc:', urlFragment);\n\n const options = getMetroOptionsFromUrl(urlFragment);\n\n return ssrLoadModule(\n path.join(serverRoot, options.mainModuleName),\n\n options,\n {\n hot: true,\n }\n );\n },\n }\n );\n }\n\n return {\n // Get the static client boundaries (no dead code elimination allowed) for the production export.\n getExpoRouterClientReferencesAsync,\n exportServerActionsAsync,\n\n async exportRoutesAsync(\n {\n platform,\n ssrManifest,\n routerOptions,\n }: {\n platform: string;\n ssrManifest: Map<string, string | null>;\n routerOptions: Record<string, any>;\n },\n files: ExportAssetMap\n ) {\n // TODO: When we add web SSR support, we need to extract CSS Modules / Assets from the bundler process to prevent FLOUC.\n const { getBuildConfig } = (\n await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions })\n ).default;\n\n // Get all the routes to render.\n const buildConfig = await getBuildConfig!(async () =>\n // TODO: Rework prefetching code to use Metro runtime.\n []\n );\n\n await Promise.all(\n Array.from(buildConfig).map(async ({ entries }) => {\n for (const { input, isStatic } of entries || []) {\n if (!isStatic) {\n debug('Skipping static export for route', { input });\n continue;\n }\n const destRscFile = path.join('_flight', platform, encodeInput(input));\n\n const pipe = await renderRscToReadableStream(\n {\n input,\n method: 'GET',\n platform,\n headers: new Headers(),\n ssrManifest,\n routerOptions,\n },\n true\n );\n\n const rsc = await streamToStringAsync(pipe);\n debug('RSC Payload', { platform, input, rsc });\n\n files.set(destRscFile, {\n contents: rsc,\n targetDomain: 'client',\n rscId: input,\n });\n }\n })\n );\n },\n\n middleware: createBuiltinAPIRequestHandler(\n // Match `/_flight/[platform]/[...path]`\n (req) => {\n return getFullUrl(req.url).pathname.startsWith(rscPathPrefix);\n },\n rscMiddleware\n ),\n onReloadRscEvent: (platform: string) => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n rscRendererCache.delete(platform);\n routerCache.delete(platform);\n },\n };\n}\n\nconst getFullUrl = (url: string) => {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'http://localhost:0');\n }\n};\n\nexport const fileURLToFilePath = (fileURL: string) => {\n try {\n return url.fileURLToPath(fileURL);\n } catch (error) {\n if (error instanceof TypeError) {\n throw Error(`Invalid URL: ${fileURL}`, { cause: error });\n }\n throw error;\n }\n};\n\nconst encodeInput = (input: string) => {\n if (input === '') {\n return 'index.txt';\n }\n if (input === 'index') {\n throw new Error('Input should not be `index`');\n }\n if (input.startsWith('/')) {\n throw new Error('Input should not start with `/`');\n }\n if (input.endsWith('/')) {\n throw new Error('Input should not end with `/`');\n }\n return input + '.txt';\n};\n\nfunction wrapBundle(str: string) {\n // Skip the metro runtime so debugging is a bit easier.\n // Replace the __r() call with an export statement.\n // Use gm to apply to the last require line. This is needed when the bundle has side-effects.\n return str.replace(/^(__r\\(.*\\);)$/gm, 'module.exports = $1');\n}\n"],"names":["createServerComponentsMiddleware","fileURLToFilePath","debug","require","getMetroServerRootMemo","memoize","getMetroServerRoot","projectRoot","rscPath","instanceMetroOptions","ssrLoadModule","ssrLoadModuleArtifacts","useClientRouter","createModuleId","routerOptions","routerModule","resolve","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","IS_METRO_BUNDLE_ERROR_SYMBOL","Response","JSON","stringify","status","isPossiblyUnableToResolveError","sanitizedServerMessage","stripAnsi","message","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","nestedServerBoundaries","processedEntryPoints","processEntryPoint","entryPoint","contents","add","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","reactServerReferences","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","publicModuleId","toPosixPath","relative","String","processEntryPoints","recursions","uniqueNestedServerBoundaries","value","has","length","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","routerCache","Map","getExpoRouterRscEntriesGetterAsync","ensureMemo","get","router","hot","entries","default","redirects","rewrites","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","filePath","join","ssrManifest","relativeFilePath","chunk","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","pathname","endsWith","chunkName","rscRendererCache","ensurePromise","ensureSSRReady","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","exportRoutesAsync","getBuildConfig","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","delete","fileURL","fileURLToPath","TypeError","cause","str","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAuCeA,gCAAgC;eAAhCA;;IAkmBHC,iBAAiB;eAAjBA;;;;yBAxoBsB;;;;;;;gEAGhB;;;;;;;yBACc;;;;;;;gEAChB;;;;;;;gEACD;;;;;;qCAE4C;qCACb;sBAErB;0BACE;oBACJ;oBACK;wBACO;gDACW;8BAKxC;;;;;;AAEP,MAAMC,QAAQC,QAAQ,SAAS;AAa/B,MAAMC,yBAAyBC,IAAAA,WAAO,EAACC,2BAAkB;AAElD,SAASN,iCACdO,WAAmB,EACnB,EACEC,OAAO,EACPC,oBAAoB,EACpBC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,EACfC,cAAc,EACdC,aAAa,EAYd;IAED,MAAMC,eAAeH,kBACjBT,QAAQa,OAAO,CAAC,qDAChBb,QAAQa,OAAO,CAAC;IAEpB,MAAMC,gBAAgBC,IAAAA,2BAAgB,EAAC;QACrCC,QAAQ,CAAC;QACT,0BAA0B;QAC1BC,SAAS;QACTZ;QACAa,SAASC,QAAQC,KAAK;QACtBC,WAAW,OAAOC;YAChB,gFAAgF;YAChF,IAAIA,KAAKC,OAAO,CAAC,YAAY,IAAI,MAAM;gBACrCD,KAAK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OC,WAAWD,IAAIE,GAAG,EAAErC,QAAQ,CAAC5C,UAAU,CAACvD;QACjD,GACAxB;QAEFiK,kBAAkB,CAACvI;YACjB,+FAA+F;YAE/FoG,iBAAiBoC,MAAM,CAACxI;YACxBsD,YAAYkF,MAAM,CAACxI;QACrB;IACF;AACF;AAEA,MAAMqI,aAAa,CAACC;IAClB,IAAI;QACF,OAAO,IAAIxC,IAAIwC;IACjB,EAAE,OAAM;QACN,OAAO,IAAIxC,IAAIwC,KAAK;IACtB;AACF;AAEO,MAAMhL,oBAAoB,CAACmL;IAChC,IAAI;QACF,OAAOH,kBAAG,CAACI,aAAa,CAACD;IAC3B,EAAE,OAAO7J,OAAO;QACd,IAAIA,iBAAiB+J,WAAW;YAC9B,MAAM9G,MAAM,CAAC,aAAa,EAAE4G,SAAS,EAAE;gBAAEG,OAAOhK;YAAM;QACxD;QACA,MAAMA;IACR;AACF;AAEA,MAAMiJ,cAAc,CAAClB;IACnB,IAAIA,UAAU,IAAI;QAChB,OAAO;IACT;IACA,IAAIA,UAAU,SAAS;QACrB,MAAM,IAAI9E,MAAM;IAClB;IACA,IAAI8E,MAAMtD,UAAU,CAAC,MAAM;QACzB,MAAM,IAAIxB,MAAM;IAClB;IACA,IAAI8E,MAAMT,QAAQ,CAAC,MAAM;QACvB,MAAM,IAAIrE,MAAM;IAClB;IACA,OAAO8E,QAAQ;AACjB;AAEA,SAASpE,WAAWsG,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAIC,OAAO,CAAC,oBAAoB;AACzC"}
|
|
@@ -21,21 +21,9 @@ _export(exports, {
|
|
|
21
21
|
return inflateManifest;
|
|
22
22
|
}
|
|
23
23
|
});
|
|
24
|
-
function _resolvefrom() {
|
|
25
|
-
const data = /*#__PURE__*/ _interop_require_default(require("resolve-from"));
|
|
26
|
-
_resolvefrom = function() {
|
|
27
|
-
return data;
|
|
28
|
-
};
|
|
29
|
-
return data;
|
|
30
|
-
}
|
|
31
24
|
const _router = require("./router");
|
|
32
|
-
function _interop_require_default(obj) {
|
|
33
|
-
return obj && obj.__esModule ? obj : {
|
|
34
|
-
default: obj
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
25
|
function getExpoRouteManifestBuilderAsync(projectRoot) {
|
|
38
|
-
return require(
|
|
26
|
+
return require('@expo/router-server/build/routes-manifest').createRoutesManifest;
|
|
39
27
|
}
|
|
40
28
|
async function fetchManifest(projectRoot, options) {
|
|
41
29
|
const getManifest = getExpoRouteManifestBuilderAsync(projectRoot);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/fetchRouterManifest.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport type { Options as RoutesManifestOptions } from '@expo/router-server/build/routes-manifest';\nimport { type
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/fetchRouterManifest.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport type { Options as RoutesManifestOptions } from '@expo/router-server/build/routes-manifest';\nimport { type RoutesManifest } from 'expo-server/private';\n\nimport { getRoutePaths } from './router';\n\nfunction getExpoRouteManifestBuilderAsync(projectRoot: string) {\n return require('@expo/router-server/build/routes-manifest')\n .createRoutesManifest as typeof import('@expo/router-server/build/routes-manifest').createRoutesManifest;\n}\n\ninterface FetchManifestOptions extends RoutesManifestOptions {\n asJson?: boolean;\n appDir: string;\n}\n\n// TODO: Simplify this now that we use Node.js directly, no need for the Metro bundler caching layer.\nasync function fetchManifest(\n projectRoot: string,\n options: FetchManifestOptions & { asJson: true }\n): Promise<RoutesManifest<string> | null>;\nasync function fetchManifest(\n projectRoot: string,\n options: FetchManifestOptions & { asJson?: false | undefined }\n): Promise<RoutesManifest<RegExp> | null>;\nasync function fetchManifest(\n projectRoot: string,\n options: FetchManifestOptions\n): Promise<RoutesManifest | null> {\n const getManifest = getExpoRouteManifestBuilderAsync(projectRoot);\n const paths = getRoutePaths(options.appDir);\n // Get the serialized manifest\n const jsonManifest = getManifest(paths, options);\n if (!jsonManifest) {\n return null;\n }\n\n if (!jsonManifest.htmlRoutes || !jsonManifest.apiRoutes) {\n throw new Error('Routes manifest is malformed: ' + JSON.stringify(jsonManifest, null, 2));\n }\n\n if (!options.asJson) {\n return inflateManifest(jsonManifest);\n } else {\n return jsonManifest;\n }\n}\n\nexport { fetchManifest };\n\n// Convert the serialized manifest to a usable format\nexport function inflateManifest(json: RoutesManifest<string>): RoutesManifest<RegExp> {\n return {\n ...json,\n middleware: json.middleware,\n htmlRoutes: json.htmlRoutes?.map((value) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n apiRoutes: json.apiRoutes?.map((value) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n notFoundRoutes: json.notFoundRoutes?.map((value) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n redirects: json.redirects?.map((value: any) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n rewrites: json.rewrites?.map((value: any) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n };\n}\n"],"names":["fetchManifest","inflateManifest","getExpoRouteManifestBuilderAsync","projectRoot","require","createRoutesManifest","options","getManifest","paths","getRoutePaths","appDir","jsonManifest","htmlRoutes","apiRoutes","Error","JSON","stringify","asJson","json","middleware","map","value","namedRegex","RegExp","notFoundRoutes","redirects","rewrites"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAgDQA,aAAa;eAAbA;;IAGOC,eAAe;eAAfA;;;wBA/Cc;AAE9B,SAASC,iCAAiCC,WAAmB;IAC3D,OAAOC,QAAQ,6CACZC,oBAAoB;AACzB;AAgBA,eAAeL,cACbG,WAAmB,EACnBG,OAA6B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BAAbR,eAAeE,GAAG,CAAC,CAACC;YAC5B,OAAO;gBACL,GAAGA,KAAK;gBACRC,YAAY,IAAIC,OAAOF,MAAMC,UAAU;YACzC;QACF;IACF;AACF"}
|
|
@@ -17,6 +17,9 @@ _export(exports, {
|
|
|
17
17
|
},
|
|
18
18
|
loadMetroConfigAsync: function() {
|
|
19
19
|
return loadMetroConfigAsync;
|
|
20
|
+
},
|
|
21
|
+
overrideExpoMetroCacheStores: function() {
|
|
22
|
+
return overrideExpoMetroCacheStores;
|
|
20
23
|
}
|
|
21
24
|
});
|
|
22
25
|
function _config() {
|
|
@@ -68,6 +71,13 @@ function _metroconfig1() {
|
|
|
68
71
|
};
|
|
69
72
|
return data;
|
|
70
73
|
}
|
|
74
|
+
function _filestore() {
|
|
75
|
+
const data = require("@expo/metro-config/file-store");
|
|
76
|
+
_filestore = function() {
|
|
77
|
+
return data;
|
|
78
|
+
};
|
|
79
|
+
return data;
|
|
80
|
+
}
|
|
71
81
|
function _chalk() {
|
|
72
82
|
const data = /*#__PURE__*/ _interop_require_default(require("chalk"));
|
|
73
83
|
_chalk = function() {
|
|
@@ -75,6 +85,13 @@ function _chalk() {
|
|
|
75
85
|
};
|
|
76
86
|
return data;
|
|
77
87
|
}
|
|
88
|
+
function _fs() {
|
|
89
|
+
const data = /*#__PURE__*/ _interop_require_default(require("fs"));
|
|
90
|
+
_fs = function() {
|
|
91
|
+
return data;
|
|
92
|
+
};
|
|
93
|
+
return data;
|
|
94
|
+
}
|
|
78
95
|
function _path() {
|
|
79
96
|
const data = /*#__PURE__*/ _interop_require_default(require("path"));
|
|
80
97
|
_path = function() {
|
|
@@ -173,6 +190,10 @@ async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, ge
|
|
|
173
190
|
}
|
|
174
191
|
}
|
|
175
192
|
};
|
|
193
|
+
overrideExpoMetroCacheStores(config, {
|
|
194
|
+
projectRoot
|
|
195
|
+
});
|
|
196
|
+
// @ts-expect-error: Set the global require cycle ignore patterns for SSR bundles. This won't work with custom global prefixes, but we don't use those.
|
|
176
197
|
globalThis.__requireCycleIgnorePatterns = (_config_resolver = config.resolver) == null ? void 0 : _config_resolver.requireCycleIgnorePatterns;
|
|
177
198
|
if (isExporting) {
|
|
178
199
|
var _exp_experiments7;
|
|
@@ -434,5 +455,37 @@ function isWatchEnabled() {
|
|
|
434
455
|
}
|
|
435
456
|
return !_env.env.CI;
|
|
436
457
|
}
|
|
458
|
+
async function overrideExpoMetroCacheStores(config, { projectRoot }) {
|
|
459
|
+
var _config_cacheStores;
|
|
460
|
+
if (!_env.env.EXPO_METRO_CACHE_STORES_DIR) {
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
// Resolve relative paths to absolute paths based on project root
|
|
464
|
+
const cacheStoresDir = _path().default.isAbsolute(_env.env.EXPO_METRO_CACHE_STORES_DIR) ? _env.env.EXPO_METRO_CACHE_STORES_DIR : _path().default.resolve(projectRoot, _env.env.EXPO_METRO_CACHE_STORES_DIR);
|
|
465
|
+
// Create the directory if it doesn't exist
|
|
466
|
+
try {
|
|
467
|
+
await _fs().default.promises.mkdir(cacheStoresDir, {
|
|
468
|
+
recursive: true
|
|
469
|
+
});
|
|
470
|
+
} catch (error) {
|
|
471
|
+
if (error.code !== 'EEXIST') {
|
|
472
|
+
_log.Log.error(`Provided EXPO_METRO_CACHE_STORES_DIR="${cacheStoresDir}" is not a directory. Use new or existing directory path.`);
|
|
473
|
+
throw error;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
// Check if user has custom cacheStores in their metro.config.js
|
|
477
|
+
if ((_config_cacheStores = config.cacheStores) == null ? void 0 : _config_cacheStores.length) {
|
|
478
|
+
_log.Log.warn(`Using EXPO_METRO_CACHE_STORES_DIR="${cacheStoresDir}" which overrides cacheStores from metro.config.js`);
|
|
479
|
+
} else {
|
|
480
|
+
_log.Log.log(_chalk().default.gray(`Using Metro cache directory: ${cacheStoresDir}`));
|
|
481
|
+
}
|
|
482
|
+
// Override cacheStores with the env-specified directory
|
|
483
|
+
// @ts-expect-error - cacheStores is a read-only property
|
|
484
|
+
config.cacheStores = [
|
|
485
|
+
new (_filestore()).FileStore({
|
|
486
|
+
root: cacheStoresDir
|
|
487
|
+
})
|
|
488
|
+
];
|
|
489
|
+
}
|
|
437
490
|
|
|
438
491
|
//# sourceMappingURL=instantiateMetro.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { Reporter } from '@expo/metro/metro';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport MetroHmrServer, { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport RevisionNotFoundError from '@expo/metro/metro/IncrementalBundler/RevisionNotFoundError';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport formatBundlingError from '@expo/metro/metro/lib/formatBundlingError';\nimport { mergeConfig, resolveConfig, type ConfigT } from '@expo/metro/metro-config';\nimport { Terminal } from '@expo/metro/metro-core';\nimport { createStableModuleIdFactory, getDefaultConfig } from '@expo/metro-config';\nimport chalk from 'chalk';\nimport http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// NOTE(@kitten): We pass a custom createStableModuleIdFactory function into the Metro module ID factory sometimes\ninterface MetroServerWithModuleIdMod extends MetroServer {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\ninterface MetroHmrServerWithModuleIdMod extends MetroHmrServer<MetroHmrClient> {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// TODO(@kitten): We assign this here to run server-side code bundled by metro\n// It's not isolated into a worker thread yet\n// Check `metro-require/require.ts` for how this setting is used\ndeclare namespace globalThis {\n let __requireCycleIgnorePatterns: readonly RegExp[] | undefined;\n}\n\nfunction asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\n\n// Wrap terminal and polyfill console.log so we can log during bundling without breaking the indicator.\nclass LogRespectingTerminal extends Terminal {\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream, { ttyPrint: true });\n\n const sendLog = (...msg: any[]) => {\n if (!msg.length) {\n this.log('');\n } else {\n const [format, ...args] = msg;\n this.log(format, ...args);\n }\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n console.log = sendLog;\n console.info = sendLog;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\ninterface LoadMetroConfigOptions {\n maxWorkers?: number;\n port?: number;\n reporter?: Reporter;\n resetCache?: boolean;\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadMetroConfigOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? env.EXPO_USE_STICKY_RESOLVER;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (exp.experiments?.reactServerComponentRoutes || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n }\n\n if (exp.experiments?.reactCanary) {\n Log.warn(`React 19 is enabled by default. Remove unused experiments.reactCanary flag.`);\n }\n\n const serverRoot = getMetroServerRoot(projectRoot);\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n // NOTE: Allow external tools to override the metro config. This is considered internal and unstable\n const configPath = env.EXPO_OVERRIDE_METRO_CONFIG ?? undefined;\n const resolvedConfig = await resolveConfig(configPath, projectRoot);\n const defaultConfig = getDefaultConfig(projectRoot);\n\n let config: ConfigT = resolvedConfig.isEmpty\n ? defaultConfig\n : await mergeConfig(defaultConfig, resolvedConfig.config);\n\n // Set the watchfolders to include the projectRoot, as Metro assumes this\n // Force-override the reporter\n config = {\n ...config,\n\n // See: `overrideConfigWithArguments` https://github.com/facebook/metro/blob/5059e26/packages/metro-config/src/loadConfig.js#L274-L339\n // Compare to `LoadOptions` type (disregard `reporter` as we don't expose this)\n resetCache: !!options.resetCache,\n maxWorkers: options.maxWorkers ?? config.maxWorkers,\n server: {\n ...config.server,\n port: options.port ?? config.server.port,\n },\n\n watchFolders: !config.watchFolders.includes(config.projectRoot)\n ? [config.projectRoot, ...config.watchFolders]\n : config.watchFolders,\n reporter: {\n update(event) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n asWritable(config.transformer).publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n asWritable(config.transformer).publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n\n if (exp.experiments?.reactCompiler) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n if (autolinkingModuleResolutionEnabled) {\n Log.warn(`Experimental Expo Autolinking module resolver is enabled.`);\n }\n\n if (serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: !!exp.experiments?.reactServerComponentRoutes,\n getMetroBundler,\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: LoadMetroConfigOptions,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: MetroServer;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n server: http.Server;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler() {\n return metro.getBundler().getBundler();\n },\n });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } =\n createMetroMiddleware(metroConfig);\n\n // Get local URL to Metro bundler server (typically configured as 127.0.0.1:8081)\n const serverBaseUrl = metroBundler\n .getUrlCreator()\n .constructUrl({ scheme: 'http', hostType: 'localhost' });\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware({\n serverBaseUrl,\n reporter,\n });\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n asWritable(metroConfig.server).enhanceMiddleware = (\n metroMiddleware: any,\n server: MetroServer\n ) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n\n const devtoolsWebsocketEndpoints = createDevToolsPluginWebsocketEndpoint({ serverBaseUrl });\n Object.assign(websocketEndpoints, devtoolsWebsocketEndpoints);\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n const { server, hmrServer, metro } = await runServer(\n metroBundler,\n metroConfig,\n {\n websocketEndpoints,\n watch: !isExporting && isWatchEnabled(),\n },\n {\n mockServer: isExporting,\n }\n );\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n projectRoot,\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: MetroServerWithModuleIdMod, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n // TODO(@kitten): Increase type-safety here\n platform: graph.transformOptions.platform!,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle:\n | typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default\n | typeof import('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // TODO: Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (\n this: MetroHmrServerWithModuleIdMod,\n group,\n options,\n changeEvent\n ) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n // TODO(@kitten): Increase type-safety here\n platform: revision.graph.transformOptions.platform!,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const resolvedRouterRoot = path.resolve(projectRoot, routerRoot).split(path.sep).join('/');\n const isRouterRoute = path.isAbsolute(filePath) && filePath.startsWith(resolvedRouterRoot);\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","asWritable","input","LogRespectingTerminal","Terminal","constructor","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","console","info","terminal","process","stdout","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","env","EXPO_USE_STICKY_RESOLVER","serverActionsEnabled","reactServerFunctions","EXPO_UNSTABLE_SERVER_FUNCTIONS","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","warn","serverRoot","getMetroServerRoot","terminalReporter","MetroTerminalReporter","configPath","EXPO_OVERRIDE_METRO_CONFIG","undefined","resolvedConfig","resolveConfig","defaultConfig","getDefaultConfig","isEmpty","mergeConfig","resetCache","maxWorkers","server","port","watchFolders","includes","reporter","update","event","globalThis","__requireCycleIgnorePatterns","resolver","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","serverBaseUrl","getUrlCreator","constructUrl","scheme","hostType","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","devtoolsWebsocketEndpoints","createDevToolsPluginWebsocketEndpoint","attachAtlasAsync","resetAtlasFile","hmrServer","runServer","watch","mockServer","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","path","sort","a","b","hmrJSBundle","require","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","push","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","error","formattedError","messageSocket","split","sep","join","dom","match","routerRoot","isRouterEntry","test","isRouterModule","resolvedRouterRoot","resolve","isRouterRoute","isAbsolute","startsWith","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;IA2NsBA,qBAAqB;eAArBA;;IAsSNC,cAAc;eAAdA;;IAzaMC,oBAAoB;eAApBA;;;;yBAxFqB;;;;;;;yBACR;;;;;;;gEAMD;;;;;;;gEAEF;;;;;;;yBACyB;;;;;;;yBAChC;;;;;;;yBACqC;;;;;;;gEAC5C;;;;;;;gEAED;;;;;;iDAEqC;uCAEhB;6BACL;uCACK;uCACA;+BACZ;wCACkB;qBACxB;qBACA;wBACS;gCACQ;6CACO;2BACV;kCACE;;;;;;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,SAASkE,KAAK,CAAC,yBAAwB,GAClF;QACA,OAAOjE,iBAAiBG,sBAAsB,CAACwE,WAAW;IAC5D;IAEA,IACE3E,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyC4E,gBAAgB,KACzD,2FAA2F;IAC3F,CAAC7E,SAASkE,KAAK,CAAC,8BAChB;QACA,OAAOjE,iBAAiBG,sBAAsB,CAACyE,gBAAgB;IACjE;IAEA,OAAO5E;AACT;AAMO,SAAS/H;IACd,IAAI+B,QAAG,CAAC6K,EAAE,EAAE;QACVrK,QAAG,CAAC3B,GAAG,CACL6D,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAAC1C,QAAG,CAAC6K,EAAE;AAChB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { Reporter } from '@expo/metro/metro';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport MetroHmrServer, { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport RevisionNotFoundError from '@expo/metro/metro/IncrementalBundler/RevisionNotFoundError';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport formatBundlingError from '@expo/metro/metro/lib/formatBundlingError';\nimport { mergeConfig, resolveConfig, type ConfigT } from '@expo/metro/metro-config';\nimport { Terminal } from '@expo/metro/metro-core';\nimport { createStableModuleIdFactory, getDefaultConfig } from '@expo/metro-config';\nimport { FileStore } from '@expo/metro-config/file-store';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// NOTE(@kitten): We pass a custom createStableModuleIdFactory function into the Metro module ID factory sometimes\ninterface MetroServerWithModuleIdMod extends MetroServer {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\ninterface MetroHmrServerWithModuleIdMod extends MetroHmrServer<MetroHmrClient> {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// TODO(@kitten): We assign this here to run server-side code bundled by metro\n// It's not isolated into a worker thread yet\n// Check `metro-require/require.ts` for how this setting is used\ndeclare namespace globalThis {\n let __requireCycleIgnorePatterns: readonly RegExp[] | undefined;\n}\n\nfunction asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\n\n// Wrap terminal and polyfill console.log so we can log during bundling without breaking the indicator.\nclass LogRespectingTerminal extends Terminal {\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream, { ttyPrint: true });\n\n const sendLog = (...msg: any[]) => {\n if (!msg.length) {\n this.log('');\n } else {\n const [format, ...args] = msg;\n this.log(format, ...args);\n }\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n console.log = sendLog;\n console.info = sendLog;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\ninterface LoadMetroConfigOptions {\n maxWorkers?: number;\n port?: number;\n reporter?: Reporter;\n resetCache?: boolean;\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadMetroConfigOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? env.EXPO_USE_STICKY_RESOLVER;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (exp.experiments?.reactServerComponentRoutes || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n }\n\n if (exp.experiments?.reactCanary) {\n Log.warn(`React 19 is enabled by default. Remove unused experiments.reactCanary flag.`);\n }\n\n const serverRoot = getMetroServerRoot(projectRoot);\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n // NOTE: Allow external tools to override the metro config. This is considered internal and unstable\n const configPath = env.EXPO_OVERRIDE_METRO_CONFIG ?? undefined;\n const resolvedConfig = await resolveConfig(configPath, projectRoot);\n const defaultConfig = getDefaultConfig(projectRoot);\n\n let config: ConfigT = resolvedConfig.isEmpty\n ? defaultConfig\n : await mergeConfig(defaultConfig, resolvedConfig.config);\n\n // Set the watchfolders to include the projectRoot, as Metro assumes this\n // Force-override the reporter\n config = {\n ...config,\n\n // See: `overrideConfigWithArguments` https://github.com/facebook/metro/blob/5059e26/packages/metro-config/src/loadConfig.js#L274-L339\n // Compare to `LoadOptions` type (disregard `reporter` as we don't expose this)\n resetCache: !!options.resetCache,\n maxWorkers: options.maxWorkers ?? config.maxWorkers,\n server: {\n ...config.server,\n port: options.port ?? config.server.port,\n },\n\n watchFolders: !config.watchFolders.includes(config.projectRoot)\n ? [config.projectRoot, ...config.watchFolders]\n : config.watchFolders,\n reporter: {\n update(event) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\noverrideExpoMetroCacheStores(config, { projectRoot });\n\n // @ts-expect-error: Set the global require cycle ignore patterns for SSR bundles. This won't work with custom global prefixes, but we don't use those.\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n asWritable(config.transformer).publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n asWritable(config.transformer).publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n\n if (exp.experiments?.reactCompiler) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n if (autolinkingModuleResolutionEnabled) {\n Log.warn(`Experimental Expo Autolinking module resolver is enabled.`);\n }\n\n if (serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: !!exp.experiments?.reactServerComponentRoutes,\n getMetroBundler,\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: LoadMetroConfigOptions,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: MetroServer;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n server: http.Server;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler() {\n return metro.getBundler().getBundler();\n },\n });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } =\n createMetroMiddleware(metroConfig);\n\n // Get local URL to Metro bundler server (typically configured as 127.0.0.1:8081)\n const serverBaseUrl = metroBundler\n .getUrlCreator()\n .constructUrl({ scheme: 'http', hostType: 'localhost' });\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware({\n serverBaseUrl,\n reporter,\n });\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n asWritable(metroConfig.server).enhanceMiddleware = (\n metroMiddleware: any,\n server: MetroServer\n ) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n\n const devtoolsWebsocketEndpoints = createDevToolsPluginWebsocketEndpoint({ serverBaseUrl });\n Object.assign(websocketEndpoints, devtoolsWebsocketEndpoints);\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n const { server, hmrServer, metro } = await runServer(\n metroBundler,\n metroConfig,\n {\n websocketEndpoints,\n watch: !isExporting && isWatchEnabled(),\n },\n {\n mockServer: isExporting,\n }\n );\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n projectRoot,\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: MetroServerWithModuleIdMod, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n // TODO(@kitten): Increase type-safety here\n platform: graph.transformOptions.platform!,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle:\n | typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default\n | typeof import('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // TODO: Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (\n this: MetroHmrServerWithModuleIdMod,\n group,\n options,\n changeEvent\n ) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n // TODO(@kitten): Increase type-safety here\n platform: revision.graph.transformOptions.platform!,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const resolvedRouterRoot = path.resolve(projectRoot, routerRoot).split(path.sep).join('/');\n const isRouterRoute = path.isAbsolute(filePath) && filePath.startsWith(resolvedRouterRoot);\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n\n/**\n * Override the Metro cache stores directory using the EXPO_METRO_CACHE_STORES_DIR environment variable.\n * Exposed for testing.\n */\nexport async function overrideExpoMetroCacheStores(\n config: ConfigT,\n { projectRoot }: { projectRoot: string }\n) {\n if (!env.EXPO_METRO_CACHE_STORES_DIR) {\n return;\n }\n\n // Resolve relative paths to absolute paths based on project root\n const cacheStoresDir = path.isAbsolute(env.EXPO_METRO_CACHE_STORES_DIR)\n ? env.EXPO_METRO_CACHE_STORES_DIR\n : path.resolve(projectRoot, env.EXPO_METRO_CACHE_STORES_DIR);\n\n // Create the directory if it doesn't exist\n try {\n await fs.promises.mkdir(cacheStoresDir, { recursive: true });\n } catch (error: any) {\n if (error.code !== 'EEXIST') {\n Log.error(\n `Provided EXPO_METRO_CACHE_STORES_DIR=\"${cacheStoresDir}\" is not a directory. Use new or existing directory path.`\n );\n throw error;\n }\n }\n\n // Check if user has custom cacheStores in their metro.config.js\n if (config.cacheStores?.length) {\n Log.warn(\n `Using EXPO_METRO_CACHE_STORES_DIR=\"${cacheStoresDir}\" which overrides cacheStores from metro.config.js`\n );\n } else {\n Log.log(chalk.gray(`Using Metro cache directory: ${cacheStoresDir}`));\n }\n\n // Override cacheStores with the env-specified directory\n // @ts-expect-error - cacheStores is a read-only property\n config.cacheStores = [\n new FileStore({\n root: cacheStoresDir,\n }),\n ];\n}\n"],"names":["instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","overrideExpoMetroCacheStores","asWritable","input","LogRespectingTerminal","Terminal","constructor","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","console","info","terminal","process","stdout","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","env","EXPO_USE_STICKY_RESOLVER","serverActionsEnabled","reactServerFunctions","EXPO_UNSTABLE_SERVER_FUNCTIONS","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","warn","serverRoot","getMetroServerRoot","terminalReporter","MetroTerminalReporter","configPath","EXPO_OVERRIDE_METRO_CONFIG","undefined","resolvedConfig","resolveConfig","defaultConfig","getDefaultConfig","isEmpty","mergeConfig","resetCache","maxWorkers","server","port","watchFolders","includes","reporter","update","event","globalThis","__requireCycleIgnorePatterns","resolver","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","serverBaseUrl","getUrlCreator","constructUrl","scheme","hostType","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","devtoolsWebsocketEndpoints","createDevToolsPluginWebsocketEndpoint","attachAtlasAsync","resetAtlasFile","hmrServer","runServer","watch","mockServer","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","path","sort","a","b","hmrJSBundle","require","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","push","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","error","formattedError","messageSocket","split","sep","join","dom","match","routerRoot","isRouterEntry","test","isRouterModule","resolvedRouterRoot","resolve","isRouterRoute","isAbsolute","startsWith","asyncRoutes","clientBoundaries","CI","EXPO_METRO_CACHE_STORES_DIR","cacheStoresDir","fs","promises","mkdir","recursive","code","cacheStores","FileStore","root"],"mappings":";;;;;;;;;;;IAgOsBA,qBAAqB;eAArBA;;IAsSNC,cAAc;eAAdA;;IA5aMC,oBAAoB;eAApBA;;IA0bAC,4BAA4B;eAA5BA;;;;yBAphBqB;;;;;;;yBACR;;;;;;;gEAMD;;;;;;;gEAEF;;;;;;;yBACyB;;;;;;;yBAChC;;;;;;;yBACqC;;;;;;;yBACpC;;;;;;;gEACR;;;;;;;gEAC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R;IACF;IAEA,gEAAgE;IAChE,KAAI/J,sBAAAA,OAAO0L,WAAW,qBAAlB1L,oBAAoBf,MAAM,EAAE;QAC9B4B,QAAG,CAACC,IAAI,CACN,CAAC,mCAAmC,EAAEsK,eAAe,kDAAkD,CAAC;IAE5G,OAAO;QACLvK,QAAG,CAAC3B,GAAG,CAAC6D,gBAAK,CAACC,IAAI,CAAC,CAAC,6BAA6B,EAAEoI,gBAAgB;IACrE;IAEA,wDAAwD;IACxD,yDAAyD;IACzDpL,OAAO0L,WAAW,GAAG;QACnB,IAAIC,CAAAA,YAAQ,WAAC,CAAC;YACZC,MAAMR;QACR;KACD;AACH"}
|
|
@@ -102,11 +102,13 @@ class ExpoGoManifestHandlerMiddleware extends _ManifestMiddleware.ManifestMiddle
|
|
|
102
102
|
break;
|
|
103
103
|
}
|
|
104
104
|
const expectSignature = req.headers['expo-expect-signature'];
|
|
105
|
+
const requestedUrl = (0, _url.parseUrl)(req.headers['host']);
|
|
105
106
|
return {
|
|
106
107
|
responseContentType,
|
|
107
108
|
platform,
|
|
108
109
|
expectSignature: expectSignature ? String(expectSignature) : null,
|
|
109
|
-
hostname:
|
|
110
|
+
hostname: requestedUrl == null ? void 0 : requestedUrl.hostname,
|
|
111
|
+
port: requestedUrl == null ? void 0 : requestedUrl.port,
|
|
110
112
|
protocol: req.headers['x-forwarded-proto']
|
|
111
113
|
};
|
|
112
114
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/ExpoGoManifestHandlerMiddleware.ts"],"sourcesContent":["import { ExpoUpdatesManifest } from '@expo/config';\nimport { Updates } from '@expo/config-plugins';\nimport accepts from 'accepts';\nimport crypto from 'crypto';\nimport { serializeDictionary, Dictionary } from 'structured-headers';\n\nimport { ManifestMiddleware, ManifestRequestInfo } from './ManifestMiddleware';\nimport { assertRuntimePlatform, parsePlatformHeader } from './resolvePlatform';\nimport { resolveRuntimeVersionWithExpoUpdatesAsync } from './resolveRuntimeVersionWithExpoUpdatesAsync';\nimport { ServerHeaders, ServerRequest } from './server.types';\nimport { getAnonymousIdAsync } from '../../../api/user/UserSettings';\nimport { ANONYMOUS_USERNAME } from '../../../api/user/user';\nimport {\n CodeSigningInfo,\n getCodeSigningInfoAsync,\n signManifestString,\n} from '../../../utils/codesigning';\nimport { CommandError } from '../../../utils/errors';\nimport {\n encodeMultipartMixed,\n FormDataField,\n EncodedFormData,\n} from '../../../utils/multipartMixed';\nimport { stripPort } from '../../../utils/url';\n\nconst debug = require('debug')('expo:start:server:middleware:ExpoGoManifestHandlerMiddleware');\n\nexport enum ResponseContentType {\n TEXT_PLAIN,\n APPLICATION_JSON,\n APPLICATION_EXPO_JSON,\n MULTIPART_MIXED,\n}\n\ninterface ExpoGoManifestRequestInfo extends ManifestRequestInfo {\n responseContentType: ResponseContentType;\n expectSignature: string | null;\n}\n\nexport class ExpoGoManifestHandlerMiddleware extends ManifestMiddleware<ExpoGoManifestRequestInfo> {\n public getParsedHeaders(req: ServerRequest): ExpoGoManifestRequestInfo {\n let platform = parsePlatformHeader(req);\n\n if (!platform) {\n debug(\n `No \"expo-platform\" header or \"platform\" query parameter specified. Falling back to \"ios\".`\n );\n platform = 'ios';\n }\n\n assertRuntimePlatform(platform);\n\n // Expo Updates clients explicitly accept \"multipart/mixed\" responses while browsers implicitly\n // accept them with \"accept: */*\". To make it easier to debug manifest responses by visiting their\n // URLs in a browser, we denote the response as \"text/plain\" if the user agent appears not to be\n // an Expo Updates client.\n const accept = accepts(req);\n const acceptedType = accept.types([\n 'unknown/unknown',\n 'multipart/mixed',\n 'application/json',\n 'application/expo+json',\n 'text/plain',\n ]);\n\n let responseContentType;\n switch (acceptedType) {\n case 'multipart/mixed':\n responseContentType = ResponseContentType.MULTIPART_MIXED;\n break;\n case 'application/json':\n responseContentType = ResponseContentType.APPLICATION_JSON;\n break;\n case 'application/expo+json':\n responseContentType = ResponseContentType.APPLICATION_EXPO_JSON;\n break;\n default:\n responseContentType = ResponseContentType.TEXT_PLAIN;\n break;\n }\n\n const expectSignature = req.headers['expo-expect-signature'];\n\n return {\n responseContentType,\n platform,\n expectSignature: expectSignature ? String(expectSignature) : null,\n hostname: stripPort(req.headers['host']),\n protocol: req.headers['x-forwarded-proto'] as 'http' | 'https' | undefined,\n };\n }\n\n private getDefaultResponseHeaders(): ServerHeaders {\n const headers = new Map<string, number | string | readonly string[]>();\n // set required headers for Expo Updates manifest specification\n headers.set('expo-protocol-version', 0);\n headers.set('expo-sfv-version', 0);\n headers.set('cache-control', 'private, max-age=0');\n return headers;\n }\n\n public async _getManifestResponseAsync(requestOptions: ExpoGoManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }> {\n const { exp, hostUri, expoGoConfig, bundleUrl } =\n await this._resolveProjectSettingsAsync(requestOptions);\n\n const runtimeVersion =\n (await resolveRuntimeVersionWithExpoUpdatesAsync({\n projectRoot: this.projectRoot,\n platform: requestOptions.platform,\n })) ??\n // if expo-updates can't determine runtime version, fall back to calculation from config-plugin.\n // this happens when expo-updates is installed but runtimeVersion hasn't yet been configured or when\n // expo-updates is not installed.\n (await Updates.getRuntimeVersionAsync(\n this.projectRoot,\n { ...exp, runtimeVersion: exp.runtimeVersion ?? { policy: 'sdkVersion' } },\n requestOptions.platform\n ));\n if (!runtimeVersion) {\n throw new CommandError(\n 'MANIFEST_MIDDLEWARE',\n `Unable to determine runtime version for platform '${requestOptions.platform}'`\n );\n }\n\n const codeSigningInfo = await getCodeSigningInfoAsync(\n exp,\n requestOptions.expectSignature,\n this.options.privateKeyPath\n );\n\n const easProjectId = exp.extra?.eas?.projectId as string | undefined | null;\n const scopeKey = await ExpoGoManifestHandlerMiddleware.getScopeKeyAsync({\n slug: exp.slug,\n codeSigningInfo,\n });\n\n const expoUpdatesManifest: ExpoUpdatesManifest = {\n id: crypto.randomUUID(),\n createdAt: new Date().toISOString(),\n runtimeVersion,\n launchAsset: {\n key: 'bundle',\n contentType: 'application/javascript',\n url: bundleUrl,\n },\n assets: [], // assets are not used in development\n metadata: {}, // required for the client to detect that this is an expo-updates manifest\n extra: {\n eas: {\n projectId: easProjectId ?? undefined,\n },\n expoClient: {\n ...exp,\n hostUri,\n },\n expoGo: expoGoConfig,\n scopeKey,\n },\n };\n\n const stringifiedManifest = JSON.stringify(expoUpdatesManifest);\n\n let manifestPartHeaders: { 'expo-signature': string } | null = null;\n let certificateChainBody: string | null = null;\n if (codeSigningInfo) {\n const signature = signManifestString(stringifiedManifest, codeSigningInfo);\n manifestPartHeaders = {\n 'expo-signature': serializeDictionary(\n convertToDictionaryItemsRepresentation({\n keyid: codeSigningInfo.keyId,\n sig: signature,\n alg: 'rsa-v1_5-sha256',\n })\n ),\n };\n certificateChainBody = codeSigningInfo.certificateChainForResponse.join('\\n');\n }\n\n const headers = this.getDefaultResponseHeaders();\n\n switch (requestOptions.responseContentType) {\n case ResponseContentType.MULTIPART_MIXED: {\n const encoded = await this.encodeFormDataAsync({\n stringifiedManifest,\n manifestPartHeaders,\n certificateChainBody,\n });\n headers.set('content-type', `multipart/mixed; boundary=${encoded.boundary}`);\n return {\n body: encoded.body,\n version: runtimeVersion,\n headers,\n };\n }\n case ResponseContentType.APPLICATION_EXPO_JSON:\n case ResponseContentType.APPLICATION_JSON:\n case ResponseContentType.TEXT_PLAIN: {\n headers.set(\n 'content-type',\n ExpoGoManifestHandlerMiddleware.getContentTypeForResponseContentType(\n requestOptions.responseContentType\n )\n );\n if (manifestPartHeaders) {\n Object.entries(manifestPartHeaders).forEach(([key, value]) => {\n headers.set(key, value);\n });\n }\n\n return {\n body: stringifiedManifest,\n version: runtimeVersion,\n headers,\n };\n }\n }\n }\n\n private static getContentTypeForResponseContentType(\n responseContentType: ResponseContentType\n ): string {\n switch (responseContentType) {\n case ResponseContentType.MULTIPART_MIXED:\n return 'multipart/mixed';\n case ResponseContentType.APPLICATION_EXPO_JSON:\n return 'application/expo+json';\n case ResponseContentType.APPLICATION_JSON:\n return 'application/json';\n case ResponseContentType.TEXT_PLAIN:\n return 'text/plain';\n }\n }\n\n private encodeFormDataAsync({\n stringifiedManifest,\n manifestPartHeaders,\n certificateChainBody,\n }: {\n stringifiedManifest: string;\n manifestPartHeaders: { 'expo-signature': string } | null;\n certificateChainBody: string | null;\n }): Promise<EncodedFormData> {\n const fields: FormDataField[] = [\n {\n name: 'manifest',\n value: stringifiedManifest,\n contentType: 'application/json',\n partHeaders: manifestPartHeaders,\n },\n ];\n if (certificateChainBody && certificateChainBody.length > 0) {\n fields.push({\n name: 'certificate_chain',\n value: certificateChainBody,\n contentType: 'application/x-pem-file',\n });\n }\n return encodeMultipartMixed(fields);\n }\n\n private static async getScopeKeyAsync({\n slug,\n codeSigningInfo,\n }: {\n slug: string;\n codeSigningInfo: CodeSigningInfo | null;\n }): Promise<string> {\n const scopeKeyFromCodeSigningInfo = codeSigningInfo?.scopeKey;\n if (scopeKeyFromCodeSigningInfo) {\n return scopeKeyFromCodeSigningInfo;\n }\n\n // Log.warn(\n // env.EXPO_OFFLINE\n // ? 'Using anonymous scope key in manifest for offline mode.'\n // : 'Using anonymous scope key in manifest.'\n // );\n return await getAnonymousScopeKeyAsync(slug);\n }\n}\n\nasync function getAnonymousScopeKeyAsync(slug: string): Promise<string> {\n const userAnonymousIdentifier = await getAnonymousIdAsync();\n return `@${ANONYMOUS_USERNAME}/${slug}-${userAnonymousIdentifier}`;\n}\n\nfunction convertToDictionaryItemsRepresentation(obj: { [key: string]: string }): Dictionary {\n return new Map(\n Object.entries(obj).map(([k, v]) => {\n return [k, [v, new Map()]];\n })\n );\n}\n"],"names":["ExpoGoManifestHandlerMiddleware","ResponseContentType","debug","require","ManifestMiddleware","getParsedHeaders","req","platform","parsePlatformHeader","assertRuntimePlatform","accept","accepts","acceptedType","types","responseContentType","expectSignature","headers","String","hostname","stripPort","protocol","getDefaultResponseHeaders","Map","set","_getManifestResponseAsync","requestOptions","exp","hostUri","expoGoConfig","bundleUrl","_resolveProjectSettingsAsync","runtimeVersion","resolveRuntimeVersionWithExpoUpdatesAsync","projectRoot","Updates","getRuntimeVersionAsync","policy","CommandError","codeSigningInfo","getCodeSigningInfoAsync","options","privateKeyPath","easProjectId","extra","eas","projectId","scopeKey","getScopeKeyAsync","slug","expoUpdatesManifest","id","crypto","randomUUID","createdAt","Date","toISOString","launchAsset","key","contentType","url","assets","metadata","undefined","expoClient","expoGo","stringifiedManifest","JSON","stringify","manifestPartHeaders","certificateChainBody","signature","signManifestString","serializeDictionary","convertToDictionaryItemsRepresentation","keyid","keyId","sig","alg","certificateChainForResponse","join","encoded","encodeFormDataAsync","boundary","body","version","getContentTypeForResponseContentType","Object","entries","forEach","value","fields","name","partHeaders","length","push","encodeMultipartMixed","scopeKeyFromCodeSigningInfo","getAnonymousScopeKeyAsync","userAnonymousIdentifier","getAnonymousIdAsync","ANONYMOUS_USERNAME","obj","map","k","v"],"mappings":";;;;;;;;;;;IAuCaA,+BAA+B;eAA/BA;;IAZDC,mBAAmB;eAAnBA;;;;yBA1BY;;;;;;;gEACJ;;;;;;;gEACD;;;;;;;yBAC6B;;;;;;oCAEQ;iCACG;2DACD;8BAEtB;sBACD;6BAK5B;wBACsB;gCAKtB;qBACmB;;;;;;AAE1B,MAAMC,QAAQC,QAAQ,SAAS;AAExB,IAAA,AAAKF,6CAAAA;;;;;WAAAA;;AAYL,MAAMD,wCAAwCI,sCAAkB;IAC9DC,iBAAiBC,GAAkB,EAA6B;QACrE,IAAIC,WAAWC,IAAAA,oCAAmB,EAACF;QAEnC,IAAI,CAACC,UAAU;YACbL,MACE,CAAC,yFAAyF,CAAC;YAE7FK,WAAW;QACb;QAEAE,IAAAA,sCAAqB,EAACF;QAEtB,+FAA+F;QAC/F,kGAAkG;QAClG,gGAAgG;QAChG,0BAA0B;QAC1B,MAAMG,SAASC,IAAAA,kBAAO,EAACL;QACvB,MAAMM,eAAeF,OAAOG,KAAK,CAAC;YAChC;YACA;YACA;YACA;YACA;SACD;QAED,IAAIC;QACJ,OAAQF;YACN,KAAK;gBAC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AK,CAAC,EAAEkD,yBAAyB;AACpE;AAEA,SAASzB,uCAAuC4B,GAA8B;IAC5E,OAAO,IAAI/E,IACTgE,OAAOC,OAAO,CAACc,KAAKC,GAAG,CAAC,CAAC,CAACC,GAAGC,EAAE;QAC7B,OAAO;YAACD;YAAG;gBAACC;gBAAG,IAAIlF;aAAM;SAAC;IAC5B;AAEJ"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/ExpoGoManifestHandlerMiddleware.ts"],"sourcesContent":["import { ExpoUpdatesManifest } from '@expo/config';\nimport { Updates } from '@expo/config-plugins';\nimport accepts from 'accepts';\nimport crypto from 'crypto';\nimport { serializeDictionary, Dictionary } from 'structured-headers';\n\nimport { ManifestMiddleware, ManifestRequestInfo } from './ManifestMiddleware';\nimport { assertRuntimePlatform, parsePlatformHeader } from './resolvePlatform';\nimport { resolveRuntimeVersionWithExpoUpdatesAsync } from './resolveRuntimeVersionWithExpoUpdatesAsync';\nimport { ServerHeaders, ServerRequest } from './server.types';\nimport { getAnonymousIdAsync } from '../../../api/user/UserSettings';\nimport { ANONYMOUS_USERNAME } from '../../../api/user/user';\nimport {\n CodeSigningInfo,\n getCodeSigningInfoAsync,\n signManifestString,\n} from '../../../utils/codesigning';\nimport { CommandError } from '../../../utils/errors';\nimport {\n encodeMultipartMixed,\n FormDataField,\n EncodedFormData,\n} from '../../../utils/multipartMixed';\nimport { parseUrl } from '../../../utils/url';\n\nconst debug = require('debug')('expo:start:server:middleware:ExpoGoManifestHandlerMiddleware');\n\nexport enum ResponseContentType {\n TEXT_PLAIN,\n APPLICATION_JSON,\n APPLICATION_EXPO_JSON,\n MULTIPART_MIXED,\n}\n\ninterface ExpoGoManifestRequestInfo extends ManifestRequestInfo {\n responseContentType: ResponseContentType;\n expectSignature: string | null;\n}\n\nexport class ExpoGoManifestHandlerMiddleware extends ManifestMiddleware<ExpoGoManifestRequestInfo> {\n public getParsedHeaders(req: ServerRequest): ExpoGoManifestRequestInfo {\n let platform = parsePlatformHeader(req);\n\n if (!platform) {\n debug(\n `No \"expo-platform\" header or \"platform\" query parameter specified. Falling back to \"ios\".`\n );\n platform = 'ios';\n }\n\n assertRuntimePlatform(platform);\n\n // Expo Updates clients explicitly accept \"multipart/mixed\" responses while browsers implicitly\n // accept them with \"accept: */*\". To make it easier to debug manifest responses by visiting their\n // URLs in a browser, we denote the response as \"text/plain\" if the user agent appears not to be\n // an Expo Updates client.\n const accept = accepts(req);\n const acceptedType = accept.types([\n 'unknown/unknown',\n 'multipart/mixed',\n 'application/json',\n 'application/expo+json',\n 'text/plain',\n ]);\n\n let responseContentType;\n switch (acceptedType) {\n case 'multipart/mixed':\n responseContentType = ResponseContentType.MULTIPART_MIXED;\n break;\n case 'application/json':\n responseContentType = ResponseContentType.APPLICATION_JSON;\n break;\n case 'application/expo+json':\n responseContentType = ResponseContentType.APPLICATION_EXPO_JSON;\n break;\n default:\n responseContentType = ResponseContentType.TEXT_PLAIN;\n break;\n }\n\n const expectSignature = req.headers['expo-expect-signature'];\n\n const requestedUrl = parseUrl(req.headers['host']);\n\n return {\n responseContentType,\n platform,\n expectSignature: expectSignature ? String(expectSignature) : null,\n hostname: requestedUrl?.hostname,\n port: requestedUrl?.port,\n protocol: req.headers['x-forwarded-proto'] as 'http' | 'https' | undefined,\n };\n }\n\n private getDefaultResponseHeaders(): ServerHeaders {\n const headers = new Map<string, number | string | readonly string[]>();\n // set required headers for Expo Updates manifest specification\n headers.set('expo-protocol-version', 0);\n headers.set('expo-sfv-version', 0);\n headers.set('cache-control', 'private, max-age=0');\n return headers;\n }\n\n public async _getManifestResponseAsync(requestOptions: ExpoGoManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }> {\n const { exp, hostUri, expoGoConfig, bundleUrl } =\n await this._resolveProjectSettingsAsync(requestOptions);\n\n const runtimeVersion =\n (await resolveRuntimeVersionWithExpoUpdatesAsync({\n projectRoot: this.projectRoot,\n platform: requestOptions.platform,\n })) ??\n // if expo-updates can't determine runtime version, fall back to calculation from config-plugin.\n // this happens when expo-updates is installed but runtimeVersion hasn't yet been configured or when\n // expo-updates is not installed.\n (await Updates.getRuntimeVersionAsync(\n this.projectRoot,\n { ...exp, runtimeVersion: exp.runtimeVersion ?? { policy: 'sdkVersion' } },\n requestOptions.platform\n ));\n if (!runtimeVersion) {\n throw new CommandError(\n 'MANIFEST_MIDDLEWARE',\n `Unable to determine runtime version for platform '${requestOptions.platform}'`\n );\n }\n\n const codeSigningInfo = await getCodeSigningInfoAsync(\n exp,\n requestOptions.expectSignature,\n this.options.privateKeyPath\n );\n\n const easProjectId = exp.extra?.eas?.projectId as string | undefined | null;\n const scopeKey = await ExpoGoManifestHandlerMiddleware.getScopeKeyAsync({\n slug: exp.slug,\n codeSigningInfo,\n });\n\n const expoUpdatesManifest: ExpoUpdatesManifest = {\n id: crypto.randomUUID(),\n createdAt: new Date().toISOString(),\n runtimeVersion,\n launchAsset: {\n key: 'bundle',\n contentType: 'application/javascript',\n url: bundleUrl,\n },\n assets: [], // assets are not used in development\n metadata: {}, // required for the client to detect that this is an expo-updates manifest\n extra: {\n eas: {\n projectId: easProjectId ?? undefined,\n },\n expoClient: {\n ...exp,\n hostUri,\n },\n expoGo: expoGoConfig,\n scopeKey,\n },\n };\n\n const stringifiedManifest = JSON.stringify(expoUpdatesManifest);\n\n let manifestPartHeaders: { 'expo-signature': string } | null = null;\n let certificateChainBody: string | null = null;\n if (codeSigningInfo) {\n const signature = signManifestString(stringifiedManifest, codeSigningInfo);\n manifestPartHeaders = {\n 'expo-signature': serializeDictionary(\n convertToDictionaryItemsRepresentation({\n keyid: codeSigningInfo.keyId,\n sig: signature,\n alg: 'rsa-v1_5-sha256',\n })\n ),\n };\n certificateChainBody = codeSigningInfo.certificateChainForResponse.join('\\n');\n }\n\n const headers = this.getDefaultResponseHeaders();\n\n switch (requestOptions.responseContentType) {\n case ResponseContentType.MULTIPART_MIXED: {\n const encoded = await this.encodeFormDataAsync({\n stringifiedManifest,\n manifestPartHeaders,\n certificateChainBody,\n });\n headers.set('content-type', `multipart/mixed; boundary=${encoded.boundary}`);\n return {\n body: encoded.body,\n version: runtimeVersion,\n headers,\n };\n }\n case ResponseContentType.APPLICATION_EXPO_JSON:\n case ResponseContentType.APPLICATION_JSON:\n case ResponseContentType.TEXT_PLAIN: {\n headers.set(\n 'content-type',\n ExpoGoManifestHandlerMiddleware.getContentTypeForResponseContentType(\n requestOptions.responseContentType\n )\n );\n if (manifestPartHeaders) {\n Object.entries(manifestPartHeaders).forEach(([key, value]) => {\n headers.set(key, value);\n });\n }\n\n return {\n body: stringifiedManifest,\n version: runtimeVersion,\n headers,\n };\n }\n }\n }\n\n private static getContentTypeForResponseContentType(\n responseContentType: ResponseContentType\n ): string {\n switch (responseContentType) {\n case ResponseContentType.MULTIPART_MIXED:\n return 'multipart/mixed';\n case ResponseContentType.APPLICATION_EXPO_JSON:\n return 'application/expo+json';\n case ResponseContentType.APPLICATION_JSON:\n return 'application/json';\n case ResponseContentType.TEXT_PLAIN:\n return 'text/plain';\n }\n }\n\n private encodeFormDataAsync({\n stringifiedManifest,\n manifestPartHeaders,\n certificateChainBody,\n }: {\n stringifiedManifest: string;\n manifestPartHeaders: { 'expo-signature': string } | null;\n certificateChainBody: string | null;\n }): Promise<EncodedFormData> {\n const fields: FormDataField[] = [\n {\n name: 'manifest',\n value: stringifiedManifest,\n contentType: 'application/json',\n partHeaders: manifestPartHeaders,\n },\n ];\n if (certificateChainBody && certificateChainBody.length > 0) {\n fields.push({\n name: 'certificate_chain',\n value: certificateChainBody,\n contentType: 'application/x-pem-file',\n });\n }\n return encodeMultipartMixed(fields);\n }\n\n private static async getScopeKeyAsync({\n slug,\n codeSigningInfo,\n }: {\n slug: string;\n codeSigningInfo: CodeSigningInfo | null;\n }): Promise<string> {\n const scopeKeyFromCodeSigningInfo = codeSigningInfo?.scopeKey;\n if (scopeKeyFromCodeSigningInfo) {\n return scopeKeyFromCodeSigningInfo;\n }\n\n // Log.warn(\n // env.EXPO_OFFLINE\n // ? 'Using anonymous scope key in manifest for offline mode.'\n // : 'Using anonymous scope key in manifest.'\n // );\n return await getAnonymousScopeKeyAsync(slug);\n }\n}\n\nasync function getAnonymousScopeKeyAsync(slug: string): Promise<string> {\n const userAnonymousIdentifier = await getAnonymousIdAsync();\n return `@${ANONYMOUS_USERNAME}/${slug}-${userAnonymousIdentifier}`;\n}\n\nfunction convertToDictionaryItemsRepresentation(obj: { [key: string]: string }): Dictionary {\n return new Map(\n Object.entries(obj).map(([k, v]) => {\n return [k, [v, new Map()]];\n })\n );\n}\n"],"names":["ExpoGoManifestHandlerMiddleware","ResponseContentType","debug","require","ManifestMiddleware","getParsedHeaders","req","platform","parsePlatformHeader","assertRuntimePlatform","accept","accepts","acceptedType","types","responseContentType","expectSignature","headers","requestedUrl","parseUrl","String","hostname","port","protocol","getDefaultResponseHeaders","Map","set","_getManifestResponseAsync","requestOptions","exp","hostUri","expoGoConfig","bundleUrl","_resolveProjectSettingsAsync","runtimeVersion","resolveRuntimeVersionWithExpoUpdatesAsync","projectRoot","Updates","getRuntimeVersionAsync","policy","CommandError","codeSigningInfo","getCodeSigningInfoAsync","options","privateKeyPath","easProjectId","extra","eas","projectId","scopeKey","getScopeKeyAsync","slug","expoUpdatesManifest","id","crypto","randomUUID","createdAt","Date","toISOString","launchAsset","key","contentType","url","assets","metadata","undefined","expoClient","expoGo","stringifiedManifest","JSON","stringify","manifestPartHeaders","certificateChainBody","signature","signManifestString","serializeDictionary","convertToDictionaryItemsRepresentation","keyid","keyId","sig","alg","certificateChainForResponse","join","encoded","encodeFormDataAsync","boundary","body","version","getContentTypeForResponseContentType","Object","entries","forEach","value","fields","name","partHeaders","length","push","encodeMultipartMixed","scopeKeyFromCodeSigningInfo","getAnonymousScopeKeyAsync","userAnonymousIdentifier","getAnonymousIdAsync","ANONYMOUS_USERNAME","obj","map","k","v"],"mappings":";;;;;;;;;;;IAuCaA,+BAA+B;eAA/BA;;IAZDC,mBAAmB;eAAnBA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