@expo/cli 0.24.21 → 0.24.23
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 +1 -1
- package/build/src/export/exportApp.js +1 -0
- package/build/src/export/exportApp.js.map +1 -1
- package/build/src/run/ios/runIosAsync.js +3 -1
- package/build/src/run/ios/runIosAsync.js.map +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js +5 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/middleware/CorsMiddleware.js +43 -12
- package/build/src/start/server/middleware/CorsMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/CreateFileMiddleware.js +63 -24
- package/build/src/start/server/middleware/CreateFileMiddleware.js.map +1 -1
- package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
- package/build/src/utils/telemetry/utils/context.js +1 -1
- package/package.json +4 -4
package/build/bin/cli
CHANGED
|
@@ -249,6 +249,7 @@ async function exportAppAsync(projectRoot, { platforms, outputDir, clear, dev, d
|
|
|
249
249
|
htmlOutputName
|
|
250
250
|
});
|
|
251
251
|
domComponentAssetsMetadata[platform] = [
|
|
252
|
+
...domComponentAssetsMetadata[platform] || [],
|
|
252
253
|
...await (0, _exportDomComponents.addDomBundleToMetadataAsync)(platformDomComponentsBundle),
|
|
253
254
|
...(0, _exportDomComponents.transformDomEntryForMd5Filename)({
|
|
254
255
|
files,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/export/exportApp.ts"],"sourcesContent":["import { getConfig } from '@expo/config';\nimport type { Platform } from '@expo/config';\nimport { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport assert from 'assert';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport path from 'path';\n\nimport { type PlatformMetadata, createMetadataJson } from './createMetadataJson';\nimport { exportAssetsAsync } from './exportAssets';\nimport {\n addDomBundleToMetadataAsync,\n exportDomComponentAsync,\n transformNativeBundleForMd5Filename,\n transformDomEntryForMd5Filename,\n} from './exportDomComponents';\nimport { assertEngineMismatchAsync, isEnableHermesManaged } from './exportHermes';\nimport { exportApiRoutesStandaloneAsync, exportFromServerAsync } from './exportStaticAsync';\nimport { getVirtualFaviconAssetsAsync } from './favicon';\nimport { getPublicExpoManifestAsync } from './getPublicExpoManifest';\nimport { copyPublicFolderAsync } from './publicFolder';\nimport { Options } from './resolveOptions';\nimport {\n ExportAssetMap,\n BundleOutput,\n getFilesFromSerialAssets,\n persistMetroFilesAsync,\n BundleAssetWithFileHashes,\n} from './saveAssets';\nimport { createAssetMap } from './writeContents';\nimport * as Log from '../log';\nimport { WebSupportProjectPrerequisite } from '../start/doctor/web/WebSupportProjectPrerequisite';\nimport { DevServerManager } from '../start/server/DevServerManager';\nimport { MetroBundlerDevServer } from '../start/server/metro/MetroBundlerDevServer';\nimport { getRouterDirectoryModuleIdWithManifest } from '../start/server/metro/router';\nimport { serializeHtmlWithAssets } from '../start/server/metro/serializeHtml';\nimport { getEntryWithServerRoot } from '../start/server/middleware/ManifestMiddleware';\nimport { getBaseUrlFromExpoConfig } from '../start/server/middleware/metroOptions';\nimport { createTemplateHtmlFromExpoConfigAsync } from '../start/server/webTemplate';\nimport { env } from '../utils/env';\nimport { CommandError } from '../utils/errors';\nimport { setNodeEnv } from '../utils/nodeEnv';\n\nexport async function exportAppAsync(\n projectRoot: string,\n {\n platforms,\n outputDir,\n clear,\n dev,\n dumpAssetmap,\n sourceMaps,\n minify,\n bytecode,\n maxWorkers,\n skipSSG,\n }: Pick<\n Options,\n | 'dumpAssetmap'\n | 'sourceMaps'\n | 'dev'\n | 'clear'\n | 'outputDir'\n | 'platforms'\n | 'minify'\n | 'bytecode'\n | 'maxWorkers'\n | 'skipSSG'\n >\n): Promise<void> {\n // Force the environment during export and do not allow overriding it.\n const environment = dev ? 'development' : 'production';\n process.env.NODE_ENV = environment;\n setNodeEnv(environment);\n\n require('@expo/env').load(projectRoot);\n\n const projectConfig = getConfig(projectRoot);\n const exp = await getPublicExpoManifestAsync(projectRoot, {\n // Web doesn't require validation.\n skipValidation: platforms.length === 1 && platforms[0] === 'web',\n });\n\n if (platforms.includes('web')) {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n }\n\n const useServerRendering = ['static', 'server'].includes(exp.web?.output ?? '');\n\n if (skipSSG && exp.web?.output !== 'server') {\n throw new CommandError('--no-ssg can only be used with `web.output: server`');\n }\n\n const baseUrl = getBaseUrlFromExpoConfig(exp);\n\n if (!bytecode && (platforms.includes('ios') || platforms.includes('android'))) {\n Log.warn(\n `Bytecode makes the app startup faster, disabling bytecode is highly discouraged and should only be used for debugging purposes.`\n );\n }\n\n // Print out logs\n if (baseUrl) {\n Log.log();\n Log.log(chalk.gray`Using (experimental) base path: ${baseUrl}`);\n // Warn if not using an absolute path.\n if (!baseUrl.startsWith('/')) {\n Log.log(\n chalk.yellow` Base path does not start with a slash. Requests will not be absolute.`\n );\n }\n }\n\n const mode = dev ? 'development' : 'production';\n const publicPath = path.resolve(projectRoot, env.EXPO_PUBLIC_FOLDER);\n const outputPath = path.resolve(projectRoot, outputDir);\n\n // Write the JS bundles to disk, and get the bundle file names (this could change with async chunk loading support).\n\n const files: ExportAssetMap = new Map();\n\n const devServerManager = await DevServerManager.startMetroAsync(projectRoot, {\n minify,\n mode,\n port: 8081,\n isExporting: true,\n location: {},\n resetDevServer: clear,\n maxWorkers,\n });\n\n const devServer = devServerManager.getDefaultDevServer();\n assert(devServer instanceof MetroBundlerDevServer);\n\n const bundles: Partial<Record<Platform, BundleOutput>> = {};\n const domComponentAssetsMetadata: Partial<Record<Platform, PlatformMetadata['assets']>> = {};\n\n const spaPlatforms =\n // TODO: Support server and static rendering for server component exports.\n useServerRendering && !devServer.isReactServerComponentsEnabled\n ? platforms.filter((platform) => platform !== 'web')\n : platforms;\n\n try {\n if (devServer.isReactServerComponentsEnabled) {\n // In RSC mode, we only need these to be in the client dir.\n // TODO: Merge back with other copy after we add SSR.\n try {\n await copyPublicFolderAsync(publicPath, path.join(outputPath, 'client'));\n } catch (error) {\n Log.error('Failed to copy public directory to dist directory');\n throw error;\n }\n } else {\n // NOTE(kitten): The public folder is currently always copied, regardless of targetDomain\n // split. Hence, there's another separate `copyPublicFolderAsync` call below for `web`\n await copyPublicFolderAsync(publicPath, outputPath);\n }\n\n let templateHtml: string | undefined;\n // Can be empty during web-only SSG.\n if (spaPlatforms.length) {\n await Promise.all(\n spaPlatforms.map(async (platform) => {\n // Assert early so the user doesn't have to wait until bundling is complete to find out that\n // Hermes won't be available.\n const isHermes = isEnableHermesManaged(exp, platform);\n if (isHermes) {\n await assertEngineMismatchAsync(projectRoot, exp, platform);\n }\n\n let bundle: {\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n files?: ExportAssetMap;\n };\n\n try {\n // Run metro bundler and create the JS bundles/source maps.\n bundle = await devServer.nativeExportBundleAsync(\n exp,\n {\n platform,\n splitChunks:\n !env.EXPO_NO_BUNDLE_SPLITTING &&\n ((devServer.isReactServerComponentsEnabled && !bytecode) || platform === 'web'),\n mainModuleName: getEntryWithServerRoot(projectRoot, {\n platform,\n pkg: projectConfig.pkg,\n }),\n mode: dev ? 'development' : 'production',\n engine: isHermes ? 'hermes' : undefined,\n serializerIncludeMaps: sourceMaps,\n bytecode: bytecode && isHermes,\n reactCompiler: !!exp.experiments?.reactCompiler,\n },\n files\n );\n } catch (error) {\n Log.log('');\n if (error instanceof Error) {\n Log.exception(error);\n } else {\n Log.error('Failed to bundle the app');\n Log.log(error as any);\n }\n process.exit(1);\n }\n\n bundles[platform] = bundle;\n\n getFilesFromSerialAssets(bundle.artifacts, {\n includeSourceMaps: sourceMaps,\n files,\n isServerHosted: devServer.isReactServerComponentsEnabled,\n });\n\n // TODO: Remove duplicates...\n const expoDomComponentReferences = bundle.artifacts\n .map((artifact) =>\n Array.isArray(artifact.metadata.expoDomComponentReferences)\n ? artifact.metadata.expoDomComponentReferences\n : []\n )\n .flat();\n await Promise.all(\n // TODO: Make a version of this which uses `this.metro.getBundler().buildGraphForEntries([])` to bundle all the DOM components at once.\n expoDomComponentReferences.map(async (filePath) => {\n const { bundle: platformDomComponentsBundle, htmlOutputName } =\n await exportDomComponentAsync({\n filePath,\n projectRoot,\n dev,\n devServer,\n isHermes,\n includeSourceMaps: sourceMaps,\n exp,\n files,\n useMd5Filename: true,\n });\n\n // Merge the assets from the DOM component into the output assets.\n // @ts-expect-error: mutate assets\n bundle.assets.push(...platformDomComponentsBundle.assets);\n\n transformNativeBundleForMd5Filename({\n domComponentReference: filePath,\n nativeBundle: bundle,\n files,\n htmlOutputName,\n });\n domComponentAssetsMetadata[platform] = [\n ...(await addDomBundleToMetadataAsync(platformDomComponentsBundle)),\n ...transformDomEntryForMd5Filename({\n files,\n htmlOutputName,\n }),\n ];\n })\n );\n\n if (platform === 'web') {\n // TODO: Unify with exportStaticAsync\n // TODO: Maybe move to the serializer.\n let html = await serializeHtmlWithAssets({\n isExporting: true,\n resources: bundle.artifacts,\n template: await createTemplateHtmlFromExpoConfigAsync(projectRoot, {\n scripts: [],\n cssLinks: [],\n exp: projectConfig.exp,\n }),\n baseUrl,\n });\n\n // Add the favicon assets to the HTML.\n const modifyHtml = await getVirtualFaviconAssetsAsync(projectRoot, {\n outputDir,\n baseUrl,\n files,\n exp: projectConfig.exp,\n });\n if (modifyHtml) {\n html = modifyHtml(html);\n }\n\n // HACK: This is used for adding SSR shims in React Server Components.\n templateHtml = html;\n\n // Generate SPA-styled HTML file.\n // If web exists, then write the template HTML file.\n files.set('index.html', {\n contents: html,\n targetDomain: devServer.isReactServerComponentsEnabled ? 'server' : 'client',\n });\n }\n })\n );\n\n if (devServer.isReactServerComponentsEnabled) {\n const isWeb = platforms.includes('web');\n\n await exportApiRoutesStandaloneAsync(devServer, {\n files,\n platform: 'web',\n apiRoutesOnly: !isWeb,\n templateHtml,\n });\n }\n\n // TODO: Use same asset system across platforms again.\n const { assets, embeddedHashSet } = await exportAssetsAsync(projectRoot, {\n files,\n exp,\n outputDir: outputPath,\n bundles,\n baseUrl,\n });\n\n if (dumpAssetmap) {\n Log.log('Creating asset map');\n files.set('assetmap.json', { contents: JSON.stringify(createAssetMap({ assets })) });\n }\n\n const targetDomain = devServer.isReactServerComponentsEnabled ? 'client/' : '';\n const fileNames = Object.fromEntries(\n Object.entries(bundles).map(([platform, bundle]) => [\n platform,\n bundle.artifacts\n .filter((asset) => asset.type === 'js')\n .map((asset) => targetDomain + asset.filename),\n ])\n );\n\n // Generate a `metadata.json` for EAS Update.\n const contents = createMetadataJson({\n bundles,\n fileNames,\n embeddedHashSet,\n domComponentAssetsMetadata,\n });\n files.set('metadata.json', { contents: JSON.stringify(contents) });\n }\n\n // Additional web-only steps...\n\n if (platforms.includes('web') && useServerRendering) {\n const exportServer = exp.web?.output === 'server';\n\n if (exportServer) {\n // TODO: Remove when this is abstracted into the files map\n await copyPublicFolderAsync(publicPath, path.resolve(outputPath, 'client'));\n }\n\n if (skipSSG) {\n Log.log('Skipping static site generation');\n await exportApiRoutesStandaloneAsync(devServer, {\n files,\n platform: 'web',\n apiRoutesOnly: true,\n });\n\n // Output a placeholder index.html if one doesn't exist in the public directory.\n // This ensures native + API routes have some content at the root URL.\n const placeholderIndex = path.resolve(outputPath, 'client/index.html');\n if (!fs.existsSync(placeholderIndex)) {\n files.set('index.html', {\n contents: `<html><body></body></html>`,\n targetDomain: 'client',\n });\n }\n } else if (\n // TODO: Support static export with RSC.\n !devServer.isReactServerComponentsEnabled\n ) {\n await exportFromServerAsync(projectRoot, devServer, {\n mode,\n files,\n clear: !!clear,\n outputDir: outputPath,\n minify,\n baseUrl,\n includeSourceMaps: sourceMaps,\n routerRoot: getRouterDirectoryModuleIdWithManifest(projectRoot, exp),\n reactCompiler: !!exp.experiments?.reactCompiler,\n exportServer,\n maxWorkers,\n isExporting: true,\n exp: projectConfig.exp,\n });\n }\n }\n } finally {\n await devServerManager.stopAsync();\n }\n\n // Write all files at the end for unified logging.\n await persistMetroFilesAsync(files, outputPath);\n}\n"],"names":["exportAppAsync","projectRoot","platforms","outputDir","clear","dev","dumpAssetmap","sourceMaps","minify","bytecode","maxWorkers","skipSSG","exp","environment","process","env","NODE_ENV","setNodeEnv","require","load","projectConfig","getConfig","getPublicExpoManifestAsync","skipValidation","length","includes","WebSupportProjectPrerequisite","assertAsync","useServerRendering","web","output","CommandError","baseUrl","getBaseUrlFromExpoConfig","Log","warn","log","chalk","gray","startsWith","yellow","mode","publicPath","path","resolve","EXPO_PUBLIC_FOLDER","outputPath","files","Map","devServerManager","DevServerManager","startMetroAsync","port","isExporting","location","resetDevServer","devServer","getDefaultDevServer","assert","MetroBundlerDevServer","bundles","domComponentAssetsMetadata","spaPlatforms","isReactServerComponentsEnabled","filter","platform","copyPublicFolderAsync","join","error","templateHtml","Promise","all","map","isHermes","isEnableHermesManaged","assertEngineMismatchAsync","bundle","nativeExportBundleAsync","splitChunks","EXPO_NO_BUNDLE_SPLITTING","mainModuleName","getEntryWithServerRoot","pkg","engine","undefined","serializerIncludeMaps","reactCompiler","experiments","Error","exception","exit","getFilesFromSerialAssets","artifacts","includeSourceMaps","isServerHosted","expoDomComponentReferences","artifact","Array","isArray","metadata","flat","filePath","platformDomComponentsBundle","htmlOutputName","exportDomComponentAsync","useMd5Filename","assets","push","transformNativeBundleForMd5Filename","domComponentReference","nativeBundle","addDomBundleToMetadataAsync","transformDomEntryForMd5Filename","html","serializeHtmlWithAssets","resources","template","createTemplateHtmlFromExpoConfigAsync","scripts","cssLinks","modifyHtml","getVirtualFaviconAssetsAsync","set","contents","targetDomain","isWeb","exportApiRoutesStandaloneAsync","apiRoutesOnly","embeddedHashSet","exportAssetsAsync","JSON","stringify","createAssetMap","fileNames","Object","fromEntries","entries","asset","type","filename","createMetadataJson","exportServer","placeholderIndex","fs","existsSync","exportFromServerAsync","routerRoot","getRouterDirectoryModuleIdWithManifest","stopAsync","persistMetroFilesAsync"],"mappings":";;;;+BA2CsBA;;;eAAAA;;;;yBA3CI;;;;;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MAAMC,IAAAA,kCAAsB,EAACtG,OAAOD;AACtC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/export/exportApp.ts"],"sourcesContent":["import { getConfig } from '@expo/config';\nimport type { Platform } from '@expo/config';\nimport { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport assert from 'assert';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport path from 'path';\n\nimport { type PlatformMetadata, createMetadataJson } from './createMetadataJson';\nimport { exportAssetsAsync } from './exportAssets';\nimport {\n addDomBundleToMetadataAsync,\n exportDomComponentAsync,\n transformNativeBundleForMd5Filename,\n transformDomEntryForMd5Filename,\n} from './exportDomComponents';\nimport { assertEngineMismatchAsync, isEnableHermesManaged } from './exportHermes';\nimport { exportApiRoutesStandaloneAsync, exportFromServerAsync } from './exportStaticAsync';\nimport { getVirtualFaviconAssetsAsync } from './favicon';\nimport { getPublicExpoManifestAsync } from './getPublicExpoManifest';\nimport { copyPublicFolderAsync } from './publicFolder';\nimport { Options } from './resolveOptions';\nimport {\n ExportAssetMap,\n BundleOutput,\n getFilesFromSerialAssets,\n persistMetroFilesAsync,\n BundleAssetWithFileHashes,\n} from './saveAssets';\nimport { createAssetMap } from './writeContents';\nimport * as Log from '../log';\nimport { WebSupportProjectPrerequisite } from '../start/doctor/web/WebSupportProjectPrerequisite';\nimport { DevServerManager } from '../start/server/DevServerManager';\nimport { MetroBundlerDevServer } from '../start/server/metro/MetroBundlerDevServer';\nimport { getRouterDirectoryModuleIdWithManifest } from '../start/server/metro/router';\nimport { serializeHtmlWithAssets } from '../start/server/metro/serializeHtml';\nimport { getEntryWithServerRoot } from '../start/server/middleware/ManifestMiddleware';\nimport { getBaseUrlFromExpoConfig } from '../start/server/middleware/metroOptions';\nimport { createTemplateHtmlFromExpoConfigAsync } from '../start/server/webTemplate';\nimport { env } from '../utils/env';\nimport { CommandError } from '../utils/errors';\nimport { setNodeEnv } from '../utils/nodeEnv';\n\nexport async function exportAppAsync(\n projectRoot: string,\n {\n platforms,\n outputDir,\n clear,\n dev,\n dumpAssetmap,\n sourceMaps,\n minify,\n bytecode,\n maxWorkers,\n skipSSG,\n }: Pick<\n Options,\n | 'dumpAssetmap'\n | 'sourceMaps'\n | 'dev'\n | 'clear'\n | 'outputDir'\n | 'platforms'\n | 'minify'\n | 'bytecode'\n | 'maxWorkers'\n | 'skipSSG'\n >\n): Promise<void> {\n // Force the environment during export and do not allow overriding it.\n const environment = dev ? 'development' : 'production';\n process.env.NODE_ENV = environment;\n setNodeEnv(environment);\n\n require('@expo/env').load(projectRoot);\n\n const projectConfig = getConfig(projectRoot);\n const exp = await getPublicExpoManifestAsync(projectRoot, {\n // Web doesn't require validation.\n skipValidation: platforms.length === 1 && platforms[0] === 'web',\n });\n\n if (platforms.includes('web')) {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n }\n\n const useServerRendering = ['static', 'server'].includes(exp.web?.output ?? '');\n\n if (skipSSG && exp.web?.output !== 'server') {\n throw new CommandError('--no-ssg can only be used with `web.output: server`');\n }\n\n const baseUrl = getBaseUrlFromExpoConfig(exp);\n\n if (!bytecode && (platforms.includes('ios') || platforms.includes('android'))) {\n Log.warn(\n `Bytecode makes the app startup faster, disabling bytecode is highly discouraged and should only be used for debugging purposes.`\n );\n }\n\n // Print out logs\n if (baseUrl) {\n Log.log();\n Log.log(chalk.gray`Using (experimental) base path: ${baseUrl}`);\n // Warn if not using an absolute path.\n if (!baseUrl.startsWith('/')) {\n Log.log(\n chalk.yellow` Base path does not start with a slash. Requests will not be absolute.`\n );\n }\n }\n\n const mode = dev ? 'development' : 'production';\n const publicPath = path.resolve(projectRoot, env.EXPO_PUBLIC_FOLDER);\n const outputPath = path.resolve(projectRoot, outputDir);\n\n // Write the JS bundles to disk, and get the bundle file names (this could change with async chunk loading support).\n\n const files: ExportAssetMap = new Map();\n\n const devServerManager = await DevServerManager.startMetroAsync(projectRoot, {\n minify,\n mode,\n port: 8081,\n isExporting: true,\n location: {},\n resetDevServer: clear,\n maxWorkers,\n });\n\n const devServer = devServerManager.getDefaultDevServer();\n assert(devServer instanceof MetroBundlerDevServer);\n\n const bundles: Partial<Record<Platform, BundleOutput>> = {};\n const domComponentAssetsMetadata: Partial<Record<Platform, PlatformMetadata['assets']>> = {};\n\n const spaPlatforms =\n // TODO: Support server and static rendering for server component exports.\n useServerRendering && !devServer.isReactServerComponentsEnabled\n ? platforms.filter((platform) => platform !== 'web')\n : platforms;\n\n try {\n if (devServer.isReactServerComponentsEnabled) {\n // In RSC mode, we only need these to be in the client dir.\n // TODO: Merge back with other copy after we add SSR.\n try {\n await copyPublicFolderAsync(publicPath, path.join(outputPath, 'client'));\n } catch (error) {\n Log.error('Failed to copy public directory to dist directory');\n throw error;\n }\n } else {\n // NOTE(kitten): The public folder is currently always copied, regardless of targetDomain\n // split. Hence, there's another separate `copyPublicFolderAsync` call below for `web`\n await copyPublicFolderAsync(publicPath, outputPath);\n }\n\n let templateHtml: string | undefined;\n // Can be empty during web-only SSG.\n if (spaPlatforms.length) {\n await Promise.all(\n spaPlatforms.map(async (platform) => {\n // Assert early so the user doesn't have to wait until bundling is complete to find out that\n // Hermes won't be available.\n const isHermes = isEnableHermesManaged(exp, platform);\n if (isHermes) {\n await assertEngineMismatchAsync(projectRoot, exp, platform);\n }\n\n let bundle: {\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n files?: ExportAssetMap;\n };\n\n try {\n // Run metro bundler and create the JS bundles/source maps.\n bundle = await devServer.nativeExportBundleAsync(\n exp,\n {\n platform,\n splitChunks:\n !env.EXPO_NO_BUNDLE_SPLITTING &&\n ((devServer.isReactServerComponentsEnabled && !bytecode) || platform === 'web'),\n mainModuleName: getEntryWithServerRoot(projectRoot, {\n platform,\n pkg: projectConfig.pkg,\n }),\n mode: dev ? 'development' : 'production',\n engine: isHermes ? 'hermes' : undefined,\n serializerIncludeMaps: sourceMaps,\n bytecode: bytecode && isHermes,\n reactCompiler: !!exp.experiments?.reactCompiler,\n },\n files\n );\n } catch (error) {\n Log.log('');\n if (error instanceof Error) {\n Log.exception(error);\n } else {\n Log.error('Failed to bundle the app');\n Log.log(error as any);\n }\n process.exit(1);\n }\n\n bundles[platform] = bundle;\n\n getFilesFromSerialAssets(bundle.artifacts, {\n includeSourceMaps: sourceMaps,\n files,\n isServerHosted: devServer.isReactServerComponentsEnabled,\n });\n\n // TODO: Remove duplicates...\n const expoDomComponentReferences = bundle.artifacts\n .map((artifact) =>\n Array.isArray(artifact.metadata.expoDomComponentReferences)\n ? artifact.metadata.expoDomComponentReferences\n : []\n )\n .flat();\n await Promise.all(\n // TODO: Make a version of this which uses `this.metro.getBundler().buildGraphForEntries([])` to bundle all the DOM components at once.\n expoDomComponentReferences.map(async (filePath) => {\n const { bundle: platformDomComponentsBundle, htmlOutputName } =\n await exportDomComponentAsync({\n filePath,\n projectRoot,\n dev,\n devServer,\n isHermes,\n includeSourceMaps: sourceMaps,\n exp,\n files,\n useMd5Filename: true,\n });\n\n // Merge the assets from the DOM component into the output assets.\n // @ts-expect-error: mutate assets\n bundle.assets.push(...platformDomComponentsBundle.assets);\n\n transformNativeBundleForMd5Filename({\n domComponentReference: filePath,\n nativeBundle: bundle,\n files,\n htmlOutputName,\n });\n domComponentAssetsMetadata[platform] = [\n ...(domComponentAssetsMetadata[platform] || []),\n ...(await addDomBundleToMetadataAsync(platformDomComponentsBundle)),\n ...transformDomEntryForMd5Filename({\n files,\n htmlOutputName,\n }),\n ];\n })\n );\n\n if (platform === 'web') {\n // TODO: Unify with exportStaticAsync\n // TODO: Maybe move to the serializer.\n let html = await serializeHtmlWithAssets({\n isExporting: true,\n resources: bundle.artifacts,\n template: await createTemplateHtmlFromExpoConfigAsync(projectRoot, {\n scripts: [],\n cssLinks: [],\n exp: projectConfig.exp,\n }),\n baseUrl,\n });\n\n // Add the favicon assets to the HTML.\n const modifyHtml = await getVirtualFaviconAssetsAsync(projectRoot, {\n outputDir,\n baseUrl,\n files,\n exp: projectConfig.exp,\n });\n if (modifyHtml) {\n html = modifyHtml(html);\n }\n\n // HACK: This is used for adding SSR shims in React Server Components.\n templateHtml = html;\n\n // Generate SPA-styled HTML file.\n // If web exists, then write the template HTML file.\n files.set('index.html', {\n contents: html,\n targetDomain: devServer.isReactServerComponentsEnabled ? 'server' : 'client',\n });\n }\n })\n );\n\n if (devServer.isReactServerComponentsEnabled) {\n const isWeb = platforms.includes('web');\n\n await exportApiRoutesStandaloneAsync(devServer, {\n files,\n platform: 'web',\n apiRoutesOnly: !isWeb,\n templateHtml,\n });\n }\n\n // TODO: Use same asset system across platforms again.\n const { assets, embeddedHashSet } = await exportAssetsAsync(projectRoot, {\n files,\n exp,\n outputDir: outputPath,\n bundles,\n baseUrl,\n });\n\n if (dumpAssetmap) {\n Log.log('Creating asset map');\n files.set('assetmap.json', { contents: JSON.stringify(createAssetMap({ assets })) });\n }\n\n const targetDomain = devServer.isReactServerComponentsEnabled ? 'client/' : '';\n const fileNames = Object.fromEntries(\n Object.entries(bundles).map(([platform, bundle]) => [\n platform,\n bundle.artifacts\n .filter((asset) => asset.type === 'js')\n .map((asset) => targetDomain + asset.filename),\n ])\n );\n\n // Generate a `metadata.json` for EAS Update.\n const contents = createMetadataJson({\n bundles,\n fileNames,\n embeddedHashSet,\n domComponentAssetsMetadata,\n });\n files.set('metadata.json', { contents: JSON.stringify(contents) });\n }\n\n // Additional web-only steps...\n\n if (platforms.includes('web') && useServerRendering) {\n const exportServer = exp.web?.output === 'server';\n\n if (exportServer) {\n // TODO: Remove when this is abstracted into the files map\n await copyPublicFolderAsync(publicPath, path.resolve(outputPath, 'client'));\n }\n\n if (skipSSG) {\n Log.log('Skipping static site generation');\n await exportApiRoutesStandaloneAsync(devServer, {\n files,\n platform: 'web',\n apiRoutesOnly: true,\n });\n\n // Output a placeholder index.html if one doesn't exist in the public directory.\n // This ensures native + API routes have some content at the root URL.\n const placeholderIndex = path.resolve(outputPath, 'client/index.html');\n if (!fs.existsSync(placeholderIndex)) {\n files.set('index.html', {\n contents: `<html><body></body></html>`,\n targetDomain: 'client',\n });\n }\n } else if (\n // TODO: Support static export with RSC.\n !devServer.isReactServerComponentsEnabled\n ) {\n await exportFromServerAsync(projectRoot, devServer, {\n mode,\n files,\n clear: !!clear,\n outputDir: outputPath,\n minify,\n baseUrl,\n includeSourceMaps: sourceMaps,\n routerRoot: getRouterDirectoryModuleIdWithManifest(projectRoot, exp),\n reactCompiler: !!exp.experiments?.reactCompiler,\n exportServer,\n maxWorkers,\n isExporting: true,\n exp: projectConfig.exp,\n });\n }\n }\n } finally {\n await devServerManager.stopAsync();\n }\n\n // Write all files at the end for unified logging.\n await persistMetroFilesAsync(files, outputPath);\n}\n"],"names":["exportAppAsync","projectRoot","platforms","outputDir","clear","dev","dumpAssetmap","sourceMaps","minify","bytecode","maxWorkers","skipSSG","exp","environment","process","env","NODE_ENV","setNodeEnv","require","load","projectConfig","getConfig","getPublicExpoManifestAsync","skipValidation","length","includes","WebSupportProjectPrerequisite","assertAsync","useServerRendering","web","output","CommandError","baseUrl","getBaseUrlFromExpoConfig","Log","warn","log","chalk","gray","startsWith","yellow","mode","publicPath","path","resolve","EXPO_PUBLIC_FOLDER","outputPath","files","Map","devServerManager","DevServerManager","startMetroAsync","port","isExporting","location","resetDevServer","devServer","getDefaultDevServer","assert","MetroBundlerDevServer","bundles","domComponentAssetsMetadata","spaPlatforms","isReactServerComponentsEnabled","filter","platform","copyPublicFolderAsync","join","error","templateHtml","Promise","all","map","isHermes","isEnableHermesManaged","assertEngineMismatchAsync","bundle","nativeExportBundleAsync","splitChunks","EXPO_NO_BUNDLE_SPLITTING","mainModuleName","getEntryWithServerRoot","pkg","engine","undefined","serializerIncludeMaps","reactCompiler","experiments","Error","exception","exit","getFilesFromSerialAssets","artifacts","includeSourceMaps","isServerHosted","expoDomComponentReferences","artifact","Array","isArray","metadata","flat","filePath","platformDomComponentsBundle","htmlOutputName","exportDomComponentAsync","useMd5Filename","assets","push","transformNativeBundleForMd5Filename","domComponentReference","nativeBundle","addDomBundleToMetadataAsync","transformDomEntryForMd5Filename","html","serializeHtmlWithAssets","resources","template","createTemplateHtmlFromExpoConfigAsync","scripts","cssLinks","modifyHtml","getVirtualFaviconAssetsAsync","set","contents","targetDomain","isWeb","exportApiRoutesStandaloneAsync","apiRoutesOnly","embeddedHashSet","exportAssetsAsync","JSON","stringify","createAssetMap","fileNames","Object","fromEntries","entries","asset","type","filename","createMetadataJson","exportServer","placeholderIndex","fs","existsSync","exportFromServerAsync","routerRoot","getRouterDirectoryModuleIdWithManifest","stopAsync","persistMetroFilesAsync"],"mappings":";;;;+BA2CsBA;;;eAAAA;;;;yBA3CI;;;;;;;gEAGP;;;;;;;gEACD;;;;;;;gEACH;;;;;;;gEACE;;;;;;oCAEyC;8BACxB;qCAM3B;8BAC0D;mCACK;yBACzB;uCACF;8BACL;4BAQ/B;+BACwB;6DACV;+CACyB;kCACb;uCACK;wBACiB;+BACf;oCACD;8BACE;6BACa;qBAClC;wBACS;yBACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpB,eAAeA,eACpBC,WAAmB,EACnB,EACEC,SAAS,EACTC,SAAS,EACTC,KAAK,EACLC,GAAG,EACHC,YAAY,EACZC,UAAU,EACVC,MAAM,EACNC,QAAQ,EACRC,UAAU,EACVC,OAAO,EAaR;QAmBwDC,UAE1CA;IAnBf,sEAAsE;IACtE,MAAMC,cAAcR,MAAM,gBAAgB;IAC1CS,QAAQC,GAAG,CAACC,QAAQ,GAAGH;IACvBI,IAAAA,mBAAU,EAACJ;IAEXK,QAAQ,aAAaC,IAAI,CAAClB;IAE1B,MAAMmB,gBAAgBC,IAAAA,mBAAS,EAACpB;IAChC,MAAMW,MAAM,MAAMU,IAAAA,iDAA0B,EAACrB,aAAa;QACxD,kCAAkC;QAClCsB,gBAAgBrB,UAAUsB,MAAM,KAAK,KAAKtB,SAAS,CAAC,EAAE,KAAK;IAC7D;IAEA,IAAIA,UAAUuB,QAAQ,CAAC,QAAQ;Q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ACzC;oBAUmBnD;gBATnB,MAAMqI,IAAAA,wCAAqB,EAAChJ,aAAauD,WAAW;oBAClDf;oBACAM;oBACA3C,OAAO,CAAC,CAACA;oBACTD,WAAW2C;oBACXtC;oBACAwB;oBACA6D,mBAAmBtF;oBACnB2I,YAAYC,IAAAA,8CAAsC,EAAClJ,aAAaW;oBAChE0E,eAAe,CAAC,GAAC1E,mBAAAA,IAAI2E,WAAW,qBAAf3E,iBAAiB0E,aAAa;oBAC/CuD;oBACAnI;oBACA2C,aAAa;oBACbzC,KAAKQ,cAAcR,GAAG;gBACxB;YACF;QACF;IACF,SAAU;QACR,MAAMqC,iBAAiBmG,SAAS;IAClC;IAEA,kDAAkD;IAClD,MAAMC,IAAAA,kCAAsB,EAACtG,OAAOD;AACtC"}
|
|
@@ -123,6 +123,7 @@ async function runIosAsync(projectRoot, options) {
|
|
|
123
123
|
// Resolve the CLI arguments into useable options.
|
|
124
124
|
const props = await (0, _profile.profile)(_resolveOptions.resolveOptionsAsync)(projectRoot, options);
|
|
125
125
|
const projectConfig = (0, _config().getConfig)(projectRoot);
|
|
126
|
+
// We only support build cache for simulator builds for now.
|
|
126
127
|
if (!options.binary && props.buildCacheProvider && props.isSimulator) {
|
|
127
128
|
const localPath = await (0, _buildcacheproviders.resolveBuildCache)({
|
|
128
129
|
projectRoot,
|
|
@@ -197,7 +198,8 @@ async function runIosAsync(projectRoot, options) {
|
|
|
197
198
|
// Find the path to the built app binary, this will be used to install the binary
|
|
198
199
|
// on a device.
|
|
199
200
|
binaryPath = await (0, _profile.profile)(_XcodeBuild.getAppBinaryPath)(buildOutput);
|
|
200
|
-
|
|
201
|
+
// We only support build cache for simulator builds for now.
|
|
202
|
+
shouldUpdateBuildCache = props.isSimulator;
|
|
201
203
|
}
|
|
202
204
|
debug('Binary path:', binaryPath);
|
|
203
205
|
// Ensure the port hasn't become busy during the build.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/run/ios/runIosAsync.ts"],"sourcesContent":["import { getConfig } from '@expo/config';\nimport spawnAsync from '@expo/spawn-async';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport path from 'path';\n\nimport * as XcodeBuild from './XcodeBuild';\nimport { Options } from './XcodeBuild.types';\nimport { getLaunchInfoForBinaryAsync, launchAppAsync } from './launchApp';\nimport { resolveOptionsAsync } from './options/resolveOptions';\nimport { getValidBinaryPathAsync } from './validateExternalBinary';\nimport { exportEagerAsync } from '../../export/embed/exportEager';\nimport * as Log from '../../log';\nimport { AppleAppIdResolver } from '../../start/platforms/ios/AppleAppIdResolver';\nimport { getContainerPathAsync, simctlAsync } from '../../start/platforms/ios/simctl';\nimport { resolveBuildCache, uploadBuildCache } from '../../utils/build-cache-providers';\nimport { maybePromptToSyncPodsAsync } from '../../utils/cocoapods';\nimport { CommandError } from '../../utils/errors';\nimport { setNodeEnv } from '../../utils/nodeEnv';\nimport { ensurePortAvailabilityAsync } from '../../utils/port';\nimport { profile } from '../../utils/profile';\nimport { getSchemesForIosAsync } from '../../utils/scheme';\nimport { ensureNativeProjectAsync } from '../ensureNativeProject';\nimport { logProjectLogsLocation } from '../hints';\nimport { startBundlerAsync } from '../startBundler';\n\nconst debug = require('debug')('expo:run:ios');\n\nexport async function runIosAsync(projectRoot: string, options: Options) {\n setNodeEnv(options.configuration === 'Release' ? 'production' : 'development');\n require('@expo/env').load(projectRoot);\n\n assertPlatform();\n\n const install = !!options.install;\n\n if ((await ensureNativeProjectAsync(projectRoot, { platform: 'ios', install })) && install) {\n await maybePromptToSyncPodsAsync(projectRoot);\n }\n\n // Resolve the CLI arguments into useable options.\n const props = await profile(resolveOptionsAsync)(projectRoot, options);\n\n const projectConfig = getConfig(projectRoot);\n if (!options.binary && props.buildCacheProvider && props.isSimulator) {\n const localPath = await resolveBuildCache({\n projectRoot,\n platform: 'ios',\n runOptions: options,\n provider: props.buildCacheProvider,\n });\n if (localPath) {\n options.binary = localPath;\n }\n }\n\n if (options.rebundle) {\n Log.warn(`The --unstable-rebundle flag is experimental and may not work as expected.`);\n // Get the existing binary path to re-bundle the app.\n\n let binaryPath: string;\n if (!options.binary) {\n if (!props.isSimulator) {\n throw new Error('Re-bundling on physical devices requires the --binary flag.');\n }\n const appId = await new AppleAppIdResolver(projectRoot).getAppIdAsync();\n const possibleBinaryPath = await getContainerPathAsync(props.device, {\n appId,\n });\n if (!possibleBinaryPath) {\n throw new CommandError(\n `Cannot rebundle because no --binary was provided and no existing binary was found on the device for ID: ${appId}.`\n );\n }\n binaryPath = possibleBinaryPath;\n Log.log('Re-using existing binary path:', binaryPath);\n // Set the binary path to the existing binary path.\n options.binary = binaryPath;\n }\n\n Log.log('Rebundling the Expo config file');\n // Re-bundle the config file the same way the app was originally bundled.\n await spawnAsync('node', [\n path.join(require.resolve('expo-constants/package.json'), '../scripts/getAppConfig.js'),\n projectRoot,\n path.join(options.binary, 'EXConstants.bundle'),\n ]);\n // Re-bundle the app.\n\n const possibleBundleOutput = path.join(options.binary, 'main.jsbundle');\n\n if (fs.existsSync(possibleBundleOutput)) {\n Log.log('Rebundling the app...');\n await exportEagerAsync(projectRoot, {\n resetCache: false,\n dev: false,\n platform: 'ios',\n assetsDest: path.join(options.binary, 'assets'),\n bundleOutput: possibleBundleOutput,\n });\n } else {\n Log.warn('Bundle output not found at expected location:', possibleBundleOutput);\n }\n }\n\n let binaryPath: string;\n let shouldUpdateBuildCache = false;\n if (options.binary) {\n binaryPath = await getValidBinaryPathAsync(options.binary, props);\n Log.log('Using custom binary path:', binaryPath);\n } else {\n let eagerBundleOptions: string | undefined;\n\n if (options.configuration === 'Release') {\n eagerBundleOptions = JSON.stringify(\n await exportEagerAsync(projectRoot, {\n dev: false,\n platform: 'ios',\n })\n );\n }\n\n // Spawn the `xcodebuild` process to create the app binary.\n const buildOutput = await XcodeBuild.buildAsync({\n ...props,\n eagerBundleOptions,\n });\n\n // Find the path to the built app binary, this will be used to install the binary\n // on a device.\n binaryPath = await profile(XcodeBuild.getAppBinaryPath)(buildOutput);\n shouldUpdateBuildCache = true;\n }\n debug('Binary path:', binaryPath);\n\n // Ensure the port hasn't become busy during the build.\n if (props.shouldStartBundler && !(await ensurePortAvailabilityAsync(projectRoot, props))) {\n props.shouldStartBundler = false;\n }\n\n const launchInfo = await getLaunchInfoForBinaryAsync(binaryPath);\n const isCustomBinary = !!options.binary;\n\n // Always close the app before launching on a simulator. Otherwise certain cached resources like the splashscreen will not be available.\n if (props.isSimulator) {\n try {\n await simctlAsync(['terminate', props.device.udid, launchInfo.bundleId]);\n } catch (error) {\n // If we failed it's likely that the app was not running to begin with and we will get an `invalid device` error\n debug('Failed to terminate app (possibly because it was not running):', error);\n }\n }\n\n // Start the dev server which creates all of the required info for\n // launching the app on a simulator.\n const manager = await startBundlerAsync(projectRoot, {\n port: props.port,\n headless: !props.shouldStartBundler,\n // If a scheme is specified then use that instead of the package name.\n\n scheme: isCustomBinary\n ? // If launching a custom binary, use the schemes in the Info.plist.\n launchInfo.schemes[0]\n : // If a scheme is specified then use that instead of the package name.\n (await getSchemesForIosAsync(projectRoot))?.[0],\n });\n\n // Install and launch the app binary on a device.\n await launchAppAsync(\n binaryPath,\n manager,\n {\n isSimulator: props.isSimulator,\n device: props.device,\n shouldStartBundler: props.shouldStartBundler,\n },\n launchInfo.bundleId\n );\n\n // Log the location of the JS logs for the device.\n if (props.shouldStartBundler) {\n logProjectLogsLocation();\n } else {\n await manager.stopAsync();\n }\n\n if (shouldUpdateBuildCache && props.buildCacheProvider) {\n await uploadBuildCache({\n projectRoot,\n platform: 'ios',\n provider: props.buildCacheProvider,\n buildPath: binaryPath,\n runOptions: options,\n });\n }\n}\n\nfunction assertPlatform() {\n if (process.platform !== 'darwin') {\n Log.exit(\n chalk`iOS apps can only be built on macOS devices. Use {cyan eas build -p ios} to build in the cloud.`\n );\n }\n}\n"],"names":["runIosAsync","debug","require","projectRoot","options","setNodeEnv","configuration","load","assertPlatform","install","ensureNativeProjectAsync","platform","maybePromptToSyncPodsAsync","props","profile","resolveOptionsAsync","projectConfig","getConfig","binary","buildCacheProvider","isSimulator","localPath","resolveBuildCache","runOptions","provider","rebundle","Log","warn","binaryPath","Error","appId","AppleAppIdResolver","getAppIdAsync","possibleBinaryPath","getContainerPathAsync","device","CommandError","log","spawnAsync","path","join","resolve","possibleBundleOutput","fs","existsSync","exportEagerAsync","resetCache","dev","assetsDest","bundleOutput","shouldUpdateBuildCache","getValidBinaryPathAsync","eagerBundleOptions","JSON","stringify","buildOutput","XcodeBuild","buildAsync","getAppBinaryPath","shouldStartBundler","ensurePortAvailabilityAsync","launchInfo","getLaunchInfoForBinaryAsync","isCustomBinary","simctlAsync","udid","bundleId","error","manager","startBundlerAsync","port","headless","scheme","schemes","getSchemesForIosAsync","launchAppAsync","logProjectLogsLocation","stopAsync","uploadBuildCache","buildPath","process","exit","chalk"],"mappings":";;;;+BA4BsBA;;;eAAAA;;;;yBA5BI;;;;;;;gEACH;;;;;;;gEACL;;;;;;;gEACH;;;;;;;gEACE;;;;;;oEAEW;2BAEgC;gCACxB;wCACI;6BACP;6DACZ;oCACc;wBACgB;qCACC;2BACT;wBACd;yBACF;sBACiB;yBACpB;wBACc;qCACG;uBACF;8BACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,MAAMC,QAAQC,QAAQ,SAAS;AAExB,eAAeF,YAAYG,WAAmB,EAAEC,OAAgB;QAwI9D;IAvIPC,IAAAA,mBAAU,EAACD,QAAQE,aAAa,KAAK,YAAY,eAAe;IAChEJ,QAAQ,aAAaK,IAAI,CAACJ;IAE1BK;IAEA,MAAMC,UAAU,CAAC,CAACL,QAAQK,OAAO;IAEjC,IAAI,AAAC,MAAMC,IAAAA,6CAAwB,EAACP,aAAa;QAAEQ,UAAU;QAAOF;IAAQ,MAAOA,SAAS;QAC1F,MAAMG,IAAAA,qCAA0B,EAACT;IACnC;IAEA,kDAAkD;IAClD,MAAMU,QAAQ,MAAMC,IAAAA,gBAAO,EAACC,mCAAmB,EAAEZ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,QAAQ;aAAC;QACzE,EAAE,OAAOC,OAAO;YACd,gHAAgH;YAChHlE,MAAM,kEAAkEkE;QAC1E;IACF;IAEA,kEAAkE;IAClE,oCAAoC;IACpC,MAAMC,UAAU,MAAMC,IAAAA,+BAAiB,EAAClE,aAAa;QACnDmE,MAAMzD,MAAMyD,IAAI;QAChBC,UAAU,CAAC1D,MAAM8C,kBAAkB;QACnC,sEAAsE;QAEtEa,QAAQT,iBAEJF,WAAWY,OAAO,CAAC,EAAE,IAEpB,QAAA,MAAMC,IAAAA,6BAAqB,EAACvE,iCAA7B,AAAC,KAA2C,CAAC,EAAE;IACrD;IAEA,iDAAiD;IACjD,MAAMwE,IAAAA,yBAAc,EAClB/C,YACAwC,SACA;QACEhD,aAAaP,MAAMO,WAAW;QAC9Be,QAAQtB,MAAMsB,MAAM;QACpBwB,oBAAoB9C,MAAM8C,kBAAkB;IAC9C,GACAE,WAAWK,QAAQ;IAGrB,kDAAkD;IAClD,IAAIrD,MAAM8C,kBAAkB,EAAE;QAC5BiB,IAAAA,6BAAsB;IACxB,OAAO;QACL,MAAMR,QAAQS,SAAS;IACzB;IAEA,IAAI3B,0BAA0BrC,MAAMM,kBAAkB,EAAE;QACtD,MAAM2D,IAAAA,qCAAgB,EAAC;YACrB3E;YACAQ,UAAU;YACVa,UAAUX,MAAMM,kBAAkB;YAClC4D,WAAWnD;YACXL,YAAYnB;QACd;IACF;AACF;AAEA,SAASI;IACP,IAAIwE,QAAQrE,QAAQ,KAAK,UAAU;QACjCe,KAAIuD,IAAI,CACNC,IAAAA,gBAAK,CAAA,CAAC,+FAA+F,CAAC;IAE1G;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/run/ios/runIosAsync.ts"],"sourcesContent":["import { getConfig } from '@expo/config';\nimport spawnAsync from '@expo/spawn-async';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport path from 'path';\n\nimport * as XcodeBuild from './XcodeBuild';\nimport { Options } from './XcodeBuild.types';\nimport { getLaunchInfoForBinaryAsync, launchAppAsync } from './launchApp';\nimport { resolveOptionsAsync } from './options/resolveOptions';\nimport { getValidBinaryPathAsync } from './validateExternalBinary';\nimport { exportEagerAsync } from '../../export/embed/exportEager';\nimport * as Log from '../../log';\nimport { AppleAppIdResolver } from '../../start/platforms/ios/AppleAppIdResolver';\nimport { getContainerPathAsync, simctlAsync } from '../../start/platforms/ios/simctl';\nimport { resolveBuildCache, uploadBuildCache } from '../../utils/build-cache-providers';\nimport { maybePromptToSyncPodsAsync } from '../../utils/cocoapods';\nimport { CommandError } from '../../utils/errors';\nimport { setNodeEnv } from '../../utils/nodeEnv';\nimport { ensurePortAvailabilityAsync } from '../../utils/port';\nimport { profile } from '../../utils/profile';\nimport { getSchemesForIosAsync } from '../../utils/scheme';\nimport { ensureNativeProjectAsync } from '../ensureNativeProject';\nimport { logProjectLogsLocation } from '../hints';\nimport { startBundlerAsync } from '../startBundler';\n\nconst debug = require('debug')('expo:run:ios');\n\nexport async function runIosAsync(projectRoot: string, options: Options) {\n setNodeEnv(options.configuration === 'Release' ? 'production' : 'development');\n require('@expo/env').load(projectRoot);\n\n assertPlatform();\n\n const install = !!options.install;\n\n if ((await ensureNativeProjectAsync(projectRoot, { platform: 'ios', install })) && install) {\n await maybePromptToSyncPodsAsync(projectRoot);\n }\n\n // Resolve the CLI arguments into useable options.\n const props = await profile(resolveOptionsAsync)(projectRoot, options);\n\n const projectConfig = getConfig(projectRoot);\n // We only support build cache for simulator builds for now.\n if (!options.binary && props.buildCacheProvider && props.isSimulator) {\n const localPath = await resolveBuildCache({\n projectRoot,\n platform: 'ios',\n runOptions: options,\n provider: props.buildCacheProvider,\n });\n if (localPath) {\n options.binary = localPath;\n }\n }\n\n if (options.rebundle) {\n Log.warn(`The --unstable-rebundle flag is experimental and may not work as expected.`);\n // Get the existing binary path to re-bundle the app.\n\n let binaryPath: string;\n if (!options.binary) {\n if (!props.isSimulator) {\n throw new Error('Re-bundling on physical devices requires the --binary flag.');\n }\n const appId = await new AppleAppIdResolver(projectRoot).getAppIdAsync();\n const possibleBinaryPath = await getContainerPathAsync(props.device, {\n appId,\n });\n if (!possibleBinaryPath) {\n throw new CommandError(\n `Cannot rebundle because no --binary was provided and no existing binary was found on the device for ID: ${appId}.`\n );\n }\n binaryPath = possibleBinaryPath;\n Log.log('Re-using existing binary path:', binaryPath);\n // Set the binary path to the existing binary path.\n options.binary = binaryPath;\n }\n\n Log.log('Rebundling the Expo config file');\n // Re-bundle the config file the same way the app was originally bundled.\n await spawnAsync('node', [\n path.join(require.resolve('expo-constants/package.json'), '../scripts/getAppConfig.js'),\n projectRoot,\n path.join(options.binary, 'EXConstants.bundle'),\n ]);\n // Re-bundle the app.\n\n const possibleBundleOutput = path.join(options.binary, 'main.jsbundle');\n\n if (fs.existsSync(possibleBundleOutput)) {\n Log.log('Rebundling the app...');\n await exportEagerAsync(projectRoot, {\n resetCache: false,\n dev: false,\n platform: 'ios',\n assetsDest: path.join(options.binary, 'assets'),\n bundleOutput: possibleBundleOutput,\n });\n } else {\n Log.warn('Bundle output not found at expected location:', possibleBundleOutput);\n }\n }\n\n let binaryPath: string;\n let shouldUpdateBuildCache = false;\n if (options.binary) {\n binaryPath = await getValidBinaryPathAsync(options.binary, props);\n Log.log('Using custom binary path:', binaryPath);\n } else {\n let eagerBundleOptions: string | undefined;\n\n if (options.configuration === 'Release') {\n eagerBundleOptions = JSON.stringify(\n await exportEagerAsync(projectRoot, {\n dev: false,\n platform: 'ios',\n })\n );\n }\n\n // Spawn the `xcodebuild` process to create the app binary.\n const buildOutput = await XcodeBuild.buildAsync({\n ...props,\n eagerBundleOptions,\n });\n\n // Find the path to the built app binary, this will be used to install the binary\n // on a device.\n binaryPath = await profile(XcodeBuild.getAppBinaryPath)(buildOutput);\n // We only support build cache for simulator builds for now.\n shouldUpdateBuildCache = props.isSimulator;\n }\n debug('Binary path:', binaryPath);\n\n // Ensure the port hasn't become busy during the build.\n if (props.shouldStartBundler && !(await ensurePortAvailabilityAsync(projectRoot, props))) {\n props.shouldStartBundler = false;\n }\n\n const launchInfo = await getLaunchInfoForBinaryAsync(binaryPath);\n const isCustomBinary = !!options.binary;\n\n // Always close the app before launching on a simulator. Otherwise certain cached resources like the splashscreen will not be available.\n if (props.isSimulator) {\n try {\n await simctlAsync(['terminate', props.device.udid, launchInfo.bundleId]);\n } catch (error) {\n // If we failed it's likely that the app was not running to begin with and we will get an `invalid device` error\n debug('Failed to terminate app (possibly because it was not running):', error);\n }\n }\n\n // Start the dev server which creates all of the required info for\n // launching the app on a simulator.\n const manager = await startBundlerAsync(projectRoot, {\n port: props.port,\n headless: !props.shouldStartBundler,\n // If a scheme is specified then use that instead of the package name.\n\n scheme: isCustomBinary\n ? // If launching a custom binary, use the schemes in the Info.plist.\n launchInfo.schemes[0]\n : // If a scheme is specified then use that instead of the package name.\n (await getSchemesForIosAsync(projectRoot))?.[0],\n });\n\n // Install and launch the app binary on a device.\n await launchAppAsync(\n binaryPath,\n manager,\n {\n isSimulator: props.isSimulator,\n device: props.device,\n shouldStartBundler: props.shouldStartBundler,\n },\n launchInfo.bundleId\n );\n\n // Log the location of the JS logs for the device.\n if (props.shouldStartBundler) {\n logProjectLogsLocation();\n } else {\n await manager.stopAsync();\n }\n\n if (shouldUpdateBuildCache && props.buildCacheProvider) {\n await uploadBuildCache({\n projectRoot,\n platform: 'ios',\n provider: props.buildCacheProvider,\n buildPath: binaryPath,\n runOptions: options,\n });\n }\n}\n\nfunction assertPlatform() {\n if (process.platform !== 'darwin') {\n Log.exit(\n chalk`iOS apps can only be built on macOS devices. Use {cyan eas build -p ios} to build in the cloud.`\n );\n }\n}\n"],"names":["runIosAsync","debug","require","projectRoot","options","setNodeEnv","configuration","load","assertPlatform","install","ensureNativeProjectAsync","platform","maybePromptToSyncPodsAsync","props","profile","resolveOptionsAsync","projectConfig","getConfig","binary","buildCacheProvider","isSimulator","localPath","resolveBuildCache","runOptions","provider","rebundle","Log","warn","binaryPath","Error","appId","AppleAppIdResolver","getAppIdAsync","possibleBinaryPath","getContainerPathAsync","device","CommandError","log","spawnAsync","path","join","resolve","possibleBundleOutput","fs","existsSync","exportEagerAsync","resetCache","dev","assetsDest","bundleOutput","shouldUpdateBuildCache","getValidBinaryPathAsync","eagerBundleOptions","JSON","stringify","buildOutput","XcodeBuild","buildAsync","getAppBinaryPath","shouldStartBundler","ensurePortAvailabilityAsync","launchInfo","getLaunchInfoForBinaryAsync","isCustomBinary","simctlAsync","udid","bundleId","error","manager","startBundlerAsync","port","headless","scheme","schemes","getSchemesForIosAsync","launchAppAsync","logProjectLogsLocation","stopAsync","uploadBuildCache","buildPath","process","exit","chalk"],"mappings":";;;;+BA4BsBA;;;eAAAA;;;;yBA5BI;;;;;;;gEACH;;;;;;;gEACL;;;;;;;gEACH;;;;;;;gEACE;;;;;;oEAEW;2BAEgC;gCACxB;wCACI;6BACP;6DACZ;oCACc;wBACgB;qCACC;2BACT;wBACd;yBACF;sBACiB;yBACpB;wBACc;qCACG;uBACF;8BACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,MAAMC,QAAQC,QAAQ,SAAS;AAExB,eAAeF,YAAYG,WAAmB,EAAEC,OAAgB;QA0I9D;IAzIPC,IAAAA,mBAAU,EAACD,QAAQE,aAAa,KAAK,YAAY,eAAe;IAChEJ,QAAQ,aAAaK,IAAI,CAACJ;IAE1BK;IAEA,MAAMC,UAAU,CAAC,CAACL,QAAQK,OAAO;IAEjC,IAAI,AAAC,MAAMC,IAAAA,6CAAwB,EAACP,aAAa;QAAEQ,UAAU;QAAOF;IAAQ,MAAOA,SAAS;QAC1F,MAAMG,IAAAA,qCAA0B,EAACT;IACnC;IAEA,kDAAkD;IAClD,MAAMU,QAAQ,MAAMC,IAAAA,gBAAO,EAACC,mCAAmB,EAAEZ,aAAaC;IAE9D,MAAMY,gBAAgBC,IAAAA,mBAAS,EAACd;IAChC,4DAA4D;IAC5D,IAAI,CAACC,QAAQc,MAAM,IAAIL,MAAMM,k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AAkEkE;QAC1E;IACF;IAEA,kEAAkE;IAClE,oCAAoC;IACpC,MAAMC,UAAU,MAAMC,IAAAA,+BAAiB,EAAClE,aAAa;QACnDmE,MAAMzD,MAAMyD,IAAI;QAChBC,UAAU,CAAC1D,MAAM8C,kBAAkB;QACnC,sEAAsE;QAEtEa,QAAQT,iBAEJF,WAAWY,OAAO,CAAC,EAAE,IAEpB,QAAA,MAAMC,IAAAA,6BAAqB,EAACvE,iCAA7B,AAAC,KAA2C,CAAC,EAAE;IACrD;IAEA,iDAAiD;IACjD,MAAMwE,IAAAA,yBAAc,EAClB/C,YACAwC,SACA;QACEhD,aAAaP,MAAMO,WAAW;QAC9Be,QAAQtB,MAAMsB,MAAM;QACpBwB,oBAAoB9C,MAAM8C,kBAAkB;IAC9C,GACAE,WAAWK,QAAQ;IAGrB,kDAAkD;IAClD,IAAIrD,MAAM8C,kBAAkB,EAAE;QAC5BiB,IAAAA,6BAAsB;IACxB,OAAO;QACL,MAAMR,QAAQS,SAAS;IACzB;IAEA,IAAI3B,0BAA0BrC,MAAMM,kBAAkB,EAAE;QACtD,MAAM2D,IAAAA,qCAAgB,EAAC;YACrB3E;YACAQ,UAAU;YACVa,UAAUX,MAAMM,kBAAkB;YAClC4D,WAAWnD;YACXL,YAAYnB;QACd;IACF;AACF;AAEA,SAASI;IACP,IAAIwE,QAAQrE,QAAQ,KAAK,UAAU;QACjCe,KAAIuD,IAAI,CACNC,IAAAA,gBAAK,CAAA,CAAC,+FAA+F,CAAC;IAE1G;AACF"}
|
|
@@ -765,7 +765,11 @@ class MetroBundlerDevServer extends _BundlerDevServer.BundlerDevServer {
|
|
|
765
765
|
// Add support for DOM components.
|
|
766
766
|
// TODO: Maybe put behind a flag for now?
|
|
767
767
|
middleware.use(domComponentRenderer);
|
|
768
|
-
middleware.use(new _CreateFileMiddleware.CreateFileMiddleware(
|
|
768
|
+
middleware.use(new _CreateFileMiddleware.CreateFileMiddleware({
|
|
769
|
+
metroRoot: serverRoot,
|
|
770
|
+
projectRoot: this.projectRoot,
|
|
771
|
+
appDir
|
|
772
|
+
}).getHandler());
|
|
769
773
|
// Append support for redirecting unhandled requests to the index.html page on web.
|
|
770
774
|
if (this.isTargetingWeb()) {
|
|
771
775
|
// This MUST be after the manifest middleware so it doesn't have a chance to serve the template `public/index.html`.
|
|
@@ -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 // 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 try {\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 } catch (error) {\n if (error instanceof Error) {\n // Space out build failures.\n const cause = error.cause as undefined | { _expoImportStack?: string };\n if (cause && '_expoImportStack' in cause) {\n error.message += '\\n\\n' + cause._expoImportStack;\n }\n }\n\n throw error;\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","cause","_expoImportStack","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","ext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AAM,IAAIK,IAAIoR,cAAc,IAAI,CAACxR,uBAAuB;gBAC9D,IAAI,CAACuS,QAAQ,CAACxS;YAChB;YAEA,OAAOoX,IAAAA,mDAAyB,EAC9B,IAAI,CAACrb,WAAW,EAChBob,IAAI1Z,GAAG,EACP0Z,IAAIpU,QAAQ,EACZL,gBAAgB/B,WAAW,IAAI,IAAI,CAACjF,oBAAoB,CAACiF,WAAW;QAExE,QA4bAwF,cAAmF,WAwQ3EkH,mBAAwD,MAwJhE,aAAa;aAELgE,yBAAyB,IAAIlV;;AA+cvC;AAEA,SAASiX,WAAWT,WAAmB;IACrC,OAAOA,YAAYF,QAAQ,CAAC;AAC9B;AAEA,SAASzN,WAAWqS,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAI7Z,OAAO,CAAC,oBAAoB;AACzC;AAEA,eAAe6Y,qBACbiB,OAAsE,EACtE1c,OAAkC;IAElC,OAAO,AAAC,CAAA,MAAM2c,IAAAA,mDAA6B,EAACD,SAAS1c,QAAO,EAAG6X,QAAQ,CAACjB,WAAW;QACjF+E,eAAe3b,QAAQ2b,aAAa;IACtC;AACF;AAEA,SAASjR,OAAUkS,KAAU;IAC3B,OAAOjZ,MAAM0J,IAAI,CAAC,IAAIqH,IAAIkI;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(\n new CreateFileMiddleware({\n metroRoot: serverRoot,\n projectRoot: this.projectRoot,\n appDir,\n }).getHandler()\n );\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 try {\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 } catch (error) {\n if (error instanceof Error) {\n // Space out build failures.\n const cause = error.cause as undefined | { _expoImportStack?: string };\n if (cause && '_expoImportStack' in cause) {\n error.message += '\\n\\n' + cause._expoImportStack;\n }\n }\n\n throw error;\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","cause","_expoImportStack","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,MAAM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eAAe6Y,qBACbiB,OAAsE,EACtE1c,OAAkC;IAElC,OAAO,AAAC,CAAA,MAAM2c,IAAAA,mDAA6B,EAACD,SAAS1c,QAAO,EAAG6X,QAAQ,CAACjB,WAAW;QACjF+E,eAAe3b,QAAQ2b,aAAa;IACtC;AACF;AAEA,SAASjR,OAAUkS,KAAU;IAC3B,OAAOjZ,MAAM0J,IAAI,CAAC,IAAIqH,IAAIkI;AAC5B"}
|
|
@@ -2,38 +2,69 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", {
|
|
3
3
|
value: true
|
|
4
4
|
});
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
_isLocalHostname: function() {
|
|
13
|
+
return _isLocalHostname;
|
|
14
|
+
},
|
|
15
|
+
createCorsMiddleware: function() {
|
|
8
16
|
return createCorsMiddleware;
|
|
9
17
|
}
|
|
10
18
|
});
|
|
11
|
-
const
|
|
12
|
-
'localhost',
|
|
13
|
-
'chrome-devtools-frontend.appspot.com',
|
|
19
|
+
const DEFAULT_ALLOWED_CORS_HOSTS = [
|
|
14
20
|
'devtools'
|
|
15
21
|
];
|
|
22
|
+
const _isLocalHostname = (hostname)=>{
|
|
23
|
+
if (hostname === 'localhost') {
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
let maybeIp = hostname;
|
|
27
|
+
const ipv6To4Prefix = '::ffff:';
|
|
28
|
+
if (maybeIp.startsWith(ipv6To4Prefix)) {
|
|
29
|
+
maybeIp = maybeIp.slice(ipv6To4Prefix.length);
|
|
30
|
+
}
|
|
31
|
+
if (maybeIp === '::1') {
|
|
32
|
+
return true;
|
|
33
|
+
} else if (/^127(?:.\d+){3}$/.test(maybeIp)) {
|
|
34
|
+
return maybeIp.split('.').every((part)=>{
|
|
35
|
+
const num = parseInt(part, 10);
|
|
36
|
+
return num >= 0 && num <= 255;
|
|
37
|
+
});
|
|
38
|
+
} else {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
16
42
|
function createCorsMiddleware(exp) {
|
|
17
43
|
var _exp_extra_router, _exp_extra, _exp_extra_router1, _exp_extra1;
|
|
18
|
-
const
|
|
19
|
-
...
|
|
44
|
+
const allowedHosts = [
|
|
45
|
+
...DEFAULT_ALLOWED_CORS_HOSTS
|
|
20
46
|
];
|
|
21
47
|
// Support for expo-router API routes
|
|
22
48
|
if ((_exp_extra = exp.extra) == null ? void 0 : (_exp_extra_router = _exp_extra.router) == null ? void 0 : _exp_extra_router.headOrigin) {
|
|
23
|
-
|
|
49
|
+
allowedHosts.push(new URL(exp.extra.router.headOrigin).host);
|
|
24
50
|
}
|
|
25
51
|
if ((_exp_extra1 = exp.extra) == null ? void 0 : (_exp_extra_router1 = _exp_extra1.router) == null ? void 0 : _exp_extra_router1.origin) {
|
|
26
|
-
|
|
52
|
+
allowedHosts.push(new URL(exp.extra.router.origin).host);
|
|
27
53
|
}
|
|
28
54
|
return (req, res, next)=>{
|
|
29
55
|
if (typeof req.headers.origin === 'string') {
|
|
30
56
|
const { host, hostname } = new URL(req.headers.origin);
|
|
31
57
|
const isSameOrigin = host === req.headers.host;
|
|
32
|
-
|
|
58
|
+
const isLocalhost = _isLocalHostname(hostname);
|
|
59
|
+
const isAllowedHost = allowedHosts.includes(host) || isLocalhost;
|
|
60
|
+
if (!isSameOrigin && !isAllowedHost) {
|
|
33
61
|
next(new Error(`Unauthorized request from ${req.headers.origin}. ` + 'This may happen because of a conflicting browser extension to intercept HTTP requests. ' + 'Disable browser extensions or use incognito mode and try again.'));
|
|
34
62
|
return;
|
|
63
|
+
} else if (!isLocalhost && isAllowedHost) {
|
|
64
|
+
// Skipped for localhost to only allow requests from this dev-sever and not escalate
|
|
65
|
+
// the cross-origin resource sharing that's allowed beyond the browser's defaults
|
|
66
|
+
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
|
|
35
67
|
}
|
|
36
|
-
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
|
|
37
68
|
maybePreventMetroResetCorsHeader(req, res);
|
|
38
69
|
}
|
|
39
70
|
// Block MIME-type sniffing.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/CorsMiddleware.ts"],"sourcesContent":["import type { ExpoConfig } from '@expo/config';\n\nimport type { ServerRequest, ServerResponse } from './server.types';\n\nconst
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/CorsMiddleware.ts"],"sourcesContent":["import type { ExpoConfig } from '@expo/config';\n\nimport type { ServerRequest, ServerResponse } from './server.types';\n\nconst DEFAULT_ALLOWED_CORS_HOSTS = [\n 'devtools', // Support local Chrome DevTools `devtools://devtools`\n];\n\n/** Check if hostname matches \"localhost\" exactly, the local IPv6,\n * a local IPV4 in the 127.0.0.0/8 range, or an IPv6-to-4 range\n * (starting with ::ffff: and ending in an IPv4) */\nexport const _isLocalHostname = (hostname: string) => {\n if (hostname === 'localhost') {\n return true;\n }\n let maybeIp = hostname;\n const ipv6To4Prefix = '::ffff:';\n if (maybeIp.startsWith(ipv6To4Prefix)) {\n maybeIp = maybeIp.slice(ipv6To4Prefix.length);\n }\n if (maybeIp === '::1') {\n return true;\n } else if (/^127(?:.\\d+){3}$/.test(maybeIp)) {\n return maybeIp.split('.').every((part) => {\n const num = parseInt(part, 10);\n return num >= 0 && num <= 255;\n });\n } else {\n return false;\n }\n};\n\nexport function createCorsMiddleware(exp: ExpoConfig) {\n const allowedHosts = [...DEFAULT_ALLOWED_CORS_HOSTS];\n // Support for expo-router API routes\n if (exp.extra?.router?.headOrigin) {\n allowedHosts.push(new URL(exp.extra.router.headOrigin).host);\n }\n if (exp.extra?.router?.origin) {\n allowedHosts.push(new URL(exp.extra.router.origin).host);\n }\n\n return (req: ServerRequest, res: ServerResponse, next: (err?: Error) => void) => {\n if (typeof req.headers.origin === 'string') {\n const { host, hostname } = new URL(req.headers.origin);\n const isSameOrigin = host === req.headers.host;\n const isLocalhost = _isLocalHostname(hostname);\n const isAllowedHost = allowedHosts.includes(host) || isLocalhost;\n if (!isSameOrigin && !isAllowedHost) {\n next(\n new Error(\n `Unauthorized request from ${req.headers.origin}. ` +\n 'This may happen because of a conflicting browser extension to intercept HTTP requests. ' +\n 'Disable browser extensions or use incognito mode and try again.'\n )\n );\n return;\n } else if (!isLocalhost && isAllowedHost) {\n // Skipped for localhost to only allow requests from this dev-sever and not escalate\n // the cross-origin resource sharing that's allowed beyond the browser's defaults\n res.setHeader('Access-Control-Allow-Origin', req.headers.origin);\n }\n\n maybePreventMetroResetCorsHeader(req, res);\n }\n\n // Block MIME-type sniffing.\n res.setHeader('X-Content-Type-Options', 'nosniff');\n\n next();\n };\n}\n\n// When accessing source maps,\n// metro will overwrite the `Access-Control-Allow-Origin` header with hardcoded `devtools://devtools` value.\n// https://github.com/facebook/metro/blob/a7f8955e6d2424b0d5f73d4bcdaf22560e1d5f27/packages/metro/src/Server.js#L540\n// This is a workaround to prevent this behavior.\nfunction maybePreventMetroResetCorsHeader(req: ServerRequest, res: ServerResponse) {\n const pathname = req.url ? new URL(req.url, `http://${req.headers.host}`).pathname : '';\n if (pathname.endsWith('.map')) {\n const setHeader = res.setHeader.bind(res);\n res.setHeader = (key, ...args) => {\n if (key !== 'Access-Control-Allow-Origin') {\n setHeader(key, ...args);\n }\n return res;\n };\n }\n}\n"],"names":["_isLocalHostname","createCorsMiddleware","DEFAULT_ALLOWED_CORS_HOSTS","hostname","maybeIp","ipv6To4Prefix","startsWith","slice","length","test","split","every","part","num","parseInt","exp","allowedHosts","extra","router","headOrigin","push","URL","host","origin","req","res","next","headers","isSameOrigin","isLocalhost","isAllowedHost","includes","Error","setHeader","maybePreventMetroResetCorsHeader","pathname","url","endsWith","bind","key","args"],"mappings":";;;;;;;;;;;IAWa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N,SAASE,IAAIG,OAAO,CAACL,IAAI;YAC9C,MAAMO,cAAc7B,iBAAiBG;YACrC,MAAM2B,gBAAgBd,aAAae,QAAQ,CAACT,SAASO;YACrD,IAAI,CAACD,gBAAgB,CAACE,eAAe;gBACnCJ,KACE,IAAIM,MACF,CAAC,0BAA0B,EAAER,IAAIG,OAAO,CAACJ,MAAM,CAAC,EAAE,CAAC,GACjD,4FACA;gBAGN;YACF,OAAO,IAAI,CAACM,eAAeC,eAAe;gBACxC,oFAAoF;gBACpF,iFAAiF;gBACjFL,IAAIQ,SAAS,CAAC,+BAA+BT,IAAIG,OAAO,CAACJ,MAAM;YACjE;YAEAW,iCAAiCV,KAAKC;QACxC;QAEA,4BAA4B;QAC5BA,IAAIQ,SAAS,CAAC,0BAA0B;QAExCP;IACF;AACF;AAEA,8BAA8B;AAC9B,4GAA4G;AAC5G,oHAAoH;AACpH,iDAAiD;AACjD,SAASQ,iCAAiCV,GAAkB,EAAEC,GAAmB;IAC/E,MAAMU,WAAWX,IAAIY,GAAG,GAAG,IAAIf,IAAIG,IAAIY,GAAG,EAAE,CAAC,OAAO,EAAEZ,IAAIG,OAAO,CAACL,IAAI,EAAE,EAAEa,QAAQ,GAAG;IACrF,IAAIA,SAASE,QAAQ,CAAC,SAAS;QAC7B,MAAMJ,YAAYR,IAAIQ,SAAS,CAACK,IAAI,CAACb;QACrCA,IAAIQ,SAAS,GAAG,CAACM,KAAK,GAAGC;YACvB,IAAID,QAAQ,+BAA+B;gBACzCN,UAAUM,QAAQC;YACpB;YACA,OAAOf;QACT;IACF;AACF"}
|
|
@@ -34,18 +34,50 @@ function _interop_require_default(obj) {
|
|
|
34
34
|
};
|
|
35
35
|
}
|
|
36
36
|
const debug = require('debug')('expo:start:server:middleware:createFile');
|
|
37
|
+
const ROUTER_INDEX_CONTENTS = `import { StyleSheet, Text, View } from "react-native";
|
|
38
|
+
|
|
39
|
+
export default function Page() {
|
|
40
|
+
return (
|
|
41
|
+
<View style={styles.container}>
|
|
42
|
+
<View style={styles.main}>
|
|
43
|
+
<Text style={styles.title}>Hello World</Text>
|
|
44
|
+
<Text style={styles.subtitle}>This is the first page of your app.</Text>
|
|
45
|
+
</View>
|
|
46
|
+
</View>
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const styles = StyleSheet.create({
|
|
51
|
+
container: {
|
|
52
|
+
flex: 1,
|
|
53
|
+
alignItems: "center",
|
|
54
|
+
padding: 24,
|
|
55
|
+
},
|
|
56
|
+
main: {
|
|
57
|
+
flex: 1,
|
|
58
|
+
justifyContent: "center",
|
|
59
|
+
maxWidth: 960,
|
|
60
|
+
marginHorizontal: "auto",
|
|
61
|
+
},
|
|
62
|
+
title: {
|
|
63
|
+
fontSize: 64,
|
|
64
|
+
fontWeight: "bold",
|
|
65
|
+
},
|
|
66
|
+
subtitle: {
|
|
67
|
+
fontSize: 36,
|
|
68
|
+
color: "#38434D",
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
`;
|
|
37
72
|
class CreateFileMiddleware extends _ExpoMiddleware.ExpoMiddleware {
|
|
38
|
-
constructor(
|
|
39
|
-
super(projectRoot, [
|
|
73
|
+
constructor(options){
|
|
74
|
+
super(options.projectRoot, [
|
|
40
75
|
'/_expo/touch'
|
|
41
|
-
]), this.
|
|
76
|
+
]), this.options = options;
|
|
42
77
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
resolveExtension(inputPath) {
|
|
47
|
-
let resolvedPath = inputPath;
|
|
48
|
-
const extension = _path().default.extname(inputPath);
|
|
78
|
+
resolveExtension(basePath, relativePath) {
|
|
79
|
+
let resolvedPath = relativePath;
|
|
80
|
+
const extension = _path().default.extname(relativePath);
|
|
49
81
|
if (extension === '.js') {
|
|
50
82
|
// Automatically convert JS files to TS files when added to a project
|
|
51
83
|
// with TypeScript.
|
|
@@ -54,7 +86,7 @@ class CreateFileMiddleware extends _ExpoMiddleware.ExpoMiddleware {
|
|
|
54
86
|
resolvedPath = resolvedPath.replace(/\.js$/, '.tsx');
|
|
55
87
|
}
|
|
56
88
|
}
|
|
57
|
-
return resolvedPath;
|
|
89
|
+
return _path().default.join(basePath, resolvedPath);
|
|
58
90
|
}
|
|
59
91
|
async parseRawBody(req) {
|
|
60
92
|
const rawBody = await new Promise((resolve, reject)=>{
|
|
@@ -69,19 +101,26 @@ class CreateFileMiddleware extends _ExpoMiddleware.ExpoMiddleware {
|
|
|
69
101
|
reject(err);
|
|
70
102
|
});
|
|
71
103
|
});
|
|
72
|
-
const
|
|
73
|
-
this.assertTouchFileBody(properties);
|
|
74
|
-
return properties;
|
|
75
|
-
}
|
|
76
|
-
assertTouchFileBody(body) {
|
|
104
|
+
const body = JSON.parse(rawBody);
|
|
77
105
|
if (typeof body !== 'object' || body == null) {
|
|
78
106
|
throw new Error('Expected object');
|
|
107
|
+
} else if (typeof body.type !== 'string') {
|
|
108
|
+
throw new Error('Expected "type" in body to be string');
|
|
79
109
|
}
|
|
80
|
-
|
|
81
|
-
|
|
110
|
+
switch(body.type){
|
|
111
|
+
case 'router_index':
|
|
112
|
+
return body;
|
|
113
|
+
default:
|
|
114
|
+
throw new Error('Unknown "type" passed in body');
|
|
82
115
|
}
|
|
83
|
-
|
|
84
|
-
|
|
116
|
+
}
|
|
117
|
+
makeOutputForInput(input) {
|
|
118
|
+
switch(input.type){
|
|
119
|
+
case 'router_index':
|
|
120
|
+
return {
|
|
121
|
+
absolutePath: this.resolveExtension(this.options.appDir, 'index.js'),
|
|
122
|
+
contents: ROUTER_INDEX_CONTENTS
|
|
123
|
+
};
|
|
85
124
|
}
|
|
86
125
|
}
|
|
87
126
|
async handleRequestAsync(req, res) {
|
|
@@ -100,18 +139,18 @@ class CreateFileMiddleware extends _ExpoMiddleware.ExpoMiddleware {
|
|
|
100
139
|
return;
|
|
101
140
|
}
|
|
102
141
|
debug(`Requested: %O`, properties);
|
|
103
|
-
const
|
|
104
|
-
if (_fs().default.existsSync(
|
|
142
|
+
const file = this.makeOutputForInput(properties);
|
|
143
|
+
if (_fs().default.existsSync(file.absolutePath)) {
|
|
105
144
|
res.statusCode = 409;
|
|
106
145
|
res.end('File already exists.');
|
|
107
146
|
return;
|
|
108
147
|
}
|
|
109
|
-
debug(`Resolved path:`,
|
|
148
|
+
debug(`Resolved path:`, file.absolutePath);
|
|
110
149
|
try {
|
|
111
|
-
await _fs().default.promises.mkdir(_path().default.dirname(
|
|
150
|
+
await _fs().default.promises.mkdir(_path().default.dirname(file.absolutePath), {
|
|
112
151
|
recursive: true
|
|
113
152
|
});
|
|
114
|
-
await _fs().default.promises.writeFile(
|
|
153
|
+
await _fs().default.promises.writeFile(file.absolutePath, file.contents, 'utf8');
|
|
115
154
|
} catch (e) {
|
|
116
155
|
debug('Error writing file', e);
|
|
117
156
|
res.statusCode = 500;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/CreateFileMiddleware.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 fs from 'fs';\nimport path from 'path';\n\nimport { ExpoMiddleware } from './ExpoMiddleware';\nimport { ServerRequest, ServerResponse } from './server.types';\n\nconst debug = require('debug')('expo:start:server:middleware:createFile') as typeof console.log;\n\
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/CreateFileMiddleware.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 fs from 'fs';\nimport path from 'path';\n\nimport { ExpoMiddleware } from './ExpoMiddleware';\nimport { ServerRequest, ServerResponse } from './server.types';\n\nconst debug = require('debug')('expo:start:server:middleware:createFile') as typeof console.log;\n\ninterface TouchFileInput {\n type: 'router_index';\n}\n\ninterface TouchFileOutput {\n absolutePath: string;\n contents: string;\n}\n\nconst ROUTER_INDEX_CONTENTS = `import { StyleSheet, Text, View } from \"react-native\";\n\nexport default function Page() {\n return (\n <View style={styles.container}>\n <View style={styles.main}>\n <Text style={styles.title}>Hello World</Text>\n <Text style={styles.subtitle}>This is the first page of your app.</Text>\n </View>\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n alignItems: \"center\",\n padding: 24,\n },\n main: {\n flex: 1,\n justifyContent: \"center\",\n maxWidth: 960,\n marginHorizontal: \"auto\",\n },\n title: {\n fontSize: 64,\n fontWeight: \"bold\",\n },\n subtitle: {\n fontSize: 36,\n color: \"#38434D\",\n },\n});\n`;\n\ninterface CreateFileMiddlewareOptions {\n /** The absolute metro or server root, used to calculate the relative dom entry path */\n metroRoot: string;\n /** The absolute project root, used to resolve the `expo/dom/entry.js` path */\n projectRoot: string;\n /** The expo-router root */\n appDir: string;\n}\n\n/**\n * Middleware for creating a file given a `POST` request with\n * `{ contents: string, path: string }` in the body.\n */\nexport class CreateFileMiddleware extends ExpoMiddleware {\n constructor(protected options: CreateFileMiddlewareOptions) {\n super(options.projectRoot, ['/_expo/touch']);\n }\n\n protected resolveExtension(basePath: string, relativePath: string): string {\n let resolvedPath = relativePath;\n const extension = path.extname(relativePath);\n if (extension === '.js') {\n // Automatically convert JS files to TS files when added to a project\n // with TypeScript.\n const tsconfigPath = path.join(this.projectRoot, 'tsconfig.json');\n if (fs.existsSync(tsconfigPath)) {\n resolvedPath = resolvedPath.replace(/\\.js$/, '.tsx');\n }\n }\n return path.join(basePath, resolvedPath);\n }\n\n protected async parseRawBody(req: ServerRequest): Promise<TouchFileInput> {\n const rawBody = await new Promise<string>((resolve, reject) => {\n let body = '';\n req.on('data', (chunk) => {\n body += chunk.toString();\n });\n req.on('end', () => {\n resolve(body);\n });\n req.on('error', (err) => {\n reject(err);\n });\n });\n\n const body = JSON.parse(rawBody);\n if (typeof body !== 'object' || body == null) {\n throw new Error('Expected object');\n } else if (typeof body.type !== 'string') {\n throw new Error('Expected \"type\" in body to be string');\n }\n\n switch (body.type) {\n case 'router_index':\n return body;\n default:\n throw new Error('Unknown \"type\" passed in body');\n }\n }\n\n private makeOutputForInput(input: TouchFileInput): TouchFileOutput {\n switch (input.type) {\n case 'router_index':\n return {\n absolutePath: this.resolveExtension(this.options.appDir, 'index.js'),\n contents: ROUTER_INDEX_CONTENTS,\n };\n }\n }\n\n async handleRequestAsync(req: ServerRequest, res: ServerResponse): Promise<void> {\n if (req.method !== 'POST') {\n res.statusCode = 405;\n res.end('Method Not Allowed');\n return;\n }\n\n let properties: TouchFileInput;\n try {\n properties = await this.parseRawBody(req);\n } catch (e) {\n debug('Error parsing request body', e);\n res.statusCode = 400;\n res.end('Bad Request');\n return;\n }\n\n debug(`Requested: %O`, properties);\n\n const file = this.makeOutputForInput(properties);\n if (fs.existsSync(file.absolutePath)) {\n res.statusCode = 409;\n res.end('File already exists.');\n return;\n }\n\n debug(`Resolved path:`, file.absolutePath);\n\n try {\n await fs.promises.mkdir(path.dirname(file.absolutePath), { recursive: true });\n await fs.promises.writeFile(file.absolutePath, file.contents, 'utf8');\n } catch (e) {\n debug('Error writing file', e);\n res.statusCode = 500;\n res.end('Error writing file.');\n return;\n }\n\n debug(`File created`);\n res.statusCode = 200;\n res.end('OK');\n }\n}\n"],"names":["CreateFileMiddleware","debug","require","ROUTER_INDEX_CONTENTS","ExpoMiddleware","constructor","options","projectRoot","resolveExtension","basePath","relativePath","resolvedPath","extension","path","extname","tsconfigPath","join","fs","existsSync","replace","parseRawBody","req","rawBody","Promise","resolve","reject","body","on","chunk","toString","err","JSON","parse","Error","type","makeOutputForInput","input","absolutePath","appDir","contents","handleRequestAsync","res","method","statusCode","end","properties","e","file","promises","mkdir","dirname","recursive","writeFile"],"mappings":"AAAA;;;;;CAKC;;;;+BAmEYA;;;eAAAA;;;;gEAlEE;;;;;;;gEACE;;;;;;gCAEc;;;;;;AAG/B,MAAMC,QAAQC,QAAQ,SAAS;AAW/B,MAAMC,wBAAwB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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CAAC,IAAI,CAACF,OAAO,CAACgC,MAAM,EAAE;oBACzDC,UAAUpC;gBACZ;QACJ;IACF;IAEA,MAAMqC,mBAAmBnB,GAAkB,EAAEoB,GAAmB,EAAiB;QAC/E,IAAIpB,IAAIqB,MAAM,KAAK,QAAQ;YACzBD,IAAIE,UAAU,GAAG;YACjBF,IAAIG,GAAG,CAAC;YACR;QACF;QAEA,IAAIC;QACJ,IAAI;YACFA,aAAa,MAAM,IAAI,CAACzB,YAAY,CAACC;QACvC,EAAE,OAAOyB,GAAG;YACV7C,MAAM,8BAA8B6C;YACpCL,IAAIE,UAAU,GAAG;YACjBF,IAAIG,GAAG,CAAC;YACR;QACF;QAEA3C,MAAM,CAAC,aAAa,CAAC,EAAE4C;QAEvB,MAAME,OAAO,IAAI,CAACZ,kBAAkB,CAACU;QACrC,IAAI5B,aAAE,CAACC,UAAU,CAAC6B,KAAKV,YAAY,GAAG;YACpCI,IAAIE,UAAU,GAAG;YACjBF,IAAIG,GAAG,CAAC;YACR;QACF;QAEA3C,MAAM,CAAC,cAAc,CAAC,EAAE8C,KAAKV,YAAY;QAEzC,IAAI;YACF,MAAMpB,aAAE,CAAC+B,QAAQ,CAACC,KAAK,CAACpC,eAAI,CAACqC,OAAO,CAACH,KAAKV,YAAY,GAAG;gBAAEc,WAAW;YAAK;YAC3E,MAAMlC,aAAE,CAAC+B,QAAQ,CAACI,SAAS,CAACL,KAAKV,YAAY,EAAEU,KAAKR,QAAQ,EAAE;QAChE,EAAE,OAAOO,GAAG;YACV7C,MAAM,sBAAsB6C;YAC5BL,IAAIE,UAAU,GAAG;YACjBF,IAAIG,GAAG,CAAC;YACR;QACF;QAEA3C,MAAM,CAAC,YAAY,CAAC;QACpBwC,IAAIE,UAAU,GAAG;QACjBF,IAAIG,GAAG,CAAC;IACV;AACF"}
|
|
@@ -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.
|
|
36
|
+
'user-agent': `expo-cli/${"0.24.23"}`,
|
|
37
37
|
authorization: 'Basic ' + _nodebuffer().Buffer.from(`${target}:`).toString('base64')
|
|
38
38
|
};
|
|
39
39
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@expo/cli",
|
|
3
|
-
"version": "0.24.
|
|
3
|
+
"version": "0.24.23",
|
|
4
4
|
"description": "The Expo CLI",
|
|
5
5
|
"main": "build/bin/cli",
|
|
6
6
|
"bin": {
|
|
@@ -48,11 +48,11 @@
|
|
|
48
48
|
"@expo/env": "~1.0.7",
|
|
49
49
|
"@expo/image-utils": "^0.7.6",
|
|
50
50
|
"@expo/json-file": "^9.1.5",
|
|
51
|
-
"@expo/metro-config": "~0.20.
|
|
51
|
+
"@expo/metro-config": "~0.20.18",
|
|
52
52
|
"@expo/osascript": "^2.2.5",
|
|
53
53
|
"@expo/package-manager": "^1.8.6",
|
|
54
54
|
"@expo/plist": "^0.3.5",
|
|
55
|
-
"@expo/prebuild-config": "^9.0.
|
|
55
|
+
"@expo/prebuild-config": "^9.0.12",
|
|
56
56
|
"@expo/schema-utils": "^0.1.0",
|
|
57
57
|
"@expo/spawn-async": "^1.7.2",
|
|
58
58
|
"@expo/ws-tunnel": "^1.0.1",
|
|
@@ -153,5 +153,5 @@
|
|
|
153
153
|
"tree-kill": "^1.2.2",
|
|
154
154
|
"tsd": "^0.28.1"
|
|
155
155
|
},
|
|
156
|
-
"gitHead": "
|
|
156
|
+
"gitHead": "2af1b39b88b98bed911587ea66adca046296e8c6"
|
|
157
157
|
}
|