@expo/cli 0.24.5 → 0.24.6

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 CHANGED
@@ -123,7 +123,7 @@ const args = (0, _arg().default)({
123
123
  });
124
124
  if (args['--version']) {
125
125
  // Version is added in the build script.
126
- console.log("0.24.5");
126
+ console.log("0.24.6");
127
127
  process.exit(0);
128
128
  }
129
129
  if (args['--non-interactive']) {
@@ -614,7 +614,8 @@ class MetroBundlerDevServer extends _BundlerDevServer.BundlerDevServer {
614
614
  targetDomain: 'server',
615
615
  contents: 'module.exports = ' + JSON.stringify(// TODO: Add a less leaky version of this across the framework with just [key, value] (module ID, chunk).
616
616
  Object.fromEntries(Array.from(ssrManifest.entries()).map(([key, value])=>[
617
- _path().default.join(serverRoot, key),
617
+ // Must match babel plugin.
618
+ './' + (0, _filePath.toPosixPath)(_path().default.relative(this.projectRoot, _path().default.join(serverRoot, key))),
618
619
  [
619
620
  key,
620
621
  value
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/MetroBundlerDevServer.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 { ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport * as runtimeEnv from '@expo/env';\nimport { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport assert from 'assert';\nimport chalk from 'chalk';\nimport { DeltaResult, TransformInputOptions } from 'metro';\nimport baseJSBundle from 'metro/src/DeltaBundler/Serializers/baseJSBundle';\nimport {\n sourceMapGeneratorNonBlocking,\n type SourceMapGeneratorOptions,\n} from 'metro/src/DeltaBundler/Serializers/sourceMapGenerator';\nimport type MetroHmrServer from 'metro/src/HmrServer';\nimport type { Client as MetroHmrClient } from 'metro/src/HmrServer';\nimport { GraphRevision } from 'metro/src/IncrementalBundler';\nimport bundleToString from 'metro/src/lib/bundleToString';\nimport getGraphId from 'metro/src/lib/getGraphId';\nimport { TransformProfile } from 'metro-babel-transformer';\nimport type { CustomResolverOptions } from 'metro-resolver/src/types';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport {\n createServerComponentsMiddleware,\n fileURLToFilePath,\n} from './createServerComponentsMiddleware';\nimport { createRouteHandlerMiddleware } from './createServerRouteMiddleware';\nimport { ExpoRouterServerManifestV1, fetchManifest } from './fetchRouterManifest';\nimport { instantiateMetroAsync } from './instantiateMetro';\nimport { getErrorOverlayHtmlAsync, IS_METRO_BUNDLE_ERROR_SYMBOL } from './metroErrorInterface';\nimport { assertMetroPrivateServer, MetroPrivateServer } from './metroPrivateServer';\nimport { metroWatchTypeScriptFiles } from './metroWatchTypeScriptFiles';\nimport {\n getRouterDirectoryModuleIdWithManifest,\n hasWarnedAboutApiRoutes,\n isApiRouteConvention,\n warnInvalidWebOutput,\n} from './router';\nimport { serializeHtmlWithAssets } from './serializeHtml';\nimport { observeAnyFileChanges, observeFileChanges } from './waitForMetroToObserveTypeScriptFile';\nimport { BundleAssetWithFileHashes, ExportAssetMap } from '../../../export/saveAssets';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { getFreePortAsync } from '../../../utils/port';\nimport { BundlerDevServer, BundlerStartOptions, DevServerInstance } from '../BundlerDevServer';\nimport {\n cachedSourceMaps,\n evalMetroAndWrapFunctions,\n evalMetroNoHandling,\n} from '../getStaticRenderFunctions';\nimport { ContextModuleSourceMapsMiddleware } from '../middleware/ContextModuleSourceMapsMiddleware';\nimport { CreateFileMiddleware } from '../middleware/CreateFileMiddleware';\nimport { DevToolsPluginMiddleware } from '../middleware/DevToolsPluginMiddleware';\nimport { createDomComponentsMiddleware } from '../middleware/DomComponentsMiddleware';\nimport { FaviconMiddleware } from '../middleware/FaviconMiddleware';\nimport { HistoryFallbackMiddleware } from '../middleware/HistoryFallbackMiddleware';\nimport { InterstitialPageMiddleware } from '../middleware/InterstitialPageMiddleware';\nimport { resolveMainModuleName } from '../middleware/ManifestMiddleware';\nimport { RuntimeRedirectMiddleware } from '../middleware/RuntimeRedirectMiddleware';\nimport { ServeStaticMiddleware } from '../middleware/ServeStaticMiddleware';\nimport {\n convertPathToModuleSpecifier,\n createBundleUrlPath,\n ExpoMetroOptions,\n createBundleOsPath,\n getAsyncRoutesFromExpoConfig,\n getBaseUrlFromExpoConfig,\n getMetroDirectBundleOptions,\n shouldEnableAsyncImports,\n} from '../middleware/metroOptions';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { startTypescriptTypeGenerationAsync } from '../type-generation/startTypescriptTypeGeneration';\n\nexport type ExpoRouterRuntimeManifest = Awaited<\n ReturnType<typeof import('expo-router/build/static/renderStaticContent').getManifest>\n>;\ntype MetroOnProgress = NonNullable<\n import('metro/src/DeltaBundler/types').Options<void>['onProgress']\n>;\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\ninterface BundleDirectResult {\n numModifiedFiles: number;\n lastModifiedDate: Date;\n nextRevId: string;\n bundle: string;\n map: string;\n /** Defined if the output is multi-bundle. */\n artifacts?: SerialAsset[];\n assets?: readonly BundleAssetWithFileHashes[];\n}\n\ninterface MetroModuleContentsResult extends BundleDirectResult {\n filename: string;\n}\n\ninterface SSRModuleContentsResult extends Omit<BundleDirectResult, 'bundle'> {\n filename: string;\n src: string;\n map: string;\n}\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\n/** Default port to use for apps running in Expo Go. */\nconst EXPO_GO_METRO_PORT = 8081;\n\n/** Default port to use for apps that run in standard React Native projects or Expo Dev Clients. */\nconst DEV_CLIENT_METRO_PORT = 8081;\n\nexport class MetroBundlerDevServer extends BundlerDevServer {\n private metro: MetroPrivateServer | null = null;\n private hmrServer: MetroHmrServer | null = null;\n private ssrHmrClients: Map<string, MetroHmrClient> = new Map();\n isReactServerComponentsEnabled?: boolean;\n isReactServerRoutesEnabled?: boolean;\n\n get name(): string {\n return 'metro';\n }\n\n async resolvePortAsync(options: Partial<BundlerStartOptions> = {}): Promise<number> {\n const port =\n // If the manually defined port is busy then an error should be thrown...\n options.port ??\n // Otherwise use the default port based on the runtime target.\n (options.devClient\n ? // Don't check if the port is busy if we're using the dev client since most clients are hardcoded to 8081.\n Number(process.env.RCT_METRO_PORT) || DEV_CLIENT_METRO_PORT\n : // Otherwise (running in Expo Go) use a free port that falls back on the classic 8081 port.\n await getFreePortAsync(EXPO_GO_METRO_PORT));\n\n return port;\n }\n\n async exportExpoRouterApiRoutesAsync({\n includeSourceMaps,\n outputDir,\n prerenderManifest,\n platform,\n }: {\n includeSourceMaps?: boolean;\n outputDir: string;\n // This does not contain the API routes info.\n prerenderManifest: ExpoRouterServerManifestV1;\n platform: string;\n }): Promise<{ files: ExportAssetMap; manifest: ExpoRouterServerManifestV1<string> }> {\n const { routerRoot } = this.instanceMetroOptions;\n assert(\n routerRoot != null,\n 'The server must be started before calling exportExpoRouterApiRoutesAsync.'\n );\n\n const appDir = path.join(this.projectRoot, routerRoot);\n const manifest = await this.getExpoRouterRoutesManifestAsync({ appDir });\n\n const files: ExportAssetMap = new Map();\n\n // Inject RSC middleware.\n const rscPath = '/_flight/[...rsc]';\n\n if (\n this.isReactServerComponentsEnabled &&\n // If the RSC route is not already in the manifest, add it.\n !manifest.apiRoutes.find((route) => route.page.startsWith('/_flight/'))\n ) {\n debug('Adding RSC route to the manifest:', rscPath);\n // NOTE: This might need to be sorted to the correct spot in the future.\n manifest.apiRoutes.push({\n file: resolveFrom(this.projectRoot, '@expo/cli/static/template/[...rsc]+api.ts'),\n page: rscPath,\n namedRegex: '^/_flight(?:/(?<rsc>.+?))?(?:/)?$',\n routeKeys: { rsc: 'rsc' },\n });\n }\n\n for (const route of manifest.apiRoutes) {\n const filepath = path.isAbsolute(route.file) ? route.file : path.join(appDir, route.file);\n const contents = await this.bundleApiRoute(filepath, { platform });\n\n const artifactFilename =\n route.page === rscPath\n ? // HACK: Add RSC renderer to the output...\n convertPathToModuleSpecifier(path.join(outputDir, '.' + rscPath + '.js'))\n : convertPathToModuleSpecifier(\n path.join(outputDir, path.relative(appDir, filepath.replace(/\\.[tj]sx?$/, '.js')))\n );\n\n if (contents) {\n let src = contents.src;\n\n if (includeSourceMaps && contents.map) {\n // TODO(kitten): Merge the source map transformer in the future\n // https://github.com/expo/expo/blob/0dffdb15/packages/%40expo/metro-config/src/serializer/serializeChunks.ts#L422-L439\n // Alternatively, check whether `sourcesRoot` helps here\n const artifactBasename = encodeURIComponent(path.basename(artifactFilename) + '.map');\n src = src.replace(\n /\\/\\/# sourceMappingURL=.*/g,\n `//# sourceMappingURL=${artifactBasename}`\n );\n\n const parsedMap =\n typeof contents.map === 'string' ? JSON.parse(contents.map) : contents.map;\n files.set(artifactFilename + '.map', {\n contents: JSON.stringify({\n version: parsedMap.version,\n sources: parsedMap.sources.map((source: string) => {\n source =\n typeof source === 'string' && source.startsWith(this.projectRoot)\n ? path.relative(this.projectRoot, source)\n : source;\n return convertPathToModuleSpecifier(source);\n }),\n sourcesContent: new Array(parsedMap.sources.length).fill(null),\n names: parsedMap.names,\n mappings: parsedMap.mappings,\n }),\n apiRouteId: route.page,\n targetDomain: 'server',\n });\n }\n files.set(artifactFilename, {\n contents: src,\n apiRouteId: route.page,\n targetDomain: 'server',\n });\n }\n // Remap the manifest files to represent the output files.\n route.file = artifactFilename;\n }\n\n return {\n manifest: {\n ...manifest,\n htmlRoutes: prerenderManifest.htmlRoutes,\n },\n files,\n };\n }\n\n async getExpoRouterRoutesManifestAsync({ appDir }: { appDir: string }) {\n // getBuiltTimeServerManifest\n const { exp } = getConfig(this.projectRoot);\n const manifest = await fetchManifest(this.projectRoot, {\n ...exp.extra?.router,\n preserveRedirectAndRewrites: true,\n asJson: true,\n appDir,\n });\n\n if (!manifest) {\n throw new CommandError(\n 'EXPO_ROUTER_SERVER_MANIFEST',\n 'Unexpected error: server manifest could not be fetched.'\n );\n }\n\n return manifest;\n }\n\n async getServerManifestAsync(): Promise<{\n serverManifest: ExpoRouterServerManifestV1;\n htmlManifest: ExpoRouterRuntimeManifest;\n }> {\n const { exp } = getConfig(this.projectRoot);\n // NOTE: This could probably be folded back into `renderStaticContent` when expo-asset and font support RSC.\n const { getBuildTimeServerManifestAsync, getManifest } = await this.ssrLoadModule<\n typeof import('expo-router/build/static/getServerManifest')\n >('expo-router/build/static/getServerManifest.js', {\n // Only use react-server environment when the routes are using react-server rendering by default.\n environment: this.isReactServerRoutesEnabled ? 'react-server' : 'node',\n });\n\n return {\n serverManifest: await getBuildTimeServerManifestAsync({ ...exp.extra?.router }),\n htmlManifest: await getManifest({ ...exp.extra?.router }),\n };\n }\n\n async getStaticRenderFunctionAsync(): Promise<{\n serverManifest: ExpoRouterServerManifestV1;\n manifest: ExpoRouterRuntimeManifest;\n renderAsync: (path: string) => Promise<string>;\n }> {\n const url = this.getDevServerUrlOrAssert();\n\n const { getStaticContent, getManifest, getBuildTimeServerManifestAsync } =\n await this.ssrLoadModule<typeof import('expo-router/build/static/renderStaticContent')>(\n 'expo-router/node/render.js',\n {\n // This must always use the legacy rendering resolution (no `react-server`) because it leverages\n // the previous React SSG utilities which aren't available in React 19.\n environment: 'node',\n }\n );\n\n const { exp } = getConfig(this.projectRoot);\n\n return {\n serverManifest: await getBuildTimeServerManifestAsync({\n ...exp.extra?.router,\n }),\n // Get routes from Expo Router.\n manifest: await getManifest({ preserveApiRoutes: false, ...exp.extra?.router }),\n // Get route generating function\n async renderAsync(path: string) {\n return await getStaticContent(new URL(path, url));\n },\n };\n }\n\n async getStaticResourcesAsync({\n includeSourceMaps,\n mainModuleName,\n clientBoundaries = this.instanceMetroOptions.clientBoundaries ?? [],\n platform = 'web',\n }: {\n includeSourceMaps?: boolean;\n mainModuleName?: string;\n clientBoundaries?: string[];\n platform?: string;\n } = {}) {\n const { mode, minify, isExporting, baseUrl, reactCompiler, routerRoot, asyncRoutes } =\n this.instanceMetroOptions;\n assert(\n mode != null &&\n isExporting != null &&\n baseUrl != null &&\n routerRoot != null &&\n reactCompiler != null &&\n asyncRoutes != null,\n 'The server must be started before calling getStaticResourcesAsync.'\n );\n\n const resolvedMainModuleName =\n mainModuleName ?? './' + resolveMainModuleName(this.projectRoot, { platform });\n return await this.metroImportAsArtifactsAsync(resolvedMainModuleName, {\n splitChunks: isExporting && !env.EXPO_NO_BUNDLE_SPLITTING,\n platform,\n mode,\n minify,\n environment: 'client',\n serializerIncludeMaps: includeSourceMaps,\n mainModuleName: resolvedMainModuleName,\n lazy: shouldEnableAsyncImports(this.projectRoot),\n asyncRoutes,\n baseUrl,\n isExporting,\n routerRoot,\n clientBoundaries,\n reactCompiler,\n bytecode: false,\n });\n }\n\n private async getStaticPageAsync(pathname: string) {\n const { mode, isExporting, clientBoundaries, baseUrl, reactCompiler, routerRoot, asyncRoutes } =\n this.instanceMetroOptions;\n assert(\n mode != null &&\n isExporting != null &&\n baseUrl != null &&\n reactCompiler != null &&\n routerRoot != null &&\n asyncRoutes != null,\n 'The server must be started before calling getStaticPageAsync.'\n );\n const platform = 'web';\n\n const devBundleUrlPathname = createBundleUrlPath({\n splitChunks: isExporting && !env.EXPO_NO_BUNDLE_SPLITTING,\n platform,\n mode,\n environment: 'client',\n reactCompiler,\n mainModuleName: resolveMainModuleName(this.projectRoot, { platform }),\n lazy: shouldEnableAsyncImports(this.projectRoot),\n baseUrl,\n isExporting,\n asyncRoutes,\n routerRoot,\n clientBoundaries,\n bytecode: false,\n });\n\n const bundleStaticHtml = async (): Promise<string> => {\n const { getStaticContent } = await this.ssrLoadModule<\n typeof import('expo-router/build/static/renderStaticContent')\n >('expo-router/node/render.js', {\n // This must always use the legacy rendering resolution (no `react-server`) because it leverages\n // the previous React SSG utilities which aren't available in React 19.\n environment: 'node',\n minify: false,\n isExporting,\n platform,\n });\n\n const location = new URL(pathname, this.getDevServerUrlOrAssert());\n return await getStaticContent(location);\n };\n\n const [{ artifacts: resources }, staticHtml] = await Promise.all([\n this.getStaticResourcesAsync({\n clientBoundaries: [],\n }),\n bundleStaticHtml(),\n ]);\n const content = serializeHtmlWithAssets({\n isExporting,\n resources,\n template: staticHtml,\n devBundleUrl: devBundleUrlPathname,\n baseUrl,\n hydrate: env.EXPO_WEB_DEV_HYDRATE,\n });\n return {\n content,\n resources,\n };\n }\n\n // Set when the server is started.\n private instanceMetroOptions: Partial<ExpoMetroOptions> = {};\n\n private ssrLoadModule: SSRLoadModuleFunc = async (\n filePath,\n specificOptions = {},\n extras = {}\n ) => {\n const res = await this.ssrLoadModuleContents(filePath, specificOptions);\n\n if (\n // TODO: hot should be a callback function for invalidating the related SSR module.\n extras.hot &&\n this.instanceMetroOptions.isExporting !== true\n ) {\n // Register SSR HMR\n const serverRoot = getMetroServerRoot(this.projectRoot);\n const relativePath = path.relative(serverRoot, res.filename);\n const url = new URL(relativePath, this.getDevServerUrlOrAssert());\n this.setupHmr(url);\n }\n\n return evalMetroAndWrapFunctions(\n this.projectRoot,\n res.src,\n res.filename,\n specificOptions.isExporting ?? this.instanceMetroOptions.isExporting!\n );\n };\n\n private async metroImportAsArtifactsAsync(\n filePath: string,\n specificOptions: Partial<Omit<ExpoMetroOptions, 'serializerOutput'>> = {}\n ) {\n const results = await this.ssrLoadModuleContents(filePath, {\n serializerOutput: 'static',\n ...specificOptions,\n });\n\n // NOTE: This could potentially need more validation in the future.\n if (results.artifacts && results.assets) {\n return {\n artifacts: results.artifacts,\n assets: results.assets,\n src: results.src,\n filename: results.filename,\n map: results.map,\n };\n }\n throw new CommandError('Invalid bundler results: ' + results);\n }\n\n private async metroLoadModuleContents(\n filePath: string,\n specificOptions: ExpoMetroOptions,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<MetroModuleContentsResult> {\n const { baseUrl } = this.instanceMetroOptions;\n assert(baseUrl != null, 'The server must be started before calling metroLoadModuleContents.');\n\n const opts: ExpoMetroOptions = {\n // TODO: Possibly issues with using an absolute path here...\n // mainModuleName: filePath,\n lazy: false,\n asyncRoutes: false,\n inlineSourceMap: false,\n engine: 'hermes',\n minify: false,\n // bytecode: false,\n // Bundle in Node.js mode for SSR.\n environment: 'node',\n // platform: 'web',\n // mode: 'development',\n //\n ...this.instanceMetroOptions,\n baseUrl,\n // routerRoot,\n // isExporting,\n ...specificOptions,\n };\n\n const expoBundleOptions = getMetroDirectBundleOptions(opts);\n\n const resolverOptions = {\n customResolverOptions: expoBundleOptions.customResolverOptions ?? {},\n dev: expoBundleOptions.dev ?? true,\n };\n\n const transformOptions: TransformInputOptions = {\n dev: expoBundleOptions.dev ?? true,\n hot: true,\n minify: expoBundleOptions.minify ?? false,\n type: 'module',\n unstable_transformProfile:\n extraOptions.unstable_transformProfile ??\n expoBundleOptions.unstable_transformProfile ??\n 'default',\n customTransformOptions: expoBundleOptions.customTransformOptions ?? Object.create(null),\n platform: expoBundleOptions.platform ?? 'web',\n // @ts-expect-error: `runtimeBytecodeVersion` does not exist in `expoBundleOptions` or `TransformInputOptions`\n runtimeBytecodeVersion: expoBundleOptions.runtimeBytecodeVersion,\n };\n\n const resolvedEntryFilePath = await this.resolveRelativePathAsync(filePath, {\n resolverOptions,\n transformOptions,\n });\n\n const filename = createBundleOsPath({\n ...opts,\n mainModuleName: resolvedEntryFilePath,\n });\n\n // https://github.com/facebook/metro/blob/2405f2f6c37a1b641cc379b9c733b1eff0c1c2a1/packages/metro/src/lib/parseOptionsFromUrl.js#L55-L87\n const results = await this._bundleDirectAsync(resolvedEntryFilePath, {\n graphOptions: {\n lazy: expoBundleOptions.lazy ?? false,\n shallow: expoBundleOptions.shallow ?? false,\n },\n resolverOptions,\n serializerOptions: {\n ...expoBundleOptions.serializerOptions,\n\n inlineSourceMap: expoBundleOptions.inlineSourceMap ?? false,\n modulesOnly: expoBundleOptions.modulesOnly ?? false,\n runModule: expoBundleOptions.runModule ?? true,\n // @ts-expect-error\n sourceUrl: expoBundleOptions.sourceUrl,\n // @ts-expect-error\n sourceMapUrl: extraOptions.sourceMapUrl ?? expoBundleOptions.sourceMapUrl,\n },\n transformOptions,\n });\n\n return {\n ...results,\n filename,\n };\n }\n\n private async ssrLoadModuleContents(\n filePath: string,\n specificOptions: Partial<ExpoMetroOptions> = {}\n ): Promise<SSRModuleContentsResult> {\n const { baseUrl, routerRoot, isExporting } = this.instanceMetroOptions;\n assert(\n baseUrl != null && routerRoot != null && isExporting != null,\n 'The server must be started before calling ssrLoadModuleContents.'\n );\n\n const opts: ExpoMetroOptions = {\n // TODO: Possibly issues with using an absolute path here...\n mainModuleName: convertPathToModuleSpecifier(filePath),\n lazy: false,\n asyncRoutes: false,\n inlineSourceMap: false,\n engine: 'hermes',\n minify: false,\n bytecode: false,\n // Bundle in Node.js mode for SSR unless RSC is enabled.\n environment: this.isReactServerComponentsEnabled ? 'react-server' : 'node',\n platform: 'web',\n mode: 'development',\n //\n ...this.instanceMetroOptions,\n\n // Mostly disable compiler in SSR bundles.\n reactCompiler: false,\n baseUrl,\n routerRoot,\n isExporting,\n\n ...specificOptions,\n };\n\n // https://github.com/facebook/metro/blob/2405f2f6c37a1b641cc379b9c733b1eff0c1c2a1/packages/metro/src/lib/parseOptionsFromUrl.js#L55-L87\n const { filename, bundle, map, ...rest } = await this.metroLoadModuleContents(filePath, opts);\n const scriptContents = wrapBundle(bundle);\n\n if (map) {\n debug('Registering SSR source map for:', filename);\n cachedSourceMaps.set(filename, { url: this.projectRoot, map });\n } else {\n debug('No SSR source map found for:', filename);\n }\n\n return {\n ...rest,\n src: scriptContents,\n filename,\n map,\n };\n }\n\n async nativeExportBundleAsync(\n exp: ExpoConfig,\n options: Omit<\n ExpoMetroOptions,\n 'routerRoot' | 'asyncRoutes' | 'isExporting' | 'serializerOutput' | 'environment'\n >,\n files: ExportAssetMap,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<{\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n files?: ExportAssetMap;\n }> {\n if (this.isReactServerComponentsEnabled) {\n return this.singlePageReactServerComponentExportAsync(exp, options, files, extraOptions);\n }\n\n return this.legacySinglePageExportBundleAsync(options, extraOptions);\n }\n\n private async singlePageReactServerComponentExportAsync(\n exp: ExpoConfig,\n options: Omit<\n ExpoMetroOptions,\n 'baseUrl' | 'routerRoot' | 'asyncRoutes' | 'isExporting' | 'serializerOutput' | 'environment'\n >,\n files: ExportAssetMap,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<{\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n files: ExportAssetMap;\n }> {\n const getReactServerReferences = (artifacts: SerialAsset[]): string[] => {\n // Get the React server action boundaries from the client bundle.\n return unique(\n artifacts\n .filter((a) => a.type === 'js')\n .map((artifact) =>\n artifact.metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref))\n )\n // TODO: Segment by module for splitting.\n .flat()\n .filter(Boolean) as string[]\n );\n };\n\n // NOTE(EvanBacon): This will not support any code elimination since it's a static pass.\n let {\n reactClientReferences: clientBoundaries,\n reactServerReferences: serverActionReferencesInServer,\n cssModules,\n } = await this.rscRenderer!.getExpoRouterClientReferencesAsync(\n {\n platform: options.platform,\n domRoot: options.domRoot,\n },\n files\n );\n\n // TODO: The output keys should be in production format or use a lookup manifest.\n\n const processClientBoundaries = async (\n reactServerReferences: string[]\n ): Promise<{\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n }> => {\n debug('Evaluated client boundaries:', clientBoundaries);\n\n // Run metro bundler and create the JS bundles/source maps.\n const bundle = await this.legacySinglePageExportBundleAsync(\n {\n ...options,\n clientBoundaries,\n },\n extraOptions\n );\n\n // Get the React server action boundaries from the client bundle.\n const newReactServerReferences = getReactServerReferences(bundle.artifacts);\n\n if (!newReactServerReferences) {\n // Possible issue with babel plugin / metro-config.\n throw new Error(\n 'Static server action references were not returned from the Metro client bundle'\n );\n }\n debug('React server action boundaries from client:', newReactServerReferences);\n\n const allKnownReactServerReferences = unique([\n ...reactServerReferences,\n ...newReactServerReferences,\n ]);\n\n // When we export the server actions that were imported from the client, we may need to re-bundle the client with the new client boundaries.\n const { clientBoundaries: nestedClientBoundaries } =\n await this.rscRenderer!.exportServerActionsAsync(\n {\n platform: options.platform,\n domRoot: options.domRoot,\n entryPoints: allKnownReactServerReferences,\n },\n files\n );\n\n // TODO: Check against all modules in the initial client bundles.\n const hasUniqueClientBoundaries = nestedClientBoundaries.some(\n (boundary) => !clientBoundaries.includes(boundary)\n );\n\n if (!hasUniqueClientBoundaries) {\n return bundle;\n }\n\n debug('Re-bundling client with nested client boundaries:', nestedClientBoundaries);\n\n clientBoundaries = unique(clientBoundaries.concat(nestedClientBoundaries));\n\n // Re-bundle the client with the new client boundaries that only exist in server actions that were imported from the client.\n // Run metro bundler and create the JS bundles/source maps.\n return processClientBoundaries(allKnownReactServerReferences);\n };\n\n const bundle = await processClientBoundaries(serverActionReferencesInServer);\n\n // Inject the global CSS that was imported during the server render.\n bundle.artifacts.push(...cssModules);\n\n const serverRoot = getMetroServerRoot(this.projectRoot);\n\n // HACK: Maybe this should be done in the serializer.\n const clientBoundariesAsOpaqueIds = clientBoundaries.map((boundary) =>\n // NOTE(cedric): relative module specifiers / IDs should always be POSIX formatted\n toPosixPath(path.relative(serverRoot, boundary))\n );\n const moduleIdToSplitBundle = (\n bundle.artifacts\n .map((artifact) => artifact?.metadata?.paths && Object.values(artifact.metadata.paths))\n .filter(Boolean)\n .flat() as Record<string, string>[]\n ).reduce((acc, paths) => ({ ...acc, ...paths }), {});\n\n debug('SSR Manifest:', moduleIdToSplitBundle, clientBoundariesAsOpaqueIds);\n\n const ssrManifest = new Map<string, string>();\n\n if (Object.keys(moduleIdToSplitBundle).length) {\n clientBoundariesAsOpaqueIds.forEach((boundary) => {\n if (boundary in moduleIdToSplitBundle) {\n ssrManifest.set(boundary, moduleIdToSplitBundle[boundary]);\n } else {\n throw new Error(\n `Could not find boundary \"${boundary}\" in the SSR manifest. Available: ${Object.keys(moduleIdToSplitBundle).join(', ')}`\n );\n }\n });\n } else {\n // Native apps with bundle splitting disabled.\n debug('No split bundles');\n clientBoundariesAsOpaqueIds.forEach((boundary) => {\n // @ts-expect-error\n ssrManifest.set(boundary, null);\n });\n }\n\n const routerOptions = exp.extra?.router;\n\n // Export the static RSC files\n await this.rscRenderer!.exportRoutesAsync(\n {\n platform: options.platform,\n ssrManifest,\n routerOptions,\n },\n files\n );\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/${options.platform}/ssr-manifest.js`, {\n targetDomain: 'server',\n contents:\n 'module.exports = ' +\n JSON.stringify(\n // TODO: Add a less leaky version of this across the framework with just [key, value] (module ID, chunk).\n Object.fromEntries(\n Array.from(ssrManifest.entries()).map(([key, value]) => [\n path.join(serverRoot, key),\n [key, value],\n ])\n )\n ),\n });\n\n return { ...bundle, files };\n }\n\n async legacySinglePageExportBundleAsync(\n options: Omit<\n ExpoMetroOptions,\n 'routerRoot' | 'asyncRoutes' | 'isExporting' | 'serializerOutput' | 'environment'\n >,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<{ artifacts: SerialAsset[]; assets: readonly BundleAssetWithFileHashes[] }> {\n const { baseUrl, routerRoot, isExporting } = this.instanceMetroOptions;\n assert(options.mainModuleName != null, 'mainModuleName must be provided in options.');\n assert(\n baseUrl != null && routerRoot != null && isExporting != null,\n 'The server must be started before calling legacySinglePageExportBundleAsync.'\n );\n\n const opts: ExpoMetroOptions = {\n ...this.instanceMetroOptions,\n baseUrl,\n routerRoot,\n isExporting,\n ...options,\n environment: 'client',\n serializerOutput: 'static',\n };\n\n // https://github.com/facebook/metro/blob/2405f2f6c37a1b641cc379b9c733b1eff0c1c2a1/packages/metro/src/lib/parseOptionsFromUrl.js#L55-L87\n if (!opts.mainModuleName.startsWith('/') && !path.isAbsolute(opts.mainModuleName)) {\n opts.mainModuleName = './' + opts.mainModuleName;\n }\n\n const output = await this.metroLoadModuleContents(opts.mainModuleName, opts, extraOptions);\n\n return {\n artifacts: output.artifacts!,\n assets: output.assets!,\n };\n }\n\n async watchEnvironmentVariables() {\n if (!this.instance) {\n throw new Error(\n 'Cannot observe environment variable changes without a running Metro instance.'\n );\n }\n if (!this.metro) {\n // This can happen when the run command is used and the server is already running in another\n // process.\n debug('Skipping Environment Variable observation because Metro is not running (headless).');\n return;\n }\n\n const envFiles = runtimeEnv\n .getFiles(process.env.NODE_ENV)\n .map((fileName) => path.join(this.projectRoot, fileName));\n\n observeFileChanges(\n {\n metro: this.metro,\n server: this.instance.server,\n },\n envFiles,\n () => {\n debug('Reloading environment variables...');\n // Force reload the environment variables.\n runtimeEnv.load(this.projectRoot, { force: true });\n }\n );\n }\n\n rscRenderer: Awaited<ReturnType<typeof createServerComponentsMiddleware>> | null = null;\n\n protected async startImplementationAsync(\n options: BundlerStartOptions\n ): Promise<DevServerInstance> {\n options.port = await this.resolvePortAsync(options);\n this.urlCreator = this.getUrlCreator(options);\n\n const config = getConfig(this.projectRoot, { skipSDKVersionRequirement: true });\n const { exp } = config;\n // NOTE: This will change in the future when it's less experimental, we enable React 19, and turn on more RSC flags by default.\n const isReactServerComponentsEnabled =\n !!exp.experiments?.reactServerComponentRoutes || !!exp.experiments?.reactServerFunctions;\n const isReactServerActionsOnlyEnabled =\n !exp.experiments?.reactServerComponentRoutes && !!exp.experiments?.reactServerFunctions;\n this.isReactServerComponentsEnabled = isReactServerComponentsEnabled;\n this.isReactServerRoutesEnabled = !!exp.experiments?.reactServerComponentRoutes;\n\n const useServerRendering = ['static', 'server'].includes(exp.web?.output ?? '');\n const hasApiRoutes = isReactServerComponentsEnabled || exp.web?.output === 'server';\n const baseUrl = getBaseUrlFromExpoConfig(exp);\n const asyncRoutes = getAsyncRoutesFromExpoConfig(exp, options.mode ?? 'development', 'web');\n const routerRoot = getRouterDirectoryModuleIdWithManifest(this.projectRoot, exp);\n const reactCompiler = !!exp.experiments?.reactCompiler;\n const appDir = path.join(this.projectRoot, routerRoot);\n const mode = options.mode ?? 'development';\n\n const routerOptions = exp.extra?.router;\n\n if (isReactServerComponentsEnabled && exp.web?.output === 'static') {\n throw new CommandError(\n `Experimental server component support does not support 'web.output: ${exp.web!.output}' yet. Use 'web.output: \"server\"' during the experimental phase.`\n );\n }\n\n // Error early about the window.location polyfill when React Server Components are enabled.\n if (isReactServerComponentsEnabled && exp?.extra?.router?.origin === false) {\n const configPath = config.dynamicConfigPath ?? config.staticConfigPath ?? '/app.json';\n const configFileName = path.basename(configPath);\n throw new CommandError(\n `The Expo Router \"origin\" property in the Expo config (${configFileName}) cannot be \"false\" when React Server Components is enabled. Remove it from the ${configFileName} file and try again.`\n );\n }\n\n const instanceMetroOptions = {\n isExporting: !!options.isExporting,\n baseUrl,\n mode,\n routerRoot,\n reactCompiler,\n minify: options.minify,\n asyncRoutes,\n // Options that are changing between platforms like engine, platform, and environment aren't set here.\n };\n this.instanceMetroOptions = instanceMetroOptions;\n\n const parsedOptions = {\n port: options.port,\n maxWorkers: options.maxWorkers,\n resetCache: options.resetDevServer,\n };\n\n // Required for symbolication:\n process.env.EXPO_DEV_SERVER_ORIGIN = `http://localhost:${options.port}`;\n\n const { metro, hmrServer, server, middleware, messageSocket } = await instantiateMetroAsync(\n this,\n parsedOptions,\n {\n isExporting: !!options.isExporting,\n exp,\n }\n );\n\n if (!options.isExporting) {\n const manifestMiddleware = await this.getManifestMiddlewareAsync(options);\n\n // Important that we noop source maps for context modules as soon as possible.\n prependMiddleware(middleware, new ContextModuleSourceMapsMiddleware().getHandler());\n\n // We need the manifest handler to be the first middleware to run so our\n // routes take precedence over static files. For example, the manifest is\n // served from '/' and if the user has an index.html file in their project\n // then the manifest handler will never run, the static middleware will run\n // and serve index.html instead of the manifest.\n // https://github.com/expo/expo/issues/13114\n prependMiddleware(middleware, manifestMiddleware.getHandler());\n\n middleware.use(\n new InterstitialPageMiddleware(this.projectRoot, {\n // TODO: Prevent this from becoming stale.\n scheme: options.location.scheme ?? null,\n }).getHandler()\n );\n middleware.use(\n new DevToolsPluginMiddleware(this.projectRoot, this.devToolsPluginManager).getHandler()\n );\n\n const deepLinkMiddleware = new RuntimeRedirectMiddleware(this.projectRoot, {\n getLocation: ({ runtime }) => {\n if (runtime === 'custom') {\n return this.urlCreator?.constructDevClientUrl();\n } else {\n return this.urlCreator?.constructUrl({\n scheme: 'exp',\n });\n }\n },\n });\n middleware.use(deepLinkMiddleware.getHandler());\n\n const serverRoot = getMetroServerRoot(this.projectRoot);\n\n const domComponentRenderer = createDomComponentsMiddleware(\n {\n metroRoot: serverRoot,\n projectRoot: this.projectRoot,\n },\n instanceMetroOptions\n );\n // Add support for DOM components.\n // TODO: Maybe put behind a flag for now?\n middleware.use(domComponentRenderer);\n\n middleware.use(new CreateFileMiddleware(this.projectRoot).getHandler());\n\n // Append support for redirecting unhandled requests to the index.html page on web.\n if (this.isTargetingWeb()) {\n // This MUST be after the manifest middleware so it doesn't have a chance to serve the template `public/index.html`.\n middleware.use(new ServeStaticMiddleware(this.projectRoot).getHandler());\n\n // This should come after the static middleware so it doesn't serve the favicon from `public/favicon.ico`.\n middleware.use(new FaviconMiddleware(this.projectRoot).getHandler());\n }\n\n if (useServerRendering || isReactServerComponentsEnabled) {\n observeAnyFileChanges(\n {\n metro,\n server,\n },\n (events) => {\n if (hasApiRoutes) {\n // NOTE(EvanBacon): We aren't sure what files the API routes are using so we'll just invalidate\n // aggressively to ensure we always have the latest. The only caching we really get here is for\n // cases where the user is making subsequent requests to the same API route without changing anything.\n // This is useful for testing but pretty suboptimal. Luckily our caching is pretty aggressive so it makes\n // up for a lot of the overhead.\n this.invalidateApiRouteCache();\n } else if (!hasWarnedAboutApiRoutes()) {\n for (const event of events) {\n if (\n // If the user did not delete a file that matches the Expo Router API Route convention, then we should warn that\n // API Routes are not enabled in the project.\n event.metadata?.type !== 'd' &&\n // Ensure the file is in the project's routes directory to prevent false positives in monorepos.\n event.filePath.startsWith(appDir) &&\n isApiRouteConvention(event.filePath)\n ) {\n warnInvalidWebOutput();\n }\n }\n }\n }\n );\n }\n\n // If React 19 is enabled, then add RSC middleware to the dev server.\n if (isReactServerComponentsEnabled) {\n this.bindRSCDevModuleInjectionHandler();\n const rscMiddleware = createServerComponentsMiddleware(this.projectRoot, {\n instanceMetroOptions: this.instanceMetroOptions,\n rscPath: '/_flight',\n ssrLoadModule: this.ssrLoadModule.bind(this),\n ssrLoadModuleArtifacts: this.metroImportAsArtifactsAsync.bind(this),\n useClientRouter: isReactServerActionsOnlyEnabled,\n createModuleId: metro._createModuleId.bind(metro),\n routerOptions,\n });\n this.rscRenderer = rscMiddleware;\n middleware.use(rscMiddleware.middleware);\n this.onReloadRscEvent = rscMiddleware.onReloadRscEvent;\n }\n\n // Append support for redirecting unhandled requests to the index.html page on web.\n if (this.isTargetingWeb()) {\n if (!useServerRendering) {\n // This MUST run last since it's the fallback.\n middleware.use(\n new HistoryFallbackMiddleware(manifestMiddleware.getHandler().internal).getHandler()\n );\n } else {\n middleware.use(\n createRouteHandlerMiddleware(this.projectRoot, {\n appDir,\n routerRoot,\n config,\n ...config.exp.extra?.router,\n bundleApiRoute: (functionFilePath) =>\n this.ssrImportApiRoute(functionFilePath, { platform: 'web' }),\n getStaticPageAsync: async (pathname) => {\n // TODO: Add server rendering when RSC is enabled.\n if (isReactServerComponentsEnabled) {\n // NOTE: This is a temporary hack to return the SPA/template index.html in development when RSC is enabled.\n // While this technically works, it doesn't provide the correct experience of server rendering the React code to HTML first.\n const html = await manifestMiddleware.getSingleHtmlTemplateAsync();\n return { content: html };\n }\n\n // Non-RSC apps will bundle the static HTML for a given pathname and respond with it.\n return this.getStaticPageAsync(pathname);\n },\n })\n );\n }\n }\n } else {\n // If React 19 is enabled, then add RSC middleware to the dev server.\n if (isReactServerComponentsEnabled) {\n this.bindRSCDevModuleInjectionHandler();\n const rscMiddleware = createServerComponentsMiddleware(this.projectRoot, {\n instanceMetroOptions: this.instanceMetroOptions,\n rscPath: '/_flight',\n ssrLoadModule: this.ssrLoadModule.bind(this),\n ssrLoadModuleArtifacts: this.metroImportAsArtifactsAsync.bind(this),\n useClientRouter: isReactServerActionsOnlyEnabled,\n createModuleId: metro._createModuleId.bind(metro),\n routerOptions,\n });\n this.rscRenderer = rscMiddleware;\n }\n }\n // Extend the close method to ensure that we clean up the local info.\n const originalClose = server.close.bind(server);\n\n server.close = (callback?: (err?: Error) => void) => {\n return originalClose((err?: Error) => {\n this.instance = null;\n this.metro = null;\n this.hmrServer = null;\n this.ssrHmrClients = new Map();\n callback?.(err);\n });\n };\n\n assertMetroPrivateServer(metro);\n this.metro = metro;\n this.hmrServer = hmrServer;\n return {\n server,\n location: {\n // The port is the main thing we want to send back.\n port: options.port,\n // localhost isn't always correct.\n host: 'localhost',\n // http is the only supported protocol on native.\n url: `http://localhost:${options.port}`,\n protocol: 'http',\n },\n middleware,\n messageSocket,\n };\n }\n\n private onReloadRscEvent: ((platform: string) => void) | null = null;\n\n private async registerSsrHmrAsync(url: string, onReload: (platform: string[]) => void) {\n if (!this.hmrServer || this.ssrHmrClients.has(url)) {\n return;\n }\n\n debug('[SSR] Register HMR:', url);\n\n const sendFn = (message: string) => {\n const data = JSON.parse(String(message)) as { type: string; body: any };\n\n switch (data.type) {\n case 'bundle-registered':\n case 'update-done':\n case 'update-start':\n break;\n case 'update':\n {\n const update = data.body;\n const {\n isInitialUpdate,\n added,\n modified,\n deleted,\n }: {\n isInitialUpdate?: boolean;\n added: {\n module: [number | string, string];\n sourceURL: string;\n sourceMappingURL: string;\n }[];\n modified: {\n module: [number | string, string];\n sourceURL: string;\n sourceMappingURL: string;\n }[];\n deleted: (number | string)[];\n } = update;\n\n const hasUpdate = added.length || modified.length || deleted.length;\n\n // NOTE: We throw away the updates and instead simply send a trigger to the client to re-fetch the server route.\n if (!isInitialUpdate && hasUpdate) {\n // Clear all SSR modules before sending the reload event. This ensures that the next event will rebuild the in-memory state from scratch.\n // @ts-expect-error\n if (typeof globalThis.__c === 'function') globalThis.__c();\n\n const allModuleIds = new Set(\n [...added, ...modified].map((m) => m.module[0]).concat(deleted)\n );\n\n const platforms = unique(\n Array.from(allModuleIds)\n .map((moduleId) => {\n if (typeof moduleId !== 'string') {\n return null;\n }\n // Extract platforms from the module IDs.\n return moduleId.match(/[?&]platform=([\\w]+)/)?.[1] ?? null;\n })\n .filter(Boolean)\n ) as string[];\n\n onReload(platforms);\n }\n }\n break;\n case 'error':\n // GraphNotFound can mean that we have an issue in metroOptions where the URL doesn't match the object props.\n Log.error('[SSR] HMR Error: ' + JSON.stringify(data, null, 2));\n\n if (data.body?.type === 'GraphNotFoundError') {\n Log.error(\n 'Available SSR HMR keys:',\n // @ts-expect-error\n (this.metro?._bundler._revisionsByGraphId as Map).keys()\n );\n }\n break;\n default:\n debug('Unknown HMR message:', data);\n break;\n }\n };\n\n const client = await this.hmrServer!.onClientConnect(url, sendFn);\n this.ssrHmrClients.set(url, client);\n // Opt in...\n client.optedIntoHMR = true;\n await this.hmrServer!._registerEntryPoint(client, url, sendFn);\n }\n\n public async waitForTypeScriptAsync(): Promise<boolean> {\n if (!this.instance) {\n throw new Error('Cannot wait for TypeScript without a running server.');\n }\n\n return new Promise<boolean>((resolve) => {\n if (!this.metro) {\n // This can happen when the run command is used and the server is already running in another\n // process. In this case we can't wait for the TypeScript check to complete because we don't\n // have access to the Metro server.\n debug('Skipping TypeScript check because Metro is not running (headless).');\n return resolve(false);\n }\n\n const off = metroWatchTypeScriptFiles({\n projectRoot: this.projectRoot,\n server: this.instance!.server,\n metro: this.metro,\n tsconfig: true,\n throttle: true,\n eventTypes: ['change', 'add'],\n callback: async () => {\n // Run once, this prevents the TypeScript project prerequisite from running on every file change.\n off();\n const { TypeScriptProjectPrerequisite } = await import(\n '../../doctor/typescript/TypeScriptProjectPrerequisite.js'\n );\n\n try {\n const req = new TypeScriptProjectPrerequisite(this.projectRoot);\n await req.bootstrapAsync();\n resolve(true);\n } catch (error: any) {\n // Ensure the process doesn't fail if the TypeScript check fails.\n // This could happen during the install.\n Log.log();\n Log.error(\n chalk.red`Failed to automatically setup TypeScript for your project. Try restarting the dev server to fix.`\n );\n Log.exception(error);\n resolve(false);\n }\n },\n });\n });\n }\n\n public async startTypeScriptServices() {\n return startTypescriptTypeGenerationAsync({\n server: this.instance?.server,\n metro: this.metro,\n projectRoot: this.projectRoot,\n });\n }\n\n protected getConfigModuleIds(): string[] {\n return ['./metro.config.js', './metro.config.json', './rn-cli.config.js'];\n }\n\n // API Routes\n\n private pendingRouteOperations = new Map<string, Promise<SSRModuleContentsResult | null>>();\n\n // Bundle the API Route with Metro and return the string contents to be evaluated in the server.\n private async bundleApiRoute(\n filePath: string,\n { platform }: { platform: string }\n ): Promise<SSRModuleContentsResult | null | undefined> {\n if (this.pendingRouteOperations.has(filePath)) {\n return this.pendingRouteOperations.get(filePath);\n }\n const bundleAsync = async (): Promise<SSRModuleContentsResult> => {\n try {\n debug('Bundle API route:', this.instanceMetroOptions.routerRoot, filePath);\n return await this.ssrLoadModuleContents(filePath, {\n isExporting: this.instanceMetroOptions.isExporting,\n platform,\n });\n } catch (error: any) {\n const appDir = this.instanceMetroOptions?.routerRoot\n ? path.join(this.projectRoot, this.instanceMetroOptions!.routerRoot!)\n : undefined;\n const relativePath = appDir ? path.relative(appDir, filePath) : filePath;\n\n // Expected errors: invalid syntax, missing resolutions.\n // Wrap with command error for better error messages.\n const err = new CommandError(\n 'API_ROUTE',\n chalk`Failed to bundle API Route: {bold ${relativePath}}\\n\\n` + error.message\n );\n\n for (const key in error) {\n // @ts-expect-error\n err[key] = error[key];\n }\n\n throw err;\n } finally {\n // pendingRouteOperations.delete(filepath);\n }\n };\n const route = bundleAsync();\n\n this.pendingRouteOperations.set(filePath, route);\n return route;\n }\n\n private async ssrImportApiRoute(\n filePath: string,\n { platform }: { platform: string }\n ): Promise<null | Record<string, Function> | Response> {\n // TODO: Cache the evaluated function.\n try {\n const apiRoute = await this.bundleApiRoute(filePath, { platform });\n\n if (!apiRoute?.src) {\n return null;\n }\n return evalMetroNoHandling(this.projectRoot, apiRoute.src, apiRoute.filename);\n } catch (error) {\n // Format any errors that were thrown in the global scope of the evaluation.\n if (error instanceof Error) {\n try {\n const htmlServerError = await getErrorOverlayHtmlAsync({\n error,\n projectRoot: this.projectRoot,\n routerRoot: this.instanceMetroOptions.routerRoot!,\n });\n\n return new Response(htmlServerError, {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n });\n } catch (internalError) {\n debug('Failed to generate Metro server error UI for API Route error:', internalError);\n throw error;\n }\n } else {\n throw error;\n }\n }\n }\n\n private invalidateApiRouteCache() {\n this.pendingRouteOperations.clear();\n }\n\n // Ensure the global is available for SSR CSS modules to inject client updates.\n private bindRSCDevModuleInjectionHandler() {\n // Used by SSR CSS modules to broadcast client updates.\n // @ts-expect-error\n globalThis.__expo_rsc_inject_module = this.sendClientModule.bind(this);\n }\n\n // NOTE: This can only target a single platform at a time (web).\n // used for sending RSC CSS to the root client in development.\n private sendClientModule({ code, id }: { code: string; id: string }) {\n this.broadcastMessage('sendDevCommand', {\n name: 'module-import',\n data: {\n code,\n id,\n },\n });\n }\n\n // Metro HMR\n\n private setupHmr(url: URL) {\n const onReload = (platforms: string[] = []) => {\n // Send reload command to client from Fast Refresh code.\n\n if (!platforms.length) {\n // TODO: When is this called?\n this.broadcastMessage('sendDevCommand', {\n name: 'rsc-reload',\n });\n } else {\n for (const platform of platforms) {\n this.onReloadRscEvent?.(platform);\n this.broadcastMessage('sendDevCommand', {\n name: 'rsc-reload',\n platform,\n });\n }\n }\n };\n\n this.registerSsrHmrAsync(url.toString(), onReload);\n }\n\n // Direct Metro access\n\n // Emulates the Metro dev server .bundle endpoint without having to go through a server.\n private async _bundleDirectAsync(\n resolvedEntryFilePath: string,\n {\n transformOptions,\n resolverOptions,\n graphOptions,\n serializerOptions,\n }: {\n transformOptions: TransformInputOptions;\n resolverOptions: {\n customResolverOptions: CustomResolverOptions;\n dev: boolean;\n };\n serializerOptions: {\n modulesOnly: boolean;\n runModule: boolean;\n sourceMapUrl: string;\n sourceUrl: string;\n inlineSourceMap: boolean;\n excludeSource: boolean;\n };\n graphOptions: {\n shallow: boolean;\n lazy: boolean;\n };\n }\n ): Promise<BundleDirectResult> {\n assert(this.metro, 'Metro server must be running to bundle directly.');\n const config = this.metro._config;\n const buildNumber = this.metro.getNewBuildNumber();\n const bundlePerfLogger = config.unstable_perfLoggerFactory?.('BUNDLING_REQUEST', {\n key: buildNumber,\n });\n\n const onProgress: MetroOnProgress = (transformedFileCount: number, totalFileCount: number) => {\n this.metro?._reporter?.update?.({\n buildID: getBuildID(buildNumber),\n type: 'bundle_transform_progressed',\n transformedFileCount,\n totalFileCount,\n });\n };\n\n const revPromise = this.getMetroRevision(resolvedEntryFilePath, {\n graphOptions,\n transformOptions,\n resolverOptions,\n });\n\n bundlePerfLogger?.point('resolvingAndTransformingDependencies_start');\n bundlePerfLogger?.annotate({\n bool: {\n initial_build: revPromise == null,\n },\n });\n this.metro?._reporter.update({\n buildID: getBuildID(buildNumber),\n bundleDetails: {\n bundleType: transformOptions.type,\n dev: transformOptions.dev,\n entryFile: resolvedEntryFilePath,\n minify: transformOptions.minify,\n platform: transformOptions.platform,\n customResolverOptions: resolverOptions.customResolverOptions,\n customTransformOptions: transformOptions.customTransformOptions ?? {},\n },\n isPrefetch: false,\n type: 'bundle_build_started',\n });\n\n try {\n let delta: DeltaResult;\n let revision: GraphRevision;\n\n // TODO: Some bug in Metro/RSC causes this to break when changing imports in server components.\n // We should resolve the bug because it results in ~6x faster bundling to reuse the graph revision.\n if (transformOptions.customTransformOptions?.environment === 'react-server') {\n const props = await this.metro.getBundler().initializeGraph(\n // NOTE: Using absolute path instead of relative input path is a breaking change.\n // entryFile,\n resolvedEntryFilePath,\n\n transformOptions,\n resolverOptions,\n {\n onProgress,\n shallow: graphOptions.shallow,\n lazy: graphOptions.lazy,\n }\n );\n delta = props.delta;\n revision = props.revision;\n } else {\n const props = await (revPromise != null\n ? this.metro.getBundler().updateGraph(await revPromise, false)\n : this.metro.getBundler().initializeGraph(\n // NOTE: Using absolute path instead of relative input path is a breaking change.\n // entryFile,\n resolvedEntryFilePath,\n\n transformOptions,\n resolverOptions,\n {\n onProgress,\n shallow: graphOptions.shallow,\n lazy: graphOptions.lazy,\n }\n ));\n delta = props.delta;\n revision = props.revision;\n }\n\n bundlePerfLogger?.annotate({\n int: {\n graph_node_count: revision.graph.dependencies.size,\n },\n });\n bundlePerfLogger?.point('resolvingAndTransformingDependencies_end');\n bundlePerfLogger?.point('serializingBundle_start');\n\n const shouldAddToIgnoreList = this.metro._shouldAddModuleToIgnoreList.bind(this.metro);\n\n const serializer = this.getMetroSerializer();\n\n const bundle = await serializer(\n // NOTE: Using absolute path instead of relative input path is a breaking change.\n // entryFile,\n resolvedEntryFilePath,\n\n revision.prepend as any,\n revision.graph as any,\n {\n asyncRequireModulePath: await this.metro._resolveRelativePath(\n config.transformer.asyncRequireModulePath,\n {\n relativeTo: 'project',\n resolverOptions,\n transformOptions,\n }\n ),\n // ...serializerOptions,\n processModuleFilter: config.serializer.processModuleFilter,\n createModuleId: this.metro._createModuleId,\n getRunModuleStatement: config.serializer.getRunModuleStatement,\n includeAsyncPaths: graphOptions.lazy,\n dev: transformOptions.dev,\n projectRoot: config.projectRoot,\n modulesOnly: serializerOptions.modulesOnly,\n runBeforeMainModule: config.serializer.getModulesRunBeforeMainModule(\n resolvedEntryFilePath\n // path.relative(config.projectRoot, entryFile)\n ),\n runModule: serializerOptions.runModule,\n sourceMapUrl: serializerOptions.sourceMapUrl,\n sourceUrl: serializerOptions.sourceUrl,\n inlineSourceMap: serializerOptions.inlineSourceMap,\n serverRoot: config.server.unstable_serverRoot ?? config.projectRoot,\n shouldAddToIgnoreList,\n\n // @ts-expect-error: passed to our serializer to enable non-serial return values.\n serializerOptions,\n }\n );\n\n this.metro._reporter.update({\n buildID: getBuildID(buildNumber),\n type: 'bundle_build_done',\n });\n\n bundlePerfLogger?.point('serializingBundle_end');\n\n let bundleCode: string | null = null;\n let bundleMap: string | null = null;\n\n // @ts-expect-error: If the output is multi-bundle...\n if (serializerOptions.output === 'static') {\n try {\n const parsed = typeof bundle === 'string' ? JSON.parse(bundle) : bundle;\n\n assert(\n 'artifacts' in parsed && Array.isArray(parsed.artifacts),\n 'Expected serializer to return an object with key artifacts to contain an array of serial assets.'\n );\n\n const artifacts = parsed.artifacts as SerialAsset[];\n const assets = parsed.assets;\n\n const bundleCode = artifacts.filter((asset) => asset.type === 'js')[0];\n const bundleMap = artifacts.filter((asset) => asset.type === 'map')?.[0]?.source ?? '';\n\n return {\n numModifiedFiles: delta.reset\n ? delta.added.size + revision.prepend.length\n : delta.added.size + delta.modified.size + delta.deleted.size,\n lastModifiedDate: revision.date,\n nextRevId: revision.id,\n bundle: bundleCode.source,\n map: bundleMap,\n artifacts,\n assets,\n };\n } catch (error: any) {\n throw new Error(\n 'Serializer did not return expected format. The project copy of `expo/metro-config` may be out of date. Error: ' +\n error.message\n );\n }\n }\n\n if (typeof bundle === 'string') {\n bundleCode = bundle;\n\n // Create the source map in a second pass...\n let { prepend, graph } = revision;\n if (serializerOptions.modulesOnly) {\n prepend = [];\n }\n\n bundleMap = await sourceMapStringAsync(\n [\n //\n ...prepend,\n ...this.metro._getSortedModules(graph),\n ],\n {\n excludeSource: serializerOptions.excludeSource,\n processModuleFilter: config.serializer.processModuleFilter,\n shouldAddToIgnoreList,\n }\n );\n } else {\n bundleCode = bundle.code;\n bundleMap = bundle.map;\n }\n\n return {\n numModifiedFiles: delta.reset\n ? delta.added.size + revision.prepend.length\n : delta.added.size + delta.modified.size + delta.deleted.size,\n lastModifiedDate: revision.date,\n nextRevId: revision.id,\n bundle: bundleCode,\n map: bundleMap,\n };\n } catch (error) {\n // Mark the error so we know how to format and return it later.\n // @ts-expect-error\n error[IS_METRO_BUNDLE_ERROR_SYMBOL] = true;\n\n this.metro._reporter.update({\n buildID: getBuildID(buildNumber),\n type: 'bundle_build_failed',\n });\n\n throw error;\n }\n }\n\n private getMetroSerializer() {\n return (\n this.metro?._config?.serializer.customSerializer ||\n ((entryPoint, preModules, graph, options) =>\n bundleToString(baseJSBundle(entryPoint, preModules, graph, options)).code)\n );\n }\n\n private getMetroRevision(\n resolvedEntryFilePath: string,\n {\n graphOptions,\n transformOptions,\n resolverOptions,\n }: {\n transformOptions: TransformInputOptions;\n resolverOptions: {\n customResolverOptions: CustomResolverOptions;\n dev: boolean;\n };\n graphOptions: {\n shallow: boolean;\n lazy: boolean;\n };\n }\n ) {\n assert(this.metro, 'Metro server must be running to bundle directly.');\n const config = this.metro._config;\n\n const graphId = getGraphId(resolvedEntryFilePath, transformOptions, {\n unstable_allowRequireContext: config.transformer.unstable_allowRequireContext,\n resolverOptions,\n shallow: graphOptions.shallow,\n lazy: graphOptions.lazy,\n });\n return this.metro.getBundler().getRevisionByGraphId(graphId);\n }\n\n private async resolveRelativePathAsync(\n moduleId: string,\n {\n resolverOptions,\n transformOptions,\n }: {\n transformOptions: TransformInputOptions;\n resolverOptions: {\n customResolverOptions: CustomResolverOptions;\n dev: boolean;\n };\n }\n ) {\n assert(this.metro, 'cannot invoke resolveRelativePathAsync without metro instance');\n return await this.metro._resolveRelativePath(convertPathToModuleSpecifier(moduleId), {\n relativeTo: 'server',\n resolverOptions,\n transformOptions,\n });\n }\n}\n\nfunction getBuildID(buildNumber: number): string {\n return buildNumber.toString(36);\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\nasync function sourceMapStringAsync(\n modules: readonly import('metro/src/DeltaBundler/types').Module<any>[],\n options: SourceMapGeneratorOptions\n): Promise<string> {\n return (await sourceMapGeneratorNonBlocking(modules, options)).toString(undefined, {\n excludeSource: options.excludeSource,\n });\n}\n\nfunction unique<T>(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n"],"names":["MetroBundlerDevServer","debug","require","EXPO_GO_METRO_PORT","DEV_CLIENT_METRO_PORT","BundlerDevServer","name","resolvePortAsync","options","port","devClient","Number","process","env","RCT_METRO_PORT","getFreePortAsync","exportExpoRouterApiRoutesAsync","includeSourceMaps","outputDir","prerenderManifest","platform","routerRoot","instanceMetroOptions","assert","appDir","path","join","projectRoot","manifest","getExpoRouterRoutesManifestAsync","files","Map","rscPath","isReactServerComponentsEnabled","apiRoutes","find","route","page","startsWith","push","file","resolveFrom","namedRegex","routeKeys","rsc","filepath","isAbsolute","contents","bundleApiRoute","artifactFilename","convertPathToModuleSpecifier","relative","replace","src","map","artifactBasename","encodeURIComponent","basename","parsedMap","JSON","parse","set","stringify","version","sources","source","sourcesContent","Array","length","fill","names","mappings","apiRouteId","targetDomain","htmlRoutes","exp","getConfig","fetchManifest","extra","router","preserveRedirectAndRewrites","asJson","CommandError","getServerManifestAsync","getBuildTimeServerManifestAsync","getManifest","ssrLoadModule","environment","isReactServerRoutesEnabled","serverManifest","htmlManifest","getStaticRenderFunctionAsync","url","getDevServerUrlOrAssert","getStaticContent","preserveApiRoutes","renderAsync","URL","getStaticResourcesAsync","mainModuleName","clientBoundaries","mode","minify","isExporting","baseUrl","reactCompiler","asyncRoutes","resolvedMainModuleName","resolveMainModuleName","metroImportAsArtifactsAsync","splitChunks","EXPO_NO_BUNDLE_SPLITTING","serializerIncludeMaps","lazy","shouldEnableAsyncImports","bytecode","getStaticPageAsync","pathname","devBundleUrlPathname","createBundleUrlPath","bundleStaticHtml","location","artifacts","resources","staticHtml","Promise","all","content","serializeHtmlWithAssets","template","devBundleUrl","hydrate","EXPO_WEB_DEV_HYDRATE","filePath","specificOptions","results","ssrLoadModuleContents","serializerOutput","assets","filename","metroLoadModuleContents","extraOptions","opts","inlineSourceMap","engine","expoBundleOptions","getMetroDirectBundleOptions","resolverOptions","customResolverOptions","dev","transformOptions","hot","type","unstable_transformProfile","customTransformOptions","Object","create","runtimeBytecodeVersion","resolvedEntryFilePath","resolveRelativePathAsync","createBundleOsPath","_bundleDirectAsync","graphOptions","shallow","serializerOptions","modulesOnly","runModule","sourceUrl","sourceMapUrl","bundle","rest","scriptContents","wrapBundle","cachedSourceMaps","nativeExportBundleAsync","singlePageReactServerComponentExportAsync","legacySinglePageExportBundleAsync","getReactServerReferences","unique","filter","a","artifact","metadata","reactServerReferences","ref","fileURLToFilePath","flat","Boolean","reactClientReferences","serverActionReferencesInServer","cssModules","rscRenderer","getExpoRouterClientReferencesAsync","domRoot","processClientBoundaries","newReactServerReferences","Error","allKnownReactServerReferences","nestedClientBoundaries","exportServerActionsAsync","entryPoints","hasUniqueClientBoundaries","some","boundary","includes","concat","serverRoot","getMetroServerRoot","clientBoundariesAsOpaqueIds","toPosixPath","moduleIdToSplitBundle","paths","values","reduce","acc","ssrManifest","keys","forEach","routerOptions","exportRoutesAsync","fromEntries","from","entries","key","value","output","watchEnvironmentVariables","instance","metro","envFiles","runtimeEnv","getFiles","NODE_ENV","fileName","observeFileChanges","server","load","force","startImplementationAsync","urlCreator","getUrlCreator","config","skipSDKVersionRequirement","experiments","reactServerComponentRoutes","reactServerFunctions","isReactServerActionsOnlyEnabled","useServerRendering","web","hasApiRoutes","getBaseUrlFromExpoConfig","getAsyncRoutesFromExpoConfig","getRouterDirectoryModuleIdWithManifest","origin","configPath","dynamicConfigPath","staticConfigPath","configFileName","parsedOptions","maxWorkers","resetCache","resetDevServer","EXPO_DEV_SERVER_ORIGIN","hmrServer","middleware","messageSocket","instantiateMetroAsync","manifestMiddleware","getManifestMiddlewareAsync","prependMiddleware","ContextModuleSourceMapsMiddleware","getHandler","use","InterstitialPageMiddleware","scheme","DevToolsPluginMiddleware","devToolsPluginManager","deepLinkMiddleware","RuntimeRedirectMiddleware","getLocation","runtime","constructDevClientUrl","constructUrl","domComponentRenderer","createDomComponentsMiddleware","metroRoot","CreateFileMiddleware","isTargetingWeb","ServeStaticMiddleware","FaviconMiddleware","observeAnyFileChanges","events","invalidateApiRouteCache","hasWarnedAboutApiRoutes","event","isApiRouteConvention","warnInvalidWebOutput","bindRSCDevModuleInjectionHandler","rscMiddleware","createServerComponentsMiddleware","bind","ssrLoadModuleArtifacts","useClientRouter","createModuleId","_createModuleId","onReloadRscEvent","HistoryFallbackMiddleware","internal","createRouteHandlerMiddleware","functionFilePath","ssrImportApiRoute","html","getSingleHtmlTemplateAsync","originalClose","close","callback","err","ssrHmrClients","assertMetroPrivateServer","host","protocol","registerSsrHmrAsync","onReload","has","sendFn","message","data","String","update","body","isInitialUpdate","added","modified","deleted","hasUpdate","globalThis","__c","allModuleIds","Set","m","module","platforms","moduleId","match","Log","error","_bundler","_revisionsByGraphId","client","onClientConnect","optedIntoHMR","_registerEntryPoint","waitForTypeScriptAsync","resolve","off","metroWatchTypeScriptFiles","tsconfig","throttle","eventTypes","TypeScriptProjectPrerequisite","req","bootstrapAsync","log","chalk","red","exception","startTypeScriptServices","startTypescriptTypeGenerationAsync","getConfigModuleIds","pendingRouteOperations","get","bundleAsync","undefined","relativePath","apiRoute","evalMetroNoHandling","htmlServerError","getErrorOverlayHtmlAsync","Response","status","headers","internalError","clear","__expo_rsc_inject_module","sendClientModule","code","id","broadcastMessage","setupHmr","toString","_config","buildNumber","getNewBuildNumber","bundlePerfLogger","unstable_perfLoggerFactory","onProgress","transformedFileCount","totalFileCount","_reporter","buildID","getBuildID","revPromise","getMetroRevision","point","annotate","bool","initial_build","bundleDetails","bundleType","entryFile","isPrefetch","delta","revision","props","getBundler","initializeGraph","updateGraph","int","graph_node_count","graph","dependencies","size","shouldAddToIgnoreList","_shouldAddModuleToIgnoreList","serializer","getMetroSerializer","prepend","asyncRequireModulePath","_resolveRelativePath","transformer","relativeTo","processModuleFilter","getRunModuleStatement","includeAsyncPaths","runBeforeMainModule","getModulesRunBeforeMainModule","unstable_serverRoot","bundleCode","bundleMap","parsed","isArray","asset","numModifiedFiles","reset","lastModifiedDate","date","nextRevId","sourceMapStringAsync","_getSortedModules","excludeSource","IS_METRO_BUNDLE_ERROR_SYMBOL","customSerializer","entryPoint","preModules","bundleToString","baseJSBundle","graphId","getGraphId","unstable_allowRequireContext","getRevisionByGraphId","extras","res","evalMetroAndWrapFunctions","str","modules","sourceMapGeneratorNonBlocking","array"],"mappings":"AAAA;;;;;CAKC;;;;+BAqHYA;;;eAAAA;;;;yBApHyB;;;;;;;yBACH;;;;;;;iEACP;;;;;;;gEAET;;;;;;;gEACD;;;;;;;gEAEO;;;;;;;yBAIlB;;;;;;;gEAIoB;;;;;;;gEACJ;;;;;;;gEAGN;;;;;;;gEACO;;;;;;kDAKjB;6CACsC;qCACa;kCACpB;qCACiC;oCACV;2CACnB;wBAMnC;+BACiC;qDACkB;qBAEtC;sBACA;wBACS;0BACD;sBACK;kCACwC;0CAKlE;mDAC2C;sCACb;0CACI;yCACK;mCACZ;2CACQ;4CACC;oCACL;2CACI;uCACJ;8BAU/B;2BAC2B;+CACiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCnD,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,qDAAqD,GACrD,MAAMC,qBAAqB;AAE3B,iGAAiG,GACjG,MAAMC,wBAAwB;AAEvB,MAAMJ,8BAA8BK,kCAAgB;IAOzD,IAAIC,OAAe;QACjB,OAAO;IACT;IAEA,MAAMC,iBAAiBC,UAAwC,CAAC,CAAC,EAAmB;QAClF,MAAMC,OACJ,yEAAyE;QACzED,QAAQC,IAAI,IACZ,8DAA8D;QAC7DD,CAAAA,QAAQE,SAAS,GAEdC,OAAOC,QAAQC,GAAG,CAACC,cAAc,KAAKV,wBAEtC,MAAMW,IAAAA,sBAAgB,EAACZ,mBAAkB;QAE/C,OAAOM;IACT;IAEA,MAAMO,+BAA+B,EACnCC,iBAAiB,EACjBC,SAAS,EACTC,iBAAiB,E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EACPwZ,IAAIlU,QAAQ,EACZL,gBAAgB/B,WAAW,IAAI,IAAI,CAACjF,oBAAoB,CAACiF,WAAW;QAExE,QA2bAwF,cAAmF,WAwQ3EkH,mBAAwD,MAwJhE,aAAa;aAELgE,yBAAyB,IAAIlV;;AAmcvC;AAEA,SAASiX,WAAWT,WAAmB;IACrC,OAAOA,YAAYF,QAAQ,CAAC;AAC9B;AAEA,SAASzN,WAAWmS,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAI3Z,OAAO,CAAC,oBAAoB;AACzC;AAEA,eAAe2Y,qBACbiB,OAAsE,EACtExc,OAAkC;IAElC,OAAO,AAAC,CAAA,MAAMyc,IAAAA,mDAA6B,EAACD,SAASxc,QAAO,EAAG6X,QAAQ,CAACjB,WAAW;QACjF6E,eAAezb,QAAQyb,aAAa;IACtC;AACF;AAEA,SAAS/Q,OAAUgS,KAAU;IAC3B,OAAO/Y,MAAM0J,IAAI,CAAC,IAAIqH,IAAIgI;AAC5B"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/MetroBundlerDevServer.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 { ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport * as runtimeEnv from '@expo/env';\nimport { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport assert from 'assert';\nimport chalk from 'chalk';\nimport { DeltaResult, TransformInputOptions } from 'metro';\nimport baseJSBundle from 'metro/src/DeltaBundler/Serializers/baseJSBundle';\nimport {\n sourceMapGeneratorNonBlocking,\n type SourceMapGeneratorOptions,\n} from 'metro/src/DeltaBundler/Serializers/sourceMapGenerator';\nimport type MetroHmrServer from 'metro/src/HmrServer';\nimport type { Client as MetroHmrClient } from 'metro/src/HmrServer';\nimport { GraphRevision } from 'metro/src/IncrementalBundler';\nimport bundleToString from 'metro/src/lib/bundleToString';\nimport getGraphId from 'metro/src/lib/getGraphId';\nimport { TransformProfile } from 'metro-babel-transformer';\nimport type { CustomResolverOptions } from 'metro-resolver/src/types';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport {\n createServerComponentsMiddleware,\n fileURLToFilePath,\n} from './createServerComponentsMiddleware';\nimport { createRouteHandlerMiddleware } from './createServerRouteMiddleware';\nimport { ExpoRouterServerManifestV1, fetchManifest } from './fetchRouterManifest';\nimport { instantiateMetroAsync } from './instantiateMetro';\nimport { getErrorOverlayHtmlAsync, IS_METRO_BUNDLE_ERROR_SYMBOL } from './metroErrorInterface';\nimport { assertMetroPrivateServer, MetroPrivateServer } from './metroPrivateServer';\nimport { metroWatchTypeScriptFiles } from './metroWatchTypeScriptFiles';\nimport {\n getRouterDirectoryModuleIdWithManifest,\n hasWarnedAboutApiRoutes,\n isApiRouteConvention,\n warnInvalidWebOutput,\n} from './router';\nimport { serializeHtmlWithAssets } from './serializeHtml';\nimport { observeAnyFileChanges, observeFileChanges } from './waitForMetroToObserveTypeScriptFile';\nimport { BundleAssetWithFileHashes, ExportAssetMap } from '../../../export/saveAssets';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { getFreePortAsync } from '../../../utils/port';\nimport { BundlerDevServer, BundlerStartOptions, DevServerInstance } from '../BundlerDevServer';\nimport {\n cachedSourceMaps,\n evalMetroAndWrapFunctions,\n evalMetroNoHandling,\n} from '../getStaticRenderFunctions';\nimport { ContextModuleSourceMapsMiddleware } from '../middleware/ContextModuleSourceMapsMiddleware';\nimport { CreateFileMiddleware } from '../middleware/CreateFileMiddleware';\nimport { DevToolsPluginMiddleware } from '../middleware/DevToolsPluginMiddleware';\nimport { createDomComponentsMiddleware } from '../middleware/DomComponentsMiddleware';\nimport { FaviconMiddleware } from '../middleware/FaviconMiddleware';\nimport { HistoryFallbackMiddleware } from '../middleware/HistoryFallbackMiddleware';\nimport { InterstitialPageMiddleware } from '../middleware/InterstitialPageMiddleware';\nimport { resolveMainModuleName } from '../middleware/ManifestMiddleware';\nimport { RuntimeRedirectMiddleware } from '../middleware/RuntimeRedirectMiddleware';\nimport { ServeStaticMiddleware } from '../middleware/ServeStaticMiddleware';\nimport {\n convertPathToModuleSpecifier,\n createBundleUrlPath,\n ExpoMetroOptions,\n createBundleOsPath,\n getAsyncRoutesFromExpoConfig,\n getBaseUrlFromExpoConfig,\n getMetroDirectBundleOptions,\n shouldEnableAsyncImports,\n} from '../middleware/metroOptions';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { startTypescriptTypeGenerationAsync } from '../type-generation/startTypescriptTypeGeneration';\n\nexport type ExpoRouterRuntimeManifest = Awaited<\n ReturnType<typeof import('expo-router/build/static/renderStaticContent').getManifest>\n>;\ntype MetroOnProgress = NonNullable<\n import('metro/src/DeltaBundler/types').Options<void>['onProgress']\n>;\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\ninterface BundleDirectResult {\n numModifiedFiles: number;\n lastModifiedDate: Date;\n nextRevId: string;\n bundle: string;\n map: string;\n /** Defined if the output is multi-bundle. */\n artifacts?: SerialAsset[];\n assets?: readonly BundleAssetWithFileHashes[];\n}\n\ninterface MetroModuleContentsResult extends BundleDirectResult {\n filename: string;\n}\n\ninterface SSRModuleContentsResult extends Omit<BundleDirectResult, 'bundle'> {\n filename: string;\n src: string;\n map: string;\n}\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\n/** Default port to use for apps running in Expo Go. */\nconst EXPO_GO_METRO_PORT = 8081;\n\n/** Default port to use for apps that run in standard React Native projects or Expo Dev Clients. */\nconst DEV_CLIENT_METRO_PORT = 8081;\n\nexport class MetroBundlerDevServer extends BundlerDevServer {\n private metro: MetroPrivateServer | null = null;\n private hmrServer: MetroHmrServer | null = null;\n private ssrHmrClients: Map<string, MetroHmrClient> = new Map();\n isReactServerComponentsEnabled?: boolean;\n isReactServerRoutesEnabled?: boolean;\n\n get name(): string {\n return 'metro';\n }\n\n async resolvePortAsync(options: Partial<BundlerStartOptions> = {}): Promise<number> {\n const port =\n // If the manually defined port is busy then an error should be thrown...\n options.port ??\n // Otherwise use the default port based on the runtime target.\n (options.devClient\n ? // Don't check if the port is busy if we're using the dev client since most clients are hardcoded to 8081.\n Number(process.env.RCT_METRO_PORT) || DEV_CLIENT_METRO_PORT\n : // Otherwise (running in Expo Go) use a free port that falls back on the classic 8081 port.\n await getFreePortAsync(EXPO_GO_METRO_PORT));\n\n return port;\n }\n\n async exportExpoRouterApiRoutesAsync({\n includeSourceMaps,\n outputDir,\n prerenderManifest,\n platform,\n }: {\n includeSourceMaps?: boolean;\n outputDir: string;\n // This does not contain the API routes info.\n prerenderManifest: ExpoRouterServerManifestV1;\n platform: string;\n }): Promise<{ files: ExportAssetMap; manifest: ExpoRouterServerManifestV1<string> }> {\n const { routerRoot } = this.instanceMetroOptions;\n assert(\n routerRoot != null,\n 'The server must be started before calling exportExpoRouterApiRoutesAsync.'\n );\n\n const appDir = path.join(this.projectRoot, routerRoot);\n const manifest = await this.getExpoRouterRoutesManifestAsync({ appDir });\n\n const files: ExportAssetMap = new Map();\n\n // Inject RSC middleware.\n const rscPath = '/_flight/[...rsc]';\n\n if (\n this.isReactServerComponentsEnabled &&\n // If the RSC route is not already in the manifest, add it.\n !manifest.apiRoutes.find((route) => route.page.startsWith('/_flight/'))\n ) {\n debug('Adding RSC route to the manifest:', rscPath);\n // NOTE: This might need to be sorted to the correct spot in the future.\n manifest.apiRoutes.push({\n file: resolveFrom(this.projectRoot, '@expo/cli/static/template/[...rsc]+api.ts'),\n page: rscPath,\n namedRegex: '^/_flight(?:/(?<rsc>.+?))?(?:/)?$',\n routeKeys: { rsc: 'rsc' },\n });\n }\n\n for (const route of manifest.apiRoutes) {\n const filepath = path.isAbsolute(route.file) ? route.file : path.join(appDir, route.file);\n const contents = await this.bundleApiRoute(filepath, { platform });\n\n const artifactFilename =\n route.page === rscPath\n ? // HACK: Add RSC renderer to the output...\n convertPathToModuleSpecifier(path.join(outputDir, '.' + rscPath + '.js'))\n : convertPathToModuleSpecifier(\n path.join(outputDir, path.relative(appDir, filepath.replace(/\\.[tj]sx?$/, '.js')))\n );\n\n if (contents) {\n let src = contents.src;\n\n if (includeSourceMaps && contents.map) {\n // TODO(kitten): Merge the source map transformer in the future\n // https://github.com/expo/expo/blob/0dffdb15/packages/%40expo/metro-config/src/serializer/serializeChunks.ts#L422-L439\n // Alternatively, check whether `sourcesRoot` helps here\n const artifactBasename = encodeURIComponent(path.basename(artifactFilename) + '.map');\n src = src.replace(\n /\\/\\/# sourceMappingURL=.*/g,\n `//# sourceMappingURL=${artifactBasename}`\n );\n\n const parsedMap =\n typeof contents.map === 'string' ? JSON.parse(contents.map) : contents.map;\n files.set(artifactFilename + '.map', {\n contents: JSON.stringify({\n version: parsedMap.version,\n sources: parsedMap.sources.map((source: string) => {\n source =\n typeof source === 'string' && source.startsWith(this.projectRoot)\n ? path.relative(this.projectRoot, source)\n : source;\n return convertPathToModuleSpecifier(source);\n }),\n sourcesContent: new Array(parsedMap.sources.length).fill(null),\n names: parsedMap.names,\n mappings: parsedMap.mappings,\n }),\n apiRouteId: route.page,\n targetDomain: 'server',\n });\n }\n files.set(artifactFilename, {\n contents: src,\n apiRouteId: route.page,\n targetDomain: 'server',\n });\n }\n // Remap the manifest files to represent the output files.\n route.file = artifactFilename;\n }\n\n return {\n manifest: {\n ...manifest,\n htmlRoutes: prerenderManifest.htmlRoutes,\n },\n files,\n };\n }\n\n async getExpoRouterRoutesManifestAsync({ appDir }: { appDir: string }) {\n // getBuiltTimeServerManifest\n const { exp } = getConfig(this.projectRoot);\n const manifest = await fetchManifest(this.projectRoot, {\n ...exp.extra?.router,\n preserveRedirectAndRewrites: true,\n asJson: true,\n appDir,\n });\n\n if (!manifest) {\n throw new CommandError(\n 'EXPO_ROUTER_SERVER_MANIFEST',\n 'Unexpected error: server manifest could not be fetched.'\n );\n }\n\n return manifest;\n }\n\n async getServerManifestAsync(): Promise<{\n serverManifest: ExpoRouterServerManifestV1;\n htmlManifest: ExpoRouterRuntimeManifest;\n }> {\n const { exp } = getConfig(this.projectRoot);\n // NOTE: This could probably be folded back into `renderStaticContent` when expo-asset and font support RSC.\n const { getBuildTimeServerManifestAsync, getManifest } = await this.ssrLoadModule<\n typeof import('expo-router/build/static/getServerManifest')\n >('expo-router/build/static/getServerManifest.js', {\n // Only use react-server environment when the routes are using react-server rendering by default.\n environment: this.isReactServerRoutesEnabled ? 'react-server' : 'node',\n });\n\n return {\n serverManifest: await getBuildTimeServerManifestAsync({ ...exp.extra?.router }),\n htmlManifest: await getManifest({ ...exp.extra?.router }),\n };\n }\n\n async getStaticRenderFunctionAsync(): Promise<{\n serverManifest: ExpoRouterServerManifestV1;\n manifest: ExpoRouterRuntimeManifest;\n renderAsync: (path: string) => Promise<string>;\n }> {\n const url = this.getDevServerUrlOrAssert();\n\n const { getStaticContent, getManifest, getBuildTimeServerManifestAsync } =\n await this.ssrLoadModule<typeof import('expo-router/build/static/renderStaticContent')>(\n 'expo-router/node/render.js',\n {\n // This must always use the legacy rendering resolution (no `react-server`) because it leverages\n // the previous React SSG utilities which aren't available in React 19.\n environment: 'node',\n }\n );\n\n const { exp } = getConfig(this.projectRoot);\n\n return {\n serverManifest: await getBuildTimeServerManifestAsync({\n ...exp.extra?.router,\n }),\n // Get routes from Expo Router.\n manifest: await getManifest({ preserveApiRoutes: false, ...exp.extra?.router }),\n // Get route generating function\n async renderAsync(path: string) {\n return await getStaticContent(new URL(path, url));\n },\n };\n }\n\n async getStaticResourcesAsync({\n includeSourceMaps,\n mainModuleName,\n clientBoundaries = this.instanceMetroOptions.clientBoundaries ?? [],\n platform = 'web',\n }: {\n includeSourceMaps?: boolean;\n mainModuleName?: string;\n clientBoundaries?: string[];\n platform?: string;\n } = {}) {\n const { mode, minify, isExporting, baseUrl, reactCompiler, routerRoot, asyncRoutes } =\n this.instanceMetroOptions;\n assert(\n mode != null &&\n isExporting != null &&\n baseUrl != null &&\n routerRoot != null &&\n reactCompiler != null &&\n asyncRoutes != null,\n 'The server must be started before calling getStaticResourcesAsync.'\n );\n\n const resolvedMainModuleName =\n mainModuleName ?? './' + resolveMainModuleName(this.projectRoot, { platform });\n return await this.metroImportAsArtifactsAsync(resolvedMainModuleName, {\n splitChunks: isExporting && !env.EXPO_NO_BUNDLE_SPLITTING,\n platform,\n mode,\n minify,\n environment: 'client',\n serializerIncludeMaps: includeSourceMaps,\n mainModuleName: resolvedMainModuleName,\n lazy: shouldEnableAsyncImports(this.projectRoot),\n asyncRoutes,\n baseUrl,\n isExporting,\n routerRoot,\n clientBoundaries,\n reactCompiler,\n bytecode: false,\n });\n }\n\n private async getStaticPageAsync(pathname: string) {\n const { mode, isExporting, clientBoundaries, baseUrl, reactCompiler, routerRoot, asyncRoutes } =\n this.instanceMetroOptions;\n assert(\n mode != null &&\n isExporting != null &&\n baseUrl != null &&\n reactCompiler != null &&\n routerRoot != null &&\n asyncRoutes != null,\n 'The server must be started before calling getStaticPageAsync.'\n );\n const platform = 'web';\n\n const devBundleUrlPathname = createBundleUrlPath({\n splitChunks: isExporting && !env.EXPO_NO_BUNDLE_SPLITTING,\n platform,\n mode,\n environment: 'client',\n reactCompiler,\n mainModuleName: resolveMainModuleName(this.projectRoot, { platform }),\n lazy: shouldEnableAsyncImports(this.projectRoot),\n baseUrl,\n isExporting,\n asyncRoutes,\n routerRoot,\n clientBoundaries,\n bytecode: false,\n });\n\n const bundleStaticHtml = async (): Promise<string> => {\n const { getStaticContent } = await this.ssrLoadModule<\n typeof import('expo-router/build/static/renderStaticContent')\n >('expo-router/node/render.js', {\n // This must always use the legacy rendering resolution (no `react-server`) because it leverages\n // the previous React SSG utilities which aren't available in React 19.\n environment: 'node',\n minify: false,\n isExporting,\n platform,\n });\n\n const location = new URL(pathname, this.getDevServerUrlOrAssert());\n return await getStaticContent(location);\n };\n\n const [{ artifacts: resources }, staticHtml] = await Promise.all([\n this.getStaticResourcesAsync({\n clientBoundaries: [],\n }),\n bundleStaticHtml(),\n ]);\n const content = serializeHtmlWithAssets({\n isExporting,\n resources,\n template: staticHtml,\n devBundleUrl: devBundleUrlPathname,\n baseUrl,\n hydrate: env.EXPO_WEB_DEV_HYDRATE,\n });\n return {\n content,\n resources,\n };\n }\n\n // Set when the server is started.\n private instanceMetroOptions: Partial<ExpoMetroOptions> = {};\n\n private ssrLoadModule: SSRLoadModuleFunc = async (\n filePath,\n specificOptions = {},\n extras = {}\n ) => {\n const res = await this.ssrLoadModuleContents(filePath, specificOptions);\n\n if (\n // TODO: hot should be a callback function for invalidating the related SSR module.\n extras.hot &&\n this.instanceMetroOptions.isExporting !== true\n ) {\n // Register SSR HMR\n const serverRoot = getMetroServerRoot(this.projectRoot);\n const relativePath = path.relative(serverRoot, res.filename);\n const url = new URL(relativePath, this.getDevServerUrlOrAssert());\n this.setupHmr(url);\n }\n\n return evalMetroAndWrapFunctions(\n this.projectRoot,\n res.src,\n res.filename,\n specificOptions.isExporting ?? this.instanceMetroOptions.isExporting!\n );\n };\n\n private async metroImportAsArtifactsAsync(\n filePath: string,\n specificOptions: Partial<Omit<ExpoMetroOptions, 'serializerOutput'>> = {}\n ) {\n const results = await this.ssrLoadModuleContents(filePath, {\n serializerOutput: 'static',\n ...specificOptions,\n });\n\n // NOTE: This could potentially need more validation in the future.\n if (results.artifacts && results.assets) {\n return {\n artifacts: results.artifacts,\n assets: results.assets,\n src: results.src,\n filename: results.filename,\n map: results.map,\n };\n }\n throw new CommandError('Invalid bundler results: ' + results);\n }\n\n private async metroLoadModuleContents(\n filePath: string,\n specificOptions: ExpoMetroOptions,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<MetroModuleContentsResult> {\n const { baseUrl } = this.instanceMetroOptions;\n assert(baseUrl != null, 'The server must be started before calling metroLoadModuleContents.');\n\n const opts: ExpoMetroOptions = {\n // TODO: Possibly issues with using an absolute path here...\n // mainModuleName: filePath,\n lazy: false,\n asyncRoutes: false,\n inlineSourceMap: false,\n engine: 'hermes',\n minify: false,\n // bytecode: false,\n // Bundle in Node.js mode for SSR.\n environment: 'node',\n // platform: 'web',\n // mode: 'development',\n //\n ...this.instanceMetroOptions,\n baseUrl,\n // routerRoot,\n // isExporting,\n ...specificOptions,\n };\n\n const expoBundleOptions = getMetroDirectBundleOptions(opts);\n\n const resolverOptions = {\n customResolverOptions: expoBundleOptions.customResolverOptions ?? {},\n dev: expoBundleOptions.dev ?? true,\n };\n\n const transformOptions: TransformInputOptions = {\n dev: expoBundleOptions.dev ?? true,\n hot: true,\n minify: expoBundleOptions.minify ?? false,\n type: 'module',\n unstable_transformProfile:\n extraOptions.unstable_transformProfile ??\n expoBundleOptions.unstable_transformProfile ??\n 'default',\n customTransformOptions: expoBundleOptions.customTransformOptions ?? Object.create(null),\n platform: expoBundleOptions.platform ?? 'web',\n // @ts-expect-error: `runtimeBytecodeVersion` does not exist in `expoBundleOptions` or `TransformInputOptions`\n runtimeBytecodeVersion: expoBundleOptions.runtimeBytecodeVersion,\n };\n\n const resolvedEntryFilePath = await this.resolveRelativePathAsync(filePath, {\n resolverOptions,\n transformOptions,\n });\n\n const filename = createBundleOsPath({\n ...opts,\n mainModuleName: resolvedEntryFilePath,\n });\n\n // https://github.com/facebook/metro/blob/2405f2f6c37a1b641cc379b9c733b1eff0c1c2a1/packages/metro/src/lib/parseOptionsFromUrl.js#L55-L87\n const results = await this._bundleDirectAsync(resolvedEntryFilePath, {\n graphOptions: {\n lazy: expoBundleOptions.lazy ?? false,\n shallow: expoBundleOptions.shallow ?? false,\n },\n resolverOptions,\n serializerOptions: {\n ...expoBundleOptions.serializerOptions,\n\n inlineSourceMap: expoBundleOptions.inlineSourceMap ?? false,\n modulesOnly: expoBundleOptions.modulesOnly ?? false,\n runModule: expoBundleOptions.runModule ?? true,\n // @ts-expect-error\n sourceUrl: expoBundleOptions.sourceUrl,\n // @ts-expect-error\n sourceMapUrl: extraOptions.sourceMapUrl ?? expoBundleOptions.sourceMapUrl,\n },\n transformOptions,\n });\n\n return {\n ...results,\n filename,\n };\n }\n\n private async ssrLoadModuleContents(\n filePath: string,\n specificOptions: Partial<ExpoMetroOptions> = {}\n ): Promise<SSRModuleContentsResult> {\n const { baseUrl, routerRoot, isExporting } = this.instanceMetroOptions;\n assert(\n baseUrl != null && routerRoot != null && isExporting != null,\n 'The server must be started before calling ssrLoadModuleContents.'\n );\n\n const opts: ExpoMetroOptions = {\n // TODO: Possibly issues with using an absolute path here...\n mainModuleName: convertPathToModuleSpecifier(filePath),\n lazy: false,\n asyncRoutes: false,\n inlineSourceMap: false,\n engine: 'hermes',\n minify: false,\n bytecode: false,\n // Bundle in Node.js mode for SSR unless RSC is enabled.\n environment: this.isReactServerComponentsEnabled ? 'react-server' : 'node',\n platform: 'web',\n mode: 'development',\n //\n ...this.instanceMetroOptions,\n\n // Mostly disable compiler in SSR bundles.\n reactCompiler: false,\n baseUrl,\n routerRoot,\n isExporting,\n\n ...specificOptions,\n };\n\n // https://github.com/facebook/metro/blob/2405f2f6c37a1b641cc379b9c733b1eff0c1c2a1/packages/metro/src/lib/parseOptionsFromUrl.js#L55-L87\n const { filename, bundle, map, ...rest } = await this.metroLoadModuleContents(filePath, opts);\n const scriptContents = wrapBundle(bundle);\n\n if (map) {\n debug('Registering SSR source map for:', filename);\n cachedSourceMaps.set(filename, { url: this.projectRoot, map });\n } else {\n debug('No SSR source map found for:', filename);\n }\n\n return {\n ...rest,\n src: scriptContents,\n filename,\n map,\n };\n }\n\n async nativeExportBundleAsync(\n exp: ExpoConfig,\n options: Omit<\n ExpoMetroOptions,\n 'routerRoot' | 'asyncRoutes' | 'isExporting' | 'serializerOutput' | 'environment'\n >,\n files: ExportAssetMap,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<{\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n files?: ExportAssetMap;\n }> {\n if (this.isReactServerComponentsEnabled) {\n return this.singlePageReactServerComponentExportAsync(exp, options, files, extraOptions);\n }\n\n return this.legacySinglePageExportBundleAsync(options, extraOptions);\n }\n\n private async singlePageReactServerComponentExportAsync(\n exp: ExpoConfig,\n options: Omit<\n ExpoMetroOptions,\n 'baseUrl' | 'routerRoot' | 'asyncRoutes' | 'isExporting' | 'serializerOutput' | 'environment'\n >,\n files: ExportAssetMap,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<{\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n files: ExportAssetMap;\n }> {\n const getReactServerReferences = (artifacts: SerialAsset[]): string[] => {\n // Get the React server action boundaries from the client bundle.\n return unique(\n artifacts\n .filter((a) => a.type === 'js')\n .map((artifact) =>\n artifact.metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref))\n )\n // TODO: Segment by module for splitting.\n .flat()\n .filter(Boolean) as string[]\n );\n };\n\n // NOTE(EvanBacon): This will not support any code elimination since it's a static pass.\n let {\n reactClientReferences: clientBoundaries,\n reactServerReferences: serverActionReferencesInServer,\n cssModules,\n } = await this.rscRenderer!.getExpoRouterClientReferencesAsync(\n {\n platform: options.platform,\n domRoot: options.domRoot,\n },\n files\n );\n\n // TODO: The output keys should be in production format or use a lookup manifest.\n\n const processClientBoundaries = async (\n reactServerReferences: string[]\n ): Promise<{\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n }> => {\n debug('Evaluated client boundaries:', clientBoundaries);\n\n // Run metro bundler and create the JS bundles/source maps.\n const bundle = await this.legacySinglePageExportBundleAsync(\n {\n ...options,\n clientBoundaries,\n },\n extraOptions\n );\n\n // Get the React server action boundaries from the client bundle.\n const newReactServerReferences = getReactServerReferences(bundle.artifacts);\n\n if (!newReactServerReferences) {\n // Possible issue with babel plugin / metro-config.\n throw new Error(\n 'Static server action references were not returned from the Metro client bundle'\n );\n }\n debug('React server action boundaries from client:', newReactServerReferences);\n\n const allKnownReactServerReferences = unique([\n ...reactServerReferences,\n ...newReactServerReferences,\n ]);\n\n // When we export the server actions that were imported from the client, we may need to re-bundle the client with the new client boundaries.\n const { clientBoundaries: nestedClientBoundaries } =\n await this.rscRenderer!.exportServerActionsAsync(\n {\n platform: options.platform,\n domRoot: options.domRoot,\n entryPoints: allKnownReactServerReferences,\n },\n files\n );\n\n // TODO: Check against all modules in the initial client bundles.\n const hasUniqueClientBoundaries = nestedClientBoundaries.some(\n (boundary) => !clientBoundaries.includes(boundary)\n );\n\n if (!hasUniqueClientBoundaries) {\n return bundle;\n }\n\n debug('Re-bundling client with nested client boundaries:', nestedClientBoundaries);\n\n clientBoundaries = unique(clientBoundaries.concat(nestedClientBoundaries));\n\n // Re-bundle the client with the new client boundaries that only exist in server actions that were imported from the client.\n // Run metro bundler and create the JS bundles/source maps.\n return processClientBoundaries(allKnownReactServerReferences);\n };\n\n const bundle = await processClientBoundaries(serverActionReferencesInServer);\n\n // Inject the global CSS that was imported during the server render.\n bundle.artifacts.push(...cssModules);\n\n const serverRoot = getMetroServerRoot(this.projectRoot);\n\n // HACK: Maybe this should be done in the serializer.\n const clientBoundariesAsOpaqueIds = clientBoundaries.map((boundary) =>\n // NOTE(cedric): relative module specifiers / IDs should always be POSIX formatted\n toPosixPath(path.relative(serverRoot, boundary))\n );\n const moduleIdToSplitBundle = (\n bundle.artifacts\n .map((artifact) => artifact?.metadata?.paths && Object.values(artifact.metadata.paths))\n .filter(Boolean)\n .flat() as Record<string, string>[]\n ).reduce((acc, paths) => ({ ...acc, ...paths }), {});\n\n debug('SSR Manifest:', moduleIdToSplitBundle, clientBoundariesAsOpaqueIds);\n\n const ssrManifest = new Map<string, string>();\n\n if (Object.keys(moduleIdToSplitBundle).length) {\n clientBoundariesAsOpaqueIds.forEach((boundary) => {\n if (boundary in moduleIdToSplitBundle) {\n ssrManifest.set(boundary, moduleIdToSplitBundle[boundary]);\n } else {\n throw new Error(\n `Could not find boundary \"${boundary}\" in the SSR manifest. Available: ${Object.keys(moduleIdToSplitBundle).join(', ')}`\n );\n }\n });\n } else {\n // Native apps with bundle splitting disabled.\n debug('No split bundles');\n clientBoundariesAsOpaqueIds.forEach((boundary) => {\n // @ts-expect-error\n ssrManifest.set(boundary, null);\n });\n }\n\n const routerOptions = exp.extra?.router;\n\n // Export the static RSC files\n await this.rscRenderer!.exportRoutesAsync(\n {\n platform: options.platform,\n ssrManifest,\n routerOptions,\n },\n files\n );\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/${options.platform}/ssr-manifest.js`, {\n targetDomain: 'server',\n contents:\n 'module.exports = ' +\n JSON.stringify(\n // TODO: Add a less leaky version of this across the framework with just [key, value] (module ID, chunk).\n Object.fromEntries(\n Array.from(ssrManifest.entries()).map(([key, value]) => [\n // Must match babel plugin.\n './' + toPosixPath(path.relative(this.projectRoot, path.join(serverRoot, key))),\n [key, value],\n ])\n )\n ),\n });\n\n return { ...bundle, files };\n }\n\n async legacySinglePageExportBundleAsync(\n options: Omit<\n ExpoMetroOptions,\n 'routerRoot' | 'asyncRoutes' | 'isExporting' | 'serializerOutput' | 'environment'\n >,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<{ artifacts: SerialAsset[]; assets: readonly BundleAssetWithFileHashes[] }> {\n const { baseUrl, routerRoot, isExporting } = this.instanceMetroOptions;\n assert(options.mainModuleName != null, 'mainModuleName must be provided in options.');\n assert(\n baseUrl != null && routerRoot != null && isExporting != null,\n 'The server must be started before calling legacySinglePageExportBundleAsync.'\n );\n\n const opts: ExpoMetroOptions = {\n ...this.instanceMetroOptions,\n baseUrl,\n routerRoot,\n isExporting,\n ...options,\n environment: 'client',\n serializerOutput: 'static',\n };\n\n // https://github.com/facebook/metro/blob/2405f2f6c37a1b641cc379b9c733b1eff0c1c2a1/packages/metro/src/lib/parseOptionsFromUrl.js#L55-L87\n if (!opts.mainModuleName.startsWith('/') && !path.isAbsolute(opts.mainModuleName)) {\n opts.mainModuleName = './' + opts.mainModuleName;\n }\n\n const output = await this.metroLoadModuleContents(opts.mainModuleName, opts, extraOptions);\n\n return {\n artifacts: output.artifacts!,\n assets: output.assets!,\n };\n }\n\n async watchEnvironmentVariables() {\n if (!this.instance) {\n throw new Error(\n 'Cannot observe environment variable changes without a running Metro instance.'\n );\n }\n if (!this.metro) {\n // This can happen when the run command is used and the server is already running in another\n // process.\n debug('Skipping Environment Variable observation because Metro is not running (headless).');\n return;\n }\n\n const envFiles = runtimeEnv\n .getFiles(process.env.NODE_ENV)\n .map((fileName) => path.join(this.projectRoot, fileName));\n\n observeFileChanges(\n {\n metro: this.metro,\n server: this.instance.server,\n },\n envFiles,\n () => {\n debug('Reloading environment variables...');\n // Force reload the environment variables.\n runtimeEnv.load(this.projectRoot, { force: true });\n }\n );\n }\n\n rscRenderer: Awaited<ReturnType<typeof createServerComponentsMiddleware>> | null = null;\n\n protected async startImplementationAsync(\n options: BundlerStartOptions\n ): Promise<DevServerInstance> {\n options.port = await this.resolvePortAsync(options);\n this.urlCreator = this.getUrlCreator(options);\n\n const config = getConfig(this.projectRoot, { skipSDKVersionRequirement: true });\n const { exp } = config;\n // NOTE: This will change in the future when it's less experimental, we enable React 19, and turn on more RSC flags by default.\n const isReactServerComponentsEnabled =\n !!exp.experiments?.reactServerComponentRoutes || !!exp.experiments?.reactServerFunctions;\n const isReactServerActionsOnlyEnabled =\n !exp.experiments?.reactServerComponentRoutes && !!exp.experiments?.reactServerFunctions;\n this.isReactServerComponentsEnabled = isReactServerComponentsEnabled;\n this.isReactServerRoutesEnabled = !!exp.experiments?.reactServerComponentRoutes;\n\n const useServerRendering = ['static', 'server'].includes(exp.web?.output ?? '');\n const hasApiRoutes = isReactServerComponentsEnabled || exp.web?.output === 'server';\n const baseUrl = getBaseUrlFromExpoConfig(exp);\n const asyncRoutes = getAsyncRoutesFromExpoConfig(exp, options.mode ?? 'development', 'web');\n const routerRoot = getRouterDirectoryModuleIdWithManifest(this.projectRoot, exp);\n const reactCompiler = !!exp.experiments?.reactCompiler;\n const appDir = path.join(this.projectRoot, routerRoot);\n const mode = options.mode ?? 'development';\n\n const routerOptions = exp.extra?.router;\n\n if (isReactServerComponentsEnabled && exp.web?.output === 'static') {\n throw new CommandError(\n `Experimental server component support does not support 'web.output: ${exp.web!.output}' yet. Use 'web.output: \"server\"' during the experimental phase.`\n );\n }\n\n // Error early about the window.location polyfill when React Server Components are enabled.\n if (isReactServerComponentsEnabled && exp?.extra?.router?.origin === false) {\n const configPath = config.dynamicConfigPath ?? config.staticConfigPath ?? '/app.json';\n const configFileName = path.basename(configPath);\n throw new CommandError(\n `The Expo Router \"origin\" property in the Expo config (${configFileName}) cannot be \"false\" when React Server Components is enabled. Remove it from the ${configFileName} file and try again.`\n );\n }\n\n const instanceMetroOptions = {\n isExporting: !!options.isExporting,\n baseUrl,\n mode,\n routerRoot,\n reactCompiler,\n minify: options.minify,\n asyncRoutes,\n // Options that are changing between platforms like engine, platform, and environment aren't set here.\n };\n this.instanceMetroOptions = instanceMetroOptions;\n\n const parsedOptions = {\n port: options.port,\n maxWorkers: options.maxWorkers,\n resetCache: options.resetDevServer,\n };\n\n // Required for symbolication:\n process.env.EXPO_DEV_SERVER_ORIGIN = `http://localhost:${options.port}`;\n\n const { metro, hmrServer, server, middleware, messageSocket } = await instantiateMetroAsync(\n this,\n parsedOptions,\n {\n isExporting: !!options.isExporting,\n exp,\n }\n );\n\n if (!options.isExporting) {\n const manifestMiddleware = await this.getManifestMiddlewareAsync(options);\n\n // Important that we noop source maps for context modules as soon as possible.\n prependMiddleware(middleware, new ContextModuleSourceMapsMiddleware().getHandler());\n\n // We need the manifest handler to be the first middleware to run so our\n // routes take precedence over static files. For example, the manifest is\n // served from '/' and if the user has an index.html file in their project\n // then the manifest handler will never run, the static middleware will run\n // and serve index.html instead of the manifest.\n // https://github.com/expo/expo/issues/13114\n prependMiddleware(middleware, manifestMiddleware.getHandler());\n\n middleware.use(\n new InterstitialPageMiddleware(this.projectRoot, {\n // TODO: Prevent this from becoming stale.\n scheme: options.location.scheme ?? null,\n }).getHandler()\n );\n middleware.use(\n new DevToolsPluginMiddleware(this.projectRoot, this.devToolsPluginManager).getHandler()\n );\n\n const deepLinkMiddleware = new RuntimeRedirectMiddleware(this.projectRoot, {\n getLocation: ({ runtime }) => {\n if (runtime === 'custom') {\n return this.urlCreator?.constructDevClientUrl();\n } else {\n return this.urlCreator?.constructUrl({\n scheme: 'exp',\n });\n }\n },\n });\n middleware.use(deepLinkMiddleware.getHandler());\n\n const serverRoot = getMetroServerRoot(this.projectRoot);\n\n const domComponentRenderer = createDomComponentsMiddleware(\n {\n metroRoot: serverRoot,\n projectRoot: this.projectRoot,\n },\n instanceMetroOptions\n );\n // Add support for DOM components.\n // TODO: Maybe put behind a flag for now?\n middleware.use(domComponentRenderer);\n\n middleware.use(new CreateFileMiddleware(this.projectRoot).getHandler());\n\n // Append support for redirecting unhandled requests to the index.html page on web.\n if (this.isTargetingWeb()) {\n // This MUST be after the manifest middleware so it doesn't have a chance to serve the template `public/index.html`.\n middleware.use(new ServeStaticMiddleware(this.projectRoot).getHandler());\n\n // This should come after the static middleware so it doesn't serve the favicon from `public/favicon.ico`.\n middleware.use(new FaviconMiddleware(this.projectRoot).getHandler());\n }\n\n if (useServerRendering || isReactServerComponentsEnabled) {\n observeAnyFileChanges(\n {\n metro,\n server,\n },\n (events) => {\n if (hasApiRoutes) {\n // NOTE(EvanBacon): We aren't sure what files the API routes are using so we'll just invalidate\n // aggressively to ensure we always have the latest. The only caching we really get here is for\n // cases where the user is making subsequent requests to the same API route without changing anything.\n // This is useful for testing but pretty suboptimal. Luckily our caching is pretty aggressive so it makes\n // up for a lot of the overhead.\n this.invalidateApiRouteCache();\n } else if (!hasWarnedAboutApiRoutes()) {\n for (const event of events) {\n if (\n // If the user did not delete a file that matches the Expo Router API Route convention, then we should warn that\n // API Routes are not enabled in the project.\n event.metadata?.type !== 'd' &&\n // Ensure the file is in the project's routes directory to prevent false positives in monorepos.\n event.filePath.startsWith(appDir) &&\n isApiRouteConvention(event.filePath)\n ) {\n warnInvalidWebOutput();\n }\n }\n }\n }\n );\n }\n\n // If React 19 is enabled, then add RSC middleware to the dev server.\n if (isReactServerComponentsEnabled) {\n this.bindRSCDevModuleInjectionHandler();\n const rscMiddleware = createServerComponentsMiddleware(this.projectRoot, {\n instanceMetroOptions: this.instanceMetroOptions,\n rscPath: '/_flight',\n ssrLoadModule: this.ssrLoadModule.bind(this),\n ssrLoadModuleArtifacts: this.metroImportAsArtifactsAsync.bind(this),\n useClientRouter: isReactServerActionsOnlyEnabled,\n createModuleId: metro._createModuleId.bind(metro),\n routerOptions,\n });\n this.rscRenderer = rscMiddleware;\n middleware.use(rscMiddleware.middleware);\n this.onReloadRscEvent = rscMiddleware.onReloadRscEvent;\n }\n\n // Append support for redirecting unhandled requests to the index.html page on web.\n if (this.isTargetingWeb()) {\n if (!useServerRendering) {\n // This MUST run last since it's the fallback.\n middleware.use(\n new HistoryFallbackMiddleware(manifestMiddleware.getHandler().internal).getHandler()\n );\n } else {\n middleware.use(\n createRouteHandlerMiddleware(this.projectRoot, {\n appDir,\n routerRoot,\n config,\n ...config.exp.extra?.router,\n bundleApiRoute: (functionFilePath) =>\n this.ssrImportApiRoute(functionFilePath, { platform: 'web' }),\n getStaticPageAsync: async (pathname) => {\n // TODO: Add server rendering when RSC is enabled.\n if (isReactServerComponentsEnabled) {\n // NOTE: This is a temporary hack to return the SPA/template index.html in development when RSC is enabled.\n // While this technically works, it doesn't provide the correct experience of server rendering the React code to HTML first.\n const html = await manifestMiddleware.getSingleHtmlTemplateAsync();\n return { content: html };\n }\n\n // Non-RSC apps will bundle the static HTML for a given pathname and respond with it.\n return this.getStaticPageAsync(pathname);\n },\n })\n );\n }\n }\n } else {\n // If React 19 is enabled, then add RSC middleware to the dev server.\n if (isReactServerComponentsEnabled) {\n this.bindRSCDevModuleInjectionHandler();\n const rscMiddleware = createServerComponentsMiddleware(this.projectRoot, {\n instanceMetroOptions: this.instanceMetroOptions,\n rscPath: '/_flight',\n ssrLoadModule: this.ssrLoadModule.bind(this),\n ssrLoadModuleArtifacts: this.metroImportAsArtifactsAsync.bind(this),\n useClientRouter: isReactServerActionsOnlyEnabled,\n createModuleId: metro._createModuleId.bind(metro),\n routerOptions,\n });\n this.rscRenderer = rscMiddleware;\n }\n }\n // Extend the close method to ensure that we clean up the local info.\n const originalClose = server.close.bind(server);\n\n server.close = (callback?: (err?: Error) => void) => {\n return originalClose((err?: Error) => {\n this.instance = null;\n this.metro = null;\n this.hmrServer = null;\n this.ssrHmrClients = new Map();\n callback?.(err);\n });\n };\n\n assertMetroPrivateServer(metro);\n this.metro = metro;\n this.hmrServer = hmrServer;\n return {\n server,\n location: {\n // The port is the main thing we want to send back.\n port: options.port,\n // localhost isn't always correct.\n host: 'localhost',\n // http is the only supported protocol on native.\n url: `http://localhost:${options.port}`,\n protocol: 'http',\n },\n middleware,\n messageSocket,\n };\n }\n\n private onReloadRscEvent: ((platform: string) => void) | null = null;\n\n private async registerSsrHmrAsync(url: string, onReload: (platform: string[]) => void) {\n if (!this.hmrServer || this.ssrHmrClients.has(url)) {\n return;\n }\n\n debug('[SSR] Register HMR:', url);\n\n const sendFn = (message: string) => {\n const data = JSON.parse(String(message)) as { type: string; body: any };\n\n switch (data.type) {\n case 'bundle-registered':\n case 'update-done':\n case 'update-start':\n break;\n case 'update':\n {\n const update = data.body;\n const {\n isInitialUpdate,\n added,\n modified,\n deleted,\n }: {\n isInitialUpdate?: boolean;\n added: {\n module: [number | string, string];\n sourceURL: string;\n sourceMappingURL: string;\n }[];\n modified: {\n module: [number | string, string];\n sourceURL: string;\n sourceMappingURL: string;\n }[];\n deleted: (number | string)[];\n } = update;\n\n const hasUpdate = added.length || modified.length || deleted.length;\n\n // NOTE: We throw away the updates and instead simply send a trigger to the client to re-fetch the server route.\n if (!isInitialUpdate && hasUpdate) {\n // Clear all SSR modules before sending the reload event. This ensures that the next event will rebuild the in-memory state from scratch.\n // @ts-expect-error\n if (typeof globalThis.__c === 'function') globalThis.__c();\n\n const allModuleIds = new Set(\n [...added, ...modified].map((m) => m.module[0]).concat(deleted)\n );\n\n const platforms = unique(\n Array.from(allModuleIds)\n .map((moduleId) => {\n if (typeof moduleId !== 'string') {\n return null;\n }\n // Extract platforms from the module IDs.\n return moduleId.match(/[?&]platform=([\\w]+)/)?.[1] ?? null;\n })\n .filter(Boolean)\n ) as string[];\n\n onReload(platforms);\n }\n }\n break;\n case 'error':\n // GraphNotFound can mean that we have an issue in metroOptions where the URL doesn't match the object props.\n Log.error('[SSR] HMR Error: ' + JSON.stringify(data, null, 2));\n\n if (data.body?.type === 'GraphNotFoundError') {\n Log.error(\n 'Available SSR HMR keys:',\n // @ts-expect-error\n (this.metro?._bundler._revisionsByGraphId as Map).keys()\n );\n }\n break;\n default:\n debug('Unknown HMR message:', data);\n break;\n }\n };\n\n const client = await this.hmrServer!.onClientConnect(url, sendFn);\n this.ssrHmrClients.set(url, client);\n // Opt in...\n client.optedIntoHMR = true;\n await this.hmrServer!._registerEntryPoint(client, url, sendFn);\n }\n\n public async waitForTypeScriptAsync(): Promise<boolean> {\n if (!this.instance) {\n throw new Error('Cannot wait for TypeScript without a running server.');\n }\n\n return new Promise<boolean>((resolve) => {\n if (!this.metro) {\n // This can happen when the run command is used and the server is already running in another\n // process. In this case we can't wait for the TypeScript check to complete because we don't\n // have access to the Metro server.\n debug('Skipping TypeScript check because Metro is not running (headless).');\n return resolve(false);\n }\n\n const off = metroWatchTypeScriptFiles({\n projectRoot: this.projectRoot,\n server: this.instance!.server,\n metro: this.metro,\n tsconfig: true,\n throttle: true,\n eventTypes: ['change', 'add'],\n callback: async () => {\n // Run once, this prevents the TypeScript project prerequisite from running on every file change.\n off();\n const { TypeScriptProjectPrerequisite } = await import(\n '../../doctor/typescript/TypeScriptProjectPrerequisite.js'\n );\n\n try {\n const req = new TypeScriptProjectPrerequisite(this.projectRoot);\n await req.bootstrapAsync();\n resolve(true);\n } catch (error: any) {\n // Ensure the process doesn't fail if the TypeScript check fails.\n // This could happen during the install.\n Log.log();\n Log.error(\n chalk.red`Failed to automatically setup TypeScript for your project. Try restarting the dev server to fix.`\n );\n Log.exception(error);\n resolve(false);\n }\n },\n });\n });\n }\n\n public async startTypeScriptServices() {\n return startTypescriptTypeGenerationAsync({\n server: this.instance?.server,\n metro: this.metro,\n projectRoot: this.projectRoot,\n });\n }\n\n protected getConfigModuleIds(): string[] {\n return ['./metro.config.js', './metro.config.json', './rn-cli.config.js'];\n }\n\n // API Routes\n\n private pendingRouteOperations = new Map<string, Promise<SSRModuleContentsResult | null>>();\n\n // Bundle the API Route with Metro and return the string contents to be evaluated in the server.\n private async bundleApiRoute(\n filePath: string,\n { platform }: { platform: string }\n ): Promise<SSRModuleContentsResult | null | undefined> {\n if (this.pendingRouteOperations.has(filePath)) {\n return this.pendingRouteOperations.get(filePath);\n }\n const bundleAsync = async (): Promise<SSRModuleContentsResult> => {\n try {\n debug('Bundle API route:', this.instanceMetroOptions.routerRoot, filePath);\n return await this.ssrLoadModuleContents(filePath, {\n isExporting: this.instanceMetroOptions.isExporting,\n platform,\n });\n } catch (error: any) {\n const appDir = this.instanceMetroOptions?.routerRoot\n ? path.join(this.projectRoot, this.instanceMetroOptions!.routerRoot!)\n : undefined;\n const relativePath = appDir ? path.relative(appDir, filePath) : filePath;\n\n // Expected errors: invalid syntax, missing resolutions.\n // Wrap with command error for better error messages.\n const err = new CommandError(\n 'API_ROUTE',\n chalk`Failed to bundle API Route: {bold ${relativePath}}\\n\\n` + error.message\n );\n\n for (const key in error) {\n // @ts-expect-error\n err[key] = error[key];\n }\n\n throw err;\n } finally {\n // pendingRouteOperations.delete(filepath);\n }\n };\n const route = bundleAsync();\n\n this.pendingRouteOperations.set(filePath, route);\n return route;\n }\n\n private async ssrImportApiRoute(\n filePath: string,\n { platform }: { platform: string }\n ): Promise<null | Record<string, Function> | Response> {\n // TODO: Cache the evaluated function.\n try {\n const apiRoute = await this.bundleApiRoute(filePath, { platform });\n\n if (!apiRoute?.src) {\n return null;\n }\n return evalMetroNoHandling(this.projectRoot, apiRoute.src, apiRoute.filename);\n } catch (error) {\n // Format any errors that were thrown in the global scope of the evaluation.\n if (error instanceof Error) {\n try {\n const htmlServerError = await getErrorOverlayHtmlAsync({\n error,\n projectRoot: this.projectRoot,\n routerRoot: this.instanceMetroOptions.routerRoot!,\n });\n\n return new Response(htmlServerError, {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n });\n } catch (internalError) {\n debug('Failed to generate Metro server error UI for API Route error:', internalError);\n throw error;\n }\n } else {\n throw error;\n }\n }\n }\n\n private invalidateApiRouteCache() {\n this.pendingRouteOperations.clear();\n }\n\n // Ensure the global is available for SSR CSS modules to inject client updates.\n private bindRSCDevModuleInjectionHandler() {\n // Used by SSR CSS modules to broadcast client updates.\n // @ts-expect-error\n globalThis.__expo_rsc_inject_module = this.sendClientModule.bind(this);\n }\n\n // NOTE: This can only target a single platform at a time (web).\n // used for sending RSC CSS to the root client in development.\n private sendClientModule({ code, id }: { code: string; id: string }) {\n this.broadcastMessage('sendDevCommand', {\n name: 'module-import',\n data: {\n code,\n id,\n },\n });\n }\n\n // Metro HMR\n\n private setupHmr(url: URL) {\n const onReload = (platforms: string[] = []) => {\n // Send reload command to client from Fast Refresh code.\n\n if (!platforms.length) {\n // TODO: When is this called?\n this.broadcastMessage('sendDevCommand', {\n name: 'rsc-reload',\n });\n } else {\n for (const platform of platforms) {\n this.onReloadRscEvent?.(platform);\n this.broadcastMessage('sendDevCommand', {\n name: 'rsc-reload',\n platform,\n });\n }\n }\n };\n\n this.registerSsrHmrAsync(url.toString(), onReload);\n }\n\n // Direct Metro access\n\n // Emulates the Metro dev server .bundle endpoint without having to go through a server.\n private async _bundleDirectAsync(\n resolvedEntryFilePath: string,\n {\n transformOptions,\n resolverOptions,\n graphOptions,\n serializerOptions,\n }: {\n transformOptions: TransformInputOptions;\n resolverOptions: {\n customResolverOptions: CustomResolverOptions;\n dev: boolean;\n };\n serializerOptions: {\n modulesOnly: boolean;\n runModule: boolean;\n sourceMapUrl: string;\n sourceUrl: string;\n inlineSourceMap: boolean;\n excludeSource: boolean;\n };\n graphOptions: {\n shallow: boolean;\n lazy: boolean;\n };\n }\n ): Promise<BundleDirectResult> {\n assert(this.metro, 'Metro server must be running to bundle directly.');\n const config = this.metro._config;\n const buildNumber = this.metro.getNewBuildNumber();\n const bundlePerfLogger = config.unstable_perfLoggerFactory?.('BUNDLING_REQUEST', {\n key: buildNumber,\n });\n\n const onProgress: MetroOnProgress = (transformedFileCount: number, totalFileCount: number) => {\n this.metro?._reporter?.update?.({\n buildID: getBuildID(buildNumber),\n type: 'bundle_transform_progressed',\n transformedFileCount,\n totalFileCount,\n });\n };\n\n const revPromise = this.getMetroRevision(resolvedEntryFilePath, {\n graphOptions,\n transformOptions,\n resolverOptions,\n });\n\n bundlePerfLogger?.point('resolvingAndTransformingDependencies_start');\n bundlePerfLogger?.annotate({\n bool: {\n initial_build: revPromise == null,\n },\n });\n this.metro?._reporter.update({\n buildID: getBuildID(buildNumber),\n bundleDetails: {\n bundleType: transformOptions.type,\n dev: transformOptions.dev,\n entryFile: resolvedEntryFilePath,\n minify: transformOptions.minify,\n platform: transformOptions.platform,\n customResolverOptions: resolverOptions.customResolverOptions,\n customTransformOptions: transformOptions.customTransformOptions ?? {},\n },\n isPrefetch: false,\n type: 'bundle_build_started',\n });\n\n try {\n let delta: DeltaResult;\n let revision: GraphRevision;\n\n // TODO: Some bug in Metro/RSC causes this to break when changing imports in server components.\n // We should resolve the bug because it results in ~6x faster bundling to reuse the graph revision.\n if (transformOptions.customTransformOptions?.environment === 'react-server') {\n const props = await this.metro.getBundler().initializeGraph(\n // NOTE: Using absolute path instead of relative input path is a breaking change.\n // entryFile,\n resolvedEntryFilePath,\n\n transformOptions,\n resolverOptions,\n {\n onProgress,\n shallow: graphOptions.shallow,\n lazy: graphOptions.lazy,\n }\n );\n delta = props.delta;\n revision = props.revision;\n } else {\n const props = await (revPromise != null\n ? this.metro.getBundler().updateGraph(await revPromise, false)\n : this.metro.getBundler().initializeGraph(\n // NOTE: Using absolute path instead of relative input path is a breaking change.\n // entryFile,\n resolvedEntryFilePath,\n\n transformOptions,\n resolverOptions,\n {\n onProgress,\n shallow: graphOptions.shallow,\n lazy: graphOptions.lazy,\n }\n ));\n delta = props.delta;\n revision = props.revision;\n }\n\n bundlePerfLogger?.annotate({\n int: {\n graph_node_count: revision.graph.dependencies.size,\n },\n });\n bundlePerfLogger?.point('resolvingAndTransformingDependencies_end');\n bundlePerfLogger?.point('serializingBundle_start');\n\n const shouldAddToIgnoreList = this.metro._shouldAddModuleToIgnoreList.bind(this.metro);\n\n const serializer = this.getMetroSerializer();\n\n const bundle = await serializer(\n // NOTE: Using absolute path instead of relative input path is a breaking change.\n // entryFile,\n resolvedEntryFilePath,\n\n revision.prepend as any,\n revision.graph as any,\n {\n asyncRequireModulePath: await this.metro._resolveRelativePath(\n config.transformer.asyncRequireModulePath,\n {\n relativeTo: 'project',\n resolverOptions,\n transformOptions,\n }\n ),\n // ...serializerOptions,\n processModuleFilter: config.serializer.processModuleFilter,\n createModuleId: this.metro._createModuleId,\n getRunModuleStatement: config.serializer.getRunModuleStatement,\n includeAsyncPaths: graphOptions.lazy,\n dev: transformOptions.dev,\n projectRoot: config.projectRoot,\n modulesOnly: serializerOptions.modulesOnly,\n runBeforeMainModule: config.serializer.getModulesRunBeforeMainModule(\n resolvedEntryFilePath\n // path.relative(config.projectRoot, entryFile)\n ),\n runModule: serializerOptions.runModule,\n sourceMapUrl: serializerOptions.sourceMapUrl,\n sourceUrl: serializerOptions.sourceUrl,\n inlineSourceMap: serializerOptions.inlineSourceMap,\n serverRoot: config.server.unstable_serverRoot ?? config.projectRoot,\n shouldAddToIgnoreList,\n\n // @ts-expect-error: passed to our serializer to enable non-serial return values.\n serializerOptions,\n }\n );\n\n this.metro._reporter.update({\n buildID: getBuildID(buildNumber),\n type: 'bundle_build_done',\n });\n\n bundlePerfLogger?.point('serializingBundle_end');\n\n let bundleCode: string | null = null;\n let bundleMap: string | null = null;\n\n // @ts-expect-error: If the output is multi-bundle...\n if (serializerOptions.output === 'static') {\n try {\n const parsed = typeof bundle === 'string' ? JSON.parse(bundle) : bundle;\n\n assert(\n 'artifacts' in parsed && Array.isArray(parsed.artifacts),\n 'Expected serializer to return an object with key artifacts to contain an array of serial assets.'\n );\n\n const artifacts = parsed.artifacts as SerialAsset[];\n const assets = parsed.assets;\n\n const bundleCode = artifacts.filter((asset) => asset.type === 'js')[0];\n const bundleMap = artifacts.filter((asset) => asset.type === 'map')?.[0]?.source ?? '';\n\n return {\n numModifiedFiles: delta.reset\n ? delta.added.size + revision.prepend.length\n : delta.added.size + delta.modified.size + delta.deleted.size,\n lastModifiedDate: revision.date,\n nextRevId: revision.id,\n bundle: bundleCode.source,\n map: bundleMap,\n artifacts,\n assets,\n };\n } catch (error: any) {\n throw new Error(\n 'Serializer did not return expected format. The project copy of `expo/metro-config` may be out of date. Error: ' +\n error.message\n );\n }\n }\n\n if (typeof bundle === 'string') {\n bundleCode = bundle;\n\n // Create the source map in a second pass...\n let { prepend, graph } = revision;\n if (serializerOptions.modulesOnly) {\n prepend = [];\n }\n\n bundleMap = await sourceMapStringAsync(\n [\n //\n ...prepend,\n ...this.metro._getSortedModules(graph),\n ],\n {\n excludeSource: serializerOptions.excludeSource,\n processModuleFilter: config.serializer.processModuleFilter,\n shouldAddToIgnoreList,\n }\n );\n } else {\n bundleCode = bundle.code;\n bundleMap = bundle.map;\n }\n\n return {\n numModifiedFiles: delta.reset\n ? delta.added.size + revision.prepend.length\n : delta.added.size + delta.modified.size + delta.deleted.size,\n lastModifiedDate: revision.date,\n nextRevId: revision.id,\n bundle: bundleCode,\n map: bundleMap,\n };\n } catch (error) {\n // Mark the error so we know how to format and return it later.\n // @ts-expect-error\n error[IS_METRO_BUNDLE_ERROR_SYMBOL] = true;\n\n this.metro._reporter.update({\n buildID: getBuildID(buildNumber),\n type: 'bundle_build_failed',\n });\n\n throw error;\n }\n }\n\n private getMetroSerializer() {\n return (\n this.metro?._config?.serializer.customSerializer ||\n ((entryPoint, preModules, graph, options) =>\n bundleToString(baseJSBundle(entryPoint, preModules, graph, options)).code)\n );\n }\n\n private getMetroRevision(\n resolvedEntryFilePath: string,\n {\n graphOptions,\n transformOptions,\n resolverOptions,\n }: {\n transformOptions: TransformInputOptions;\n resolverOptions: {\n customResolverOptions: CustomResolverOptions;\n dev: boolean;\n };\n graphOptions: {\n shallow: boolean;\n lazy: boolean;\n };\n }\n ) {\n assert(this.metro, 'Metro server must be running to bundle directly.');\n const config = this.metro._config;\n\n const graphId = getGraphId(resolvedEntryFilePath, transformOptions, {\n unstable_allowRequireContext: config.transformer.unstable_allowRequireContext,\n resolverOptions,\n shallow: graphOptions.shallow,\n lazy: graphOptions.lazy,\n });\n return this.metro.getBundler().getRevisionByGraphId(graphId);\n }\n\n private async resolveRelativePathAsync(\n moduleId: string,\n {\n resolverOptions,\n transformOptions,\n }: {\n transformOptions: TransformInputOptions;\n resolverOptions: {\n customResolverOptions: CustomResolverOptions;\n dev: boolean;\n };\n }\n ) {\n assert(this.metro, 'cannot invoke resolveRelativePathAsync without metro instance');\n return await this.metro._resolveRelativePath(convertPathToModuleSpecifier(moduleId), {\n relativeTo: 'server',\n resolverOptions,\n transformOptions,\n });\n }\n}\n\nfunction getBuildID(buildNumber: number): string {\n return buildNumber.toString(36);\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\nasync function sourceMapStringAsync(\n modules: readonly import('metro/src/DeltaBundler/types').Module<any>[],\n options: SourceMapGeneratorOptions\n): Promise<string> {\n return (await sourceMapGeneratorNonBlocking(modules, options)).toString(undefined, {\n excludeSource: options.excludeSource,\n });\n}\n\nfunction unique<T>(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n"],"names":["MetroBundlerDevServer","debug","require","EXPO_GO_METRO_PORT","DEV_CLIENT_METRO_PORT","BundlerDevServer","name","resolvePortAsync","options","port","devClient","Number","process","env","RCT_METRO_PORT","getFreePortAsync","exportExpoRouterApiRoutesAsync","includeSourceMaps","outputDir","prerenderManifest","platform","routerRoot","instanceMetroOptions","assert","appDir","path","join","projectRoot","manifest","getExpoRouterRoutesManifestAsync","files","Map","rscPath","isReactServerComponentsEnabled","apiRoutes","find","route","page","startsWith","push","file","resolveFrom","namedRegex","routeKeys","rsc","filepath","isAbsolute","contents","bundleApiRoute","artifactFilename","convertPathToModuleSpecifier","relative","replace","src","map","artifactBasename","encodeURIComponent","basename","parsedMap","JSON","parse","set","stringify","version","sources","source","sourcesContent","Array","length","fill","names","mappings","apiRouteId","targetDomain","htmlRoutes","exp","getConfig","fetchManifest","extra","router","preserveRedirectAndRewrites","asJson","CommandError","getServerManifestAsync","getBuildTimeServerManifestAsync","getManifest","ssrLoadModule","environment","isReactServerRoutesEnabled","serverManifest","htmlManifest","getStaticRenderFunctionAsync","url","getDevServerUrlOrAssert","getStaticContent","preserveApiRoutes","renderAsync","URL","getStaticResourcesAsync","mainModuleName","clientBoundaries","mode","minify","isExporting","baseUrl","reactCompiler","asyncRoutes","resolvedMainModuleName","resolveMainModuleName","metroImportAsArtifactsAsync","splitChunks","EXPO_NO_BUNDLE_SPLITTING","serializerIncludeMaps","lazy","shouldEnableAsyncImports","bytecode","getStaticPageAsync","pathname","devBundleUrlPathname","createBundleUrlPath","bundleStaticHtml","location","artifacts","resources","staticHtml","Promise","all","content","serializeHtmlWithAssets","template","devBundleUrl","hydrate","EXPO_WEB_DEV_HYDRATE","filePath","specificOptions","results","ssrLoadModuleContents","serializerOutput","assets","filename","metroLoadModuleContents","extraOptions","opts","inlineSourceMap","engine","expoBundleOptions","getMetroDirectBundleOptions","resolverOptions","customResolverOptions","dev","transformOptions","hot","type","unstable_transformProfile","customTransformOptions","Object","create","runtimeBytecodeVersion","resolvedEntryFilePath","resolveRelativePathAsync","createBundleOsPath","_bundleDirectAsync","graphOptions","shallow","serializerOptions","modulesOnly","runModule","sourceUrl","sourceMapUrl","bundle","rest","scriptContents","wrapBundle","cachedSourceMaps","nativeExportBundleAsync","singlePageReactServerComponentExportAsync","legacySinglePageExportBundleAsync","getReactServerReferences","unique","filter","a","artifact","metadata","reactServerReferences","ref","fileURLToFilePath","flat","Boolean","reactClientReferences","serverActionReferencesInServer","cssModules","rscRenderer","getExpoRouterClientReferencesAsync","domRoot","processClientBoundaries","newReactServerReferences","Error","allKnownReactServerReferences","nestedClientBoundaries","exportServerActionsAsync","entryPoints","hasUniqueClientBoundaries","some","boundary","includes","concat","serverRoot","getMetroServerRoot","clientBoundariesAsOpaqueIds","toPosixPath","moduleIdToSplitBundle","paths","values","reduce","acc","ssrManifest","keys","forEach","routerOptions","exportRoutesAsync","fromEntries","from","entries","key","value","output","watchEnvironmentVariables","instance","metro","envFiles","runtimeEnv","getFiles","NODE_ENV","fileName","observeFileChanges","server","load","force","startImplementationAsync","urlCreator","getUrlCreator","config","skipSDKVersionRequirement","experiments","reactServerComponentRoutes","reactServerFunctions","isReactServerActionsOnlyEnabled","useServerRendering","web","hasApiRoutes","getBaseUrlFromExpoConfig","getAsyncRoutesFromExpoConfig","getRouterDirectoryModuleIdWithManifest","origin","configPath","dynamicConfigPath","staticConfigPath","configFileName","parsedOptions","maxWorkers","resetCache","resetDevServer","EXPO_DEV_SERVER_ORIGIN","hmrServer","middleware","messageSocket","instantiateMetroAsync","manifestMiddleware","getManifestMiddlewareAsync","prependMiddleware","ContextModuleSourceMapsMiddleware","getHandler","use","InterstitialPageMiddleware","scheme","DevToolsPluginMiddleware","devToolsPluginManager","deepLinkMiddleware","RuntimeRedirectMiddleware","getLocation","runtime","constructDevClientUrl","constructUrl","domComponentRenderer","createDomComponentsMiddleware","metroRoot","CreateFileMiddleware","isTargetingWeb","ServeStaticMiddleware","FaviconMiddleware","observeAnyFileChanges","events","invalidateApiRouteCache","hasWarnedAboutApiRoutes","event","isApiRouteConvention","warnInvalidWebOutput","bindRSCDevModuleInjectionHandler","rscMiddleware","createServerComponentsMiddleware","bind","ssrLoadModuleArtifacts","useClientRouter","createModuleId","_createModuleId","onReloadRscEvent","HistoryFallbackMiddleware","internal","createRouteHandlerMiddleware","functionFilePath","ssrImportApiRoute","html","getSingleHtmlTemplateAsync","originalClose","close","callback","err","ssrHmrClients","assertMetroPrivateServer","host","protocol","registerSsrHmrAsync","onReload","has","sendFn","message","data","String","update","body","isInitialUpdate","added","modified","deleted","hasUpdate","globalThis","__c","allModuleIds","Set","m","module","platforms","moduleId","match","Log","error","_bundler","_revisionsByGraphId","client","onClientConnect","optedIntoHMR","_registerEntryPoint","waitForTypeScriptAsync","resolve","off","metroWatchTypeScriptFiles","tsconfig","throttle","eventTypes","TypeScriptProjectPrerequisite","req","bootstrapAsync","log","chalk","red","exception","startTypeScriptServices","startTypescriptTypeGenerationAsync","getConfigModuleIds","pendingRouteOperations","get","bundleAsync","undefined","relativePath","apiRoute","evalMetroNoHandling","htmlServerError","getErrorOverlayHtmlAsync","Response","status","headers","internalError","clear","__expo_rsc_inject_module","sendClientModule","code","id","broadcastMessage","setupHmr","toString","_config","buildNumber","getNewBuildNumber","bundlePerfLogger","unstable_perfLoggerFactory","onProgress","transformedFileCount","totalFileCount","_reporter","buildID","getBuildID","revPromise","getMetroRevision","point","annotate","bool","initial_build","bundleDetails","bundleType","entryFile","isPrefetch","delta","revision","props","getBundler","initializeGraph","updateGraph","int","graph_node_count","graph","dependencies","size","shouldAddToIgnoreList","_shouldAddModuleToIgnoreList","serializer","getMetroSerializer","prepend","asyncRequireModulePath","_resolveRelativePath","transformer","relativeTo","processModuleFilter","getRunModuleStatement","includeAsyncPaths","runBeforeMainModule","getModulesRunBeforeMainModule","unstable_serverRoot","bundleCode","bundleMap","parsed","isArray","asset","numModifiedFiles","reset","lastModifiedDate","date","nextRevId","sourceMapStringAsync","_getSortedModules","excludeSource","IS_METRO_BUNDLE_ERROR_SYMBOL","customSerializer","entryPoint","preModules","bundleToString","baseJSBundle","graphId","getGraphId","unstable_allowRequireContext","getRevisionByGraphId","extras","res","evalMetroAndWrapFunctions","str","modules","sourceMapGeneratorNonBlocking","array"],"mappings":"AAAA;;;;;CAKC;;;;+BAqHYA;;;eAAAA;;;;yBApHyB;;;;;;;yBACH;;;;;;;iEACP;;;;;;;gEAET;;;;;;;gEACD;;;;;;;gEAEO;;;;;;;yBAIlB;;;;;;;gEAIoB;;;;;;;gEACJ;;;;;;;gEAGN;;;;;;;gEACO;;;;;;kDAKjB;6CACsC;qCACa;kCACpB;qCACiC;oCACV;2CACnB;wBAMnC;+BACiC;qDACkB;qBAEtC;sBACA;wBACS;0BACD;sBACK;kCACwC;0CAKlE;mDAC2C;sCACb;0CACI;yCACK;mCACZ;2CACQ;4CACC;oCACL;2CACI;uCACJ;8BAU/B;2BAC2B;+CACiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCnD,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,qDAAqD,GACrD,MAAMC,qBAAqB;AAE3B,iGAAiG,GACjG,MAAMC,wBAAwB;AAEvB,MAAMJ,8BAA8BK,kCAAgB;IAOzD,IAAIC,OAAe;QACjB,OAAO;IACT;IAEA,MAAMC,iBAAiBC,UAAwC,CAAC,CAAC,EAAmB;QAClF,MAAMC,OACJ,yEAAyE;QACzED,QAAQC,IAAI,IACZ,8DAA8D;QAC7DD,CAAAA,QAAQE,SAAS,GAEdC,OAAOC,QAAQC,GAAG,CAACC,cAAc,KAAKV,wBAEtC,MAAMW,IAAAA,sBAAgB,EAACZ,mBAAkB;QAE/C,OAAOM;IACT;IAEA,MAAMO,+BA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c,IAAI,CAACxR,uBAAuB;gBAC9D,IAAI,CAACuS,QAAQ,CAACxS;YAChB;YAEA,OAAOkX,IAAAA,mDAAyB,EAC9B,IAAI,CAACnb,WAAW,EAChBkb,IAAIxZ,GAAG,EACPwZ,IAAIlU,QAAQ,EACZL,gBAAgB/B,WAAW,IAAI,IAAI,CAACjF,oBAAoB,CAACiF,WAAW;QAExE,QA4bAwF,cAAmF,WAwQ3EkH,mBAAwD,MAwJhE,aAAa;aAELgE,yBAAyB,IAAIlV;;AAmcvC;AAEA,SAASiX,WAAWT,WAAmB;IACrC,OAAOA,YAAYF,QAAQ,CAAC;AAC9B;AAEA,SAASzN,WAAWmS,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAI3Z,OAAO,CAAC,oBAAoB;AACzC;AAEA,eAAe2Y,qBACbiB,OAAsE,EACtExc,OAAkC;IAElC,OAAO,AAAC,CAAA,MAAMyc,IAAAA,mDAA6B,EAACD,SAASxc,QAAO,EAAG6X,QAAQ,CAACjB,WAAW;QACjF6E,eAAezb,QAAQyb,aAAa;IACtC;AACF;AAEA,SAAS/Q,OAAUgS,KAAU;IAC3B,OAAO/Y,MAAM0J,IAAI,CAAC,IAAIqH,IAAIgI;AAC5B"}
@@ -182,8 +182,10 @@ function createServerComponentsMiddleware(projectRoot, { rscPath, instanceMetroO
182
182
  targetDomain: 'server',
183
183
  contents: wrapBundle(contents.src)
184
184
  });
185
+ // Match babel plugin.
186
+ const publicModuleId = './' + (0, _filePath.toPosixPath)(_path().default.relative(projectRoot, entryPoint));
185
187
  // Import relative to `dist/server/_expo/rsc/web/router.js`
186
- manifest[entryPoint] = [
188
+ manifest[publicModuleId] = [
187
189
  String(relativeName),
188
190
  outputName
189
191
  ];
@@ -276,13 +278,14 @@ function createServerComponentsMiddleware(projectRoot, { rscPath, instanceMetroO
276
278
  const { mode, minify = false, isExporting, baseUrl, routerRoot, asyncRoutes, preserveEnvVars, reactCompiler, lazy } = instanceMetroOptions;
277
279
  (0, _assert().default)(isExporting != null && baseUrl != null && mode != null && routerRoot != null && asyncRoutes != null, `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`);
278
280
  return (file, isServer)=>{
281
+ const filePath = _path().default.join(projectRoot, file.startsWith('file://') ? fileURLToFilePath(file) : file);
279
282
  if (isExporting) {
280
283
  (0, _assert().default)(context.ssrManifest, 'SSR manifest must exist when exporting');
281
- const relativeFilePath = (0, _filePath.toPosixPath)(_path().default.relative(serverRoot, file));
284
+ const relativeFilePath = (0, _filePath.toPosixPath)(_path().default.relative(serverRoot, filePath));
282
285
  (0, _assert().default)(context.ssrManifest.has(relativeFilePath), `SSR manifest is missing client boundary "${relativeFilePath}"`);
283
286
  const chunk = context.ssrManifest.get(relativeFilePath);
284
287
  return {
285
- id: String(createModuleId(file, {
288
+ id: String(createModuleId(filePath, {
286
289
  platform: context.platform,
287
290
  environment: 'client'
288
291
  })),
@@ -317,7 +320,6 @@ function createServerComponentsMiddleware(projectRoot, { rscPath, instanceMetroO
317
320
  // TICKLE: Handshake 1
318
321
  searchParams.set('xRSC', '1');
319
322
  clientReferenceUrl.search = searchParams.toString();
320
- const filePath = file.startsWith('file://') ? fileURLToFilePath(file) : file;
321
323
  const relativeFilePath = _path().default.relative(serverRoot, filePath);
322
324
  clientReferenceUrl.pathname = relativeFilePath;
323
325
  // Ensure url.pathname ends with '.bundle'
@@ -405,6 +407,7 @@ function createServerComponentsMiddleware(projectRoot, { rscPath, instanceMetroO
405
407
  const serverRoot = getMetroServerRootMemo(projectRoot);
406
408
  debug('[SSR] loadServerModuleRsc:', urlFragment);
407
409
  const options = (0, _metroOptions.getMetroOptionsFromUrl)(urlFragment);
410
+ console.log('loadServerModuleRsc:', serverRoot, options.mainModuleName);
408
411
  return ssrLoadModule(_path().default.join(serverRoot, options.mainModuleName), options, {
409
412
  hot: true
410
413
  });
@@ -474,7 +477,16 @@ const getFullUrl = (url)=>{
474
477
  }
475
478
  };
476
479
  const fileURLToFilePath = (fileURL)=>{
477
- return _url().default.fileURLToPath(fileURL);
480
+ try {
481
+ return _url().default.fileURLToPath(fileURL);
482
+ } catch (error) {
483
+ if (error instanceof TypeError) {
484
+ throw Error(`Invalid URL: ${fileURL}`, {
485
+ cause: error
486
+ });
487
+ }
488
+ throw error;
489
+ }
478
490
  };
479
491
  const encodeInput = (input)=>{
480
492
  if (input === '') {
@@ -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 { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport { getRscMiddleware } from '@expo/server/build/middleware/rsc';\nimport assert from 'assert';\nimport { EntriesDev } from 'expo-router/build/rsc/server';\nimport path from 'path';\nimport url from 'url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport { 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 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,\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/build/rsc/router/noopRouter'\n : 'expo-router/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 // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[entryPoint] = [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/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>;\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 if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n const relativeFilePath = toPosixPath(path.relative(serverRoot, file));\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(createModuleId(file, { platform: context.platform, environment: 'client' })),\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 filePath = file.startsWith('file://') ? fileURLToFilePath(file) : file;\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<string, typeof import('expo-router/build/rsc/rsc-renderer')>();\n\n let ensurePromise: Promise<any> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n const runtime = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'metro-runtime/src/modules/empty-module.js',\n {\n environment: 'react-server',\n platform: 'web',\n }\n );\n return runtime;\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<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'expo-router/build/rsc/rsc-renderer',\n {\n environment: 'react-server',\n platform,\n }\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>;\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(path.join(serverRoot, options.mainModuleName), options, {\n hot: true,\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>;\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 return url.fileURLToPath(fileURL);\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","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","ssrManifest","relativeFilePath","toPosixPath","relative","chunk","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","filePath","pathname","endsWith","chunkName","rscRendererCache","ensurePromise","ensureSSRReady","runtime","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","join","exportRoutesAsync","getBuildConfig","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","delete","fileURL","fileURLToPath","str","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAuCeA,gCAAgC;eAAhCA;;IAslBHC,iBAAiB;eAAjBA;;;;yBA5nBsB;;;;;;;yBAEF;;;;;;;gEACd;;;;;;;gEAEF;;;;;;;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,kBACjB,4CACA;IAEJ,MAAMI,gBAAgBC,IAAAA,uBAAgB,EAAC;QACrCC,QAAQ,CAAC;QACT,0BAA0B;QAC1BC,SAAS;QACTX;QACAY,SAASC,QAAQC,KAAK;QACtBC,WAA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CAACpD;QACjD,GACAxB;QAEFiK,kBAAkB,CAACvI;YACjB,+FAA+F;YAE/FkG,iBAAiBsC,MAAM,CAACxI;YACxBmD,YAAYqF,MAAM,CAACxI;QACrB;IACF;AACF;AAEA,MAAMqI,aAAa,CAACC;IAClB,IAAI;QACF,OAAO,IAAI3C,IAAI2C;IACjB,EAAE,OAAM;QACN,OAAO,IAAI3C,IAAI2C,KAAK;IACtB;AACF;AAEO,MAAM/K,oBAAoB,CAACkL;IAChC,OAAOH,cAAG,CAACI,aAAa,CAACD;AAC3B;AAEA,MAAMZ,cAAc,CAACnB;IACnB,IAAIA,UAAU,IAAI;QAChB,OAAO;IACT;IACA,IAAIA,UAAU,SAAS;QACrB,MAAM,IAAI7E,MAAM;IAClB;IACA,IAAI6E,MAAMxD,UAAU,CAAC,MAAM;QACzB,MAAM,IAAIrB,MAAM;IAClB;IACA,IAAI6E,MAAMV,QAAQ,CAAC,MAAM;QACvB,MAAM,IAAInE,MAAM;IAClB;IACA,OAAO6E,QAAQ;AACjB;AAEA,SAASnE,WAAWoG,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAIC,OAAO,CAAC,oBAAoB;AACzC"}
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 { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport { getRscMiddleware } from '@expo/server/build/middleware/rsc';\nimport assert from 'assert';\nimport { EntriesDev } from 'expo-router/build/rsc/server';\nimport path from 'path';\nimport url from 'url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport { 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 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,\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/build/rsc/router/noopRouter'\n : 'expo-router/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/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>;\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<string, typeof import('expo-router/build/rsc/rsc-renderer')>();\n\n let ensurePromise: Promise<any> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n const runtime = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'metro-runtime/src/modules/empty-module.js',\n {\n environment: 'react-server',\n platform: 'web',\n }\n );\n return runtime;\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<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'expo-router/build/rsc/rsc-renderer',\n {\n environment: 'react-server',\n platform,\n }\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>;\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 console.log('loadServerModuleRsc:', serverRoot, options.mainModuleName);\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>;\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","runtime","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","log","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;;IAqmBHC,iBAAiB;eAAjBA;;;;yBA3oBsB;;;;;;;yBAEF;;;;;;;gEACd;;;;;;;gEAEF;;;;;;;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,kBACjB,4CACA;IAEJ,MAAMI,gBAAgBC,IAAAA,uBAAgB,EAAC;QACrCC,QAAQ,CAAC;QACT,0BAA0B;QAC1BC,SAAS;QACTX;QACAY,SAASC,QAAQC,KAAK;QACtBC,WAAW,OAAOC;YAChB,gFAAgF;YAChF,IAAIA,KAAKC,OAAO,CAAC,YAAY,IAAI,MAAM;gBACrCD,KAAKC,OAAO,CAAC,YAAY,GAAGC,IAAAA,gBAAY;YAC1C;YACA,IAAIF,KAAKC,OAAO,CAAC,kBAAkB,IAAI,MAAM;gBAC3CD,KAAKC,OAAO,CAAC,kBAAkB,GAAGD,KAAKC,OAAO,CAAC,YAAY;YAC7D;YACA,IAAID,KAAKC,OAAO,CAAC,oBAAoB,IAAI,MAAM;gBAC7CD,KAAKC,OAAO,CAAC,oBAAoB,GAAG;YACtC;YAEA,kCAAkC;YAClC,IAAI;gBACF,OAAO,MAAME,0BAA0B;oBACrC,GAAGH,IAAI;oBACPC,SAAS,IAAIG,QAAQJ,KAAKC,OAAO;oBACjCI,MAAML,KAAKK,IAAI;oBACff;gBACF;YACF,EAAE,OAAOQ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,EAAE,OAAO/J,OAAO;QACd,IAAIA,iBAAiBiK,WAAW;YAC9B,MAAMhH,MAAM,CAAC,aAAa,EAAE8G,SAAS,EAAE;gBAAEG,OAAOlK;YAAM;QACxD;QACA,MAAMA;IACR;AACF;AAEA,MAAMmJ,cAAc,CAACnB;IACnB,IAAIA,UAAU,IAAI;QAChB,OAAO;IACT;IACA,IAAIA,UAAU,SAAS;QACrB,MAAM,IAAI/E,MAAM;IAClB;IACA,IAAI+E,MAAMvD,UAAU,CAAC,MAAM;QACzB,MAAM,IAAIxB,MAAM;IAClB;IACA,IAAI+E,MAAMV,QAAQ,CAAC,MAAM;QACvB,MAAM,IAAIrE,MAAM;IAClB;IACA,OAAO+E,QAAQ;AACjB;AAEA,SAASrE,WAAWwG,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAIC,OAAO,CAAC,oBAAoB;AACzC"}
@@ -156,7 +156,9 @@ function withWebPolyfills(config, { getMetroBundler }) {
156
156
  return [
157
157
  ...polyfills,
158
158
  virtualModuleId,
159
- virtualEnvVarId
159
+ virtualEnvVarId,
160
+ // Removed on server platforms during the transform.
161
+ require.resolve('expo/virtual/streams.js')
160
162
  ];
161
163
  };
162
164
  return {
@@ -685,7 +687,8 @@ async function withMetroMultiPlatformAsync(projectRoot, { config, exp, platformB
685
687
  // @ts-expect-error: watchFolders is readonly
686
688
  config.watchFolders.push(_path().default.join(require.resolve('metro-runtime/package.json'), '../..'));
687
689
  // @ts-expect-error: watchFolders is readonly
688
- config.watchFolders.push(_path().default.join(require.resolve('@expo/metro-config/package.json'), '../..'));
690
+ config.watchFolders.push(_path().default.join(require.resolve('@expo/metro-config/package.json'), '../..'), // For virtual modules
691
+ _path().default.join(require.resolve('expo/package.json'), '..'));
689
692
  if (isReactCanaryEnabled) {
690
693
  // @ts-expect-error: watchFolders is readonly
691
694
  config.watchFolders.push(_path().default.join(require.resolve('@expo/cli/package.json'), '..'));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.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 { ExpoConfig, Platform } from '@expo/config';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport Bundler from 'metro/src/Bundler';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext, CustomResolutionContext } from 'metro-resolver';\nimport * as metroResolver from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { createFallbackModuleResolver } from './createExpoFallbackResolver';\nimport { createFastResolver, FailedToResolvePathError } from './createExpoMetroResolver';\nimport { isNodeExternal, shouldCreateVirtualCanary, shouldCreateVirtualShim } from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { getMetroBundlerWithVirtualModules } from './metroVirtualModules';\nimport {\n withMetroErrorReportingResolver,\n withMetroMutatedResolverContext,\n withMetroResolvers,\n} from './withMetroResolvers';\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { isServerEnvironment } from '../middleware/metroOptions';\nimport { PlatformBundlers } from '../platformBundlers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nexport type StrictResolver = (moduleName: string) => Resolution;\nexport type StrictResolverFactory = (\n context: ResolutionContext,\n platform: string | null\n) => StrictResolver;\n\nconst ASSET_REGISTRY_SRC = `const assets=[];module.exports={registerAsset:s=>assets.push(s),getAssetByID:s=>assets[s-1]};`;\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(\n config: ConfigT,\n {\n getMetroBundler,\n }: {\n getMetroBundler: () => Bundler;\n }\n): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform?: string | null }): readonly string[] => {\n const virtualEnvVarId = `\\0polyfill:environment-variables`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualEnvVarId,\n (() => {\n return `//`;\n })()\n );\n\n const virtualModuleId = `\\0polyfill:external-require`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n (() => {\n if (ctx.platform === 'web') {\n return `global.$$require_external = typeof window === \"undefined\" ? require : () => null;`;\n } else {\n // Wrap in try/catch to support Android.\n return 'try { global.$$require_external = typeof expo === \"undefined\" ? require : (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} } catch { global.$$require_external = (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} }';\n }\n })()\n );\n\n if (ctx.platform === 'web') {\n return [\n virtualModuleId,\n virtualEnvVarId,\n // Ensure that the error-guard polyfill is included in the web polyfills to\n // make metro-runtime work correctly.\n // TODO: This module is pretty big for a function that simply re-throws an error that doesn't need to be caught.\n require.resolve('@react-native/js-polyfills/error-guard'),\n ];\n }\n\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n return [...polyfills, virtualModuleId, virtualEnvVarId];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function getNodejsExtensions(srcExts: readonly string[]): string[] {\n const mjsExts = srcExts.filter((ext) => /mjs$/.test(ext));\n const nodejsSourceExtensions = srcExts.filter((ext) => !/mjs$/.test(ext));\n // find index of last `*.js` extension\n const jsIndex = nodejsSourceExtensions.reduce((index, ext, i) => {\n return /jsx?$/.test(ext) ? i : index;\n }, -1);\n\n // insert `*.mjs` extensions after `*.js` extensions\n nodejsSourceExtensions.splice(jsIndex + 1, 0, ...mjsExts);\n\n return nodejsSourceExtensions;\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n * - Alias react-native renderer code to a vendored React canary build on native.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n tsconfig,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n tsconfig: TsConfigPaths | null;\n isTsconfigPathsEnabled?: boolean;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled?: boolean;\n isReactServerComponentsEnabled?: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isReactServerComponentsEnabled) {\n Log.warn(`React Server Components (beta) is enabled.`);\n }\n if (isReactCanaryEnabled) {\n Log.warn(`Experimental React 19 canary is enabled.`);\n }\n if (isFastResolverEnabled) {\n Log.log(chalk.dim`Fast resolver is enabled.`);\n }\n\n const defaultResolver = metroResolver.resolve;\n const resolver = isFastResolverEnabled\n ? createFastResolver({\n preserveSymlinks: true,\n blockList: !config.resolver?.blockList\n ? []\n : Array.isArray(config.resolver?.blockList)\n ? config.resolver?.blockList\n : [config.resolver?.blockList],\n })\n : defaultResolver;\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n 'react-native/index': 'react-native-web',\n 'react-native/Libraries/Image/resolveAssetSource': 'expo-asset/build/resolveAssetSource',\n },\n };\n\n let _universalAliases: [RegExp, string][] | null;\n\n function getUniversalAliases() {\n if (_universalAliases) {\n return _universalAliases;\n }\n\n _universalAliases = [];\n\n // This package is currently always installed as it is included in the `expo` package.\n if (resolveFrom.silent(config.projectRoot, '@expo/vector-icons')) {\n debug('Enabling alias: react-native-vector-icons -> @expo/vector-icons');\n _universalAliases.push([/^react-native-vector-icons(\\/.*)?/, '@expo/vector-icons$1']);\n }\n if (isReactServerComponentsEnabled) {\n if (resolveFrom.silent(config.projectRoot, 'expo-router/rsc')) {\n debug('Enabling bridge alias: expo-router -> expo-router/rsc');\n _universalAliases.push([/^expo-router$/, 'expo-router/rsc']);\n // Bridge the internal entry point which is a standalone import to ensure package.json resolution works as expected.\n _universalAliases.push([/^expo-router\\/entry-classic$/, 'expo-router/rsc/entry']);\n }\n }\n return _universalAliases;\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve =\n isTsconfigPathsEnabled && (tsconfig?.paths || tsconfig?.baseUrl != null)\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsconfig.baseUrl,\n })\n : null;\n\n // TODO: Move this to be a transform key for invalidation.\n if (!isExporting && isInteractive()) {\n if (isTsconfigPathsEnabled) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(config.projectRoot, [\n './tsconfig.json',\n './jsconfig.json',\n ]);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(config.projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n }\n\n let nodejsSourceExtensions: string[] | null = null;\n\n const getStrictResolver: StrictResolverFactory = (\n { resolveRequest, ...context },\n platform\n ): StrictResolver => {\n return function doResolve(moduleName: string): Resolution {\n return resolver(context, moduleName, platform);\n };\n };\n\n function getOptionalResolver(context: ResolutionContext, platform: string | null) {\n const doResolve = getStrictResolver(context, platform);\n return function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n };\n }\n\n // TODO: This is a hack to get resolveWeak working.\n const idFactory = (config.serializer?.createModuleIdFactory?.() ??\n ((id: number | string, context: { platform: string; environment?: string }): number | string =>\n id)) as (\n id: number | string,\n context: { platform: string; environment?: string }\n ) => number | string;\n\n const getAssetRegistryModule = () => {\n const virtualModuleId = `\\0polyfill:assets-registry`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n ASSET_REGISTRY_SRC\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n } as const;\n };\n\n // If Node.js pass-through, then remap to a module like `module.exports = $$require_external(<module>)`.\n // If module should be shimmed, remap to an empty module.\n const externals: {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => boolean;\n replace: 'empty' | 'node' | 'weak';\n }[] = [\n {\n match: (context: ResolutionContext, moduleName: string) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for Node.js environments.\n !isServerEnvironment(context.customResolverOptions?.environment)\n ) {\n return false;\n }\n\n if (context.customResolverOptions?.environment === 'react-server') {\n // Ensure these non-react-server modules are excluded when bundling for React Server Components in development.\n return /^(source-map-support(\\/.*)?|@babel\\/runtime\\/.+|debug|metro-runtime\\/src\\/modules\\/HMRClient|metro|acorn-loose|acorn|chalk|ws|ansi-styles|supports-color|color-convert|has-flag|utf-8-validate|color-name|react-refresh\\/runtime|@remix-run\\/node\\/.+)$/.test(\n moduleName\n );\n }\n\n // TODO: Windows doesn't support externals somehow.\n if (process.platform === 'win32') {\n return /^(source-map-support(\\/.*)?)$/.test(moduleName);\n }\n\n // Extern these modules in standard Node.js environments in development to prevent API routes side-effects\n // from leaking into the dev server process.\n return /^(source-map-support(\\/.*)?|react|@radix-ui\\/.+|@babel\\/runtime\\/.+|react-dom(\\/.+)?|debug|acorn-loose|acorn|css-in-js-utils\\/lib\\/.+|hyphenate-style-name|color|color-string|color-convert|color-name|fontfaceobserver|fast-deep-equal|query-string|escape-string-regexp|invariant|postcss-value-parser|memoize-one|nullthrows|strict-uri-encode|decode-uri-component|split-on-first|filter-obj|warn-once|simple-swizzle|is-arrayish|inline-style-prefixer\\/.+)$/.test(\n moduleName\n );\n },\n replace: 'node',\n },\n // Externals to speed up async split chunks by extern-ing common packages that appear in the root client chunk.\n {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for client environments.\n isServerEnvironment(context.customResolverOptions?.environment) ||\n // Only enable for client boundaries\n !context.customResolverOptions.clientboundary\n ) {\n return false;\n }\n\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return false;\n }\n\n const isExternal = // Extern these modules in standard Node.js environments.\n /^(deprecated-react-native-prop-types|react|react\\/jsx-dev-runtime|scheduler|react-native|react-dom(\\/.+)?|metro-runtime(\\/.+)?)$/.test(\n moduleName\n ) ||\n // TODO: Add more\n /^@babel\\/runtime\\/helpers\\/(wrapNativeSuper)$/.test(moduleName);\n\n return isExternal;\n },\n replace: 'weak',\n },\n ];\n\n const metroConfigWithCustomResolver = withMetroResolvers(config, [\n // Mock out production react imports in development.\n function requestDevMockProdReact(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // This resolution is dev-only to prevent bundling the production React packages in development.\n if (!context.dev) return null;\n\n if (\n // Match react-native renderers.\n (platform !== 'web' &&\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/]react-native[\\\\/]/) &&\n moduleName.match(/([\\\\/]ReactFabric|ReactNativeRenderer)-prod/)) ||\n // Match react production imports.\n (moduleName.match(/\\.production(\\.min)?\\.js$/) &&\n // Match if the import originated from a react package.\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/](react[-\\\\/]|scheduler[\\\\/])/))\n ) {\n debug(`Skipping production module: ${moduleName}`);\n // /Users/path/to/expo/node_modules/react/index.js ./cjs/react.production.min.js\n // /Users/path/to/expo/node_modules/react/jsx-dev-runtime.js ./cjs/react-jsx-dev-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n // /Users/path/to/expo/node_modules/react-refresh/runtime.js ./cjs/react-refresh-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/scheduler/index.native.js ./cjs/scheduler.native.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n return {\n type: 'empty',\n };\n }\n return null;\n },\n // tsconfig paths\n function requestTsconfigPaths(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n return (\n tsConfigResolve?.(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n getOptionalResolver(context, platform)\n ) ?? null\n );\n },\n\n // Node.js externals support\n function requestNodeExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n const moduleId = isNodeExternal(moduleName);\n if (!moduleId) {\n return null;\n }\n\n if (\n // In browser runtimes, we want to either resolve a local node module by the same name, or shim the module to\n // prevent crashing when Node.js built-ins are imported.\n !isServer\n ) {\n // Perform optional resolve first. If the module doesn't exist (no module in the node_modules)\n // then we can mock the file to use an empty module.\n const result = getOptionalResolver(context, platform)(moduleName);\n\n if (!result && platform !== 'web') {\n // Preserve previous behavior where native throws an error on node.js internals.\n return null;\n }\n\n return (\n result ?? {\n // In this case, mock the file to use an empty module.\n type: 'empty',\n }\n );\n }\n const contents = `module.exports=$$require_external('node:${moduleId}');`;\n debug(`Virtualizing Node.js \"${moduleId}\"`);\n const virtualModuleId = `\\0node:${moduleId}`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n },\n\n // Custom externals support\n function requestCustomExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return null;\n }\n // Skip applying JS externals for CSS files.\n if (/\\.(s?css|sass)$/.test(context.originModulePath)) {\n return null;\n }\n\n const environment = context.customResolverOptions?.environment;\n\n const strictResolve = getStrictResolver(context, platform);\n\n for (const external of externals) {\n if (external.match(context, moduleName, platform)) {\n if (external.replace === 'empty') {\n debug(`Redirecting external \"${moduleName}\" to \"${external.replace}\"`);\n return {\n type: external.replace,\n };\n } else if (external.replace === 'weak') {\n // TODO: Make this use require.resolveWeak again. Previously this was just resolving to the same path.\n const realModule = strictResolve(moduleName);\n const realPath = realModule.type === 'sourceFile' ? realModule.filePath : moduleName;\n const opaqueId = idFactory(realPath, {\n platform: platform!,\n environment,\n });\n\n const contents =\n typeof opaqueId === 'number'\n ? `module.exports=/*${moduleName}*/__r(${opaqueId})`\n : `module.exports=/*${moduleName}*/__r(${JSON.stringify(opaqueId)})`;\n // const contents = `module.exports=/*${moduleName}*/__r(require.resolveWeak('${moduleName}'))`;\n // const generatedModuleId = fastHashMemoized(contents);\n const virtualModuleId = `\\0weak:${opaqueId}`;\n debug('Virtualizing module:', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else if (external.replace === 'node') {\n const contents = `module.exports=$$require_external('${moduleName}')`;\n const virtualModuleId = `\\0node:${moduleName}`;\n debug('Virtualizing Node.js (custom):', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else {\n throw new CommandError(\n `Invalid external alias type: \"${external.replace}\" for module \"${moduleName}\" (platform: ${platform}, originModulePath: ${context.originModulePath})`\n );\n }\n }\n }\n return null;\n },\n\n // Basic moduleId aliases\n function requestAlias(context: ResolutionContext, moduleName: string, platform: string | null) {\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n const redirectedModuleName = aliases[platform][moduleName];\n return getStrictResolver(context, platform)(redirectedModuleName);\n }\n\n for (const [matcher, alias] of getUniversalAliases()) {\n const match = moduleName.match(matcher);\n if (match) {\n const aliasedModule = alias.replace(\n /\\$(\\d+)/g,\n (_, index) => match[parseInt(index, 10)] ?? ''\n );\n const doResolve = getStrictResolver(context, platform);\n debug(`Alias \"${moduleName}\" to \"${aliasedModule}\"`);\n return doResolve(aliasedModule);\n }\n }\n\n return null;\n },\n\n // Polyfill for asset registry\n function requestStableAssetRegistry(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n if (/^@react-native\\/assets-registry\\/registry(\\.js)?$/.test(moduleName)) {\n return getAssetRegistryModule();\n }\n\n if (\n platform === 'web' &&\n context.originModulePath.match(/node_modules[\\\\/]react-native-web[\\\\/]/) &&\n moduleName.includes('/modules/AssetRegistry')\n ) {\n return getAssetRegistryModule();\n }\n\n return null;\n },\n\n // TODO: Reduce these as much as possible in the future.\n // Complex post-resolution rewrites.\n function requestPostRewrites(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const doResolve = getStrictResolver(context, platform);\n\n const result = doResolve(moduleName);\n\n if (result.type !== 'sourceFile') {\n return result;\n }\n\n if (platform === 'web') {\n if (result.filePath.includes('node_modules')) {\n // // Disallow importing confusing native modules on web\n if (moduleName.includes('react-native/Libraries/Utilities/codegenNativeCommands')) {\n throw new FailedToResolvePathError(\n `Importing native-only module \"${moduleName}\" on web from: ${context.originModulePath}`\n );\n }\n\n // Replace with static shims\n\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const shimFile = shouldCreateVirtualShim(normalName);\n if (shimFile) {\n const virtualId = `\\0shim:${normalName}`;\n const bundler = getMetroBundlerWithVirtualModules(getMetroBundler());\n if (!bundler.hasVirtualModule(virtualId)) {\n bundler.setVirtualModule(virtualId, fs.readFileSync(shimFile, 'utf8'));\n }\n debug(`Redirecting module \"${result.filePath}\" to shim`);\n\n return {\n ...result,\n filePath: virtualId,\n };\n }\n }\n } else {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n // react-native/Libraries/Core/InitializeCore\n const normal = normalizeSlashes(result.filePath);\n\n // Shim out React Native native runtime globals in server mode for native.\n if (isServer) {\n if (normal.endsWith('react-native/Libraries/Core/InitializeCore.js')) {\n debug('Shimming out InitializeCore for React Native in native SSR bundle');\n return {\n type: 'empty',\n };\n }\n }\n\n // When server components are enabled, redirect React Native's renderer to the canary build\n // this will enable the use hook and other requisite features from React 19.\n if (isReactCanaryEnabled && result.filePath.includes('node_modules')) {\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const canaryFile = shouldCreateVirtualCanary(normalName);\n if (canaryFile) {\n debug(`Redirecting React Native module \"${result.filePath}\" to canary build`);\n return {\n ...result,\n filePath: canaryFile,\n };\n }\n }\n }\n\n return result;\n },\n\n // If at this point, we haven't resolved a module yet, if it's a module specifier for a known dependency\n // of either `expo` or `expo-router`, attempt to resolve it from these origin modules instead\n createFallbackModuleResolver({\n originModuleNames: ['expo', 'expo-router'],\n getStrictResolver,\n }),\n ]);\n\n // Ensure we mutate the resolution context to include the custom resolver options for server and web.\n const metroConfigWithCustomContext = withMetroMutatedResolverContext(\n metroConfigWithCustomResolver,\n (\n immutableContext: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ): CustomResolutionContext => {\n const context: Mutable<CustomResolutionContext> = {\n ...immutableContext,\n preferNativePlatform: platform !== 'web',\n };\n\n // TODO: Remove this when we have React 19 in the expo/expo monorepo.\n if (\n isReactCanaryEnabled &&\n // Change the node modules path for react and react-dom to use the vendor in Expo CLI.\n /^(react|react\\/.*|react-dom|react-dom\\/.*)$/.test(moduleName)\n ) {\n context.nodeModulesPaths = [\n path.join(require.resolve('@expo/cli/package.json'), '../static/canary-full'),\n ];\n }\n\n if (isServerEnvironment(context.customResolverOptions?.environment)) {\n // Adjust nodejs source extensions to sort mjs after js, including platform variants.\n if (nodejsSourceExtensions === null) {\n nodejsSourceExtensions = getNodejsExtensions(context.sourceExts);\n }\n context.sourceExts = nodejsSourceExtensions;\n\n context.unstable_enablePackageExports = true;\n context.unstable_conditionsByPlatform = {};\n\n const isReactServerComponents =\n context.customResolverOptions?.environment === 'react-server';\n\n if (isReactServerComponents) {\n // NOTE: Align the behavior across server and client. This is a breaking change so we'll just roll it out with React Server Components.\n // This ensures that react-server and client code both resolve `module` and `main` in the same order.\n if (platform === 'web') {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['module', 'main'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'module', 'main'];\n }\n } else {\n if (platform === 'web') {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['main', 'module'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'main', 'module'];\n }\n }\n\n // Enable react-server import conditions.\n if (context.customResolverOptions?.environment === 'react-server') {\n context.unstable_conditionNames = ['node', 'react-server', 'workerd'];\n } else {\n context.unstable_conditionNames = ['node'];\n }\n } else {\n // Non-server changes\n\n if (!env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE && platform && platform in preferredMainFields) {\n context.mainFields = preferredMainFields[platform];\n }\n }\n\n return context;\n }\n );\n\n return withMetroErrorReportingResolver(metroConfigWithCustomContext);\n}\n\n/** @returns `true` if the incoming resolution should be swapped. */\nexport function shouldAliasModule(\n input: {\n platform: string | null;\n result: Resolution;\n },\n alias: { platform: string; output: string }\n): boolean {\n return (\n input.platform === alias.platform &&\n input.result?.type === 'sourceFile' &&\n typeof input.result?.filePath === 'string' &&\n normalizeSlashes(input.result.filePath).endsWith(alias.output)\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isNamedRequiresEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n config: ConfigT;\n exp: ExpoConfig;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled: boolean;\n isReactServerComponentsEnabled: boolean;\n isNamedRequiresEnabled: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isNamedRequiresEnabled) {\n debug('Using Expo metro require runtime.');\n // Change the default metro-runtime to a custom one that supports bundle splitting.\n require('metro-config/src/defaults/defaults').moduleSystem = require.resolve(\n '@expo/cli/build/metro-require/require'\n );\n }\n\n if (!config.projectRoot) {\n // @ts-expect-error: read-only types\n config.projectRoot = projectRoot;\n }\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n // This is used for running Expo CLI in development against projects outside the monorepo.\n if (!isDirectoryIn(__dirname, projectRoot)) {\n if (!config.watchFolders) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders = [];\n }\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('metro-runtime/package.json'), '../..'));\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(\n path.join(require.resolve('@expo/metro-config/package.json'), '../..')\n );\n if (isReactCanaryEnabled) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('@expo/cli/package.json'), '..'));\n }\n }\n\n // TODO: Remove this\n // @ts-expect-error: Invalidate the cache when the location of expo-router changes on-disk.\n config.transformer._expoRouterPath = resolveFrom.silent(projectRoot, 'expo-router');\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(\n ([platform, bundler]) => bundler === 'metro' && exp.platforms?.includes(platform as Platform)\n )\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n config = withWebPolyfills(config, { getMetroBundler });\n\n return withExtendedResolver(config, {\n tsconfig,\n isExporting,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n });\n}\n\nfunction isDirectoryIn(targetPath: string, rootPath: string) {\n return targetPath.startsWith(rootPath) && targetPath.length >= rootPath.length;\n}\n"],"names":["getNodejsExtensions","shouldAliasModule","withExtendedResolver","withMetroMultiPlatformAsync","ASSET_REGISTRY_SRC","debug","require","withWebPolyfills","config","getMetroBundler","originalGetPolyfills","serializer","getPolyfills","bind","ctx","virtualEnvVarId","getMetroBundlerWithVirtualModules","setVirtualModule","virtualModuleId","platform","resolve","polyfills","normalizeSlashes","p","replace","srcExts","mjsExts","filter","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","isTsconfigPathsEnabled","isFastResolverEnabled","isExporting","isReactCanaryEnabled","isReactServerComponentsEnabled","Log","warn","log","chalk","dim","defaultResolver","metroResolver","resolver","createFastResolver","preserveSymlinks","blockList","Array","isArray","aliases","web","_universalAliases","getUniversalAliases","resolveFrom","silent","projectRoot","push","preferredMainFields","tsConfigResolve","paths","baseUrl","resolveWithTsConfigPaths","hasBaseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","getStrictResolver","resolveRequest","context","doResolve","moduleName","getOptionalResolver","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","idFactory","createModuleIdFactory","id","getAssetRegistryModule","type","filePath","externals","match","customResolverOptions","exporting","isServerEnvironment","environment","process","clientboundary","endsWith","isExternal","metroConfigWithCustomResolver","withMetroResolvers","requestDevMockProdReact","dev","originModulePath","requestTsconfigPaths","requestNodeExternals","isServer","moduleId","isNodeExternal","result","contents","requestCustomExternals","strictResolve","external","realModule","realPath","opaqueId","JSON","stringify","CommandError","requestAlias","redirectedModuleName","matcher","alias","aliasedModule","_","parseInt","requestStableAssetRegistry","includes","requestPostRewrites","FailedToResolvePathError","normalName","shimFile","shouldCreateVirtualShim","virtualId","bundler","hasVirtualModule","fs","readFileSync","normal","canaryFile","shouldCreateVirtualCanary","createFallbackModuleResolver","originModuleNames","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","nodeModulesPaths","path","join","sourceExts","unstable_enablePackageExports","unstable_conditionsByPlatform","isReactServerComponents","mainFields","unstable_conditionNames","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","input","output","exp","platformBundlers","isNamedRequiresEnabled","moduleSystem","EXPO_PUBLIC_PROJECT_ROOT","isDirectoryIn","__dirname","watchFolders","transformer","_expoRouterPath","expoConfigPlatforms","entries","platforms","map","Set","concat","targetPath","rootPath","startsWith"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IA6GeA,mBAAmB;eAAnBA;;IAkpBAC,iBAAiB;eAAjBA;;IA5nBAC,oBAAoB;eAApBA;;IA4oBMC,2BAA2B;eAA3BA;;;;gEA7wBJ;;;;;;;gEACH;;;;;;;iEAIgB;;;;;;;gEACd;;;;;;;gEACO;;;;;;4CAEqB;yCACgB;2BACsB;6BACZ;qCACrB;oCAK3C;qBACa;8BACS;qBACT;wBACS;sBACI;6BACH;mCACwB;0CACb;8BACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWpC,MAAMC,qBAAqB,CAAC,6FAA6F,CAAC;AAE1H,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,SAASC,iBACPC,MAAe,EACf,EACEC,eAAe,EAGhB;IAED,MAAMC,uBAAuBF,OAAOG,UAAU,CAACC,YAAY,GACvDJ,OAAOG,UAAU,CAACC,YAAY,CAACC,IAAI,CAACL,OAAOG,UAAU,IACrD,IAAM,EAAE;IAEZ,MAAMC,eAAe,CAACE;QACpB,MAAMC,kBAAkB,CAAC,gCAAgC,CAAC;QAE1DC,IAAAA,sDAAiC,EAACP,mBAAmBQ,gBAAgB,CACnEF,iBACA,AAAC,CAAA;YACC,OAAO,CAAC,EAAE,CAAC;QACb,CAAA;QAGF,MAAMG,kBAAkB,CAAC,2BAA2B,CAAC;QAErDF,IAAAA,sDAAiC,EAACP,mBAAmBQ,gBAAgB,CACnEC,iBACA,A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AAQ;QAClC4B;QACAG;QACAF;QACAC;QACAE;QACAC;QACAhC;IACF;AACF;AAEA,SAASuK,cAAcW,UAAkB,EAAEC,QAAgB;IACzD,OAAOD,WAAWE,UAAU,CAACD,aAAaD,WAAW7G,MAAM,IAAI8G,SAAS9G,MAAM;AAChF"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.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 { ExpoConfig, Platform } from '@expo/config';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport Bundler from 'metro/src/Bundler';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext, CustomResolutionContext } from 'metro-resolver';\nimport * as metroResolver from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { createFallbackModuleResolver } from './createExpoFallbackResolver';\nimport { createFastResolver, FailedToResolvePathError } from './createExpoMetroResolver';\nimport { isNodeExternal, shouldCreateVirtualCanary, shouldCreateVirtualShim } from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { getMetroBundlerWithVirtualModules } from './metroVirtualModules';\nimport {\n withMetroErrorReportingResolver,\n withMetroMutatedResolverContext,\n withMetroResolvers,\n} from './withMetroResolvers';\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { isServerEnvironment } from '../middleware/metroOptions';\nimport { PlatformBundlers } from '../platformBundlers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nexport type StrictResolver = (moduleName: string) => Resolution;\nexport type StrictResolverFactory = (\n context: ResolutionContext,\n platform: string | null\n) => StrictResolver;\n\nconst ASSET_REGISTRY_SRC = `const assets=[];module.exports={registerAsset:s=>assets.push(s),getAssetByID:s=>assets[s-1]};`;\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(\n config: ConfigT,\n {\n getMetroBundler,\n }: {\n getMetroBundler: () => Bundler;\n }\n): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform?: string | null }): readonly string[] => {\n const virtualEnvVarId = `\\0polyfill:environment-variables`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualEnvVarId,\n (() => {\n return `//`;\n })()\n );\n\n const virtualModuleId = `\\0polyfill:external-require`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n (() => {\n if (ctx.platform === 'web') {\n return `global.$$require_external = typeof window === \"undefined\" ? require : () => null;`;\n } else {\n // Wrap in try/catch to support Android.\n return 'try { global.$$require_external = typeof expo === \"undefined\" ? require : (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} } catch { global.$$require_external = (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} }';\n }\n })()\n );\n\n if (ctx.platform === 'web') {\n return [\n virtualModuleId,\n virtualEnvVarId,\n // Ensure that the error-guard polyfill is included in the web polyfills to\n // make metro-runtime work correctly.\n // TODO: This module is pretty big for a function that simply re-throws an error that doesn't need to be caught.\n require.resolve('@react-native/js-polyfills/error-guard'),\n ];\n }\n\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n return [\n ...polyfills,\n virtualModuleId,\n virtualEnvVarId,\n // Removed on server platforms during the transform.\n require.resolve('expo/virtual/streams.js'),\n ];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function getNodejsExtensions(srcExts: readonly string[]): string[] {\n const mjsExts = srcExts.filter((ext) => /mjs$/.test(ext));\n const nodejsSourceExtensions = srcExts.filter((ext) => !/mjs$/.test(ext));\n // find index of last `*.js` extension\n const jsIndex = nodejsSourceExtensions.reduce((index, ext, i) => {\n return /jsx?$/.test(ext) ? i : index;\n }, -1);\n\n // insert `*.mjs` extensions after `*.js` extensions\n nodejsSourceExtensions.splice(jsIndex + 1, 0, ...mjsExts);\n\n return nodejsSourceExtensions;\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n * - Alias react-native renderer code to a vendored React canary build on native.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n tsconfig,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n tsconfig: TsConfigPaths | null;\n isTsconfigPathsEnabled?: boolean;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled?: boolean;\n isReactServerComponentsEnabled?: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isReactServerComponentsEnabled) {\n Log.warn(`React Server Components (beta) is enabled.`);\n }\n if (isReactCanaryEnabled) {\n Log.warn(`Experimental React 19 canary is enabled.`);\n }\n if (isFastResolverEnabled) {\n Log.log(chalk.dim`Fast resolver is enabled.`);\n }\n\n const defaultResolver = metroResolver.resolve;\n const resolver = isFastResolverEnabled\n ? createFastResolver({\n preserveSymlinks: true,\n blockList: !config.resolver?.blockList\n ? []\n : Array.isArray(config.resolver?.blockList)\n ? config.resolver?.blockList\n : [config.resolver?.blockList],\n })\n : defaultResolver;\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n 'react-native/index': 'react-native-web',\n 'react-native/Libraries/Image/resolveAssetSource': 'expo-asset/build/resolveAssetSource',\n },\n };\n\n let _universalAliases: [RegExp, string][] | null;\n\n function getUniversalAliases() {\n if (_universalAliases) {\n return _universalAliases;\n }\n\n _universalAliases = [];\n\n // This package is currently always installed as it is included in the `expo` package.\n if (resolveFrom.silent(config.projectRoot, '@expo/vector-icons')) {\n debug('Enabling alias: react-native-vector-icons -> @expo/vector-icons');\n _universalAliases.push([/^react-native-vector-icons(\\/.*)?/, '@expo/vector-icons$1']);\n }\n if (isReactServerComponentsEnabled) {\n if (resolveFrom.silent(config.projectRoot, 'expo-router/rsc')) {\n debug('Enabling bridge alias: expo-router -> expo-router/rsc');\n _universalAliases.push([/^expo-router$/, 'expo-router/rsc']);\n // Bridge the internal entry point which is a standalone import to ensure package.json resolution works as expected.\n _universalAliases.push([/^expo-router\\/entry-classic$/, 'expo-router/rsc/entry']);\n }\n }\n return _universalAliases;\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve =\n isTsconfigPathsEnabled && (tsconfig?.paths || tsconfig?.baseUrl != null)\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsconfig.baseUrl,\n })\n : null;\n\n // TODO: Move this to be a transform key for invalidation.\n if (!isExporting && isInteractive()) {\n if (isTsconfigPathsEnabled) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(config.projectRoot, [\n './tsconfig.json',\n './jsconfig.json',\n ]);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(config.projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n }\n\n let nodejsSourceExtensions: string[] | null = null;\n\n const getStrictResolver: StrictResolverFactory = (\n { resolveRequest, ...context },\n platform\n ): StrictResolver => {\n return function doResolve(moduleName: string): Resolution {\n return resolver(context, moduleName, platform);\n };\n };\n\n function getOptionalResolver(context: ResolutionContext, platform: string | null) {\n const doResolve = getStrictResolver(context, platform);\n return function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n };\n }\n\n // TODO: This is a hack to get resolveWeak working.\n const idFactory = (config.serializer?.createModuleIdFactory?.() ??\n ((id: number | string, context: { platform: string; environment?: string }): number | string =>\n id)) as (\n id: number | string,\n context: { platform: string; environment?: string }\n ) => number | string;\n\n const getAssetRegistryModule = () => {\n const virtualModuleId = `\\0polyfill:assets-registry`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n ASSET_REGISTRY_SRC\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n } as const;\n };\n\n // If Node.js pass-through, then remap to a module like `module.exports = $$require_external(<module>)`.\n // If module should be shimmed, remap to an empty module.\n const externals: {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => boolean;\n replace: 'empty' | 'node' | 'weak';\n }[] = [\n {\n match: (context: ResolutionContext, moduleName: string) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for Node.js environments.\n !isServerEnvironment(context.customResolverOptions?.environment)\n ) {\n return false;\n }\n\n if (context.customResolverOptions?.environment === 'react-server') {\n // Ensure these non-react-server modules are excluded when bundling for React Server Components in development.\n return /^(source-map-support(\\/.*)?|@babel\\/runtime\\/.+|debug|metro-runtime\\/src\\/modules\\/HMRClient|metro|acorn-loose|acorn|chalk|ws|ansi-styles|supports-color|color-convert|has-flag|utf-8-validate|color-name|react-refresh\\/runtime|@remix-run\\/node\\/.+)$/.test(\n moduleName\n );\n }\n\n // TODO: Windows doesn't support externals somehow.\n if (process.platform === 'win32') {\n return /^(source-map-support(\\/.*)?)$/.test(moduleName);\n }\n\n // Extern these modules in standard Node.js environments in development to prevent API routes side-effects\n // from leaking into the dev server process.\n return /^(source-map-support(\\/.*)?|react|@radix-ui\\/.+|@babel\\/runtime\\/.+|react-dom(\\/.+)?|debug|acorn-loose|acorn|css-in-js-utils\\/lib\\/.+|hyphenate-style-name|color|color-string|color-convert|color-name|fontfaceobserver|fast-deep-equal|query-string|escape-string-regexp|invariant|postcss-value-parser|memoize-one|nullthrows|strict-uri-encode|decode-uri-component|split-on-first|filter-obj|warn-once|simple-swizzle|is-arrayish|inline-style-prefixer\\/.+)$/.test(\n moduleName\n );\n },\n replace: 'node',\n },\n // Externals to speed up async split chunks by extern-ing common packages that appear in the root client chunk.\n {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for client environments.\n isServerEnvironment(context.customResolverOptions?.environment) ||\n // Only enable for client boundaries\n !context.customResolverOptions.clientboundary\n ) {\n return false;\n }\n\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return false;\n }\n\n const isExternal = // Extern these modules in standard Node.js environments.\n /^(deprecated-react-native-prop-types|react|react\\/jsx-dev-runtime|scheduler|react-native|react-dom(\\/.+)?|metro-runtime(\\/.+)?)$/.test(\n moduleName\n ) ||\n // TODO: Add more\n /^@babel\\/runtime\\/helpers\\/(wrapNativeSuper)$/.test(moduleName);\n\n return isExternal;\n },\n replace: 'weak',\n },\n ];\n\n const metroConfigWithCustomResolver = withMetroResolvers(config, [\n // Mock out production react imports in development.\n function requestDevMockProdReact(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // This resolution is dev-only to prevent bundling the production React packages in development.\n if (!context.dev) return null;\n\n if (\n // Match react-native renderers.\n (platform !== 'web' &&\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/]react-native[\\\\/]/) &&\n moduleName.match(/([\\\\/]ReactFabric|ReactNativeRenderer)-prod/)) ||\n // Match react production imports.\n (moduleName.match(/\\.production(\\.min)?\\.js$/) &&\n // Match if the import originated from a react package.\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/](react[-\\\\/]|scheduler[\\\\/])/))\n ) {\n debug(`Skipping production module: ${moduleName}`);\n // /Users/path/to/expo/node_modules/react/index.js ./cjs/react.production.min.js\n // /Users/path/to/expo/node_modules/react/jsx-dev-runtime.js ./cjs/react-jsx-dev-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n // /Users/path/to/expo/node_modules/react-refresh/runtime.js ./cjs/react-refresh-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/scheduler/index.native.js ./cjs/scheduler.native.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n return {\n type: 'empty',\n };\n }\n return null;\n },\n // tsconfig paths\n function requestTsconfigPaths(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n return (\n tsConfigResolve?.(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n getOptionalResolver(context, platform)\n ) ?? null\n );\n },\n\n // Node.js externals support\n function requestNodeExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n const moduleId = isNodeExternal(moduleName);\n if (!moduleId) {\n return null;\n }\n\n if (\n // In browser runtimes, we want to either resolve a local node module by the same name, or shim the module to\n // prevent crashing when Node.js built-ins are imported.\n !isServer\n ) {\n // Perform optional resolve first. If the module doesn't exist (no module in the node_modules)\n // then we can mock the file to use an empty module.\n const result = getOptionalResolver(context, platform)(moduleName);\n\n if (!result && platform !== 'web') {\n // Preserve previous behavior where native throws an error on node.js internals.\n return null;\n }\n\n return (\n result ?? {\n // In this case, mock the file to use an empty module.\n type: 'empty',\n }\n );\n }\n const contents = `module.exports=$$require_external('node:${moduleId}');`;\n debug(`Virtualizing Node.js \"${moduleId}\"`);\n const virtualModuleId = `\\0node:${moduleId}`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n },\n\n // Custom externals support\n function requestCustomExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return null;\n }\n // Skip applying JS externals for CSS files.\n if (/\\.(s?css|sass)$/.test(context.originModulePath)) {\n return null;\n }\n\n const environment = context.customResolverOptions?.environment;\n\n const strictResolve = getStrictResolver(context, platform);\n\n for (const external of externals) {\n if (external.match(context, moduleName, platform)) {\n if (external.replace === 'empty') {\n debug(`Redirecting external \"${moduleName}\" to \"${external.replace}\"`);\n return {\n type: external.replace,\n };\n } else if (external.replace === 'weak') {\n // TODO: Make this use require.resolveWeak again. Previously this was just resolving to the same path.\n const realModule = strictResolve(moduleName);\n const realPath = realModule.type === 'sourceFile' ? realModule.filePath : moduleName;\n const opaqueId = idFactory(realPath, {\n platform: platform!,\n environment,\n });\n\n const contents =\n typeof opaqueId === 'number'\n ? `module.exports=/*${moduleName}*/__r(${opaqueId})`\n : `module.exports=/*${moduleName}*/__r(${JSON.stringify(opaqueId)})`;\n // const contents = `module.exports=/*${moduleName}*/__r(require.resolveWeak('${moduleName}'))`;\n // const generatedModuleId = fastHashMemoized(contents);\n const virtualModuleId = `\\0weak:${opaqueId}`;\n debug('Virtualizing module:', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else if (external.replace === 'node') {\n const contents = `module.exports=$$require_external('${moduleName}')`;\n const virtualModuleId = `\\0node:${moduleName}`;\n debug('Virtualizing Node.js (custom):', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else {\n throw new CommandError(\n `Invalid external alias type: \"${external.replace}\" for module \"${moduleName}\" (platform: ${platform}, originModulePath: ${context.originModulePath})`\n );\n }\n }\n }\n return null;\n },\n\n // Basic moduleId aliases\n function requestAlias(context: ResolutionContext, moduleName: string, platform: string | null) {\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n const redirectedModuleName = aliases[platform][moduleName];\n return getStrictResolver(context, platform)(redirectedModuleName);\n }\n\n for (const [matcher, alias] of getUniversalAliases()) {\n const match = moduleName.match(matcher);\n if (match) {\n const aliasedModule = alias.replace(\n /\\$(\\d+)/g,\n (_, index) => match[parseInt(index, 10)] ?? ''\n );\n const doResolve = getStrictResolver(context, platform);\n debug(`Alias \"${moduleName}\" to \"${aliasedModule}\"`);\n return doResolve(aliasedModule);\n }\n }\n\n return null;\n },\n\n // Polyfill for asset registry\n function requestStableAssetRegistry(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n if (/^@react-native\\/assets-registry\\/registry(\\.js)?$/.test(moduleName)) {\n return getAssetRegistryModule();\n }\n\n if (\n platform === 'web' &&\n context.originModulePath.match(/node_modules[\\\\/]react-native-web[\\\\/]/) &&\n moduleName.includes('/modules/AssetRegistry')\n ) {\n return getAssetRegistryModule();\n }\n\n return null;\n },\n\n // TODO: Reduce these as much as possible in the future.\n // Complex post-resolution rewrites.\n function requestPostRewrites(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const doResolve = getStrictResolver(context, platform);\n\n const result = doResolve(moduleName);\n\n if (result.type !== 'sourceFile') {\n return result;\n }\n\n if (platform === 'web') {\n if (result.filePath.includes('node_modules')) {\n // // Disallow importing confusing native modules on web\n if (moduleName.includes('react-native/Libraries/Utilities/codegenNativeCommands')) {\n throw new FailedToResolvePathError(\n `Importing native-only module \"${moduleName}\" on web from: ${context.originModulePath}`\n );\n }\n\n // Replace with static shims\n\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const shimFile = shouldCreateVirtualShim(normalName);\n if (shimFile) {\n const virtualId = `\\0shim:${normalName}`;\n const bundler = getMetroBundlerWithVirtualModules(getMetroBundler());\n if (!bundler.hasVirtualModule(virtualId)) {\n bundler.setVirtualModule(virtualId, fs.readFileSync(shimFile, 'utf8'));\n }\n debug(`Redirecting module \"${result.filePath}\" to shim`);\n\n return {\n ...result,\n filePath: virtualId,\n };\n }\n }\n } else {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n // react-native/Libraries/Core/InitializeCore\n const normal = normalizeSlashes(result.filePath);\n\n // Shim out React Native native runtime globals in server mode for native.\n if (isServer) {\n if (normal.endsWith('react-native/Libraries/Core/InitializeCore.js')) {\n debug('Shimming out InitializeCore for React Native in native SSR bundle');\n return {\n type: 'empty',\n };\n }\n }\n\n // When server components are enabled, redirect React Native's renderer to the canary build\n // this will enable the use hook and other requisite features from React 19.\n if (isReactCanaryEnabled && result.filePath.includes('node_modules')) {\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const canaryFile = shouldCreateVirtualCanary(normalName);\n if (canaryFile) {\n debug(`Redirecting React Native module \"${result.filePath}\" to canary build`);\n return {\n ...result,\n filePath: canaryFile,\n };\n }\n }\n }\n\n return result;\n },\n\n // If at this point, we haven't resolved a module yet, if it's a module specifier for a known dependency\n // of either `expo` or `expo-router`, attempt to resolve it from these origin modules instead\n createFallbackModuleResolver({\n originModuleNames: ['expo', 'expo-router'],\n getStrictResolver,\n }),\n ]);\n\n // Ensure we mutate the resolution context to include the custom resolver options for server and web.\n const metroConfigWithCustomContext = withMetroMutatedResolverContext(\n metroConfigWithCustomResolver,\n (\n immutableContext: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ): CustomResolutionContext => {\n const context: Mutable<CustomResolutionContext> = {\n ...immutableContext,\n preferNativePlatform: platform !== 'web',\n };\n\n // TODO: Remove this when we have React 19 in the expo/expo monorepo.\n if (\n isReactCanaryEnabled &&\n // Change the node modules path for react and react-dom to use the vendor in Expo CLI.\n /^(react|react\\/.*|react-dom|react-dom\\/.*)$/.test(moduleName)\n ) {\n context.nodeModulesPaths = [\n path.join(require.resolve('@expo/cli/package.json'), '../static/canary-full'),\n ];\n }\n\n if (isServerEnvironment(context.customResolverOptions?.environment)) {\n // Adjust nodejs source extensions to sort mjs after js, including platform variants.\n if (nodejsSourceExtensions === null) {\n nodejsSourceExtensions = getNodejsExtensions(context.sourceExts);\n }\n context.sourceExts = nodejsSourceExtensions;\n\n context.unstable_enablePackageExports = true;\n context.unstable_conditionsByPlatform = {};\n\n const isReactServerComponents =\n context.customResolverOptions?.environment === 'react-server';\n\n if (isReactServerComponents) {\n // NOTE: Align the behavior across server and client. This is a breaking change so we'll just roll it out with React Server Components.\n // This ensures that react-server and client code both resolve `module` and `main` in the same order.\n if (platform === 'web') {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['module', 'main'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'module', 'main'];\n }\n } else {\n if (platform === 'web') {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['main', 'module'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'main', 'module'];\n }\n }\n\n // Enable react-server import conditions.\n if (context.customResolverOptions?.environment === 'react-server') {\n context.unstable_conditionNames = ['node', 'react-server', 'workerd'];\n } else {\n context.unstable_conditionNames = ['node'];\n }\n } else {\n // Non-server changes\n\n if (!env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE && platform && platform in preferredMainFields) {\n context.mainFields = preferredMainFields[platform];\n }\n }\n\n return context;\n }\n );\n\n return withMetroErrorReportingResolver(metroConfigWithCustomContext);\n}\n\n/** @returns `true` if the incoming resolution should be swapped. */\nexport function shouldAliasModule(\n input: {\n platform: string | null;\n result: Resolution;\n },\n alias: { platform: string; output: string }\n): boolean {\n return (\n input.platform === alias.platform &&\n input.result?.type === 'sourceFile' &&\n typeof input.result?.filePath === 'string' &&\n normalizeSlashes(input.result.filePath).endsWith(alias.output)\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isNamedRequiresEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n config: ConfigT;\n exp: ExpoConfig;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled: boolean;\n isReactServerComponentsEnabled: boolean;\n isNamedRequiresEnabled: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isNamedRequiresEnabled) {\n debug('Using Expo metro require runtime.');\n // Change the default metro-runtime to a custom one that supports bundle splitting.\n require('metro-config/src/defaults/defaults').moduleSystem = require.resolve(\n '@expo/cli/build/metro-require/require'\n );\n }\n\n if (!config.projectRoot) {\n // @ts-expect-error: read-only types\n config.projectRoot = projectRoot;\n }\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n // This is used for running Expo CLI in development against projects outside the monorepo.\n if (!isDirectoryIn(__dirname, projectRoot)) {\n if (!config.watchFolders) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders = [];\n }\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('metro-runtime/package.json'), '../..'));\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(\n path.join(require.resolve('@expo/metro-config/package.json'), '../..'),\n // For virtual modules\n path.join(require.resolve('expo/package.json'), '..')\n );\n if (isReactCanaryEnabled) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('@expo/cli/package.json'), '..'));\n }\n }\n\n // TODO: Remove this\n // @ts-expect-error: Invalidate the cache when the location of expo-router changes on-disk.\n config.transformer._expoRouterPath = resolveFrom.silent(projectRoot, 'expo-router');\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(\n ([platform, bundler]) => bundler === 'metro' && exp.platforms?.includes(platform as Platform)\n )\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n config = withWebPolyfills(config, { getMetroBundler });\n\n return withExtendedResolver(config, {\n tsconfig,\n isExporting,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n });\n}\n\nfunction isDirectoryIn(targetPath: string, rootPath: string) {\n return targetPath.startsWith(rootPath) && targetPath.length >= rootPath.length;\n}\n"],"names":["getNodejsExtensions","shouldAliasModule","withExtendedResolver","withMetroMultiPlatformAsync","ASSET_REGISTRY_SRC","debug","require","withWebPolyfills","config","getMetroBundler","originalGetPolyfills","serializer","getPolyfills","bind","ctx","virtualEnvVarId","getMetroBundlerWithVirtualModules","setVirtualModule","virtualModuleId","platform","resolve","polyfills","normalizeSlashes","p","replace","srcExts","mjsExts","filter","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","isTsconfigPathsEnabled","isFastResolverEnabled","isExporting","isReactCanaryEnabled","isReactServerComponentsEnabled","Log","warn","log","chalk","dim","defaultResolver","metroResolver","resolver","createFastResolver","preserveSymlinks","blockList","Array","isArray","aliases","web","_universalAliases","getUniversalAliases","resolveFrom","silent","projectRoot","push","preferredMainFields","tsConfigResolve","paths","baseUrl","resolveWithTsConfigPaths","hasBaseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","getStrictResolver","resolveRequest","context","doResolve","moduleName","getOptionalResolver","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","idFactory","createModuleIdFactory","id","getAssetRegistryModule","type","filePath","externals","match","customResolverOptions","exporting","isServerEnvironment","environment","process","clientboundary","endsWith","isExternal","metroConfigWithCustomResolver","withMetroResolvers","requestDevMockProdReact","dev","originModulePath","requestTsconfigPaths","requestNodeExternals","isServer","moduleId","isNodeExternal","result","contents","requestCustomExternals","strictResolve","external","realModule","realPath","opaqueId","JSON","stringify","CommandError","requestAlias","redirectedModuleName","matcher","alias","aliasedModule","_","parseInt","requestStableAssetRegistry","includes","requestPostRewrites","FailedToResolvePathError","normalName","shimFile","shouldCreateVirtualShim","virtualId","bundler","hasVirtualModule","fs","readFileSync","normal","canaryFile","shouldCreateVirtualCanary","createFallbackModuleResolver","originModuleNames","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","nodeModulesPaths","path","join","sourceExts","unstable_enablePackageExports","unstable_conditionsByPlatform","isReactServerComponents","mainFields","unstable_conditionNames","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","input","output","exp","platformBundlers","isNamedRequiresEnabled","moduleSystem","EXPO_PUBLIC_PROJECT_ROOT","isDirectoryIn","__dirname","watchFolders","transformer","_expoRouterPath","expoConfigPlatforms","entries","platforms","map","Set","concat","targetPath","rootPath","startsWith"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAmHeA,mBAAmB;eAAnBA;;IAkpBAC,iBAAiB;eAAjBA;;IA5nBAC,oBAAoB;eAApBA;;IA4oBMC,2BAA2B;eAA3BA;;;;gEAnxBJ;;;;;;;gEACH;;;;;;;iEAIgB;;;;;;;gEACd;;;;;;;gEACO;;;;;;4CAEqB;yCACgB;2BACsB;6BACZ;qCACrB;oCAK3C;qBACa;8BACS;qBACT;wBACS;sBACI;6BACH;mCACwB;0CACb;8BACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWpC,MAAMC,qBAAqB,CAAC,6FAA6F,CAAC;AAE1H,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,SAASC,iBACPC,MAAe,EACf,EACEC,eAAe,EAGhB;IAED,MAAMC,uBAAuBF,OAAOG,UAAU,CAACC,YAAY,GACvDJ,OAAOG,UAAU,CAACC,YAAY,CAACC,IAAI,CAACL,OAAOG,UAAU,IACrD,IAAM,EAAE;I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AAIY,SAAS,qBAAbZ,eAAelC,QAAQ,CAACtH;OAEzEqK,GAAG,CAAC,CAAC,CAACrK,SAAS,GAAKA;IAEvB,IAAIkC,MAAMC,OAAO,CAAC9C,OAAOyC,QAAQ,CAACsI,SAAS,GAAG;QAC5CF,sBAAsB;eAAI,IAAII,IAAIJ,oBAAoBK,MAAM,CAAClL,OAAOyC,QAAQ,CAACsI,SAAS;SAAG;IAC3F;IAEA,yCAAyC;IACzC/K,OAAOyC,QAAQ,CAACsI,SAAS,GAAGF;IAE5B7K,SAASD,iBAAiBC,QAAQ;QAAEC;IAAgB;IAEpD,OAAOP,qBAAqBM,QAAQ;QAClC4B;QACAG;QACAF;QACAC;QACAE;QACAC;QACAhC;IACF;AACF;AAEA,SAASuK,cAAcW,UAAkB,EAAEC,QAAgB;IACzD,OAAOD,WAAWE,UAAU,CAACD,aAAaD,WAAW7G,MAAM,IAAI8G,SAAS9G,MAAM;AAChF"}
@@ -33,7 +33,7 @@ class FetchClient {
33
33
  this.headers = {
34
34
  accept: 'application/json',
35
35
  'content-type': 'application/json',
36
- 'user-agent': `expo-cli/${"0.24.5"}`,
36
+ 'user-agent': `expo-cli/${"0.24.6"}`,
37
37
  authorization: 'Basic ' + _nodebuffer().Buffer.from(`${target}:`).toString('base64')
38
38
  };
39
39
  }
@@ -83,7 +83,7 @@ function createContext() {
83
83
  cpu: summarizeCpuInfo(),
84
84
  app: {
85
85
  name: 'expo/cli',
86
- version: "0.24.5"
86
+ version: "0.24.6"
87
87
  },
88
88
  ci: _ciinfo().isCI ? {
89
89
  name: _ciinfo().name,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expo/cli",
3
- "version": "0.24.5",
3
+ "version": "0.24.6",
4
4
  "description": "The Expo CLI",
5
5
  "main": "build/bin/cli",
6
6
  "bin": {
@@ -48,7 +48,7 @@
48
48
  "@expo/env": "~1.0.4",
49
49
  "@expo/image-utils": "^0.7.3",
50
50
  "@expo/json-file": "^9.1.3",
51
- "@expo/metro-config": "~0.20.7",
51
+ "@expo/metro-config": "~0.20.8",
52
52
  "@expo/osascript": "^2.2.3",
53
53
  "@expo/package-manager": "^1.8.3",
54
54
  "@expo/plist": "^0.3.3",
@@ -152,5 +152,5 @@
152
152
  "tree-kill": "^1.2.2",
153
153
  "tsd": "^0.28.1"
154
154
  },
155
- "gitHead": "3cd208465df78e385ca9380531bbbfe33ca68e81"
155
+ "gitHead": "a639a661a5329e58f916cf69b8f1a7718bbdd26e"
156
156
  }