@expo/cli 55.0.0-canary-20251216-3f01dbf → 55.0.0-canary-20251223-b83b31e

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.
@@ -106,9 +106,7 @@ function createAutolinkingModuleResolver(input, { getStrictResolver }) {
106
106
  // We instead resolve as if it was a dependency from within the module (self-require/import)
107
107
  const context = {
108
108
  ...immutableContext,
109
- nodeModulesPaths: [
110
- resolvedModulePath
111
- ],
109
+ nodeModulesPaths: [],
112
110
  originModulePath: resolvedModulePath
113
111
  };
114
112
  const res = getStrictResolver(context, platform)(moduleName);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/createExpoAutolinkingResolver.ts"],"sourcesContent":["import type { ResolutionContext } from '@expo/metro/metro-resolver';\nimport type { ResolutionResult as AutolinkingResolutionResult } from 'expo-modules-autolinking/exports';\n\nimport type { StrictResolverFactory } from './withMetroMultiPlatform';\nimport type { ExpoCustomMetroResolver } from './withMetroResolvers';\n\nconst debug = require('debug')(\n 'expo:start:server:metro:autolinking-resolver'\n) as typeof console.log;\n\n// This is a list of known modules we want to always include in sticky resolution\n// Specifying these skips platform- and module-specific checks and always includes them in the output\nconst KNOWN_STICKY_DEPENDENCIES = [\n // NOTE: react and react-dom aren't native modules, but must also be deduplicated in bundles\n 'react',\n 'react-dom',\n // NOTE: react-native won't be in autolinking output, since it's special\n // We include it here manually, since we know it should be an unduplicated direct dependency\n 'react-native',\n // Peer dependencies from expo\n 'react-native-webview',\n '@expo/dom-webview',\n // Dependencies from expo\n 'expo-asset',\n 'expo-constants',\n 'expo-file-system',\n 'expo-font',\n 'expo-keep-awake',\n 'expo-modules-core',\n // Peer dependencies from expo-router\n 'react-native-gesture-handler',\n 'react-native-reanimated',\n];\n\nconst AUTOLINKING_PLATFORMS = ['android', 'ios', 'web'] as const;\ntype AutolinkingPlatform = (typeof AUTOLINKING_PLATFORMS)[number];\n\nconst escapeDependencyName = (dependency: string) =>\n dependency.replace(/[*.?()[\\]]/g, (x) => `\\\\${x}`);\n\n/** Converts a list of module names to a regex that may either match bare module names or sub-modules of modules */\nexport const _dependenciesToRegex = (dependencies: string[]) =>\n new RegExp(`^(${dependencies.map(escapeDependencyName).join('|')})($|/.*)`);\n\nconst getAutolinkingExports = (): typeof import('expo/internal/unstable-autolinking-exports') =>\n require('expo/internal/unstable-autolinking-exports');\n\ninterface PlatformModuleDescription {\n platform: AutolinkingPlatform;\n moduleTestRe: RegExp;\n resolvedModulePaths: Record<string, string>;\n}\n\nconst toPlatformModuleDescription = (\n dependencies: AutolinkingResolutionResult,\n platform: AutolinkingPlatform\n): PlatformModuleDescription => {\n const resolvedModulePaths: Record<string, string> = {};\n const resolvedModuleNames: string[] = [];\n for (const dependencyName in dependencies) {\n const dependency = dependencies[dependencyName];\n if (dependency) {\n resolvedModuleNames.push(dependency.name);\n resolvedModulePaths[dependency.name] = dependency.path;\n }\n }\n debug(\n `Sticky resolution for ${platform} registered ${resolvedModuleNames.length} resolutions:`,\n resolvedModuleNames\n );\n return {\n platform,\n moduleTestRe: _dependenciesToRegex(resolvedModuleNames),\n resolvedModulePaths,\n };\n};\n\nexport type AutolinkingModuleResolverInput = {\n [platform in AutolinkingPlatform]?: PlatformModuleDescription;\n};\n\nexport async function createAutolinkingModuleResolverInput({\n platforms,\n projectRoot,\n}: {\n projectRoot: string;\n platforms: string[];\n}): Promise<AutolinkingModuleResolverInput> {\n const autolinking = getAutolinkingExports();\n const linker = autolinking.makeCachedDependenciesLinker({ projectRoot });\n\n return Object.fromEntries(\n await Promise.all(\n platforms\n .filter((platform): platform is AutolinkingPlatform => {\n return AUTOLINKING_PLATFORMS.includes(platform as any);\n })\n .map(async (platform) => {\n const dependencies = await autolinking.scanDependencyResolutionsForPlatform(\n linker,\n platform,\n KNOWN_STICKY_DEPENDENCIES\n );\n const moduleDescription = toPlatformModuleDescription(dependencies, platform);\n return [platform, moduleDescription] satisfies [\n AutolinkingPlatform,\n PlatformModuleDescription,\n ];\n })\n )\n ) as AutolinkingModuleResolverInput;\n}\n\nexport function createAutolinkingModuleResolver(\n input: AutolinkingModuleResolverInput | undefined,\n { getStrictResolver }: { getStrictResolver: StrictResolverFactory }\n): ExpoCustomMetroResolver | undefined {\n if (!input) {\n return undefined;\n }\n\n const fileSpecifierRe = /^[\\\\/]|^\\.\\.?(?:$|[\\\\/])/i;\n const isAutolinkingPlatform = (platform: string | null): platform is AutolinkingPlatform =>\n !!platform && (input as any)[platform] != null;\n\n return function requestStickyModule(immutableContext, moduleName, platform) {\n // NOTE(@kitten): We currently don't include Web. The `expo-doctor` check already warns\n // about duplicates, and we can try to add Web later on. We should expand expo-modules-autolinking\n // properly to support web first however\n if (!isAutolinkingPlatform(platform)) {\n return null;\n } else if (fileSpecifierRe.test(moduleName)) {\n return null;\n }\n\n const moduleDescription = input[platform]!;\n const moduleMatch = moduleDescription.moduleTestRe.exec(moduleName);\n if (moduleMatch) {\n const resolvedModulePath =\n moduleDescription.resolvedModulePaths[moduleMatch[1]] || moduleName;\n // We instead resolve as if it was a dependency from within the module (self-require/import)\n const context: ResolutionContext = {\n ...immutableContext,\n nodeModulesPaths: [resolvedModulePath],\n originModulePath: resolvedModulePath,\n };\n const res = getStrictResolver(context, platform)(moduleName);\n debug(`Sticky resolution for ${platform}: ${moduleName} -> from: ${resolvedModulePath}`);\n return res;\n }\n\n return null;\n };\n}\n"],"names":["_dependenciesToRegex","createAutolinkingModuleResolver","createAutolinkingModuleResolverInput","debug","require","KNOWN_STICKY_DEPENDENCIES","AUTOLINKING_PLATFORMS","escapeDependencyName","dependency","replace","x","dependencies","RegExp","map","join","getAutolinkingExports","toPlatformModuleDescription","platform","resolvedModulePaths","resolvedModuleNames","dependencyName","push","name","path","length","moduleTestRe","platforms","projectRoot","autolinking","linker","makeCachedDependenciesLinker","Object","fromEntries","Promise","all","filter","includes","scanDependencyResolutionsForPlatform","moduleDescription","input","getStrictResolver","undefined","fileSpecifierRe","isAutolinkingPlatform","requestStickyModule","immutableContext","moduleName","test","moduleMatch","exec","resolvedModulePath","context","nodeModulesPaths","originModulePath","res"],"mappings":";;;;;;;;;;;IAyCaA,oBAAoB;eAApBA;;IAwEGC,+BAA+B;eAA/BA;;IAhCMC,oCAAoC;eAApCA;;;AA3EtB,MAAMC,QAAQC,QAAQ,SACpB;AAGF,iFAAiF;AACjF,qGAAqG;AACrG,MAAMC,4BAA4B;IAChC,4FAA4F;IAC5F;IACA;IACA,wEAAwE;IACxE,4FAA4F;IAC5F;IACA,8BAA8B;IAC9B;IACA;IACA,yBAAyB;IACzB;IACA;IACA;IACA;IACA;IACA;IACA,qCAAqC;IACrC;IACA;CACD;AAED,MAAMC,wBAAwB;IAAC;IAAW;IAAO;CAAM;AAGvD,MAAMC,uBAAuB,CAACC,aAC5BA,WAAWC,OAAO,CAAC,eAAe,CAACC,IAAM,CAAC,EAAE,EAAEA,GAAG;AAG5C,MAAMV,uBAAuB,CAACW,eACnC,IAAIC,OAAO,CAAC,EAAE,EAAED,aAAaE,GAAG,CAACN,sBAAsBO,IAAI,CAAC,KAAK,QAAQ,CAAC;AAE5E,MAAMC,wBAAwB,IAC5BX,QAAQ;AAQV,MAAMY,8BAA8B,CAClCL,cACAM;IAEA,MAAMC,sBAA8C,CAAC;IACrD,MAAMC,sBAAgC,EAAE;IACxC,IAAK,MAAMC,kBAAkBT,aAAc;QACzC,MAAMH,aAAaG,YAAY,CAACS,eAAe;QAC/C,IAAIZ,YAAY;YACdW,oBAAoBE,IAAI,CAACb,WAAWc,IAAI;YACxCJ,mBAAmB,CAACV,WAAWc,IAAI,CAAC,GAAGd,WAAWe,IAAI;QACxD;IACF;IACApB,MACE,CAAC,sBAAsB,EAAEc,SAAS,YAAY,EAAEE,oBAAoBK,MAAM,CAAC,aAAa,CAAC,EACzFL;IAEF,OAAO;QACLF;QACAQ,cAAczB,qBAAqBmB;QACnCD;IACF;AACF;AAMO,eAAehB,qCAAqC,EACzDwB,SAAS,EACTC,WAAW,EAIZ;IAC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UAAU,EAAEI,oBAAoB;YACvF,OAAOI;QACT;QAEA,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/createExpoAutolinkingResolver.ts"],"sourcesContent":["import type { ResolutionContext } from '@expo/metro/metro-resolver';\nimport type { ResolutionResult as AutolinkingResolutionResult } from 'expo-modules-autolinking/exports';\n\nimport type { StrictResolverFactory } from './withMetroMultiPlatform';\nimport type { ExpoCustomMetroResolver } from './withMetroResolvers';\n\nconst debug = require('debug')(\n 'expo:start:server:metro:autolinking-resolver'\n) as typeof console.log;\n\n// This is a list of known modules we want to always include in sticky resolution\n// Specifying these skips platform- and module-specific checks and always includes them in the output\nconst KNOWN_STICKY_DEPENDENCIES = [\n // NOTE: react and react-dom aren't native modules, but must also be deduplicated in bundles\n 'react',\n 'react-dom',\n // NOTE: react-native won't be in autolinking output, since it's special\n // We include it here manually, since we know it should be an unduplicated direct dependency\n 'react-native',\n // Peer dependencies from expo\n 'react-native-webview',\n '@expo/dom-webview',\n // Dependencies from expo\n 'expo-asset',\n 'expo-constants',\n 'expo-file-system',\n 'expo-font',\n 'expo-keep-awake',\n 'expo-modules-core',\n // Peer dependencies from expo-router\n 'react-native-gesture-handler',\n 'react-native-reanimated',\n];\n\nconst AUTOLINKING_PLATFORMS = ['android', 'ios', 'web'] as const;\ntype AutolinkingPlatform = (typeof AUTOLINKING_PLATFORMS)[number];\n\nconst escapeDependencyName = (dependency: string) =>\n dependency.replace(/[*.?()[\\]]/g, (x) => `\\\\${x}`);\n\n/** Converts a list of module names to a regex that may either match bare module names or sub-modules of modules */\nexport const _dependenciesToRegex = (dependencies: string[]) =>\n new RegExp(`^(${dependencies.map(escapeDependencyName).join('|')})($|/.*)`);\n\nconst getAutolinkingExports = (): typeof import('expo/internal/unstable-autolinking-exports') =>\n require('expo/internal/unstable-autolinking-exports');\n\ninterface PlatformModuleDescription {\n platform: AutolinkingPlatform;\n moduleTestRe: RegExp;\n resolvedModulePaths: Record<string, string>;\n}\n\nconst toPlatformModuleDescription = (\n dependencies: AutolinkingResolutionResult,\n platform: AutolinkingPlatform\n): PlatformModuleDescription => {\n const resolvedModulePaths: Record<string, string> = {};\n const resolvedModuleNames: string[] = [];\n for (const dependencyName in dependencies) {\n const dependency = dependencies[dependencyName];\n if (dependency) {\n resolvedModuleNames.push(dependency.name);\n resolvedModulePaths[dependency.name] = dependency.path;\n }\n }\n debug(\n `Sticky resolution for ${platform} registered ${resolvedModuleNames.length} resolutions:`,\n resolvedModuleNames\n );\n return {\n platform,\n moduleTestRe: _dependenciesToRegex(resolvedModuleNames),\n resolvedModulePaths,\n };\n};\n\nexport type AutolinkingModuleResolverInput = {\n [platform in AutolinkingPlatform]?: PlatformModuleDescription;\n};\n\nexport async function createAutolinkingModuleResolverInput({\n platforms,\n projectRoot,\n}: {\n projectRoot: string;\n platforms: string[];\n}): Promise<AutolinkingModuleResolverInput> {\n const autolinking = getAutolinkingExports();\n const linker = autolinking.makeCachedDependenciesLinker({ projectRoot });\n\n return Object.fromEntries(\n await Promise.all(\n platforms\n .filter((platform): platform is AutolinkingPlatform => {\n return AUTOLINKING_PLATFORMS.includes(platform as any);\n })\n .map(async (platform) => {\n const dependencies = await autolinking.scanDependencyResolutionsForPlatform(\n linker,\n platform,\n KNOWN_STICKY_DEPENDENCIES\n );\n const moduleDescription = toPlatformModuleDescription(dependencies, platform);\n return [platform, moduleDescription] satisfies [\n AutolinkingPlatform,\n PlatformModuleDescription,\n ];\n })\n )\n ) as AutolinkingModuleResolverInput;\n}\n\nexport function createAutolinkingModuleResolver(\n input: AutolinkingModuleResolverInput | undefined,\n { getStrictResolver }: { getStrictResolver: StrictResolverFactory }\n): ExpoCustomMetroResolver | undefined {\n if (!input) {\n return undefined;\n }\n\n const fileSpecifierRe = /^[\\\\/]|^\\.\\.?(?:$|[\\\\/])/i;\n const isAutolinkingPlatform = (platform: string | null): platform is AutolinkingPlatform =>\n !!platform && (input as any)[platform] != null;\n\n return function requestStickyModule(immutableContext, moduleName, platform) {\n // NOTE(@kitten): We currently don't include Web. The `expo-doctor` check already warns\n // about duplicates, and we can try to add Web later on. We should expand expo-modules-autolinking\n // properly to support web first however\n if (!isAutolinkingPlatform(platform)) {\n return null;\n } else if (fileSpecifierRe.test(moduleName)) {\n return null;\n }\n\n const moduleDescription = input[platform]!;\n const moduleMatch = moduleDescription.moduleTestRe.exec(moduleName);\n if (moduleMatch) {\n const resolvedModulePath =\n moduleDescription.resolvedModulePaths[moduleMatch[1]] || moduleName;\n // We instead resolve as if it was a dependency from within the module (self-require/import)\n const context: ResolutionContext = {\n ...immutableContext,\n nodeModulesPaths: [],\n originModulePath: resolvedModulePath,\n };\n const res = getStrictResolver(context, platform)(moduleName);\n debug(`Sticky resolution for ${platform}: ${moduleName} -> from: ${resolvedModulePath}`);\n return res;\n }\n\n return null;\n };\n}\n"],"names":["_dependenciesToRegex","createAutolinkingModuleResolver","createAutolinkingModuleResolverInput","debug","require","KNOWN_STICKY_DEPENDENCIES","AUTOLINKING_PLATFORMS","escapeDependencyName","dependency","replace","x","dependencies","RegExp","map","join","getAutolinkingExports","toPlatformModuleDescription","platform","resolvedModulePaths","resolvedModuleNames","dependencyName","push","name","path","length","moduleTestRe","platforms","projectRoot","autolinking","linker","makeCachedDependenciesLinker","Object","fromEntries","Promise","all","filter","includes","scanDependencyResolutionsForPlatform","moduleDescription","input","getStrictResolver","undefined","fileSpecifierRe","isAutolinkingPlatform","requestStickyModule","immutableContext","moduleName","test","moduleMatch","exec","resolvedModulePath","context","nodeModulesPaths","originModulePath","res"],"mappings":";;;;;;;;;;;IAyCaA,oBAAoB;eAApBA;;IAwEGC,+BAA+B;eAA/BA;;IAhCMC,oCAAoC;eAApCA;;;AA3EtB,MAAMC,QAAQC,QAAQ,SACpB;AAGF,iFAAiF;AACjF,qGAAqG;AACrG,MAAMC,4BAA4B;IAChC,4FAA4F;IAC5F;IACA;IACA,wEAAwE;IACxE,4FAA4F;IAC5F;IACA,8BAA8B;IAC9B;IACA;IACA,y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A;YAAUqB;SAAkB;IAItC;AAGR;AAEO,SAASrC,gCACdsC,KAAiD,EACjD,EAAEC,iBAAiB,EAAgD;IAEnE,IAAI,CAACD,OAAO;QACV,OAAOE;IACT;IAEA,MAAMC,kBAAkB;IACxB,MAAMC,wBAAwB,CAAC1B,WAC7B,CAAC,CAACA,YAAY,AAACsB,KAAa,CAACtB,SAAS,IAAI;IAE5C,OAAO,SAAS2B,oBAAoBC,gBAAgB,EAAEC,UAAU,EAAE7B,QAAQ;QACxE,uFAAuF;QACvF,kGAAkG;QAClG,wCAAwC;QACxC,IAAI,CAAC0B,sBAAsB1B,WAAW;YACpC,OAAO;QACT,OAAO,IAAIyB,gBAAgBK,IAAI,CAACD,aAAa;YAC3C,OAAO;QACT;QAEA,MAAMR,oBAAoBC,KAAK,CAACtB,SAAS;QACzC,MAAM+B,cAAcV,kBAAkBb,YAAY,CAACwB,IAAI,CAACH;QACxD,IAAIE,aAAa;YACf,MAAME,qBACJZ,kBAAkBpB,mBAAmB,CAAC8B,WAAW,CAAC,EAAE,CAAC,IAAIF;YAC3D,4FAA4F;YAC5F,MAAMK,UAA6B;gBACjC,GAAGN,gBAAgB;gBACnBO,kBAAkB,EAAE;gBACpBC,kBAAkBH;YACpB;YACA,MAAMI,MAAMd,kBAAkBW,SAASlC,UAAU6B;YACjD3C,MAAM,CAAC,sBAAsB,EAAEc,SAAS,EAAE,EAAE6B,WAAW,UAAU,EAAEI,oBAAoB;YACvF,OAAOI;QACT;QAEA,OAAO;IACT;AACF"}
@@ -125,9 +125,7 @@ function createFallbackModuleResolver({ projectRoot, originModuleNames, getStric
125
125
  // We instead resolve as if it was depended on by the `originModulePath` (the module named in `originModuleNames`)
126
126
  const context = {
127
127
  ...immutableContext,
128
- nodeModulesPaths: [
129
- moduleDescription.originModulePath
130
- ],
128
+ nodeModulesPaths: [],
131
129
  // NOTE(@kitten): We need to add a fake filename here. Metro performs a `path.dirname` on this path
132
130
  // and then searches `${path.dirname(originModulePath)}/node_modules`. If we don't add it, we miss
133
131
  // fallback resolution for packages that failed to hoist
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/createExpoFallbackResolver.ts"],"sourcesContent":["// This file creates the fallback resolver\n// The fallback resolver applies only to module imports and should be the last resolver\n// in the chain. It applies to failed Node module resolution of modules and will attempt\n// to resolve them to `expo` and `expo-router` dependencies that couldn't be resolved.\n// This resolves isolated dependency issues, where we expect dependencies of `expo`\n// and `expo-router` to be resolvable, due to hoisting, but they aren't hoisted in\n// a user's project.\n// See: https://github.com/expo/expo/pull/34286\n\nimport type { ResolutionContext, PackageJson } from '@expo/metro/metro-resolver/types';\nimport path from 'path';\n\nimport type { StrictResolver, StrictResolverFactory } from './withMetroMultiPlatform';\nimport type { ExpoCustomMetroResolver } from './withMetroResolvers';\n\n/** A record of dependencies that we know are only used for scripts and config-plugins\n * @privateRemarks\n * This includes dependencies we never resolve indirectly. Generally, we only want\n * to add fallback resolutions for dependencies of `expo` and `expo-router` that\n * are either transpiled into output code or resolved from other Expo packages\n * without them having direct dependencies on these dependencies.\n * Meaning: If you update this list, exclude what a user might use when they\n * forget to specify their own dependencies, rather than what we use ourselves\n * only in `expo` and `expo-router`.\n */\nconst EXCLUDE_ORIGIN_MODULES: Record<string, true | undefined> = {\n '@expo/config': true,\n '@expo/config-plugins': true,\n 'schema-utils': true, // Used by `expo-router/plugin`\n semver: true, // Used by `expo-router/doctor`\n};\n\ninterface PackageMetaPeerDependenciesMetaEntry {\n [propName: string]: unknown;\n optional?: boolean;\n}\n\ninterface PackageMeta extends PackageJson {\n readonly [propName: string]: unknown;\n readonly dependencies?: Record<string, unknown>;\n readonly peerDependencies?: Record<string, unknown>;\n readonly peerDependenciesMeta?: Record<\n string,\n PackageMetaPeerDependenciesMetaEntry | undefined | null\n >;\n}\n\ninterface ModuleDescription {\n originModulePath: string;\n moduleTestRe: RegExp;\n}\n\nconst debug = require('debug')('expo:start:server:metro:fallback-resolver') as typeof console.log;\n\n/** Converts a list of module names to a regex that may either match bare module names or sub-modules of modules */\nconst dependenciesToRegex = (dependencies: string[]) =>\n new RegExp(`^(?:${dependencies.join('|')})(?:$|/)`);\n\n/** Resolves an origin module and outputs a filter regex and target path for it */\nconst getModuleDescriptionWithResolver = (\n context: ResolutionContext,\n resolve: StrictResolver,\n originModuleName: string\n): ModuleDescription | null => {\n let filePath: string | undefined;\n let packageMeta: PackageMeta | undefined | null;\n try {\n const resolution = resolve(path.join(originModuleName, 'package.json'));\n if (resolution.type !== 'sourceFile') {\n debug(`Fallback module resolution failed for origin module: ${originModuleName})`);\n return null;\n }\n filePath = resolution.filePath;\n // Upcast PackageJson to PackageMeta\n packageMeta = context.getPackage(filePath) as PackageMeta | null | undefined;\n if (!packageMeta) {\n return null;\n }\n } catch (error: any) {\n debug(\n `Fallback module resolution threw: ${error.constructor.name}. (module: ${filePath || originModuleName})`\n );\n return null;\n }\n let dependencies: string[] = [];\n if (packageMeta.dependencies) dependencies.push(...Object.keys(packageMeta.dependencies));\n if (packageMeta.peerDependencies) {\n const peerDependenciesMeta = packageMeta.peerDependenciesMeta;\n let peerDependencies = Object.keys(packageMeta.peerDependencies);\n // We explicitly include non-optional peer dependencies. Non-optional peer dependencies of\n // `expo` and `expo-router` are either expected to be accessible on a project-level, since\n // both are meant to be installed is direct dependencies, or shouldn't be accessible when\n // they're fulfilled as isolated dependencies.\n // The exception are only *optional* peer dependencies, since when they're installed\n // automatically by newer package manager behaviour, they may become isolated dependencies\n // that we still wish to access.\n if (peerDependenciesMeta) {\n peerDependencies = peerDependencies.filter((dependency) => {\n const peerMeta = peerDependenciesMeta[dependency];\n return peerMeta && typeof peerMeta === 'object' && peerMeta.optional === true;\n });\n }\n dependencies.push(...peerDependencies);\n }\n // We deduplicate the dependencies and exclude modules that we know are only used for scripts or config-plugins\n dependencies = dependencies.filter((moduleName, index, dependenciesArr) => {\n if (EXCLUDE_ORIGIN_MODULES[moduleName]) return false;\n return dependenciesArr.indexOf(moduleName) === index;\n });\n // Return test regex for dependencies and full origin module path to resolve through\n const originModulePath = path.dirname(filePath);\n return dependencies.length\n ? { originModulePath, moduleTestRe: dependenciesToRegex(dependencies) }\n : null;\n};\n\n/** Creates a fallback module resolver that resolves dependencis of modules named in `originModuleNames` via their path.\n * @remarks\n * The fallback resolver targets modules dependended on by modules named in `originModuleNames` and resolves\n * them from the module root of these origin modules instead.\n * It should only be used as a fallback after normal Node resolution (and other resolvers) have failed for:\n * - the `expo` package\n * - the `expo-router` package\n * Dependencies mentioned as either optional peer dependencies or direct dependencies by these modules may be isolated\n * and inaccessible via standard Node module resolution. This may happen when either transpilation adds these\n * dependencies to other parts of the tree (e.g. `@babel/runtime`) or when a dependency fails to hoist due to either\n * a corrupted dependency tree or when a peer dependency is fulfilled incorrectly (e.g. `expo-asset`)\n * @privateRemarks\n * This does NOT follow Node resolution and is *only* intended to provide a fallback for modules that we depend on\n * ourselves and know we can resolve (via expo or expo-router)!\n */\nexport function createFallbackModuleResolver({\n projectRoot,\n originModuleNames,\n getStrictResolver,\n}: {\n projectRoot: string;\n originModuleNames: string[];\n getStrictResolver: StrictResolverFactory;\n}): ExpoCustomMetroResolver {\n const _moduleDescriptionsCache: Record<string, ModuleDescription | null> = {};\n\n const getModuleDescription = (\n immutableContext: ResolutionContext,\n originModuleName: string,\n platform: string | null\n ) => {\n if (_moduleDescriptionsCache[originModuleName] !== undefined) {\n return _moduleDescriptionsCache[originModuleName];\n }\n // Resolve the origin module itself via the project root rather than the file that requested the missing module\n // The addition of `package.json` doesn't matter here. We just need a file path that'll be turned into a directory path\n // We don't need to modify `nodeModulesPaths` since it's guaranteed to contain the project's node modules paths\n const context: ResolutionContext = {\n ...immutableContext,\n originModulePath: path.join(projectRoot, 'package.json'),\n };\n return (_moduleDescriptionsCache[originModuleName] = getModuleDescriptionWithResolver(\n context,\n getStrictResolver(context, platform),\n originModuleName\n ));\n };\n\n const fileSpecifierRe = /^[\\\\/]|^\\.\\.?(?:$|[\\\\/])/i;\n\n return function requestFallbackModule(immutableContext, moduleName, platform) {\n // Early return if `moduleName` cannot be a module specifier\n // This doesn't have to be accurate as this resolver is a fallback for failed resolutions and\n // we're only doing this to avoid unnecessary resolution work\n if (fileSpecifierRe.test(moduleName)) {\n return null;\n }\n\n for (const originModuleName of originModuleNames) {\n const moduleDescription = getModuleDescription(immutableContext, originModuleName, platform);\n if (moduleDescription && moduleDescription.moduleTestRe.test(moduleName)) {\n // We instead resolve as if it was depended on by the `originModulePath` (the module named in `originModuleNames`)\n const context: ResolutionContext = {\n ...immutableContext,\n nodeModulesPaths: [moduleDescription.originModulePath],\n // NOTE(@kitten): We need to add a fake filename here. Metro performs a `path.dirname` on this path\n // and then searches `${path.dirname(originModulePath)}/node_modules`. If we don't add it, we miss\n // fallback resolution for packages that failed to hoist\n originModulePath: path.join(moduleDescription.originModulePath, 'index.js'),\n };\n const res = getStrictResolver(context, platform)(moduleName);\n debug(\n `Fallback resolution for ${platform}: ${moduleName} -> from origin: ${originModuleName}`\n );\n return res;\n }\n }\n\n return null;\n };\n}\n"],"names":["createFallbackModuleResolver","EXCLUDE_ORIGIN_MODULES","semver","debug","require","dependenciesToRegex","dependencies","RegExp","join","getModuleDescriptionWithResolver","context","resolve","originModuleName","filePath","packageMeta","resolution","path","type","getPackage","error","constructor","name","push","Object","keys","peerDependencies","peerDependenciesMeta","filter","dependency","peerMeta","optional","moduleName","index","dependenciesArr","indexOf","originModulePath","dirname","length","moduleTestRe","projectRoot","originModuleNames","getStrictResolver","_moduleDescriptionsCache","getModuleDescription","immutableContext","platform","undefined","fileSpecifierRe","requestFallbackModule","test","moduleDescription","nodeModulesPaths","res"],"mappings":"AAAA,0CAA0C;AAC1C,uFAAuF;AACvF,wFAAwF;AACxF,sFAAsF;AACtF,mFAAmF;AACnF,kFAAkF;AAClF,oBAAoB;AACpB,+CAA+C;;;;;+BA4H/BA;;;eAAAA;;;;gEAzHC;;;;;;;;;;;AAKjB;;;;;;;;;CASC,GACD,MAAMC,yBAA2D;IAC/D,gBAA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AClB,aAAa;gBACxE,kHAAkH;gBAClH,MAAMrB,UAA6B;oBACjC,GAAGkC,gBAAgB;oBACnBO,kBAAkB;wBAACD,kBAAkBf,gBAAgB;qBAAC;oBACtD,mGAAmG;oBACnG,kGAAkG;oBAClG,wDAAwD;oBACxDA,kBAAkBnB,eAAI,CAACR,IAAI,CAAC0C,kBAAkBf,gBAAgB,EAAE;gBAClE;gBACA,MAAMiB,MAAMX,kBAAkB/B,SAASmC,UAAUd;gBACjD5B,MACE,CAAC,wBAAwB,EAAE0C,SAAS,EAAE,EAAEd,WAAW,iBAAiB,EAAEnB,kBAAkB;gBAE1F,OAAOwC;YACT;QACF;QAEA,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/createExpoFallbackResolver.ts"],"sourcesContent":["// This file creates the fallback resolver\n// The fallback resolver applies only to module imports and should be the last resolver\n// in the chain. It applies to failed Node module resolution of modules and will attempt\n// to resolve them to `expo` and `expo-router` dependencies that couldn't be resolved.\n// This resolves isolated dependency issues, where we expect dependencies of `expo`\n// and `expo-router` to be resolvable, due to hoisting, but they aren't hoisted in\n// a user's project.\n// See: https://github.com/expo/expo/pull/34286\n\nimport type { ResolutionContext, PackageJson } from '@expo/metro/metro-resolver/types';\nimport path from 'path';\n\nimport type { StrictResolver, StrictResolverFactory } from './withMetroMultiPlatform';\nimport type { ExpoCustomMetroResolver } from './withMetroResolvers';\n\n/** A record of dependencies that we know are only used for scripts and config-plugins\n * @privateRemarks\n * This includes dependencies we never resolve indirectly. Generally, we only want\n * to add fallback resolutions for dependencies of `expo` and `expo-router` that\n * are either transpiled into output code or resolved from other Expo packages\n * without them having direct dependencies on these dependencies.\n * Meaning: If you update this list, exclude what a user might use when they\n * forget to specify their own dependencies, rather than what we use ourselves\n * only in `expo` and `expo-router`.\n */\nconst EXCLUDE_ORIGIN_MODULES: Record<string, true | undefined> = {\n '@expo/config': true,\n '@expo/config-plugins': true,\n 'schema-utils': true, // Used by `expo-router/plugin`\n semver: true, // Used by `expo-router/doctor`\n};\n\ninterface PackageMetaPeerDependenciesMetaEntry {\n [propName: string]: unknown;\n optional?: boolean;\n}\n\ninterface PackageMeta extends PackageJson {\n readonly [propName: string]: unknown;\n readonly dependencies?: Record<string, unknown>;\n readonly peerDependencies?: Record<string, unknown>;\n readonly peerDependenciesMeta?: Record<\n string,\n PackageMetaPeerDependenciesMetaEntry | undefined | null\n >;\n}\n\ninterface ModuleDescription {\n originModulePath: string;\n moduleTestRe: RegExp;\n}\n\nconst debug = require('debug')('expo:start:server:metro:fallback-resolver') as typeof console.log;\n\n/** Converts a list of module names to a regex that may either match bare module names or sub-modules of modules */\nconst dependenciesToRegex = (dependencies: string[]) =>\n new RegExp(`^(?:${dependencies.join('|')})(?:$|/)`);\n\n/** Resolves an origin module and outputs a filter regex and target path for it */\nconst getModuleDescriptionWithResolver = (\n context: ResolutionContext,\n resolve: StrictResolver,\n originModuleName: string\n): ModuleDescription | null => {\n let filePath: string | undefined;\n let packageMeta: PackageMeta | undefined | null;\n try {\n const resolution = resolve(path.join(originModuleName, 'package.json'));\n if (resolution.type !== 'sourceFile') {\n debug(`Fallback module resolution failed for origin module: ${originModuleName})`);\n return null;\n }\n filePath = resolution.filePath;\n // Upcast PackageJson to PackageMeta\n packageMeta = context.getPackage(filePath) as PackageMeta | null | undefined;\n if (!packageMeta) {\n return null;\n }\n } catch (error: any) {\n debug(\n `Fallback module resolution threw: ${error.constructor.name}. (module: ${filePath || originModuleName})`\n );\n return null;\n }\n let dependencies: string[] = [];\n if (packageMeta.dependencies) dependencies.push(...Object.keys(packageMeta.dependencies));\n if (packageMeta.peerDependencies) {\n const peerDependenciesMeta = packageMeta.peerDependenciesMeta;\n let peerDependencies = Object.keys(packageMeta.peerDependencies);\n // We explicitly include non-optional peer dependencies. Non-optional peer dependencies of\n // `expo` and `expo-router` are either expected to be accessible on a project-level, since\n // both are meant to be installed is direct dependencies, or shouldn't be accessible when\n // they're fulfilled as isolated dependencies.\n // The exception are only *optional* peer dependencies, since when they're installed\n // automatically by newer package manager behaviour, they may become isolated dependencies\n // that we still wish to access.\n if (peerDependenciesMeta) {\n peerDependencies = peerDependencies.filter((dependency) => {\n const peerMeta = peerDependenciesMeta[dependency];\n return peerMeta && typeof peerMeta === 'object' && peerMeta.optional === true;\n });\n }\n dependencies.push(...peerDependencies);\n }\n // We deduplicate the dependencies and exclude modules that we know are only used for scripts or config-plugins\n dependencies = dependencies.filter((moduleName, index, dependenciesArr) => {\n if (EXCLUDE_ORIGIN_MODULES[moduleName]) return false;\n return dependenciesArr.indexOf(moduleName) === index;\n });\n // Return test regex for dependencies and full origin module path to resolve through\n const originModulePath = path.dirname(filePath);\n return dependencies.length\n ? { originModulePath, moduleTestRe: dependenciesToRegex(dependencies) }\n : null;\n};\n\n/** Creates a fallback module resolver that resolves dependencis of modules named in `originModuleNames` via their path.\n * @remarks\n * The fallback resolver targets modules dependended on by modules named in `originModuleNames` and resolves\n * them from the module root of these origin modules instead.\n * It should only be used as a fallback after normal Node resolution (and other resolvers) have failed for:\n * - the `expo` package\n * - the `expo-router` package\n * Dependencies mentioned as either optional peer dependencies or direct dependencies by these modules may be isolated\n * and inaccessible via standard Node module resolution. This may happen when either transpilation adds these\n * dependencies to other parts of the tree (e.g. `@babel/runtime`) or when a dependency fails to hoist due to either\n * a corrupted dependency tree or when a peer dependency is fulfilled incorrectly (e.g. `expo-asset`)\n * @privateRemarks\n * This does NOT follow Node resolution and is *only* intended to provide a fallback for modules that we depend on\n * ourselves and know we can resolve (via expo or expo-router)!\n */\nexport function createFallbackModuleResolver({\n projectRoot,\n originModuleNames,\n getStrictResolver,\n}: {\n projectRoot: string;\n originModuleNames: string[];\n getStrictResolver: StrictResolverFactory;\n}): ExpoCustomMetroResolver {\n const _moduleDescriptionsCache: Record<string, ModuleDescription | null> = {};\n\n const getModuleDescription = (\n immutableContext: ResolutionContext,\n originModuleName: string,\n platform: string | null\n ) => {\n if (_moduleDescriptionsCache[originModuleName] !== undefined) {\n return _moduleDescriptionsCache[originModuleName];\n }\n // Resolve the origin module itself via the project root rather than the file that requested the missing module\n // The addition of `package.json` doesn't matter here. We just need a file path that'll be turned into a directory path\n // We don't need to modify `nodeModulesPaths` since it's guaranteed to contain the project's node modules paths\n const context: ResolutionContext = {\n ...immutableContext,\n originModulePath: path.join(projectRoot, 'package.json'),\n };\n return (_moduleDescriptionsCache[originModuleName] = getModuleDescriptionWithResolver(\n context,\n getStrictResolver(context, platform),\n originModuleName\n ));\n };\n\n const fileSpecifierRe = /^[\\\\/]|^\\.\\.?(?:$|[\\\\/])/i;\n\n return function requestFallbackModule(immutableContext, moduleName, platform) {\n // Early return if `moduleName` cannot be a module specifier\n // This doesn't have to be accurate as this resolver is a fallback for failed resolutions and\n // we're only doing this to avoid unnecessary resolution work\n if (fileSpecifierRe.test(moduleName)) {\n return null;\n }\n\n for (const originModuleName of originModuleNames) {\n const moduleDescription = getModuleDescription(immutableContext, originModuleName, platform);\n if (moduleDescription && moduleDescription.moduleTestRe.test(moduleName)) {\n // We instead resolve as if it was depended on by the `originModulePath` (the module named in `originModuleNames`)\n const context: ResolutionContext = {\n ...immutableContext,\n nodeModulesPaths: [],\n // NOTE(@kitten): We need to add a fake filename here. Metro performs a `path.dirname` on this path\n // and then searches `${path.dirname(originModulePath)}/node_modules`. If we don't add it, we miss\n // fallback resolution for packages that failed to hoist\n originModulePath: path.join(moduleDescription.originModulePath, 'index.js'),\n };\n const res = getStrictResolver(context, platform)(moduleName);\n debug(\n `Fallback resolution for ${platform}: ${moduleName} -> from origin: ${originModuleName}`\n );\n return res;\n }\n }\n\n return null;\n };\n}\n"],"names":["createFallbackModuleResolver","EXCLUDE_ORIGIN_MODULES","semver","debug","require","dependenciesToRegex","dependencies","RegExp","join","getModuleDescriptionWithResolver","context","resolve","originModuleName","filePath","packageMeta","resolution","path","type","getPackage","error","constructor","name","push","Object","keys","peerDependencies","peerDependenciesMeta","filter","dependency","peerMeta","optional","moduleName","index","dependenciesArr","indexOf","originModulePath","dirname","length","moduleTestRe","projectRoot","originModuleNames","getStrictResolver","_moduleDescriptionsCache","getModuleDescription","immutableContext","platform","undefined","fileSpecifierRe","requestFallbackModule","test","moduleDescription","nodeModulesPaths","res"],"mappings":"AAAA,0CAA0C;AAC1C,uFAAuF;AACvF,wFAAwF;AACxF,sFAAsF;AACtF,mFAAmF;AACnF,kFAAkF;AAClF,oBAAoB;AACpB,+CAA+C;;;;;+BA4H/BA;;;eAAAA;;;;gEAzHC;;;;;;;;;;;AAKjB;;;;;;;;;CASC,GACD,MAAMC,yBAA2D;IAC/D,gBAAgB;IAChB,wBAAwB;IACxB,gBAAgB;IAChBC,QAAQ;AACV;AAsBA,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,iHAAiH,GACjH,MAAMC,sBAAsB,CAACC,eAC3B,IAAIC,OAAO,CAAC,IAAI,EAAED,aAAaE,IAAI,CAAC,KAAK,QAAQ,CAAC;AAEpD,gFAAgF,GAChF,MAAMC,mCAAmC,CACvCC,SACAC,SACAC;IAEA,IAAIC;IACJ,IAAIC;IACJ,IAAI;QACF,MAAMC,aAAaJ,QAAQK,eAAI,CAACR,IAAI,CAACI,kBAAkB;QACvD,IAAIG,WAAWE,IAAI,KAAK,cAAc;YACpCd,MAAM,CAAC,qDAAqD,EAAES,iBAAiB,CAAC,CAAC;YACjF,OAAO;QACT;QACAC,WAAWE,WAAWF,QAAQ;QAC9B,oCAAoC;QACpCC,cAAcJ,QAAQQ,UAAU,CAACL;QACjC,IAAI,CAACC,aAAa;YAChB,OAAO;QACT;IACF,EAAE,OAAOK,OAAY;QACnBhB,MACE,CAAC,kCAAkC,EAAEgB,MAAMC,WAAW,CAACC,IAAI,CAAC,WAAW,EAAER,YAAYD,iBAAiB,CAAC,CAAC;QAE1G,OAAO;IACT;IACA,IAAIN,eAAyB,EAAE;IAC/B,IAAIQ,YAAYR,YAAY,EAAEA,aAAagB,IAAI,IAAIC,OAAOC,IAAI,CAACV,YAAYR,YAAY;IACvF,IAAIQ,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C,WAC3BjC;IAEJ;IAEA,MAAMmC,kBAAkB;IAExB,OAAO,SAASC,sBAAsBJ,gBAAgB,EAAEb,UAAU,EAAEc,QAAQ;QAC1E,4DAA4D;QAC5D,6FAA6F;QAC7F,6DAA6D;QAC7D,IAAIE,gBAAgBE,IAAI,CAAClB,aAAa;YACpC,OAAO;QACT;QAEA,KAAK,MAAMnB,oBAAoB4B,kBAAmB;YAChD,MAAMU,oBAAoBP,qBAAqBC,kBAAkBhC,kBAAkBiC;YACnF,IAAIK,qBAAqBA,kBAAkBZ,YAAY,CAACW,IAAI,CAAClB,aAAa;gBACxE,kHAAkH;gBAClH,MAAMrB,UAA6B;oBACjC,GAAGkC,gBAAgB;oBACnBO,kBAAkB,EAAE;oBACpB,mGAAmG;oBACnG,kGAAkG;oBAClG,wDAAwD;oBACxDhB,kBAAkBnB,eAAI,CAACR,IAAI,CAAC0C,kBAAkBf,gBAAgB,EAAE;gBAClE;gBACA,MAAMiB,MAAMX,kBAAkB/B,SAASmC,UAAUd;gBACjD5B,MACE,CAAC,wBAAwB,EAAE0C,SAAS,EAAE,EAAEd,WAAW,iBAAiB,EAAEnB,kBAAkB;gBAE1F,OAAOwC;YACT;QACF;QAEA,OAAO;IACT;AACF"}
@@ -343,11 +343,10 @@ function createServerComponentsMiddleware(projectRoot, { rscPath, instanceMetroO
343
343
  let ensurePromise = null;
344
344
  async function ensureSSRReady() {
345
345
  // TODO: Extract CSS Modules / Assets from the bundler process
346
- const runtime = await ssrLoadModule('metro-runtime/src/modules/empty-module.js', {
346
+ await ssrLoadModule(null, {
347
347
  environment: 'react-server',
348
348
  platform: 'web'
349
349
  });
350
- return runtime;
351
350
  }
352
351
  const ensureMemo = ()=>{
353
352
  ensurePromise ??= ensureSSRReady();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/createServerComponentsMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport type { EntriesDev } from '@expo/router-server/build/rsc/server';\nimport assert from 'assert';\nimport { getRscMiddleware } from 'expo-server/private';\nimport path from 'node:path';\nimport url from 'node:url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport type { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n type ExpoMetroOptions,\n getMetroOptionsFromUrl,\n} from '../middleware/metroOptions';\n\nconst debug = require('debug')('expo:rsc') as typeof console.log;\n\ntype SSRLoadModuleArtifactsFunc = (\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>\n) => Promise<{ artifacts: SerialAsset[]; src: string }>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\nconst getMetroServerRootMemo = memoize(getMetroServerRoot);\n\nexport function createServerComponentsMiddleware(\n projectRoot: string,\n {\n rscPath,\n instanceMetroOptions,\n ssrLoadModule,\n ssrLoadModuleArtifacts,\n useClientRouter,\n createModuleId,\n routerOptions,\n }: {\n rscPath: string;\n instanceMetroOptions: Partial<ExpoMetroOptions>;\n ssrLoadModule: SSRLoadModuleFunc;\n ssrLoadModuleArtifacts: SSRLoadModuleArtifactsFunc;\n useClientRouter: boolean;\n createModuleId: (\n filePath: string,\n context: { platform: string; environment: string }\n ) => string | number;\n routerOptions: Record<string, any>;\n }\n) {\n const routerModule = useClientRouter\n ? '@expo/router-server/build/rsc/router/noopRouter'\n : '@expo/router-server/build/rsc/router/expo-definedRouter';\n\n const rscMiddleware = getRscMiddleware({\n config: {},\n // Disabled in development\n baseUrl: '',\n rscPath,\n onError: console.error,\n renderRsc: async (args) => {\n // In development we should add simulated versions of common production headers.\n if (args.headers['x-real-ip'] == null) {\n args.headers['x-real-ip'] = getIpAddress();\n }\n if (args.headers['x-forwarded-for'] == null) {\n args.headers['x-forwarded-for'] = args.headers['x-real-ip'];\n }\n if (args.headers['x-forwarded-proto'] == null) {\n args.headers['x-forwarded-proto'] = 'http';\n }\n\n // Dev server-only implementation.\n try {\n return await renderRscToReadableStream({\n ...args,\n headers: new Headers(args.headers),\n body: args.body!,\n routerOptions,\n });\n } catch (error: any) {\n // If you get a codeFrame error during SSR like when using a Class component in React Server Components, then this\n // will throw with:\n // {\n // rawObject: {\n // type: 'TransformError',\n // lineNumber: 0,\n // errors: [ [Object] ],\n // name: 'SyntaxError',\n // message: '...',\n // }\n // }\n\n // TODO: Revisit all error handling now that we do direct metro bundling...\n await logMetroError(projectRoot, { error });\n\n if (error[IS_METRO_BUNDLE_ERROR_SYMBOL]) {\n throw new Response(JSON.stringify(error), {\n status: isPossiblyUnableToResolveError(error) ? 404 : 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n const sanitizedServerMessage = stripAnsi(error.message) ?? error.message;\n throw new Response(sanitizedServerMessage, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n }\n },\n });\n\n let rscPathPrefix = rscPath;\n if (rscPathPrefix !== '/') {\n rscPathPrefix += '/';\n }\n\n async function exportServerActionsAsync(\n {\n platform,\n entryPoints,\n domRoot,\n }: { platform: string; entryPoints: string[]; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n clientBoundaries: string[];\n manifest: Record<string, [string, string]>;\n }> {\n const uniqueEntryPoints = [...new Set(entryPoints)];\n // TODO: Support multiple entry points in a single split server bundle...\n const manifest: Record<string, [string, string]> = {};\n const nestedClientBoundaries: string[] = [];\n const nestedServerBoundaries: string[] = [];\n const processedEntryPoints = new Set<string>();\n async function processEntryPoint(entryPoint: string) {\n processedEntryPoints.add(entryPoint);\n\n const contents = await ssrLoadModuleArtifacts(entryPoint, {\n environment: 'react-server',\n platform,\n // Ignore the metro runtime to avoid overwriting the original in the API route.\n modulesOnly: true,\n // Required\n runModule: true,\n // Required to ensure assets load as client boundaries.\n domRoot,\n });\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactClientReferences) {\n nestedClientBoundaries.push(...reactClientReferences!);\n }\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactServerReferences) {\n nestedServerBoundaries.push(...reactServerReferences!);\n }\n\n // Naive check to ensure the module runtime is not included in the server action bundle.\n if (contents.src.includes('The experimental Metro feature')) {\n throw new Error(\n 'Internal error: module runtime should not be included in server action bundles: ' +\n entryPoint\n );\n }\n\n const relativeName = createModuleId(entryPoint, {\n platform,\n environment: 'react-server',\n });\n const safeName = path.basename(contents.artifacts.find((a) => a.type === 'js')!.filename!);\n\n const outputName = `_expo/rsc/${platform}/${safeName}`;\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(outputName, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n // Match babel plugin.\n const publicModuleId = './' + toPosixPath(path.relative(projectRoot, entryPoint));\n\n // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[publicModuleId] = [String(relativeName), outputName];\n }\n\n async function processEntryPoints(entryPoints: string[], recursions = 0) {\n // Arbitrary recursion limit to prevent infinite loops.\n if (recursions > 10) {\n throw new Error('Recursion limit exceeded while processing server boundaries');\n }\n\n for (const entryPoint of entryPoints) {\n await processEntryPoint(entryPoint);\n }\n\n // When a server action has other server actions inside of it, we need to process those as well to ensure all entry points are in the manifest and accounted for.\n let uniqueNestedServerBoundaries = [...new Set(nestedServerBoundaries)];\n // Filter out values that have already been processed.\n uniqueNestedServerBoundaries = uniqueNestedServerBoundaries.filter(\n (value) => !processedEntryPoints.has(value)\n );\n if (uniqueNestedServerBoundaries.length) {\n debug('bundling nested server action boundaries', uniqueNestedServerBoundaries);\n return processEntryPoints(uniqueNestedServerBoundaries, recursions + 1);\n }\n }\n\n await processEntryPoints(uniqueEntryPoints);\n\n // Save the SSR manifest so we can perform more replacements in the server renderer and with server actions.\n files.set(`_expo/rsc/${platform}/action-manifest.js`, {\n targetDomain: 'server',\n contents: 'module.exports = ' + JSON.stringify(manifest),\n });\n\n return { manifest, clientBoundaries: nestedClientBoundaries };\n }\n\n async function getExpoRouterClientReferencesAsync(\n { platform, domRoot }: { platform: string; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n reactClientReferences: string[];\n reactServerReferences: string[];\n cssModules: SerialAsset[];\n }> {\n const contents = await ssrLoadModuleArtifacts(routerModule, {\n environment: 'react-server',\n platform,\n modulesOnly: true,\n domRoot,\n });\n\n // Extract the global CSS modules that are imported from the router.\n // These will be injected in the head of the HTML document for the website.\n const cssModules = contents.artifacts.filter((a) => a.type.startsWith('css'));\n\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactServerReferences) {\n throw new Error(\n 'Static server action references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactServerReferences);\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactClientReferences) {\n throw new Error(\n 'Static client references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactClientReferences);\n\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(`_expo/rsc/${platform}/router.js`, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n return { reactClientReferences, reactServerReferences, cssModules };\n }\n\n const routerCache = new Map<string, EntriesDev>();\n\n async function getExpoRouterRscEntriesGetterAsync({\n platform,\n routerOptions,\n }: {\n platform: string;\n routerOptions: Record<string, any>;\n }) {\n await ensureMemo();\n // We can only cache this if we're using the client router since it doesn't change or use HMR\n if (routerCache.has(platform) && useClientRouter) {\n return routerCache.get(platform)!;\n }\n\n const router = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/router/expo-definedRouter')\n >(\n routerModule,\n {\n environment: 'react-server',\n modulesOnly: true,\n platform,\n },\n {\n hot: !useClientRouter,\n }\n );\n\n const entries = router.default({\n redirects: routerOptions?.redirects,\n rewrites: routerOptions?.rewrites,\n });\n\n routerCache.set(platform, entries);\n return entries;\n }\n\n function getResolveClientEntry(context: {\n platform: string;\n engine?: 'hermes' | null;\n ssrManifest?: Map<string, string | null>;\n }): (\n file: string,\n isServer: boolean\n ) => {\n id: string;\n chunks: string[];\n } {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n const {\n mode,\n minify = false,\n isExporting,\n baseUrl,\n routerRoot,\n asyncRoutes,\n preserveEnvVars,\n reactCompiler,\n lazy,\n } = instanceMetroOptions;\n\n assert(\n isExporting != null &&\n baseUrl != null &&\n mode != null &&\n routerRoot != null &&\n asyncRoutes != null,\n `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`\n );\n\n return (file: string, isServer: boolean) => {\n const filePath = path.join(\n projectRoot,\n file.startsWith('file://') ? fileURLToFilePath(file) : file\n );\n\n if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n\n const relativeFilePath = toPosixPath(path.relative(serverRoot, filePath));\n\n assert(\n context.ssrManifest.has(relativeFilePath),\n `SSR manifest is missing client boundary \"${relativeFilePath}\"`\n );\n\n const chunk = context.ssrManifest.get(relativeFilePath);\n\n return {\n id: String(\n createModuleId(filePath, { platform: context.platform, environment: 'client' })\n ),\n chunks: chunk != null ? [chunk] : [],\n };\n }\n\n const environment = isServer ? 'react-server' : 'client';\n const searchParams = createBundleUrlSearchParams({\n mainModuleName: '',\n platform: context.platform,\n mode,\n minify,\n lazy,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n reactCompiler: !!reactCompiler,\n engine: context.engine ?? undefined,\n bytecode: false,\n clientBoundaries: [],\n inlineSourceMap: false,\n environment,\n modulesOnly: true,\n runModule: false,\n });\n\n searchParams.set('resolver.clientboundary', String(true));\n\n const clientReferenceUrl = new URL('http://a');\n\n // TICKLE: Handshake 1\n searchParams.set('xRSC', '1');\n\n clientReferenceUrl.search = searchParams.toString();\n\n const relativeFilePath = path.relative(serverRoot, filePath);\n\n clientReferenceUrl.pathname = relativeFilePath;\n\n // Ensure url.pathname ends with '.bundle'\n if (!clientReferenceUrl.pathname.endsWith('.bundle')) {\n clientReferenceUrl.pathname += '.bundle';\n }\n\n // Return relative URLs to help Android fetch from wherever it was loaded from since it doesn't support localhost.\n const chunkName = clientReferenceUrl.pathname + clientReferenceUrl.search;\n\n return {\n id: String(createModuleId(filePath, { platform: context.platform, environment })),\n chunks: [chunkName],\n };\n };\n }\n\n const rscRendererCache = new Map<\n string,\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >();\n\n let ensurePromise: Promise<any> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n const runtime = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >('metro-runtime/src/modules/empty-module.js', {\n environment: 'react-server',\n platform: 'web',\n });\n return runtime;\n }\n const ensureMemo = () => {\n ensurePromise ??= ensureSSRReady();\n return ensurePromise;\n };\n\n async function getRscRendererAsync(platform: string) {\n await ensureMemo();\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRendererCache.has(platform)) {\n return rscRendererCache.get(platform)!;\n }\n\n // TODO: Extract CSS Modules / Assets from the bundler process\n const renderer = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >('@expo/router-server/build/rsc/rsc-renderer', {\n environment: 'react-server',\n platform,\n });\n\n rscRendererCache.set(platform, renderer);\n return renderer;\n }\n\n const rscRenderContext = new Map<string, any>();\n\n function getRscRenderContext(platform: string) {\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRenderContext.has(platform)) {\n return rscRenderContext.get(platform)!;\n }\n\n const context = {};\n\n rscRenderContext.set(platform, context);\n return context;\n }\n\n async function renderRscToReadableStream(\n {\n input,\n headers,\n method,\n platform,\n body,\n engine,\n contentType,\n ssrManifest,\n decodedBody,\n routerOptions,\n }: {\n input: string;\n headers: Headers;\n method: 'POST' | 'GET';\n platform: string;\n body?: ReadableStream<Uint8Array>;\n engine?: 'hermes' | null;\n contentType?: string;\n ssrManifest?: Map<string, string | null>;\n decodedBody?: unknown;\n routerOptions: Record<string, any>;\n },\n isExporting: boolean | undefined = instanceMetroOptions.isExporting\n ) {\n assert(\n isExporting != null,\n 'The server must be started before calling renderRscToReadableStream.'\n );\n\n if (method === 'POST') {\n assert(body, 'Server request must be provided when method is POST (server actions)');\n }\n\n const context = getRscRenderContext(platform);\n\n context['__expo_requestHeaders'] = headers;\n\n const { renderRsc } = await getRscRendererAsync(platform);\n\n return renderRsc(\n {\n body,\n decodedBody,\n context,\n config: {},\n input,\n contentType,\n },\n {\n isExporting,\n entries: await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions }),\n resolveClientEntry: getResolveClientEntry({ platform, engine, ssrManifest }),\n async loadServerModuleRsc(urlFragment) {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n debug('[SSR] loadServerModuleRsc:', urlFragment);\n\n const options = getMetroOptionsFromUrl(urlFragment);\n\n return ssrLoadModule(\n path.join(serverRoot, options.mainModuleName),\n\n options,\n {\n hot: true,\n }\n );\n },\n }\n );\n }\n\n return {\n // Get the static client boundaries (no dead code elimination allowed) for the production export.\n getExpoRouterClientReferencesAsync,\n exportServerActionsAsync,\n\n async exportRoutesAsync(\n {\n platform,\n ssrManifest,\n routerOptions,\n }: {\n platform: string;\n ssrManifest: Map<string, string | null>;\n routerOptions: Record<string, any>;\n },\n files: ExportAssetMap\n ) {\n // TODO: When we add web SSR support, we need to extract CSS Modules / Assets from the bundler process to prevent FLOUC.\n const { getBuildConfig } = (\n await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions })\n ).default;\n\n // Get all the routes to render.\n const buildConfig = await getBuildConfig!(async () =>\n // TODO: Rework prefetching code to use Metro runtime.\n []\n );\n\n await Promise.all(\n Array.from(buildConfig).map(async ({ entries }) => {\n for (const { input, isStatic } of entries || []) {\n if (!isStatic) {\n debug('Skipping static export for route', { input });\n continue;\n }\n const destRscFile = path.join('_flight', platform, encodeInput(input));\n\n const pipe = await renderRscToReadableStream(\n {\n input,\n method: 'GET',\n platform,\n headers: new Headers(),\n ssrManifest,\n routerOptions,\n },\n true\n );\n\n const rsc = await streamToStringAsync(pipe);\n debug('RSC Payload', { platform, input, rsc });\n\n files.set(destRscFile, {\n contents: rsc,\n targetDomain: 'client',\n rscId: input,\n });\n }\n })\n );\n },\n\n middleware: createBuiltinAPIRequestHandler(\n // Match `/_flight/[platform]/[...path]`\n (req) => {\n return getFullUrl(req.url).pathname.startsWith(rscPathPrefix);\n },\n rscMiddleware\n ),\n onReloadRscEvent: (platform: string) => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n rscRendererCache.delete(platform);\n routerCache.delete(platform);\n },\n };\n}\n\nconst getFullUrl = (url: string) => {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'http://localhost:0');\n }\n};\n\nexport const fileURLToFilePath = (fileURL: string) => {\n try {\n return url.fileURLToPath(fileURL);\n } catch (error) {\n if (error instanceof TypeError) {\n throw Error(`Invalid URL: ${fileURL}`, { cause: error });\n }\n throw error;\n }\n};\n\nconst encodeInput = (input: string) => {\n if (input === '') {\n return 'index.txt';\n }\n if (input === 'index') {\n throw new Error('Input should not be `index`');\n }\n if (input.startsWith('/')) {\n throw new Error('Input should not start with `/`');\n }\n if (input.endsWith('/')) {\n throw new Error('Input should not end with `/`');\n }\n return input + '.txt';\n};\n\nfunction wrapBundle(str: string) {\n // Skip the metro runtime so debugging is a bit easier.\n // Replace the __r() call with an export statement.\n // Use gm to apply to the last require line. This is needed when the bundle has side-effects.\n return str.replace(/^(__r\\(.*\\);)$/gm, 'module.exports = $1');\n}\n"],"names":["createServerComponentsMiddleware","fileURLToFilePath","debug","require","getMetroServerRootMemo","memoize","getMetroServerRoot","projectRoot","rscPath","instanceMetroOptions","ssrLoadModule","ssrLoadModuleArtifacts","useClientRouter","createModuleId","routerOptions","routerModule","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","IS_METRO_BUNDLE_ERROR_SYMBOL","Response","JSON","stringify","status","isPossiblyUnableToResolveError","sanitizedServerMessage","stripAnsi","message","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","nestedServerBoundaries","processedEntryPoints","processEntryPoint","entryPoint","contents","add","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","reactServerReferences","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","publicModuleId","toPosixPath","relative","String","processEntryPoints","recursions","uniqueNestedServerBoundaries","value","has","length","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","routerCache","Map","getExpoRouterRscEntriesGetterAsync","ensureMemo","get","router","hot","entries","default","redirects","rewrites","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","filePath","join","ssrManifest","relativeFilePath","chunk","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","pathname","endsWith","chunkName","rscRendererCache","ensurePromise","ensureSSRReady","runtime","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","exportRoutesAsync","getBuildConfig","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","delete","fileURL","fileURLToPath","TypeError","cause","str","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAuCeA,gCAAgC;eAAhCA;;IAqmBHC,iBAAiB;eAAjBA;;;;yBA3oBsB;;;;;;;gEAGhB;;;;;;;yBACc;;;;;;;gEAChB;;;;;;;gEACD;;;;;;qCAE4C;qCACb;sBAErB;0BACE;oBACJ;oBACK;wBACO;gDACW;8BAKxC;;;;;;AAEP,MAAMC,QAAQC,QAAQ,SAAS;AAa/B,MAAMC,yBAAyBC,IAAAA,WAAO,EAACC,2BAAkB;AAElD,SAASN,iCACdO,WAAmB,EACnB,EACEC,OAAO,EACPC,oBAAoB,EACpBC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,EACfC,cAAc,EACdC,aAAa,EAYd;IAED,MAAMC,eAAeH,kBACjB,oDACA;IAEJ,MAAMI,gBAAgBC,IAAAA,2BAAgB,EAAC;QACrCC,QAAQ,CAAC;QACT,0BAA0B;QAC1BC,SAAS;QACTX;QACAY,SAASC,QAAQC,KAAK;QACtBC,WAAW,OAAOC;YAChB,gFAAgF;YAChF,IAAIA,KAAKC,OAAO,CAAC,YAAY,IAAI,MAAM;gBACrCD,KAAKC,OAAO,CAAC,YAAY,GAAGC,IAAAA,gBAAY;YAC1C;YACA,IAAIF,KAAKC,OAAO,CAAC,kBAAkB,IAAI,MAAM;gBAC3CD,KAAKC,OAAO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iBqC,MAAM,CAACzI;YACxBsD,YAAYmF,MAAM,CAACzI;QACrB;IACF;AACF;AAEA,MAAMsI,aAAa,CAACC;IAClB,IAAI;QACF,OAAO,IAAIzC,IAAIyC;IACjB,EAAE,OAAM;QACN,OAAO,IAAIzC,IAAIyC,KAAK;IACtB;AACF;AAEO,MAAMhL,oBAAoB,CAACmL;IAChC,IAAI;QACF,OAAOH,kBAAG,CAACI,aAAa,CAACD;IAC3B,EAAE,OAAO9J,OAAO;QACd,IAAIA,iBAAiBgK,WAAW;YAC9B,MAAM/G,MAAM,CAAC,aAAa,EAAE6G,SAAS,EAAE;gBAAEG,OAAOjK;YAAM;QACxD;QACA,MAAMA;IACR;AACF;AAEA,MAAMkJ,cAAc,CAAClB;IACnB,IAAIA,UAAU,IAAI;QAChB,OAAO;IACT;IACA,IAAIA,UAAU,SAAS;QACrB,MAAM,IAAI/E,MAAM;IAClB;IACA,IAAI+E,MAAMvD,UAAU,CAAC,MAAM;QACzB,MAAM,IAAIxB,MAAM;IAClB;IACA,IAAI+E,MAAMV,QAAQ,CAAC,MAAM;QACvB,MAAM,IAAIrE,MAAM;IAClB;IACA,OAAO+E,QAAQ;AACjB;AAEA,SAASrE,WAAWuG,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAIC,OAAO,CAAC,oBAAoB;AACzC"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/createServerComponentsMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport type { EntriesDev } from '@expo/router-server/build/rsc/server';\nimport assert from 'assert';\nimport { getRscMiddleware } from 'expo-server/private';\nimport path from 'node:path';\nimport url from 'node:url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport type { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n type ExpoMetroOptions,\n getMetroOptionsFromUrl,\n} from '../middleware/metroOptions';\n\nconst debug = require('debug')('expo:rsc') as typeof console.log;\n\ntype SSRLoadModuleArtifactsFunc = (\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>\n) => Promise<{ artifacts: SerialAsset[]; src: string }>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string | null,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\nconst getMetroServerRootMemo = memoize(getMetroServerRoot);\n\nexport function createServerComponentsMiddleware(\n projectRoot: string,\n {\n rscPath,\n instanceMetroOptions,\n ssrLoadModule,\n ssrLoadModuleArtifacts,\n useClientRouter,\n createModuleId,\n routerOptions,\n }: {\n rscPath: string;\n instanceMetroOptions: Partial<ExpoMetroOptions>;\n ssrLoadModule: SSRLoadModuleFunc;\n ssrLoadModuleArtifacts: SSRLoadModuleArtifactsFunc;\n useClientRouter: boolean;\n createModuleId: (\n filePath: string,\n context: { platform: string; environment: string }\n ) => string | number;\n routerOptions: Record<string, any>;\n }\n) {\n const routerModule = useClientRouter\n ? '@expo/router-server/build/rsc/router/noopRouter'\n : '@expo/router-server/build/rsc/router/expo-definedRouter';\n\n const rscMiddleware = getRscMiddleware({\n config: {},\n // Disabled in development\n baseUrl: '',\n rscPath,\n onError: console.error,\n renderRsc: async (args) => {\n // In development we should add simulated versions of common production headers.\n if (args.headers['x-real-ip'] == null) {\n args.headers['x-real-ip'] = getIpAddress();\n }\n if (args.headers['x-forwarded-for'] == null) {\n args.headers['x-forwarded-for'] = args.headers['x-real-ip'];\n }\n if (args.headers['x-forwarded-proto'] == null) {\n args.headers['x-forwarded-proto'] = 'http';\n }\n\n // Dev server-only implementation.\n try {\n return await renderRscToReadableStream({\n ...args,\n headers: new Headers(args.headers),\n body: args.body!,\n routerOptions,\n });\n } catch (error: any) {\n // If you get a codeFrame error during SSR like when using a Class component in React Server Components, then this\n // will throw with:\n // {\n // rawObject: {\n // type: 'TransformError',\n // lineNumber: 0,\n // errors: [ [Object] ],\n // name: 'SyntaxError',\n // message: '...',\n // }\n // }\n\n // TODO: Revisit all error handling now that we do direct metro bundling...\n await logMetroError(projectRoot, { error });\n\n if (error[IS_METRO_BUNDLE_ERROR_SYMBOL]) {\n throw new Response(JSON.stringify(error), {\n status: isPossiblyUnableToResolveError(error) ? 404 : 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n const sanitizedServerMessage = stripAnsi(error.message) ?? error.message;\n throw new Response(sanitizedServerMessage, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n }\n },\n });\n\n let rscPathPrefix = rscPath;\n if (rscPathPrefix !== '/') {\n rscPathPrefix += '/';\n }\n\n async function exportServerActionsAsync(\n {\n platform,\n entryPoints,\n domRoot,\n }: { platform: string; entryPoints: string[]; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n clientBoundaries: string[];\n manifest: Record<string, [string, string]>;\n }> {\n const uniqueEntryPoints = [...new Set(entryPoints)];\n // TODO: Support multiple entry points in a single split server bundle...\n const manifest: Record<string, [string, string]> = {};\n const nestedClientBoundaries: string[] = [];\n const nestedServerBoundaries: string[] = [];\n const processedEntryPoints = new Set<string>();\n async function processEntryPoint(entryPoint: string) {\n processedEntryPoints.add(entryPoint);\n\n const contents = await ssrLoadModuleArtifacts(entryPoint, {\n environment: 'react-server',\n platform,\n // Ignore the metro runtime to avoid overwriting the original in the API route.\n modulesOnly: true,\n // Required\n runModule: true,\n // Required to ensure assets load as client boundaries.\n domRoot,\n });\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactClientReferences) {\n nestedClientBoundaries.push(...reactClientReferences!);\n }\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactServerReferences) {\n nestedServerBoundaries.push(...reactServerReferences!);\n }\n\n // Naive check to ensure the module runtime is not included in the server action bundle.\n if (contents.src.includes('The experimental Metro feature')) {\n throw new Error(\n 'Internal error: module runtime should not be included in server action bundles: ' +\n entryPoint\n );\n }\n\n const relativeName = createModuleId(entryPoint, {\n platform,\n environment: 'react-server',\n });\n const safeName = path.basename(contents.artifacts.find((a) => a.type === 'js')!.filename!);\n\n const outputName = `_expo/rsc/${platform}/${safeName}`;\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(outputName, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n // Match babel plugin.\n const publicModuleId = './' + toPosixPath(path.relative(projectRoot, entryPoint));\n\n // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[publicModuleId] = [String(relativeName), outputName];\n }\n\n async function processEntryPoints(entryPoints: string[], recursions = 0) {\n // Arbitrary recursion limit to prevent infinite loops.\n if (recursions > 10) {\n throw new Error('Recursion limit exceeded while processing server boundaries');\n }\n\n for (const entryPoint of entryPoints) {\n await processEntryPoint(entryPoint);\n }\n\n // When a server action has other server actions inside of it, we need to process those as well to ensure all entry points are in the manifest and accounted for.\n let uniqueNestedServerBoundaries = [...new Set(nestedServerBoundaries)];\n // Filter out values that have already been processed.\n uniqueNestedServerBoundaries = uniqueNestedServerBoundaries.filter(\n (value) => !processedEntryPoints.has(value)\n );\n if (uniqueNestedServerBoundaries.length) {\n debug('bundling nested server action boundaries', uniqueNestedServerBoundaries);\n return processEntryPoints(uniqueNestedServerBoundaries, recursions + 1);\n }\n }\n\n await processEntryPoints(uniqueEntryPoints);\n\n // Save the SSR manifest so we can perform more replacements in the server renderer and with server actions.\n files.set(`_expo/rsc/${platform}/action-manifest.js`, {\n targetDomain: 'server',\n contents: 'module.exports = ' + JSON.stringify(manifest),\n });\n\n return { manifest, clientBoundaries: nestedClientBoundaries };\n }\n\n async function getExpoRouterClientReferencesAsync(\n { platform, domRoot }: { platform: string; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n reactClientReferences: string[];\n reactServerReferences: string[];\n cssModules: SerialAsset[];\n }> {\n const contents = await ssrLoadModuleArtifacts(routerModule, {\n environment: 'react-server',\n platform,\n modulesOnly: true,\n domRoot,\n });\n\n // Extract the global CSS modules that are imported from the router.\n // These will be injected in the head of the HTML document for the website.\n const cssModules = contents.artifacts.filter((a) => a.type.startsWith('css'));\n\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactServerReferences) {\n throw new Error(\n 'Static server action references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactServerReferences);\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactClientReferences) {\n throw new Error(\n 'Static client references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactClientReferences);\n\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(`_expo/rsc/${platform}/router.js`, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n return { reactClientReferences, reactServerReferences, cssModules };\n }\n\n const routerCache = new Map<string, EntriesDev>();\n\n async function getExpoRouterRscEntriesGetterAsync({\n platform,\n routerOptions,\n }: {\n platform: string;\n routerOptions: Record<string, any>;\n }) {\n await ensureMemo();\n // We can only cache this if we're using the client router since it doesn't change or use HMR\n if (routerCache.has(platform) && useClientRouter) {\n return routerCache.get(platform)!;\n }\n\n const router = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/router/expo-definedRouter')\n >(\n routerModule,\n {\n environment: 'react-server',\n modulesOnly: true,\n platform,\n },\n {\n hot: !useClientRouter,\n }\n );\n\n const entries = router.default({\n redirects: routerOptions?.redirects,\n rewrites: routerOptions?.rewrites,\n });\n\n routerCache.set(platform, entries);\n return entries;\n }\n\n function getResolveClientEntry(context: {\n platform: string;\n engine?: 'hermes' | null;\n ssrManifest?: Map<string, string | null>;\n }): (\n file: string,\n isServer: boolean\n ) => {\n id: string;\n chunks: string[];\n } {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n const {\n mode,\n minify = false,\n isExporting,\n baseUrl,\n routerRoot,\n asyncRoutes,\n preserveEnvVars,\n reactCompiler,\n lazy,\n } = instanceMetroOptions;\n\n assert(\n isExporting != null &&\n baseUrl != null &&\n mode != null &&\n routerRoot != null &&\n asyncRoutes != null,\n `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`\n );\n\n return (file: string, isServer: boolean) => {\n const filePath = path.join(\n projectRoot,\n file.startsWith('file://') ? fileURLToFilePath(file) : file\n );\n\n if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n\n const relativeFilePath = toPosixPath(path.relative(serverRoot, filePath));\n\n assert(\n context.ssrManifest.has(relativeFilePath),\n `SSR manifest is missing client boundary \"${relativeFilePath}\"`\n );\n\n const chunk = context.ssrManifest.get(relativeFilePath);\n\n return {\n id: String(\n createModuleId(filePath, { platform: context.platform, environment: 'client' })\n ),\n chunks: chunk != null ? [chunk] : [],\n };\n }\n\n const environment = isServer ? 'react-server' : 'client';\n const searchParams = createBundleUrlSearchParams({\n mainModuleName: '',\n platform: context.platform,\n mode,\n minify,\n lazy,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n reactCompiler: !!reactCompiler,\n engine: context.engine ?? undefined,\n bytecode: false,\n clientBoundaries: [],\n inlineSourceMap: false,\n environment,\n modulesOnly: true,\n runModule: false,\n });\n\n searchParams.set('resolver.clientboundary', String(true));\n\n const clientReferenceUrl = new URL('http://a');\n\n // TICKLE: Handshake 1\n searchParams.set('xRSC', '1');\n\n clientReferenceUrl.search = searchParams.toString();\n\n const relativeFilePath = path.relative(serverRoot, filePath);\n\n clientReferenceUrl.pathname = relativeFilePath;\n\n // Ensure url.pathname ends with '.bundle'\n if (!clientReferenceUrl.pathname.endsWith('.bundle')) {\n clientReferenceUrl.pathname += '.bundle';\n }\n\n // Return relative URLs to help Android fetch from wherever it was loaded from since it doesn't support localhost.\n const chunkName = clientReferenceUrl.pathname + clientReferenceUrl.search;\n\n return {\n id: String(createModuleId(filePath, { platform: context.platform, environment })),\n chunks: [chunkName],\n };\n };\n }\n\n const rscRendererCache = new Map<\n string,\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >();\n\n let ensurePromise: Promise<unknown> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n await ssrLoadModule(null, {\n environment: 'react-server',\n platform: 'web',\n });\n }\n const ensureMemo = () => {\n ensurePromise ??= ensureSSRReady();\n return ensurePromise;\n };\n\n async function getRscRendererAsync(platform: string) {\n await ensureMemo();\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRendererCache.has(platform)) {\n return rscRendererCache.get(platform)!;\n }\n\n // TODO: Extract CSS Modules / Assets from the bundler process\n const renderer = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >('@expo/router-server/build/rsc/rsc-renderer', {\n environment: 'react-server',\n platform,\n });\n\n rscRendererCache.set(platform, renderer);\n return renderer;\n }\n\n const rscRenderContext = new Map<string, any>();\n\n function getRscRenderContext(platform: string) {\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRenderContext.has(platform)) {\n return rscRenderContext.get(platform)!;\n }\n\n const context = {};\n\n rscRenderContext.set(platform, context);\n return context;\n }\n\n async function renderRscToReadableStream(\n {\n input,\n headers,\n method,\n platform,\n body,\n engine,\n contentType,\n ssrManifest,\n decodedBody,\n routerOptions,\n }: {\n input: string;\n headers: Headers;\n method: 'POST' | 'GET';\n platform: string;\n body?: ReadableStream<Uint8Array>;\n engine?: 'hermes' | null;\n contentType?: string;\n ssrManifest?: Map<string, string | null>;\n decodedBody?: unknown;\n routerOptions: Record<string, any>;\n },\n isExporting: boolean | undefined = instanceMetroOptions.isExporting\n ) {\n assert(\n isExporting != null,\n 'The server must be started before calling renderRscToReadableStream.'\n );\n\n if (method === 'POST') {\n assert(body, 'Server request must be provided when method is POST (server actions)');\n }\n\n const context = getRscRenderContext(platform);\n\n context['__expo_requestHeaders'] = headers;\n\n const { renderRsc } = await getRscRendererAsync(platform);\n\n return renderRsc(\n {\n body,\n decodedBody,\n context,\n config: {},\n input,\n contentType,\n },\n {\n isExporting,\n entries: await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions }),\n resolveClientEntry: getResolveClientEntry({ platform, engine, ssrManifest }),\n async loadServerModuleRsc(urlFragment) {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n debug('[SSR] loadServerModuleRsc:', urlFragment);\n\n const options = getMetroOptionsFromUrl(urlFragment);\n\n return ssrLoadModule(\n path.join(serverRoot, options.mainModuleName),\n\n options,\n {\n hot: true,\n }\n );\n },\n }\n );\n }\n\n return {\n // Get the static client boundaries (no dead code elimination allowed) for the production export.\n getExpoRouterClientReferencesAsync,\n exportServerActionsAsync,\n\n async exportRoutesAsync(\n {\n platform,\n ssrManifest,\n routerOptions,\n }: {\n platform: string;\n ssrManifest: Map<string, string | null>;\n routerOptions: Record<string, any>;\n },\n files: ExportAssetMap\n ) {\n // TODO: When we add web SSR support, we need to extract CSS Modules / Assets from the bundler process to prevent FLOUC.\n const { getBuildConfig } = (\n await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions })\n ).default;\n\n // Get all the routes to render.\n const buildConfig = await getBuildConfig!(async () =>\n // TODO: Rework prefetching code to use Metro runtime.\n []\n );\n\n await Promise.all(\n Array.from(buildConfig).map(async ({ entries }) => {\n for (const { input, isStatic } of entries || []) {\n if (!isStatic) {\n debug('Skipping static export for route', { input });\n continue;\n }\n const destRscFile = path.join('_flight', platform, encodeInput(input));\n\n const pipe = await renderRscToReadableStream(\n {\n input,\n method: 'GET',\n platform,\n headers: new Headers(),\n ssrManifest,\n routerOptions,\n },\n true\n );\n\n const rsc = await streamToStringAsync(pipe);\n debug('RSC Payload', { platform, input, rsc });\n\n files.set(destRscFile, {\n contents: rsc,\n targetDomain: 'client',\n rscId: input,\n });\n }\n })\n );\n },\n\n middleware: createBuiltinAPIRequestHandler(\n // Match `/_flight/[platform]/[...path]`\n (req) => {\n return getFullUrl(req.url).pathname.startsWith(rscPathPrefix);\n },\n rscMiddleware\n ),\n onReloadRscEvent: (platform: string) => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n rscRendererCache.delete(platform);\n routerCache.delete(platform);\n },\n };\n}\n\nconst getFullUrl = (url: string) => {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'http://localhost:0');\n }\n};\n\nexport const fileURLToFilePath = (fileURL: string) => {\n try {\n return url.fileURLToPath(fileURL);\n } catch (error) {\n if (error instanceof TypeError) {\n throw Error(`Invalid URL: ${fileURL}`, { cause: error });\n }\n throw error;\n }\n};\n\nconst encodeInput = (input: string) => {\n if (input === '') {\n return 'index.txt';\n }\n if (input === 'index') {\n throw new Error('Input should not be `index`');\n }\n if (input.startsWith('/')) {\n throw new Error('Input should not start with `/`');\n }\n if (input.endsWith('/')) {\n throw new Error('Input should not end with `/`');\n }\n return input + '.txt';\n};\n\nfunction wrapBundle(str: string) {\n // Skip the metro runtime so debugging is a bit easier.\n // Replace the __r() call with an export statement.\n // Use gm to apply to the last require line. This is needed when the bundle has side-effects.\n return str.replace(/^(__r\\(.*\\);)$/gm, 'module.exports = $1');\n}\n"],"names":["createServerComponentsMiddleware","fileURLToFilePath","debug","require","getMetroServerRootMemo","memoize","getMetroServerRoot","projectRoot","rscPath","instanceMetroOptions","ssrLoadModule","ssrLoadModuleArtifacts","useClientRouter","createModuleId","routerOptions","routerModule","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","IS_METRO_BUNDLE_ERROR_SYMBOL","Response","JSON","stringify","status","isPossiblyUnableToResolveError","sanitizedServerMessage","stripAnsi","message","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","nestedServerBoundaries","processedEntryPoints","processEntryPoint","entryPoint","contents","add","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","reactServerReferences","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","publicModuleId","toPosixPath","relative","String","processEntryPoints","recursions","uniqueNestedServerBoundaries","value","has","length","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","routerCache","Map","getExpoRouterRscEntriesGetterAsync","ensureMemo","get","router","hot","entries","default","redirects","rewrites","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","filePath","join","ssrManifest","relativeFilePath","chunk","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","pathname","endsWith","chunkName","rscRendererCache","ensurePromise","ensureSSRReady","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","exportRoutesAsync","getBuildConfig","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","delete","fileURL","fileURLToPath","TypeError","cause","str","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAuCeA,gCAAgC;eAAhCA;;IAkmBHC,iBAAiB;eAAjBA;;;;yBAxoBsB;;;;;;;gEAGhB;;;;;;;yBACc;;;;;;;gEAChB;;;;;;;gEACD;;;;;;qCAE4C;qCACb;sBAErB;0BACE;oBACJ;oBACK;wBACO;gDACW;8BAKxC;;;;;;AAEP,MAAMC,QAAQC,QAAQ,SAAS;AAa/B,MAAMC,yBAAyBC,IAAAA,WAAO,EAACC,2BAAkB;AAElD,SAASN,iCACdO,WAAmB,EACnB,EACEC,OAAO,EACPC,oBAAoB,EACpBC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,EACfC,cAAc,EACdC,aAAa,EAYd;IAED,MAAMC,eAAeH,kBACjB,oDACA;IAEJ,MAAMI,gBAAgBC,IAAAA,2BAAgB,EAAC;QACrCC,QAAQ,CAAC;QACT,0BAA0B;QAC1BC,SAAS;QACTX;QACAY,SAASC,QAAQC,KAAK;QACtBC,WAAW,OAAOC;YAChB,gFAAgF;YAChF,IAAIA,KAAKC,OAAO,CAAC,YAAY,IAAI,MAAM;gBACrCD,KAAKC,OAAO,CAAC,YAAY,GAAGC,IAAAA,gBAAY;YAC1C;YACA,IAAIF,KAAKC,OAAO,CAAC,kBAAkB,IAAI,MAAM;gBAC3CD,KAAKC,OAAO,CAAC,kBAAkB,GAAGD,KAAKC,OAAO,CAAC,YAAY;YAC7D;YACA,IAAID,KAAKC,OAAO,CAAC,oBAAoB,IAAI,MAAM;gBAC7CD,KAAKC,OAAO,CAAC,oBAAoB,GAAG;YACtC;YAEA,kCAAkC;YAClC,IAAI;gBACF,OAAO,MAAME,0BAA0B;oBACrC,GAAGH,IAAI;oBACPC,SAAS,IAAIG,QAAQJ,KAAKC,OAAO;oBACjCI,MAAML,KAAKK,IAAI;oBACff;gBACF;YACF,EAAE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,MAAM,CAAC,aAAa,EAAE4G,SAAS,EAAE;gBAAEG,OAAOhK;YAAM;QACxD;QACA,MAAMA;IACR;AACF;AAEA,MAAMiJ,cAAc,CAAClB;IACnB,IAAIA,UAAU,IAAI;QAChB,OAAO;IACT;IACA,IAAIA,UAAU,SAAS;QACrB,MAAM,IAAI9E,MAAM;IAClB;IACA,IAAI8E,MAAMtD,UAAU,CAAC,MAAM;QACzB,MAAM,IAAIxB,MAAM;IAClB;IACA,IAAI8E,MAAMT,QAAQ,CAAC,MAAM;QACvB,MAAM,IAAIrE,MAAM;IAClB;IACA,OAAO8E,QAAQ;AACjB;AAEA,SAASpE,WAAWsG,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAIC,OAAO,CAAC,oBAAoB;AACzC"}
@@ -143,14 +143,17 @@ async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, ge
143
143
  }
144
144
  const serverRoot = (0, _paths().getMetroServerRoot)(projectRoot);
145
145
  const terminalReporter = new _MetroTerminalReporter.MetroTerminalReporter(serverRoot, terminal);
146
- const hasConfig = await (0, _metroconfig().resolveConfig)(options.config, projectRoot);
147
- let config = {
148
- ...await (0, _metroconfig().loadConfig)({
149
- cwd: projectRoot,
150
- projectRoot,
151
- ...options
152
- }, // If the project does not have a metro.config.js, then we use the default config.
153
- hasConfig.isEmpty ? (0, _metroconfig1().getDefaultConfig)(projectRoot) : undefined),
146
+ const defaultConfig = (0, _metroconfig1().getDefaultConfig)(projectRoot);
147
+ const resolvedConfig = await (0, _metroconfig().resolveConfig)(options.config, projectRoot);
148
+ let config = resolvedConfig.isEmpty ? defaultConfig : await (0, _metroconfig().mergeConfig)(defaultConfig, resolvedConfig.config);
149
+ // Set the watchfolders to include the projectRoot, as Metro assumes this
150
+ // Force-override the reporter
151
+ config = {
152
+ ...config,
153
+ watchFolders: !config.watchFolders.includes(config.projectRoot) ? [
154
+ config.projectRoot,
155
+ ...config.watchFolders
156
+ ] : config.watchFolders,
154
157
  reporter: {
155
158
  update (event) {
156
159
  terminalReporter.update(event);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport MetroHmrServer, { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport RevisionNotFoundError from '@expo/metro/metro/IncrementalBundler/RevisionNotFoundError';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport formatBundlingError from '@expo/metro/metro/lib/formatBundlingError';\nimport { loadConfig, resolveConfig, type ConfigT } from '@expo/metro/metro-config';\nimport { Terminal } from '@expo/metro/metro-core';\nimport {\n createStableModuleIdFactory,\n getDefaultConfig,\n type LoadOptions,\n} from '@expo/metro-config';\nimport chalk from 'chalk';\nimport http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// NOTE(@kitten): We pass a custom createStableModuleIdFactory function into the Metro module ID factory sometimes\ninterface MetroServerWithModuleIdMod extends MetroServer {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\ninterface MetroHmrServerWithModuleIdMod extends MetroHmrServer<MetroHmrClient> {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// TODO(@kitten): We assign this here to run server-side code bundled by metro\n// It's not isolated into a worker thread yet\n// Check `metro-require/require.ts` for how this setting is used\ndeclare namespace globalThis {\n let __requireCycleIgnorePatterns: readonly RegExp[] | undefined;\n}\n\nfunction asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\n\n// Wrap terminal and polyfill console.log so we can log during bundling without breaking the indicator.\nclass LogRespectingTerminal extends Terminal {\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream, { ttyPrint: true });\n\n const sendLog = (...msg: any[]) => {\n if (!msg.length) {\n this.log('');\n } else {\n const [format, ...args] = msg;\n this.log(format, ...args);\n }\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n console.log = sendLog;\n console.info = sendLog;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? env.EXPO_USE_STICKY_RESOLVER;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (exp.experiments?.reactServerComponentRoutes || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n }\n\n if (exp.experiments?.reactCanary) {\n Log.warn(`React 19 is enabled by default. Remove unused experiments.reactCanary flag.`);\n }\n\n const serverRoot = getMetroServerRoot(projectRoot);\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n const hasConfig = await resolveConfig(options.config, projectRoot);\n let config: ConfigT = {\n ...(await loadConfig(\n { cwd: projectRoot, projectRoot, ...options },\n // If the project does not have a metro.config.js, then we use the default config.\n hasConfig.isEmpty ? getDefaultConfig(projectRoot) : undefined\n )),\n reporter: {\n update(event: any) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n asWritable(config.transformer).publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n asWritable(config.transformer).publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n\n if (exp.experiments?.reactCompiler) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n if (autolinkingModuleResolutionEnabled) {\n Log.warn(`Experimental Expo Autolinking module resolver is enabled.`);\n }\n\n if (serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: !!exp.experiments?.reactServerComponentRoutes,\n getMetroBundler,\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: Omit<LoadOptions, 'logger'>,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: MetroServer;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n server: http.Server;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler() {\n return metro.getBundler().getBundler();\n },\n });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } =\n createMetroMiddleware(metroConfig);\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware(\n metroBundler,\n reporter\n );\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n asWritable(metroConfig.server).enhanceMiddleware = (\n metroMiddleware: any,\n server: MetroServer\n ) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n const { server, hmrServer, metro } = await runServer(\n metroBundler,\n metroConfig,\n {\n websocketEndpoints: {\n ...websocketEndpoints,\n ...createDevToolsPluginWebsocketEndpoint(),\n },\n watch: !isExporting && isWatchEnabled(),\n },\n {\n mockServer: isExporting,\n }\n );\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n projectRoot,\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: MetroServerWithModuleIdMod, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n // TODO(@kitten): Increase type-safety here\n platform: graph.transformOptions.platform!,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle:\n | typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default\n | typeof import('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // TODO: Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (\n this: MetroHmrServerWithModuleIdMod,\n group,\n options,\n changeEvent\n ) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n // TODO(@kitten): Increase type-safety here\n platform: revision.graph.transformOptions.platform!,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const isRouterRoute =\n path.isAbsolute(filePath) && filePath.startsWith(path.resolve(projectRoot, routerRoot));\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","asWritable","input","LogRespectingTerminal","Terminal","constructor","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","console","info","terminal","process","stdout","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","env","EXPO_USE_STICKY_RESOLVER","serverActionsEnabled","reactServerFunctions","EXPO_UNSTABLE_SERVER_FUNCTIONS","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","warn","serverRoot","getMetroServerRoot","terminalReporter","MetroTerminalReporter","hasConfig","resolveConfig","loadConfig","cwd","isEmpty","getDefaultConfig","undefined","reporter","update","event","globalThis","__requireCycleIgnorePatterns","resolver","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","server","enhanceMiddleware","metroMiddleware","attachAtlasAsync","resetAtlasFile","hmrServer","runServer","createDevToolsPluginWebsocketEndpoint","watch","mockServer","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","path","sort","a","b","hmrJSBundle","require","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","push","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","error","formattedError","messageSocket","split","sep","join","dom","match","routerRoot","isRouterEntry","test","isRouterModule","isRouterRoute","isAbsolute","startsWith","resolve","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;IAoMsBA,qBAAqB;eAArBA;;IAiSNC,cAAc;eAAdA;;IAjZMC,oBAAoB;eAApBA;;;;yBApFqB;;;;;;;y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src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport MetroHmrServer, { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport RevisionNotFoundError from '@expo/metro/metro/IncrementalBundler/RevisionNotFoundError';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport formatBundlingError from '@expo/metro/metro/lib/formatBundlingError';\nimport {\n mergeConfig,\n resolveConfig,\n type InputConfigT,\n type ConfigT,\n} from '@expo/metro/metro-config';\nimport { Terminal } from '@expo/metro/metro-core';\nimport {\n createStableModuleIdFactory,\n getDefaultConfig,\n type LoadOptions,\n} from '@expo/metro-config';\nimport chalk from 'chalk';\nimport http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// NOTE(@kitten): We pass a custom createStableModuleIdFactory function into the Metro module ID factory sometimes\ninterface MetroServerWithModuleIdMod extends MetroServer {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\ninterface MetroHmrServerWithModuleIdMod extends MetroHmrServer<MetroHmrClient> {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// TODO(@kitten): We assign this here to run server-side code bundled by metro\n// It's not isolated into a worker thread yet\n// Check `metro-require/require.ts` for how this setting is used\ndeclare namespace globalThis {\n let __requireCycleIgnorePatterns: readonly RegExp[] | undefined;\n}\n\nfunction asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\n\n// Wrap terminal and polyfill console.log so we can log during bundling without breaking the indicator.\nclass LogRespectingTerminal extends Terminal {\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream, { ttyPrint: true });\n\n const sendLog = (...msg: any[]) => {\n if (!msg.length) {\n this.log('');\n } else {\n const [format, ...args] = msg;\n this.log(format, ...args);\n }\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n console.log = sendLog;\n console.info = sendLog;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? env.EXPO_USE_STICKY_RESOLVER;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (exp.experiments?.reactServerComponentRoutes || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n }\n\n if (exp.experiments?.reactCanary) {\n Log.warn(`React 19 is enabled by default. Remove unused experiments.reactCanary flag.`);\n }\n\n const serverRoot = getMetroServerRoot(projectRoot);\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n const defaultConfig = getDefaultConfig(projectRoot);\n const resolvedConfig = await resolveConfig(options.config, projectRoot);\n\n let config: ConfigT = resolvedConfig.isEmpty\n ? defaultConfig\n : await mergeConfig(defaultConfig, resolvedConfig.config);\n // Set the watchfolders to include the projectRoot, as Metro assumes this\n // Force-override the reporter\n config = {\n ...config,\n watchFolders: !config.watchFolders.includes(config.projectRoot)\n ? [config.projectRoot, ...config.watchFolders]\n : config.watchFolders,\n reporter: {\n update(event) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n asWritable(config.transformer).publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n asWritable(config.transformer).publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n\n if (exp.experiments?.reactCompiler) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n if (autolinkingModuleResolutionEnabled) {\n Log.warn(`Experimental Expo Autolinking module resolver is enabled.`);\n }\n\n if (serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: !!exp.experiments?.reactServerComponentRoutes,\n getMetroBundler,\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: Omit<LoadOptions, 'logger'>,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: MetroServer;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n server: http.Server;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler() {\n return metro.getBundler().getBundler();\n },\n });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } =\n createMetroMiddleware(metroConfig);\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware(\n metroBundler,\n reporter\n );\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n asWritable(metroConfig.server).enhanceMiddleware = (\n metroMiddleware: any,\n server: MetroServer\n ) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n const { server, hmrServer, metro } = await runServer(\n metroBundler,\n metroConfig,\n {\n websocketEndpoints: {\n ...websocketEndpoints,\n ...createDevToolsPluginWebsocketEndpoint(),\n },\n watch: !isExporting && isWatchEnabled(),\n },\n {\n mockServer: isExporting,\n }\n );\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n projectRoot,\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: MetroServerWithModuleIdMod, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n // TODO(@kitten): Increase type-safety here\n platform: graph.transformOptions.platform!,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle:\n | typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default\n | typeof import('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // TODO: Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (\n this: MetroHmrServerWithModuleIdMod,\n group,\n options,\n changeEvent\n ) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n // TODO(@kitten): Increase type-safety here\n platform: revision.graph.transformOptions.platform!,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const isRouterRoute =\n path.isAbsolute(filePath) && filePath.startsWith(path.resolve(projectRoot, routerRoot));\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","asWritable","input","LogRespectingTerminal","Terminal","constructor","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","console","info","terminal","process","stdout","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","env","EXPO_USE_STICKY_RESOLVER","serverActionsEnabled","reactServerFunctions","EXPO_UNSTABLE_SERVER_FUNCTIONS","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","warn","serverRoot","getMetroServerRoot","terminalReporter","MetroTerminalReporter","defaultConfig","getDefaultConfig","resolvedConfig","resolveConfig","isEmpty","mergeConfig","watchFolders","includes","reporter","update","event","globalThis","__requireCycleIgnorePatterns","resolver","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","server","enhanceMiddleware","metroMiddleware","attachAtlasAsync","resetAtlasFile","hmrServer","runServer","createDevToolsPluginWebsocketEndpoint","watch","mockServer","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","path","sort","a","b","hmrJSBundle","require","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","push","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","error","formattedError","messageSocket","split","sep","join","dom","match","routerRoot","isRouterEntry","test","isRouterModule","isRouterRoute","isAbsolute","startsWith","resolve","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;IA+MsBA,qBAAqB;eAArBA;;IAiSNC,cAAc;eA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OAAO3E;AACT;AAMO,SAASnH;IACd,IAAI+B,QAAG,CAACgK,EAAE,EAAE;QACVxJ,QAAG,CAAC3B,GAAG,CACLsD,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAACnC,QAAG,CAACgK,EAAE;AAChB"}
@@ -113,13 +113,16 @@ const runServer = async (metroBundler, config, { hasReducedPerformance = false,
113
113
  // requests in case it takes the packager more than the default
114
114
  // timeout of 120 seconds to respond to a request.
115
115
  httpServer.timeout = 0;
116
- httpServer.on('close', ()=>{
117
- end();
118
- });
119
116
  // Extend the close method to ensure all websocket servers are closed, and connections are terminated
120
117
  const originalClose = httpServer.close.bind(httpServer);
121
118
  httpServer.close = function closeHttpServer(callback) {
122
- originalClose(callback);
119
+ originalClose((err)=>{
120
+ // Always call end() to clean up Metro workers, even if the server wasn't started.
121
+ // The 'close' event doesn't fire for servers that were never started (mockServer case),
122
+ // so we need to call end() explicitly here.
123
+ end();
124
+ callback == null ? void 0 : callback(err);
125
+ });
123
126
  // Close all websocket servers, including possible client connections (see: https://github.com/websockets/ws/issues/2137#issuecomment-1507469375)
124
127
  for (const endpoint of Object.values(websocketEndpoints)){
125
128
  endpoint.close();