@expo/cli 56.1.15 → 56.1.17

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.
Files changed (41) hide show
  1. package/build/bin/cli +1 -1
  2. package/build/src/events/index.js +1 -1
  3. package/build/src/export/createMetadataJson.js.map +1 -1
  4. package/build/src/export/embed/exportEmbedAsync.js +6 -3
  5. package/build/src/export/embed/exportEmbedAsync.js.map +1 -1
  6. package/build/src/export/embed/resolveOptions.js +2 -1
  7. package/build/src/export/embed/resolveOptions.js.map +1 -1
  8. package/build/src/export/exportApp.js +1 -1
  9. package/build/src/export/exportApp.js.map +1 -1
  10. package/build/src/export/exportHermes.js +9 -1
  11. package/build/src/export/exportHermes.js.map +1 -1
  12. package/build/src/export/resolveOptions.js +9 -10
  13. package/build/src/export/resolveOptions.js.map +1 -1
  14. package/build/src/export/saveAssets.js.map +1 -1
  15. package/build/src/prebuild/prebuildAsync.js +3 -1
  16. package/build/src/prebuild/prebuildAsync.js.map +1 -1
  17. package/build/src/start/doctor/apple/SimulatorAppPrerequisite.js +53 -91
  18. package/build/src/start/doctor/apple/SimulatorAppPrerequisite.js.map +1 -1
  19. package/build/src/start/platforms/ios/AppleDeviceManager.js +8 -2
  20. package/build/src/start/platforms/ios/AppleDeviceManager.js.map +1 -1
  21. package/build/src/start/platforms/ios/ensureSimulatorAppRunning.js +26 -11
  22. package/build/src/start/platforms/ios/ensureSimulatorAppRunning.js.map +1 -1
  23. package/build/src/start/server/metro/createExpoAutolinkingResolver.js +21 -8
  24. package/build/src/start/server/metro/createExpoAutolinkingResolver.js.map +1 -1
  25. package/build/src/start/server/metro/instantiateMetro.js +5 -2
  26. package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
  27. package/build/src/start/server/metro/withMetroMultiPlatform.js +88 -11
  28. package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
  29. package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js +3 -1
  30. package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js.map +1 -1
  31. package/build/src/start/server/middleware/InterstitialPageMiddleware.js +3 -1
  32. package/build/src/start/server/middleware/InterstitialPageMiddleware.js.map +1 -1
  33. package/build/src/start/server/middleware/resolvePlatform.js +4 -2
  34. package/build/src/start/server/middleware/resolvePlatform.js.map +1 -1
  35. package/build/src/start/server/platformBundlers.js +3 -1
  36. package/build/src/start/server/platformBundlers.js.map +1 -1
  37. package/build/src/utils/findUp.js +17 -19
  38. package/build/src/utils/findUp.js.map +1 -1
  39. package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
  40. package/build/src/utils/telemetry/utils/context.js +1 -1
  41. package/package.json +14 -14
@@ -9,7 +9,7 @@ Object.defineProperty(exports, "ensureSimulatorAppRunningAsync", {
9
9
  }
10
10
  });
11
11
  function _osascript() {
12
- const data = /*#__PURE__*/ _interop_require_wildcard(require("@expo/osascript"));
12
+ const data = require("@expo/osascript");
13
13
  _osascript = function() {
14
14
  return data;
15
15
  };
@@ -95,8 +95,8 @@ async function waitForSimulatorAppToStart({ maxWaitTime } = {}) {
95
95
  // I think the app can be open while no simulators are booted.
96
96
  async function isSimulatorAppRunningAsync() {
97
97
  try {
98
- const zeroMeansNo = (await _osascript().execAsync('tell app "System Events" to count processes whose name is "Simulator"')).trim();
99
- if (zeroMeansNo === '0') {
98
+ const result = await (0, _osascript().spawnAsync)('tell app "System Events" to count processes whose name is "Simulator" or name is "DeviceHub"');
99
+ if (result.stdout.trim() === '0') {
100
100
  return false;
101
101
  }
102
102
  } catch (error) {
@@ -108,15 +108,30 @@ async function isSimulatorAppRunningAsync() {
108
108
  return true;
109
109
  }
110
110
  async function openSimulatorAppAsync(device) {
111
- const args = [
112
- '-a',
113
- 'Simulator'
114
- ];
115
- if (device.udid) {
116
- // This has no effect if the app is already running.
117
- args.push('--args', '-CurrentDeviceUDID', device.udid);
111
+ try {
112
+ const args = [
113
+ '-a',
114
+ 'Simulator'
115
+ ];
116
+ if (device.udid) {
117
+ // This has no effect if the app is already running.
118
+ args.push('--args', '-CurrentDeviceUDID', device.udid);
119
+ }
120
+ await (0, _spawnasync().default)('open', args);
121
+ } catch {
122
+ // Xcode 27+ replaces Simulator.app with DeviceHub, so `open -a Simulator` fails.
123
+ // DeviceHub registers the `devices://` URL scheme, which lets us focus the right
124
+ // device by its UDID — `open -a DeviceHub` can only bring the app forward.
125
+ const deviceHubArgs = device.udid ? [
126
+ `devices://device/open?id=${device.udid}`
127
+ ] : [
128
+ '-a',
129
+ 'DeviceHub'
130
+ ];
131
+ await (0, _spawnasync().default)('open', deviceHubArgs).catch(()=>{
132
+ // Noop - we can't do much more here
133
+ });
118
134
  }
119
- await (0, _spawnasync().default)('open', args);
120
135
  }
121
136
 
122
137
  //# sourceMappingURL=ensureSimulatorAppRunning.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/platforms/ios/ensureSimulatorAppRunning.ts"],"sourcesContent":["import * as osascript from '@expo/osascript';\nimport spawnAsync from '@expo/spawn-async';\n\nimport type { Device } from './simctl';\nimport * as Log from '../../../log';\nimport { waitForActionAsync } from '../../../utils/delay';\nimport { CommandError } from '../../../utils/errors';\n\n/** Open the Simulator.app and return when the system registers it as 'open'. */\nexport async function ensureSimulatorAppRunningAsync(\n device: Partial<Pick<Device, 'udid'>>,\n {\n maxWaitTime,\n }: {\n maxWaitTime?: number;\n } = {}\n): Promise<void> {\n if (await isSimulatorAppRunningAsync()) {\n return;\n }\n\n Log.log(`\\u203A Opening the iOS simulator, this might take a moment.`);\n\n // In theory this would ensure the correct simulator is booted as well.\n // This isn't theory though, this is Xcode.\n await openSimulatorAppAsync(device);\n\n if (!(await waitForSimulatorAppToStart({ maxWaitTime }))) {\n throw new CommandError(\n 'SIMULATOR_TIMEOUT',\n `Simulator app did not open fast enough. Try opening Simulator first, then running your app.`\n );\n }\n}\n\nasync function waitForSimulatorAppToStart({\n maxWaitTime,\n}: { maxWaitTime?: number } = {}): Promise<boolean> {\n return waitForActionAsync<boolean>({\n interval: 50,\n maxWaitTime,\n action: isSimulatorAppRunningAsync,\n });\n}\n\n// I think the app can be open while no simulators are booted.\nasync function isSimulatorAppRunningAsync(): Promise<boolean> {\n try {\n const zeroMeansNo = (\n await osascript.execAsync(\n 'tell app \"System Events\" to count processes whose name is \"Simulator\"'\n )\n ).trim();\n if (zeroMeansNo === '0') {\n return false;\n }\n } catch (error: any) {\n if (error.message.includes('Application isn’t running')) {\n return false;\n }\n throw error;\n }\n\n return true;\n}\n\nasync function openSimulatorAppAsync(device: { udid?: string }) {\n const args = ['-a', 'Simulator'];\n if (device.udid) {\n // This has no effect if the app is already running.\n args.push('--args', '-CurrentDeviceUDID', device.udid);\n }\n await spawnAsync('open', args);\n}\n"],"names":["ensureSimulatorAppRunningAsync","device","maxWaitTime","isSimulatorAppRunningAsync","Log","log","openSimulatorAppAsync","waitForSimulatorAppToStart","CommandError","waitForActionAsync","interval","action","zeroMeansNo","osascript","execAsync","trim","error","message","includes","args","udid","push","spawnAsync"],"mappings":";;;;+BASsBA;;;eAAAA;;;;iEATK;;;;;;;gEACJ;;;;;;6DAGF;uBACc;wBACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGtB,eAAeA,+BACpBC,MAAqC,EACrC,EACEC,WAAW,EAGZ,GAAG,CAAC,CAAC;IAEN,IAAI,MAAMC,8BAA8B;QACtC;IACF;IAEAC,KAAIC,GAAG,CAAC,CAAC,2DAA2D,CAAC;IAErE,uEAAuE;IACvE,2CAA2C;IAC3C,MAAMC,sBAAsBL;IAE5B,IAAI,CAAE,MAAMM,2BAA2B;QAAEL;IAAY,IAAK;QACxD,MAAM,IAAIM,oBAAY,CACpB,qBACA,CAAC,2FAA2F,CAAC;IAEjG;AACF;AAEA,eAAeD,2BAA2B,EACxCL,WAAW,EACc,GAAG,CAAC,CAAC;IAC9B,OAAOO,IAAAA,yBAAkB,EAAU;QACjCC,UAAU;QACVR;QACAS,QAAQR;IACV;AACF;AAEA,8DAA8D;AAC9D,eAAeA;IACb,IAAI;QACF,MAAMS,cAAc,AAClB,CAAA,MAAMC,aAAUC,SAAS,CACvB,wEACF,EACAC,IAAI;QACN,IAAIH,gBAAgB,KAAK;YACvB,OAAO;QACT;IACF,EAAE,OAAOI,OAAY;QACnB,IAAIA,MAAMC,OAAO,CAACC,QAAQ,CAAC,8BAA8B;YACvD,OAAO;QACT;QACA,MAAMF;IACR;IAEA,OAAO;AACT;AAEA,eAAeV,sBAAsBL,MAAyB;IAC5D,MAAMkB,OAAO;QAAC;QAAM;KAAY;IAChC,IAAIlB,OAAOmB,IAAI,EAAE;QACf,oDAAoD;QACpDD,KAAKE,IAAI,CAAC,UAAU,sBAAsBpB,OAAOmB,IAAI;IACvD;IACA,MAAME,IAAAA,qBAAU,EAAC,QAAQH;AAC3B"}
1
+ {"version":3,"sources":["../../../../../src/start/platforms/ios/ensureSimulatorAppRunning.ts"],"sourcesContent":["import { spawnAsync as spawnAppleScriptAsync } from '@expo/osascript';\nimport spawnAsync from '@expo/spawn-async';\n\nimport type { Device } from './simctl';\nimport * as Log from '../../../log';\nimport { waitForActionAsync } from '../../../utils/delay';\nimport { CommandError } from '../../../utils/errors';\n\n/** Open the Simulator.app and return when the system registers it as 'open'. */\nexport async function ensureSimulatorAppRunningAsync(\n device: Partial<Pick<Device, 'udid'>>,\n {\n maxWaitTime,\n }: {\n maxWaitTime?: number;\n } = {}\n): Promise<void> {\n if (await isSimulatorAppRunningAsync()) {\n return;\n }\n\n Log.log(`\\u203A Opening the iOS simulator, this might take a moment.`);\n\n // In theory this would ensure the correct simulator is booted as well.\n // This isn't theory though, this is Xcode.\n await openSimulatorAppAsync(device);\n\n if (!(await waitForSimulatorAppToStart({ maxWaitTime }))) {\n throw new CommandError(\n 'SIMULATOR_TIMEOUT',\n `Simulator app did not open fast enough. Try opening Simulator first, then running your app.`\n );\n }\n}\n\nasync function waitForSimulatorAppToStart({\n maxWaitTime,\n}: { maxWaitTime?: number } = {}): Promise<boolean> {\n return waitForActionAsync<boolean>({\n interval: 50,\n maxWaitTime,\n action: isSimulatorAppRunningAsync,\n });\n}\n\n// I think the app can be open while no simulators are booted.\nasync function isSimulatorAppRunningAsync(): Promise<boolean> {\n try {\n const result = await spawnAppleScriptAsync(\n 'tell app \"System Events\" to count processes whose name is \"Simulator\" or name is \"DeviceHub\"'\n );\n if (result.stdout.trim() === '0') {\n return false;\n }\n } catch (error: any) {\n if (error.message.includes('Application isn’t running')) {\n return false;\n }\n throw error;\n }\n\n return true;\n}\n\nasync function openSimulatorAppAsync(device: { udid?: string }) {\n try {\n const args = ['-a', 'Simulator'];\n if (device.udid) {\n // This has no effect if the app is already running.\n args.push('--args', '-CurrentDeviceUDID', device.udid);\n }\n await spawnAsync('open', args);\n } catch {\n // Xcode 27+ replaces Simulator.app with DeviceHub, so `open -a Simulator` fails.\n // DeviceHub registers the `devices://` URL scheme, which lets us focus the right\n // device by its UDID — `open -a DeviceHub` can only bring the app forward.\n const deviceHubArgs = device.udid\n ? [`devices://device/open?id=${device.udid}`]\n : ['-a', 'DeviceHub'];\n await spawnAsync('open', deviceHubArgs).catch(() => {\n // Noop - we can't do much more here\n });\n }\n}\n"],"names":["ensureSimulatorAppRunningAsync","device","maxWaitTime","isSimulatorAppRunningAsync","Log","log","openSimulatorAppAsync","waitForSimulatorAppToStart","CommandError","waitForActionAsync","interval","action","result","spawnAppleScriptAsync","stdout","trim","error","message","includes","args","udid","push","spawnAsync","deviceHubArgs","catch"],"mappings":";;;;+BASsBA;;;eAAAA;;;;yBAT8B;;;;;;;gEAC7B;;;;;;6DAGF;uBACc;wBACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGtB,eAAeA,+BACpBC,MAAqC,EACrC,EACEC,WAAW,EAGZ,GAAG,CAAC,CAAC;IAEN,IAAI,MAAMC,8BAA8B;QACtC;IACF;IAEAC,KAAIC,GAAG,CAAC,CAAC,2DAA2D,CAAC;IAErE,uEAAuE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+ 'macos'
56
58
  ];
57
59
  const escapeDependencyName = (dependency)=>dependency.replace(/[*.?()[\]]/g, (x)=>`\\${x}`);
58
60
  const _dependenciesToRegex = (dependencies)=>new RegExp(`^(${dependencies.map(escapeDependencyName).join('|')})($|/.*)`);
59
61
  const getAutolinkingExports = ()=>require('expo/internal/unstable-autolinking-exports');
60
- const toPlatformModuleDescription = (dependencies, platform)=>{
62
+ const toPlatformModuleDescription = (dependencies, platform, supportPackage)=>{
61
63
  const resolvedModulePaths = {};
62
64
  const resolvedModuleNames = [];
63
65
  for(const dependencyName in dependencies){
@@ -67,11 +69,17 @@ const toPlatformModuleDescription = (dependencies, platform)=>{
67
69
  resolvedModulePaths[dependency.name] = dependency.path;
68
70
  }
69
71
  }
72
+ // Redirect `react-native` to the platform's support package
73
+ const moduleNameRewrites = {};
74
+ if (supportPackage && supportPackage !== 'react-native' && resolvedModulePaths[supportPackage]) {
75
+ moduleNameRewrites['react-native'] = supportPackage;
76
+ }
70
77
  debug(`Sticky resolution for ${platform} registered ${resolvedModuleNames.length} resolutions:`, resolvedModuleNames);
71
78
  return {
72
79
  platform,
73
80
  moduleTestRe: _dependenciesToRegex(resolvedModuleNames),
74
- resolvedModulePaths
81
+ resolvedModulePaths,
82
+ moduleNameRewrites
75
83
  };
76
84
  };
77
85
  async function createAutolinkingModuleResolverInput({ platforms, projectRoot }) {
@@ -83,7 +91,8 @@ async function createAutolinkingModuleResolverInput({ platforms, projectRoot })
83
91
  return AUTOLINKING_PLATFORMS.includes(platform);
84
92
  }).map(async (platform)=>{
85
93
  const dependencies = await autolinking.scanDependencyResolutionsForPlatform(linker, platform, KNOWN_STICKY_DEPENDENCIES);
86
- const moduleDescription = toPlatformModuleDescription(dependencies, platform);
94
+ const supportPackage = autolinking.getSupportPackageForPlatform(platform);
95
+ const moduleDescription = toPlatformModuleDescription(dependencies, platform, supportPackage);
87
96
  return [
88
97
  platform,
89
98
  moduleDescription
@@ -108,15 +117,19 @@ function createAutolinkingModuleResolver(input, { getStrictResolver }) {
108
117
  const moduleDescription = input[platform];
109
118
  const moduleMatch = moduleDescription.moduleTestRe.exec(moduleName);
110
119
  if (moduleMatch) {
111
- const resolvedModulePath = moduleDescription.resolvedModulePaths[moduleMatch[1]] || moduleName;
112
- // We instead resolve as if it was a dependency from within the module (self-require/import)
120
+ var _moduleDescription_moduleNameRewrites;
121
+ const matchedName = moduleMatch[1];
122
+ const rewriteTarget = (_moduleDescription_moduleNameRewrites = moduleDescription.moduleNameRewrites) == null ? void 0 : _moduleDescription_moduleNameRewrites[matchedName];
123
+ const resolvedModuleName = rewriteTarget != null ? rewriteTarget + moduleMatch[2] : moduleName;
124
+ const resolvedModulePath = moduleDescription.resolvedModulePaths[rewriteTarget ?? matchedName] || resolvedModuleName;
125
+ // We instead resolve as if it was a dependency from within the (target) module
113
126
  const context = {
114
127
  ...immutableContext,
115
128
  nodeModulesPaths: [],
116
129
  originModulePath: resolvedModulePath
117
130
  };
118
- const res = getStrictResolver(context, platform)(moduleName);
119
- debug(`Sticky resolution for ${platform}: ${moduleName} -> from: ${resolvedModulePath}`);
131
+ const res = getStrictResolver(context, platform)(resolvedModuleName);
132
+ debug(`Sticky resolution for ${platform}: ${moduleName} -> ${resolvedModuleName} (from: ${resolvedModulePath})`);
120
133
  return res;
121
134
  }
122
135
  return null;
@@ -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 // NOTE: We may redirect dependencies from react-native to react-native-web. This fails if\n // a sub-dependency cannot access react-native-web, so we define it here\n 'react-native-web',\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 // Has a context that needs to be deduplicated\n '@react-navigation/core',\n '@react-navigation/native',\n];\n\nconst AUTOLINKING_PLATFORMS = ['android', 'ios', 'web'] as const;\n\nexport type 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":";;;;;;;;;;;QAgDaA;eAAAA;;QAwEGC;eAAAA;;QAhCMC;eAAAA;;;AAlFtB,MAAMC,QAAQC,QAAQ,SACpB;AAGF,iFAAiF;AACjF,qGAAqG;AACrG,MAAMC,4BAA4B;IAChC,4FAA4F;IAC5F;IACA;IACA,wEAAwE;IACxE,4FAA4F;IAC5F;IACA,0FAA0F;IAC1F,wEAAwE;IACxE;IACA,8BAA8B;IAC9B;IACA;IACA,yBAAyB;IACzB;IACA;IACA;IACA;IACA;IACA;IACA,qCAAqC;IACrC;IACA;IACA,8CAA8C;IAC9C;IACA;CACD;AAED,MAAMC,wBAAwB;IAAC;IAAW;IAAO;CAAM;AAIvD,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,s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7B,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,CAAE,IAAIF;YAC5D,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"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/createExpoAutolinkingResolver.ts"],"sourcesContent":["import type { Platform } from '@expo/config';\nimport 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 // NOTE: We may redirect dependencies from react-native to react-native-web. This fails if\n // a sub-dependency cannot access react-native-web, so we define it here\n 'react-native-web',\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 // Has a context that needs to be deduplicated\n '@react-navigation/core',\n '@react-navigation/native',\n];\n\nconst AUTOLINKING_PLATFORMS: readonly Platform[] = ['android', 'ios', 'web', 'tvos', 'macos'];\n\nexport type AutolinkingPlatform = Platform;\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 moduleNameRewrites: Record<string, string | undefined>;\n}\n\nconst toPlatformModuleDescription = (\n dependencies: AutolinkingResolutionResult,\n platform: AutolinkingPlatform,\n supportPackage: string | null\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 // Redirect `react-native` to the platform's support package\n const moduleNameRewrites: Record<string, string | undefined> = {};\n if (supportPackage && supportPackage !== 'react-native' && resolvedModulePaths[supportPackage]) {\n moduleNameRewrites['react-native'] = supportPackage;\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 moduleNameRewrites,\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 supportPackage = autolinking.getSupportPackageForPlatform(platform);\n const moduleDescription = toPlatformModuleDescription(\n dependencies,\n platform,\n supportPackage\n );\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 matchedName = moduleMatch[1]!;\n const rewriteTarget = moduleDescription.moduleNameRewrites?.[matchedName];\n const resolvedModuleName =\n rewriteTarget != null ? rewriteTarget + moduleMatch[2]! : moduleName;\n const resolvedModulePath =\n moduleDescription.resolvedModulePaths[rewriteTarget ?? matchedName] || resolvedModuleName;\n // We instead resolve as if it was a dependency from within the (target) module\n const context: ResolutionContext = {\n ...immutableContext,\n nodeModulesPaths: [],\n originModulePath: resolvedModulePath,\n };\n const res = getStrictResolver(context, platform)(resolvedModuleName);\n debug(\n `Sticky resolution for ${platform}: ${moduleName} -> ${resolvedModuleName} (from: ${resolvedModulePath})`\n );\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","supportPackage","resolvedModulePaths","resolvedModuleNames","dependencyName","push","name","path","moduleNameRewrites","length","moduleTestRe","platforms","projectRoot","autolinking","linker","makeCachedDependenciesLinker","Object","fromEntries","Promise","all","filter","includes","scanDependencyResolutionsForPlatform","getSupportPackageForPlatform","moduleDescription","input","getStrictResolver","undefined","fileSpecifierRe","isAutolinkingPlatform","requestStickyModule","immutableContext","moduleName","test","moduleMatch","exec","matchedName","rewriteTarget","resolvedModuleName","resolvedModulePath","context","nodeModulesPaths","originModulePath","res"],"mappings":";;;;;;;;;;;QAiDaA;eAAAA;;QAqFGC;eAAAA;;QArCMC;eAAAA;;;AA1FtB,MAAMC,QAAQC,QAAQ,SACpB;AAGF,iFAAiF;AACjF,qGAAqG;AACrG,MAAMC,4BAA4B;IAChC,4FAA4F;IAC5F;IACA;IACA,wEAAwE;IACxE,4FAA4F;IAC5F;IACA,0FAA0F;IAC1F,wEAAwE;IACxE;IACA,8BAA8B;IAC9B;IACA;IACA,yBAAyB;IACzB;IACA;IACA;IACA;IAC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MACE,CAAC,sBAAsB,EAAEc,SAAS,EAAE,EAAEgC,WAAW,IAAI,EAAEM,mBAAmB,QAAQ,EAAEC,mBAAmB,CAAC,CAAC;YAE3G,OAAOI;QACT;QAEA,OAAO;IACT;AACF"}
@@ -201,8 +201,11 @@ async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, ge
201
201
  // folder is different (presumably a parent) we're in a monorepo
202
202
  const serverRoot = (0, _paths().getMetroServerRoot)(projectRoot);
203
203
  const isWorkspace = serverRoot !== projectRoot;
204
- // Autolinking Module Resolution will be enabled by default when we're in a monorepo
205
- const autolinkingModuleResolutionEnabled = ((_exp_experiments = exp.experiments) == null ? void 0 : _exp_experiments.autolinkingModuleResolution) ?? isWorkspace;
204
+ // Out-of-tree platforms (tvos/macos) rely on the autolinking module resolver to remap the
205
+ // react-native package to their support package, and require autolinking module resolution
206
+ const targetsOutOfTreePlatform = (0, _config().getPlatformsFromConfig)(projectRoot, exp).some((platform)=>platform === 'tvos' || platform === 'macos');
207
+ // Autolinking Module Resolution is enabled by default in a monorepo or for out-of-tree platforms.
208
+ const autolinkingModuleResolutionEnabled = ((_exp_experiments = exp.experiments) == null ? void 0 : _exp_experiments.autolinkingModuleResolution) ?? (isWorkspace || targetsOutOfTreePlatform);
206
209
  const serverActionsEnabled = ((_exp_experiments1 = exp.experiments) == null ? void 0 : _exp_experiments1.reactServerFunctions) ?? _env.env.EXPO_UNSTABLE_SERVER_FUNCTIONS;
207
210
  const serverComponentsEnabled = !!((_exp_experiments2 = exp.experiments) == null ? void 0 : _exp_experiments2.reactServerComponentRoutes);
208
211
  if (serverActionsEnabled) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { Reporter } from '@expo/metro/metro';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport type { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport type MetroHmrServer 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 { Terminal } from '@expo/metro/metro-core';\nimport type { createStableModuleIdFactory } from '@expo/metro-config';\nimport { loadUserConfig } from '@expo/metro-config';\nimport { patchTransformFileForPackedMaps } from '@expo/metro-config/build/serializer/packedMap';\nimport { patchMetroSourceMapStringForPackedMaps } from '@expo/metro-config/build/serializer/sourceMap';\nimport chalk from 'chalk';\nimport type http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport type { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { replaceMetroFileMap } from './createFileMap-fork';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer, type ServerAddressInfo, type SecureServerOptions } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { events, shouldReduceLogs } from '../../../events';\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// prettier-ignore\nexport const event = events('metro', (t) => [\n t.event<'config', {\n serverRoot: string;\n projectRoot: string;\n exporting: boolean;\n flags: {\n autolinkingModuleResolution: boolean;\n serverActions: boolean;\n serverComponents: boolean;\n reactCompiler: boolean;\n optimizeGraph?: boolean;\n treeshaking?: boolean;\n logbox?: boolean;\n };\n }>(),\n t.event<'instantiate', {\n atlas: boolean;\n workers: number | null;\n host: string | null;\n port: number | null;\n }>(),\n]);\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/**\n * Extends Metro's Terminal to intercept all console methods so they don't\n * corrupt the progress bar status lines.\n *\n * console.log/info are routed through terminal.log() (stdout, managed).\n * console.warn/error are routed through logStderr() which clears the\n * status from stdout before writing to stderr, then restores it.\n * Without this, unmanaged stderr writes shift the cursor and cause\n * progress bars to get stuck as permanent output.\n */\nclass LogRespectingTerminal extends Terminal {\n #stderrQueue: string[] = [];\n #drainingStderr = false;\n\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 const sendStderr = (...msg: any[]) => {\n if (!msg.length) {\n this.logStderr('');\n } else {\n const [format, ...args] = msg;\n this.logStderr(require('util').format(format, ...args));\n }\n };\n\n console.log = sendLog;\n console.info = sendLog;\n console.warn = sendStderr;\n console.error = sendStderr;\n\n // NOTE(@kitten): We flush the stderr queue immediately when we're about to exit\n process.on('exit', () => {\n if (!this.#drainingStderr && this.#stderrQueue.length) {\n this.#drainingStderr = true;\n this.status('');\n const lines = this.#stderrQueue.splice(0);\n process.stderr.write(lines.join('\\n') + '\\n');\n }\n });\n }\n\n /** Write to stderr without corrupting Terminal's cursor tracking. */\n logStderr(line: string): void {\n if (!(process.stdout as any).isTTY) {\n process.stderr.write(line + '\\n');\n return;\n }\n this.#stderrQueue.push(line);\n this.#drainStderr();\n }\n\n async #drainStderr(): Promise<void> {\n if (this.#drainingStderr) return;\n this.#drainingStderr = true;\n\n while (this.#stderrQueue.length > 0) {\n // Clear status, flush to ensure it's removed from screen\n const prev = this.status('');\n await this.flush();\n\n // Write to stderr while status is cleared\n const lines = this.#stderrQueue.splice(0);\n process.stderr.write(lines.join('\\n') + '\\n');\n\n // Restore status\n this.status(prev);\n }\n\n this.#drainingStderr = false;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\ninterface LoadMetroConfigOptions {\n maxWorkers?: number;\n port?: number;\n reporter?: Reporter;\n resetCache?: boolean;\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadMetroConfigOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n // We're resolving a monorepo root, higher up than the `projectRoot`. If this\n // folder is different (presumably a parent) we're in a monorepo\n const serverRoot = getMetroServerRoot(projectRoot);\n const isWorkspace = serverRoot !== projectRoot;\n\n // Autolinking Module Resolution will be enabled by default when we're in a monorepo\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? isWorkspace;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n const serverComponentsEnabled = !!exp.experiments?.reactServerComponentRoutes;\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 (serverComponentsEnabled || 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 terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n let config = await loadUserConfig({\n projectRoot,\n serverRoot,\n // NOTE: Allow external tools to override the metro config. This is considered internal and unstable\n overrideConfigPath: env.EXPO_OVERRIDE_METRO_CONFIG ?? undefined,\n });\n\n config = {\n ...config,\n // See: `overrideConfigWithArguments` https://github.com/facebook/metro/blob/5059e26/packages/metro-config/src/loadConfig.js#L274-L339\n // Compare to `LoadOptions` type (disregard `reporter` as we don't expose this)\n resetCache: !!options.resetCache,\n maxWorkers: options.maxWorkers ?? config.maxWorkers,\n server: {\n ...config.server,\n port: options.port ?? config.server.port,\n },\n // Force-override the reporter\n reporter: {\n update(event) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n // On-Demand Filesystem is enabled by default\n // TODO(@kitten): Add to config-types JSON schema\n const onDemandFilesystem = exp.experiments?.onDemandFilesystem ?? true;\n asWritable(config.resolver).unstable_onDemandFilesystem = onDemandFilesystem;\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 const reduceLogs = shouldReduceLogs();\n\n const reactCompilerEnabled = !!exp.experiments?.reactCompiler;\n if (!reduceLogs && reactCompilerEnabled) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (!reduceLogs && autolinkingModuleResolutionEnabled) {\n Log.log(chalk.gray`Expo Autolinking module resolution 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 (!reduceLogs && env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n\n if (!reduceLogs && 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 serverRoot,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: serverComponentsEnabled,\n getMetroBundler,\n });\n\n event('config', {\n serverRoot: event.path(serverRoot),\n projectRoot: event.path(projectRoot),\n exporting: isExporting,\n flags: {\n autolinkingModuleResolution: autolinkingModuleResolutionEnabled,\n serverActions: serverActionsEnabled,\n serverComponents: serverComponentsEnabled,\n reactCompiler: reactCompilerEnabled,\n optimizeGraph: env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH,\n treeshaking: env.EXPO_UNSTABLE_TREE_SHAKING,\n logbox: env.EXPO_UNSTABLE_LOG_BOX,\n },\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\ninterface InstantiateMetroConfigOptions extends LoadMetroConfigOptions {\n host?: string;\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: InstantiateMetroConfigOptions,\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 address: ServerAddressInfo | null;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n const getMetroBundler = () => metro.getBundler().getBundler();\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler,\n });\n\n // Get local URL to Metro bundler server (typically configured as 127.0.0.1:8081)\n const serverBaseUrl = metroBundler\n .getUrlCreator()\n .constructUrl({ scheme: 'http', hostType: 'localhost' });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } = createMetroMiddleware(\n metroConfig,\n { getMetroBundler, serverBaseUrl }\n );\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware({\n serverBaseUrl,\n reporter,\n });\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware({ serverBaseUrl }));\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n asWritable(metroConfig.server).enhanceMiddleware = (\n metroMiddleware: any,\n server: MetroServer\n ) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n\n const devtoolsWebsocketEndpoints = createDevToolsPluginWebsocketEndpoint();\n Object.assign(websocketEndpoints, devtoolsWebsocketEndpoints);\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n // Support HTTPS based on the metro's tls server config\n // TODO(@kitten): Remove cast once `@expo/metro` is updated to a Metro version that supports the tls config\n const tls = (metroConfig.server as typeof metroConfig.server & { tls?: SecureServerOptions })\n ?.tls;\n const secureServerOptions = tls\n ? {\n key: tls.key,\n cert: tls.cert,\n ca: tls.ca,\n requestCert: tls.requestCert,\n }\n : undefined;\n\n const watch = !isExporting && isWatchEnabled();\n\n const { address, server, hmrServer, metro } = await replaceMetroFileMap(() => {\n return runServer(\n metroBundler,\n metroConfig,\n {\n host: options.host,\n websocketEndpoints,\n watch,\n secureServerOptions,\n },\n {\n mockServer: isExporting,\n }\n );\n });\n\n event('instantiate', {\n atlas: env.EXPO_ATLAS,\n workers: metroConfig.maxWorkers ?? null,\n host: address?.address ?? null,\n port: address?.port ?? null,\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 // Layered on top of the prune patch above. Both fresh worker results\n // and cache hits flow through `Bundler.transformFile`, so wrapping\n // here covers both.\n patchTransformFileForPackedMaps(metro.getBundler().getBundler());\n patchMetroSourceMapStringForPackedMaps();\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 address,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const resolvedRouterRoot = path.resolve(projectRoot, routerRoot).split(path.sep).join('/');\n const isRouterRoute = path.isAbsolute(filePath) && filePath.startsWith(resolvedRouterRoot);\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["event","instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","events","t","asWritable","input","LogRespectingTerminal","Terminal","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","sendStderr","logStderr","require","console","info","warn","error","process","on","status","lines","splice","stderr","write","join","line","stdout","isTTY","push","prev","terminal","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","serverRoot","getMetroServerRoot","isWorkspace","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","serverActionsEnabled","reactServerFunctions","env","EXPO_UNSTABLE_SERVER_FUNCTIONS","serverComponentsEnabled","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","terminalReporter","MetroTerminalReporter","loadUserConfig","overrideConfigPath","EXPO_OVERRIDE_METRO_CONFIG","undefined","resetCache","maxWorkers","server","port","reporter","update","onDemandFilesystem","resolver","unstable_onDemandFilesystem","globalThis","__requireCycleIgnorePatterns","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reduceLogs","shouldReduceLogs","reactCompilerEnabled","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","path","exporting","flags","serverActions","serverComponents","optimizeGraph","treeshaking","logbox","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","serverBaseUrl","getUrlCreator","constructUrl","scheme","hostType","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","devtoolsWebsocketEndpoints","createDevToolsPluginWebsocketEndpoint","attachAtlasAsync","resetAtlasFile","tls","secureServerOptions","key","cert","ca","requestCert","watch","address","hmrServer","replaceMetroFileMap","runServer","host","mockServer","atlas","EXPO_ATLAS","workers","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","patchTransformFileForPackedMaps","patchMetroSourceMapStringForPackedMaps","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","sort","a","b","hmrJSBundle","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","formattedError","messageSocket","split","sep","dom","match","routerRoot","isRouterEntry","test","isRouterModule","resolvedRouterRoot","resolve","isRouterRoute","isAbsolute","startsWith","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;QAuCaA;eAAAA;;QAySSC;eAAAA;;QAyUNC;eAAAA;;QAreMC;eAAAA;;;;yBApLqB;;;;;;;yBACR;;;;;;;gEAOD;;;;;;;gEAEF;;;;;;;yBACP;;;;;;;yBAEM;;;;;;;yBACiB;;;;;;;yBACO;;;;;;;gEACrC;;;;;;;gEAED;;;;;;iDAEqC;uCAEhB;mCACF;6BACH;uCACK;uCACA;+BACsC;wCAChC;wBACH;qBACrB;qBACA;wBACS;gCACQ;6CACO;2BACV;kCACE;;;;;;AAG7B,MAAMH,QAAQI,IAAAA,cAAM,EAAC,SAAS,CAACC,IAAM;QAC1CA,EAAEL,KAAK;QAcPK,EAAEL,KAAK;KAMR;AAsBD,SAASM,WAAcC,KAAQ;IAC7B,OAAOA;AACT;AAEA;;;;;;;;;CASC,GACD,MAAMC,8B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,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyCwE,WAAW,KACpD,+IAA+I;IAC/I,CAAEzE,CAAAA,SAAS+D,KAAK,CAAC,0BAA0B/D,SAAS+D,KAAK,CAAC,yBAAwB,GAClF;QACA,OAAO9D,iBAAiBG,sBAAsB,CAACqE,WAAW;IAC5D;IAEA,IACExE,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyCyE,gBAAgB,KACzD,2FAA2F;IAC3F,CAAC1E,SAAS+D,KAAK,CAAC,8BAChB;QACA,OAAO9D,iBAAiBG,sBAAsB,CAACsE,gBAAgB;IACjE;IAEA,OAAOzE;AACT;AAMO,SAASjK;IACd,IAAIqD,QAAG,CAACsL,EAAE,EAAE;QACVhL,QAAG,CAAC9C,GAAG,CACL0E,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAAClC,QAAG,CAACsL,EAAE;AAChB"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig, getPlatformsFromConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { Reporter } from '@expo/metro/metro';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport type { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport type MetroHmrServer 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 { Terminal } from '@expo/metro/metro-core';\nimport type { createStableModuleIdFactory } from '@expo/metro-config';\nimport { loadUserConfig } from '@expo/metro-config';\nimport { patchTransformFileForPackedMaps } from '@expo/metro-config/build/serializer/packedMap';\nimport { patchMetroSourceMapStringForPackedMaps } from '@expo/metro-config/build/serializer/sourceMap';\nimport chalk from 'chalk';\nimport type http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport type { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { replaceMetroFileMap } from './createFileMap-fork';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer, type ServerAddressInfo, type SecureServerOptions } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { events, shouldReduceLogs } from '../../../events';\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// prettier-ignore\nexport const event = events('metro', (t) => [\n t.event<'config', {\n serverRoot: string;\n projectRoot: string;\n exporting: boolean;\n flags: {\n autolinkingModuleResolution: boolean;\n serverActions: boolean;\n serverComponents: boolean;\n reactCompiler: boolean;\n optimizeGraph?: boolean;\n treeshaking?: boolean;\n logbox?: boolean;\n };\n }>(),\n t.event<'instantiate', {\n atlas: boolean;\n workers: number | null;\n host: string | null;\n port: number | null;\n }>(),\n]);\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/**\n * Extends Metro's Terminal to intercept all console methods so they don't\n * corrupt the progress bar status lines.\n *\n * console.log/info are routed through terminal.log() (stdout, managed).\n * console.warn/error are routed through logStderr() which clears the\n * status from stdout before writing to stderr, then restores it.\n * Without this, unmanaged stderr writes shift the cursor and cause\n * progress bars to get stuck as permanent output.\n */\nclass LogRespectingTerminal extends Terminal {\n #stderrQueue: string[] = [];\n #drainingStderr = false;\n\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 const sendStderr = (...msg: any[]) => {\n if (!msg.length) {\n this.logStderr('');\n } else {\n const [format, ...args] = msg;\n this.logStderr(require('util').format(format, ...args));\n }\n };\n\n console.log = sendLog;\n console.info = sendLog;\n console.warn = sendStderr;\n console.error = sendStderr;\n\n // NOTE(@kitten): We flush the stderr queue immediately when we're about to exit\n process.on('exit', () => {\n if (!this.#drainingStderr && this.#stderrQueue.length) {\n this.#drainingStderr = true;\n this.status('');\n const lines = this.#stderrQueue.splice(0);\n process.stderr.write(lines.join('\\n') + '\\n');\n }\n });\n }\n\n /** Write to stderr without corrupting Terminal's cursor tracking. */\n logStderr(line: string): void {\n if (!(process.stdout as any).isTTY) {\n process.stderr.write(line + '\\n');\n return;\n }\n this.#stderrQueue.push(line);\n this.#drainStderr();\n }\n\n async #drainStderr(): Promise<void> {\n if (this.#drainingStderr) return;\n this.#drainingStderr = true;\n\n while (this.#stderrQueue.length > 0) {\n // Clear status, flush to ensure it's removed from screen\n const prev = this.status('');\n await this.flush();\n\n // Write to stderr while status is cleared\n const lines = this.#stderrQueue.splice(0);\n process.stderr.write(lines.join('\\n') + '\\n');\n\n // Restore status\n this.status(prev);\n }\n\n this.#drainingStderr = false;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\ninterface LoadMetroConfigOptions {\n maxWorkers?: number;\n port?: number;\n reporter?: Reporter;\n resetCache?: boolean;\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadMetroConfigOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n // We're resolving a monorepo root, higher up than the `projectRoot`. If this\n // folder is different (presumably a parent) we're in a monorepo\n const serverRoot = getMetroServerRoot(projectRoot);\n const isWorkspace = serverRoot !== projectRoot;\n\n // Out-of-tree platforms (tvos/macos) rely on the autolinking module resolver to remap the\n // react-native package to their support package, and require autolinking module resolution\n const targetsOutOfTreePlatform = getPlatformsFromConfig(projectRoot, exp).some(\n (platform) => platform === 'tvos' || platform === 'macos'\n );\n\n // Autolinking Module Resolution is enabled by default in a monorepo or for out-of-tree platforms.\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? (isWorkspace || targetsOutOfTreePlatform);\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n const serverComponentsEnabled = !!exp.experiments?.reactServerComponentRoutes;\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 (serverComponentsEnabled || 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 terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n let config = await loadUserConfig({\n projectRoot,\n serverRoot,\n // NOTE: Allow external tools to override the metro config. This is considered internal and unstable\n overrideConfigPath: env.EXPO_OVERRIDE_METRO_CONFIG ?? undefined,\n });\n\n config = {\n ...config,\n // See: `overrideConfigWithArguments` https://github.com/facebook/metro/blob/5059e26/packages/metro-config/src/loadConfig.js#L274-L339\n // Compare to `LoadOptions` type (disregard `reporter` as we don't expose this)\n resetCache: !!options.resetCache,\n maxWorkers: options.maxWorkers ?? config.maxWorkers,\n server: {\n ...config.server,\n port: options.port ?? config.server.port,\n },\n // Force-override the reporter\n reporter: {\n update(event) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n // On-Demand Filesystem is enabled by default\n // TODO(@kitten): Add to config-types JSON schema\n const onDemandFilesystem = exp.experiments?.onDemandFilesystem ?? true;\n asWritable(config.resolver).unstable_onDemandFilesystem = onDemandFilesystem;\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 const reduceLogs = shouldReduceLogs();\n\n const reactCompilerEnabled = !!exp.experiments?.reactCompiler;\n if (!reduceLogs && reactCompilerEnabled) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (!reduceLogs && autolinkingModuleResolutionEnabled) {\n Log.log(chalk.gray`Expo Autolinking module resolution 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 (!reduceLogs && env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n\n if (!reduceLogs && 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 serverRoot,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: serverComponentsEnabled,\n getMetroBundler,\n });\n\n event('config', {\n serverRoot: event.path(serverRoot),\n projectRoot: event.path(projectRoot),\n exporting: isExporting,\n flags: {\n autolinkingModuleResolution: autolinkingModuleResolutionEnabled,\n serverActions: serverActionsEnabled,\n serverComponents: serverComponentsEnabled,\n reactCompiler: reactCompilerEnabled,\n optimizeGraph: env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH,\n treeshaking: env.EXPO_UNSTABLE_TREE_SHAKING,\n logbox: env.EXPO_UNSTABLE_LOG_BOX,\n },\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\ninterface InstantiateMetroConfigOptions extends LoadMetroConfigOptions {\n host?: string;\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: InstantiateMetroConfigOptions,\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 address: ServerAddressInfo | null;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n const getMetroBundler = () => metro.getBundler().getBundler();\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler,\n });\n\n // Get local URL to Metro bundler server (typically configured as 127.0.0.1:8081)\n const serverBaseUrl = metroBundler\n .getUrlCreator()\n .constructUrl({ scheme: 'http', hostType: 'localhost' });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } = createMetroMiddleware(\n metroConfig,\n { getMetroBundler, serverBaseUrl }\n );\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware({\n serverBaseUrl,\n reporter,\n });\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware({ serverBaseUrl }));\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n asWritable(metroConfig.server).enhanceMiddleware = (\n metroMiddleware: any,\n server: MetroServer\n ) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n\n const devtoolsWebsocketEndpoints = createDevToolsPluginWebsocketEndpoint();\n Object.assign(websocketEndpoints, devtoolsWebsocketEndpoints);\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n // Support HTTPS based on the metro's tls server config\n // TODO(@kitten): Remove cast once `@expo/metro` is updated to a Metro version that supports the tls config\n const tls = (metroConfig.server as typeof metroConfig.server & { tls?: SecureServerOptions })\n ?.tls;\n const secureServerOptions = tls\n ? {\n key: tls.key,\n cert: tls.cert,\n ca: tls.ca,\n requestCert: tls.requestCert,\n }\n : undefined;\n\n const watch = !isExporting && isWatchEnabled();\n\n const { address, server, hmrServer, metro } = await replaceMetroFileMap(() => {\n return runServer(\n metroBundler,\n metroConfig,\n {\n host: options.host,\n websocketEndpoints,\n watch,\n secureServerOptions,\n },\n {\n mockServer: isExporting,\n }\n );\n });\n\n event('instantiate', {\n atlas: env.EXPO_ATLAS,\n workers: metroConfig.maxWorkers ?? null,\n host: address?.address ?? null,\n port: address?.port ?? null,\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 // Layered on top of the prune patch above. Both fresh worker results\n // and cache hits flow through `Bundler.transformFile`, so wrapping\n // here covers both.\n patchTransformFileForPackedMaps(metro.getBundler().getBundler());\n patchMetroSourceMapStringForPackedMaps();\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 address,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const resolvedRouterRoot = path.resolve(projectRoot, routerRoot).split(path.sep).join('/');\n const isRouterRoute = path.isAbsolute(filePath) && filePath.startsWith(resolvedRouterRoot);\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["event","instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","events","t","asWritable","input","LogRespectingTerminal","Terminal","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","sendStderr","logStderr","require","console","info","warn","error","process","on","status","lines","splice","stderr","write","join","line","stdout","isTTY","push","prev","terminal","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","serverRoot","getMetroServerRoot","isWorkspace","targetsOutOfTreePlatform","getPlatformsFromConfig","some","platform","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","serverActionsEnabled","reactServerFunctions","env","EXPO_UNSTABLE_SERVER_FUNCTIONS","serverComponentsEnabled","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","terminalReporter","MetroTerminalReporter","loadUserConfig","overrideConfigPath","EXPO_OVERRIDE_METRO_CONFIG","undefined","resetCache","maxWorkers","server","port","reporter","update","onDemandFilesystem","resolver","unstable_onDemandFilesystem","globalThis","__requireCycleIgnorePatterns","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reduceLogs","shouldReduceLogs","reactCompilerEnabled","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","path","exporting","flags","serverActions","serverComponents","optimizeGraph","treeshaking","logbox","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","serverBaseUrl","getUrlCreator","constructUrl","scheme","hostType","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","devtoolsWebsocketEndpoints","createDevToolsPluginWebsocketEndpoint","attachAtlasAsync","resetAtlasFile","tls","secureServerOptions","key","cert","ca","requestCert","watch","address","hmrServer","replaceMetroFileMap","runServer","host","mockServer","atlas","EXPO_ATLAS","workers","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","patchTransformFileForPackedMaps","patchMetroSourceMapStringForPackedMaps","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","environment","module","_createModuleId","sort","a","b","hmrJSBundle","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","formattedError","messageSocket","split","sep","dom","match","routerRoot","isRouterEntry","test","isRouterModule","resolvedRouterRoot","resolve","isRouterRoute","isAbsolute","startsWith","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;QAuCaA;eAAAA;;QA+SSC;eAAAA;;QAyUNC;eAAAA;;QA3eMC;eAAAA;;;;yBApL6C;;;;;;;yBAChC;;;;;;;gEAOD;;;;;;;gEAEF;;;;;;;yBACP;;;;;;;yBAEM;;;;;;;yBACiB;;;;;;;yBACO;;;;;;;gEACrC;;;;;;;gEAED;;;;;;iDAEqC;uCAEhB;mCACF;6BACH;uCACK;uCACA;+BACsC;wCAChC;wBACH;qBACrB;qBACA;wBACS;gCACQ;6CACO;2BACV;kCACE;;;;;;AAG7B,MAAMH,QAAQI,IAAAA,cAAM,EAAC,SAAS,CAACC,IAAM;QAC1CA,EAAEL,KAAK;QAcPK,EAAEL,KAAK;KAMR;AAsBD,SAASM,WAAcC,KAAQ;IAC7B,OAAOA;AACT;AAEA;;;;;;;;;CASC,GACD,MAAMC,8BAA8BC,qBAAQ;IAC1C,CAAA,WAAY,CAAgB;IAC5B,CAAA,cAAe,CAAS;IAExB,YAAYC,MAAkE,CAAE;QAC9E,KAAK,CAACA,QAAQ;YAAEC,UAAU;QAAK,SAJjC,CAAA,WAAY,GAAa,EAAE,OAC3B,CAA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,iBAAiBG,sBAAsB,qBAAvCH,0CAAyCuE,WAAW,KACpD,+IAA+I;IAC/I,CAAExE,CAAAA,SAAS8D,KAAK,CAAC,0BAA0B9D,SAAS8D,KAAK,CAAC,yBAAwB,GAClF;QACA,OAAO7D,iBAAiBG,sBAAsB,CAACoE,WAAW;IAC5D;IAEA,IACEvE,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyCwE,gBAAgB,KACzD,2FAA2F;IAC3F,CAACzE,SAAS8D,KAAK,CAAC,8BAChB;QACA,OAAO7D,iBAAiBG,sBAAsB,CAACqE,gBAAgB;IACjE;IAEA,OAAOxE;AACT;AAMO,SAASrK;IACd,IAAIyD,QAAG,CAACqL,EAAE,EAAE;QACV/K,QAAG,CAAClD,GAAG,CACL8E,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAAClC,QAAG,CAACqL,EAAE;AAChB"}
@@ -27,6 +27,20 @@ _export(exports, {
27
27
  return withMetroMultiPlatformAsync;
28
28
  }
29
29
  });
30
+ function _config() {
31
+ const data = require("@expo/config");
32
+ _config = function() {
33
+ return data;
34
+ };
35
+ return data;
36
+ }
37
+ function _paths() {
38
+ const data = require("@expo/config/paths");
39
+ _paths = function() {
40
+ return data;
41
+ };
42
+ return data;
43
+ }
30
44
  function _metroresolver() {
31
45
  const data = require("@expo/metro/metro-resolver");
32
46
  _metroresolver = function() {
@@ -74,10 +88,68 @@ function _interop_require_default(obj) {
74
88
  };
75
89
  }
76
90
  const ASSET_REGISTRY_SRC = `const assets=[];module.exports={registerAsset:s=>assets.push(s),getAssetByID:s=>assets[s-1]};`;
91
+ function constructPlatformExtensions(config) {
92
+ var _config_resolver;
93
+ const platformExtensions = Object.create(null);
94
+ // TODO(@kitten): Temporary internal override config for per-platform extensions
95
+ let unstable_platformExtensions;
96
+ if (config.resolver && 'unstable_platformExtensions' in config.resolver && config.resolver.unstable_platformExtensions && typeof config.resolver.unstable_platformExtensions === 'object') {
97
+ unstable_platformExtensions = config.resolver.unstable_platformExtensions;
98
+ }
99
+ for (const platform of ((_config_resolver = config.resolver) == null ? void 0 : _config_resolver.platforms) ?? []){
100
+ const customPlatformExtensions = unstable_platformExtensions == null ? void 0 : unstable_platformExtensions[platform];
101
+ const sourceExts = (0, _paths().getPlatformExtensions)(platform, config.resolver.sourceExts, customPlatformExtensions);
102
+ // Platform-less resolution drops the platform's package-exports conditions, so fold them in.
103
+ const unstable_conditionNames = [
104
+ ...config.resolver.unstable_conditionNames,
105
+ ...config.resolver.unstable_conditionsByPlatform[platform] ?? []
106
+ ];
107
+ if (sourceExts) {
108
+ platformExtensions[platform] = {
109
+ sourceExts,
110
+ unstable_conditionNames
111
+ };
112
+ }
113
+ }
114
+ return platformExtensions;
115
+ }
116
+ function resolveWithPlatformExtensions(platformExtensions, context, moduleName) {
117
+ const platformContext = asWritable(context);
118
+ platformContext.preferNativePlatform = false;
119
+ platformContext.sourceExts = platformExtensions.sourceExts;
120
+ platformContext.unstable_conditionNames = platformExtensions.unstable_conditionNames;
121
+ return (0, _metroresolver().resolve)(platformContext, moduleName, null);
122
+ }
77
123
  const debug = require('debug')('expo:start:server:metro:multi-platform');
78
124
  function asWritable(input) {
79
125
  return input;
80
126
  }
127
+ const _reactNativeHostPackages = new Map();
128
+ const _reactNativeHostPathPatterns = new Map();
129
+ function getReactNativeHostPackage(platform) {
130
+ if (!platform) {
131
+ return null;
132
+ }
133
+ let supportPackage = _reactNativeHostPackages.get(platform);
134
+ if (supportPackage === undefined) {
135
+ const { getSupportPackageForPlatform } = require('expo/internal/unstable-autolinking-exports');
136
+ supportPackage = getSupportPackageForPlatform(platform);
137
+ _reactNativeHostPackages.set(platform, supportPackage);
138
+ }
139
+ return supportPackage;
140
+ }
141
+ function getReactNativeHostPathPattern(platform) {
142
+ if (!platform) {
143
+ return null;
144
+ }
145
+ let pattern = _reactNativeHostPathPatterns.get(platform);
146
+ if (pattern === undefined) {
147
+ const supportPackage = getReactNativeHostPackage(platform);
148
+ pattern = supportPackage ? new RegExp(`[\\\\/]node_modules[\\\\/]${supportPackage}[\\\\/]`) : null;
149
+ _reactNativeHostPathPatterns.set(platform, pattern);
150
+ }
151
+ return pattern;
152
+ }
81
153
  function withWebPolyfills(config, { getMetroBundler }) {
82
154
  const originalGetPolyfills = config.serializer.getPolyfills ? config.serializer.getPolyfills.bind(config.serializer) : ()=>[];
83
155
  const getPolyfills = (ctx)=>{
@@ -211,9 +283,14 @@ function withExtendedResolver(config, { autolinkingModuleResolverInput, isTsconf
211
283
  ]
212
284
  };
213
285
  let nodejsSourceExtensions = null;
286
+ const platformExtensions = constructPlatformExtensions(config);
214
287
  const getStrictResolver = ({ resolveRequest, ...context }, platform)=>{
215
288
  return function doResolve(moduleName) {
216
- return (0, _metroresolver().resolve)(context, moduleName, platform);
289
+ if (platform != null && platformExtensions[platform]) {
290
+ return resolveWithPlatformExtensions(platformExtensions[platform], context, moduleName);
291
+ } else {
292
+ return (0, _metroresolver().resolve)(context, moduleName, platform);
293
+ }
217
294
  };
218
295
  };
219
296
  function getOptionalResolver(context, platform) {
@@ -309,10 +386,11 @@ function withExtendedResolver(config, { autolinkingModuleResolverInput, isTsconf
309
386
  const metroConfigWithCustomResolver = (0, _withMetroResolvers.withMetroResolvers)(config, [
310
387
  // Mock out production react imports in development.
311
388
  function requestDevMockProdReact(context, moduleName, platform) {
389
+ var _getReactNativeHostPathPattern;
312
390
  // This resolution is dev-only to prevent bundling the production React packages in development.
313
391
  if (!context.dev) return null;
314
- if (// Match react-native renderers.
315
- platform !== 'web' && context.originModulePath.match(/[\\/]node_modules[\\/]react-native[\\/]/) && moduleName.match(/([\\/]ReactFabric|ReactNativeRenderer)-prod/) || // Match react production imports.
392
+ if (// Match react-native renderers (in the platform's react-native host package).
393
+ platform !== 'web' && ((_getReactNativeHostPathPattern = getReactNativeHostPathPattern(platform)) == null ? void 0 : _getReactNativeHostPathPattern.test(context.originModulePath)) && moduleName.match(/([\\/]ReactFabric|ReactNativeRenderer)-prod/) || // Match react production imports.
316
394
  moduleName.match(/\.production(\.min)?\.js$/) && // Match if the import originated from a react package.
317
395
  context.originModulePath.match(/[\\/]node_modules[\\/](react[-\\/]|scheduler[\\/])/)) {
318
396
  debug(`Skipping production module: ${moduleName}`);
@@ -565,21 +643,22 @@ function withExtendedResolver(config, { autolinkingModuleResolverInput, isTsconf
565
643
  } else {
566
644
  var _context_customResolverOptions, _context_customResolverOptions1;
567
645
  const isServer = ((_context_customResolverOptions = context.customResolverOptions) == null ? void 0 : _context_customResolverOptions.environment) === 'node' || ((_context_customResolverOptions1 = context.customResolverOptions) == null ? void 0 : _context_customResolverOptions1.environment) === 'react-server';
646
+ const hostPackage = getReactNativeHostPackage(platform) ?? 'react-native';
568
647
  // Shim out React Native native runtime globals in server mode for native.
569
648
  if (isServer) {
570
- const emptyModule = doReplace('react-native/Libraries/Core/InitializeCore.js', undefined);
649
+ const emptyModule = doReplace(`${hostPackage}/Libraries/Core/InitializeCore.js`, undefined);
571
650
  if (emptyModule) {
572
651
  debug('Shimming out InitializeCore for React Native in native SSR bundle');
573
652
  return emptyModule;
574
653
  }
575
654
  }
576
- const hmrModule = doReplaceStrict('react-native/Libraries/Utilities/HMRClient.js', 'expo/src/async-require/hmr.ts');
655
+ const hmrModule = doReplaceStrict(`${hostPackage}/Libraries/Utilities/HMRClient.js`, 'expo/src/async-require/hmr.ts');
577
656
  if (hmrModule) return hmrModule;
578
657
  if (useExpoUnstableLogBox) {
579
658
  // TODO(@kitten): This can never resolve with isolated dependencies
580
- const logBoxModule = doReplace('react-native/Libraries/LogBox/LogBoxInspectorContainer.js', '@expo/log-box/swap-rn-logbox.js');
659
+ const logBoxModule = doReplace(`${hostPackage}/Libraries/LogBox/LogBoxInspectorContainer.js`, '@expo/log-box/swap-rn-logbox.js');
581
660
  if (logBoxModule) return logBoxModule;
582
- const logBoxParserModule = doReplace('react-native/Libraries/LogBox/Data/parseLogBoxLog.js', '@expo/log-box/swap-rn-logbox-parser.js');
661
+ const logBoxParserModule = doReplace(`${hostPackage}/Libraries/LogBox/Data/parseLogBoxLog.js`, '@expo/log-box/swap-rn-logbox-parser.js');
583
662
  if (logBoxParserModule) return logBoxParserModule;
584
663
  }
585
664
  }
@@ -716,10 +795,8 @@ async function withMetroMultiPlatformAsync(projectRoot, { config, exp, platformB
716
795
  watchFolders.push(_path().default.dirname(metroRequirePolyfill));
717
796
  // Required for @expo/metro-runtime to format paths in the web LogBox.
718
797
  process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;
719
- let expoConfigPlatforms = Object.entries(platformBundlers).filter(([platform, bundler])=>{
720
- var _exp_platforms;
721
- return bundler === 'metro' && ((_exp_platforms = exp.platforms) == null ? void 0 : _exp_platforms.includes(platform));
722
- }).map(([platform])=>platform);
798
+ const configPlatforms = (0, _config().getPlatformsFromConfig)(projectRoot, exp);
799
+ let expoConfigPlatforms = Object.entries(platformBundlers).filter(([platform, bundler])=>bundler === 'metro' && configPlatforms.includes(platform)).map(([platform])=>platform);
723
800
  if (Array.isArray(config.resolver.platforms)) {
724
801
  expoConfigPlatforms = [
725
802
  ...new Set(expoConfigPlatforms.concat(config.resolver.platforms))