@expo/cli 0.15.0 → 0.16.0

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 (148) hide show
  1. package/build/bin/cli +10 -3
  2. package/build/bin/cli.map +1 -1
  3. package/build/src/api/user/actions.js +1 -1
  4. package/build/src/api/user/actions.js.map +1 -1
  5. package/build/src/export/createMetadataJson.js +2 -1
  6. package/build/src/export/createMetadataJson.js.map +1 -1
  7. package/build/src/export/embed/exportEmbedAsync.js +50 -3
  8. package/build/src/export/embed/exportEmbedAsync.js.map +1 -1
  9. package/build/src/export/embed/xcodeCompilerLogger.js +97 -0
  10. package/build/src/export/embed/xcodeCompilerLogger.js.map +1 -0
  11. package/build/src/export/exportApp.js +90 -103
  12. package/build/src/export/exportApp.js.map +1 -1
  13. package/build/src/export/exportAssets.js +18 -23
  14. package/build/src/export/exportAssets.js.map +1 -1
  15. package/build/src/export/exportAsync.js +1 -1
  16. package/build/src/export/exportAsync.js.map +1 -1
  17. package/build/src/export/exportHermes.js +0 -90
  18. package/build/src/export/exportHermes.js.map +1 -1
  19. package/build/src/export/exportStaticAsync.js +137 -108
  20. package/build/src/export/exportStaticAsync.js.map +1 -1
  21. package/build/src/export/favicon.js +12 -4
  22. package/build/src/export/favicon.js.map +1 -1
  23. package/build/src/export/fork-bundleAsync.js +74 -49
  24. package/build/src/export/fork-bundleAsync.js.map +1 -1
  25. package/build/src/export/metroAssetLocalPath.js +1 -1
  26. package/build/src/export/metroAssetLocalPath.js.map +1 -1
  27. package/build/src/export/persistMetroAssets.js +28 -17
  28. package/build/src/export/persistMetroAssets.js.map +1 -1
  29. package/build/src/export/publicFolder.js +7 -0
  30. package/build/src/export/publicFolder.js.map +1 -1
  31. package/build/src/export/saveAssets.js +176 -12
  32. package/build/src/export/saveAssets.js.map +1 -1
  33. package/build/src/export/writeContents.js +8 -107
  34. package/build/src/export/writeContents.js.map +1 -1
  35. package/build/src/install/installAsync.js +29 -10
  36. package/build/src/install/installAsync.js.map +1 -1
  37. package/build/src/prebuild/prebuildAsync.js +9 -2
  38. package/build/src/prebuild/prebuildAsync.js.map +1 -1
  39. package/build/src/run/hints.js +4 -0
  40. package/build/src/run/hints.js.map +1 -1
  41. package/build/src/run/index.js +101 -0
  42. package/build/src/run/index.js.map +1 -0
  43. package/build/src/start/doctor/dependencies/bundledNativeModules.js +2 -2
  44. package/build/src/start/doctor/dependencies/bundledNativeModules.js.map +1 -1
  45. package/build/src/start/doctor/dependencies/getVersionedPackages.js +10 -3
  46. package/build/src/start/doctor/dependencies/getVersionedPackages.js.map +1 -1
  47. package/build/src/start/doctor/dependencies/resolvePackages.js +66 -0
  48. package/build/src/start/doctor/dependencies/resolvePackages.js.map +1 -0
  49. package/build/src/start/doctor/dependencies/validateDependenciesVersions.js +2 -30
  50. package/build/src/start/doctor/dependencies/validateDependenciesVersions.js.map +1 -1
  51. package/build/src/start/interface/interactiveActions.js +24 -8
  52. package/build/src/start/interface/interactiveActions.js.map +1 -1
  53. package/build/src/start/server/getStaticRenderFunctions.js +8 -4
  54. package/build/src/start/server/getStaticRenderFunctions.js.map +1 -1
  55. package/build/src/start/server/metro/MetroBundlerDevServer.js +39 -16
  56. package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
  57. package/build/src/start/server/metro/MetroTerminalReporter.js +6 -2
  58. package/build/src/start/server/metro/MetroTerminalReporter.js.map +1 -1
  59. package/build/src/start/server/metro/TerminalReporter.js +18 -1
  60. package/build/src/start/server/metro/TerminalReporter.js.map +1 -1
  61. package/build/src/start/server/metro/bundleApiRoutes.js +3 -2
  62. package/build/src/start/server/metro/bundleApiRoutes.js.map +1 -1
  63. package/build/src/start/server/metro/createExpoMetroResolver.js +22 -5
  64. package/build/src/start/server/metro/createExpoMetroResolver.js.map +1 -1
  65. package/build/src/start/server/metro/createJResolver.js +5 -2
  66. package/build/src/start/server/metro/createJResolver.js.map +1 -1
  67. package/build/src/start/server/metro/createServerRouteMiddleware.js +2 -1
  68. package/build/src/start/server/metro/createServerRouteMiddleware.js.map +1 -1
  69. package/build/src/start/server/metro/{inspector-proxy/device.js → debugging/InspectorDevice.js} +8 -38
  70. package/build/src/start/server/metro/debugging/InspectorDevice.js.map +1 -0
  71. package/build/src/start/server/metro/debugging/InspectorProxy.js +116 -0
  72. package/build/src/start/server/metro/debugging/InspectorProxy.js.map +1 -0
  73. package/build/src/start/server/metro/debugging/createDebugMiddleware.js +45 -0
  74. package/build/src/start/server/metro/debugging/createDebugMiddleware.js.map +1 -0
  75. package/build/src/start/server/metro/{inspector-proxy/handlers → debugging/inspectorHandlers}/NetworkResponse.js +3 -4
  76. package/build/src/start/server/metro/debugging/inspectorHandlers/NetworkResponse.js.map +1 -0
  77. package/build/src/start/server/metro/debugging/inspectorHandlers/PageReload.js.map +1 -0
  78. package/build/src/start/server/metro/{inspector-proxy/handlers → debugging/inspectorHandlers}/VscodeDebuggerGetPossibleBreakpoints.js +2 -2
  79. package/build/src/start/server/metro/debugging/inspectorHandlers/VscodeDebuggerGetPossibleBreakpoints.js.map +1 -0
  80. package/build/src/start/server/metro/{inspector-proxy/handlers → debugging/inspectorHandlers}/VscodeDebuggerScriptParsed.js +3 -2
  81. package/build/src/start/server/metro/debugging/inspectorHandlers/VscodeDebuggerScriptParsed.js.map +1 -0
  82. package/build/src/start/server/metro/{inspector-proxy/handlers → debugging/inspectorHandlers}/VscodeDebuggerSetBreakpointByUrl.js +3 -2
  83. package/build/src/start/server/metro/debugging/inspectorHandlers/VscodeDebuggerSetBreakpointByUrl.js.map +1 -0
  84. package/build/src/start/server/metro/{inspector-proxy/handlers → debugging/inspectorHandlers}/VscodeRuntimeCallFunctionOn.js +2 -2
  85. package/build/src/start/server/metro/debugging/inspectorHandlers/VscodeRuntimeCallFunctionOn.js.map +1 -0
  86. package/build/src/start/server/metro/{inspector-proxy/handlers → debugging/inspectorHandlers}/VscodeRuntimeGetProperties.js +5 -4
  87. package/build/src/start/server/metro/debugging/inspectorHandlers/VscodeRuntimeGetProperties.js.map +1 -0
  88. package/build/src/start/server/metro/debugging/inspectorHandlers/types.js.map +1 -0
  89. package/build/src/start/server/metro/debugging/inspectorHandlers/utils.js +20 -0
  90. package/build/src/start/server/metro/debugging/inspectorHandlers/utils.js.map +1 -0
  91. package/build/src/start/server/metro/getCssModulesFromBundler.js.map +1 -1
  92. package/build/src/start/server/metro/instantiateMetro.js +8 -5
  93. package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
  94. package/build/src/start/server/metro/metroErrorInterface.js +3 -2
  95. package/build/src/start/server/metro/metroErrorInterface.js.map +1 -1
  96. package/build/src/start/server/metro/router.js +1 -5
  97. package/build/src/start/server/metro/router.js.map +1 -1
  98. package/build/src/start/server/metro/runServer-fork.js +0 -19
  99. package/build/src/start/server/metro/runServer-fork.js.map +1 -1
  100. package/build/src/start/server/metro/serializeHtml.js +20 -4
  101. package/build/src/start/server/metro/serializeHtml.js.map +1 -1
  102. package/build/src/start/server/metro/withMetroMultiPlatform.js +48 -85
  103. package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
  104. package/build/src/start/server/middleware/ManifestMiddleware.js +12 -5
  105. package/build/src/start/server/middleware/ManifestMiddleware.js.map +1 -1
  106. package/build/src/start/server/middleware/inspector/JsInspector.js +22 -1
  107. package/build/src/start/server/middleware/inspector/JsInspector.js.map +1 -1
  108. package/build/src/start/server/middleware/metroOptions.js +62 -9
  109. package/build/src/start/server/middleware/metroOptions.js.map +1 -1
  110. package/build/src/start/server/type-generation/__typetests__/fixtures/basic.js.map +1 -1
  111. package/build/src/start/server/type-generation/__typetests__/route.test.js +11 -3
  112. package/build/src/start/server/type-generation/__typetests__/route.test.js.map +1 -1
  113. package/build/src/start/server/type-generation/routes.js +6 -4
  114. package/build/src/start/server/type-generation/routes.js.map +1 -1
  115. package/build/src/start/server/type-generation/startTypescriptTypeGeneration.js +1 -1
  116. package/build/src/start/server/type-generation/startTypescriptTypeGeneration.js.map +1 -1
  117. package/build/src/utils/analytics/rudderstackClient.js +2 -2
  118. package/build/src/utils/codesigning.js +11 -1
  119. package/build/src/utils/codesigning.js.map +1 -1
  120. package/build/src/utils/env.js +7 -1
  121. package/build/src/utils/env.js.map +1 -1
  122. package/build/src/utils/tsconfig/loadTsConfigPaths.js +3 -11
  123. package/build/src/utils/tsconfig/loadTsConfigPaths.js.map +1 -1
  124. package/build/src/utils/tsconfig/resolveWithTsConfigPaths.js +22 -12
  125. package/build/src/utils/tsconfig/resolveWithTsConfigPaths.js.map +1 -1
  126. package/package.json +10 -10
  127. package/static/template/index.html +14 -95
  128. package/build/src/export/printBundleSizes.js +0 -101
  129. package/build/src/export/printBundleSizes.js.map +0 -1
  130. package/build/src/start/server/metro/inspector-proxy/device.js.map +0 -1
  131. package/build/src/start/server/metro/inspector-proxy/handlers/NetworkResponse.js.map +0 -1
  132. package/build/src/start/server/metro/inspector-proxy/handlers/PageReload.js.map +0 -1
  133. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerGetPossibleBreakpoints.js.map +0 -1
  134. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerScriptParsed.js.map +0 -1
  135. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerSetBreakpointByUrl.js.map +0 -1
  136. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeRuntimeCallFunctionOn.js.map +0 -1
  137. package/build/src/start/server/metro/inspector-proxy/handlers/VscodeRuntimeGetProperties.js.map +0 -1
  138. package/build/src/start/server/metro/inspector-proxy/handlers/types.js.map +0 -1
  139. package/build/src/start/server/metro/inspector-proxy/handlers/utils.js +0 -11
  140. package/build/src/start/server/metro/inspector-proxy/handlers/utils.js.map +0 -1
  141. package/build/src/start/server/metro/inspector-proxy/index.js +0 -30
  142. package/build/src/start/server/metro/inspector-proxy/index.js.map +0 -1
  143. package/build/src/start/server/metro/inspector-proxy/proxy.js +0 -169
  144. package/build/src/start/server/metro/inspector-proxy/proxy.js.map +0 -1
  145. package/build/src/start/server/middleware/inspector/createJsInspectorMiddleware.js +0 -64
  146. package/build/src/start/server/middleware/inspector/createJsInspectorMiddleware.js.map +0 -1
  147. /package/build/src/start/server/metro/{inspector-proxy/handlers → debugging/inspectorHandlers}/PageReload.js +0 -0
  148. /package/build/src/start/server/metro/{inspector-proxy/handlers → debugging/inspectorHandlers}/types.js +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { Terminal } from 'metro-core';\nimport path from 'path';\n\nimport { logWarning, TerminalReporter } from './TerminalReporter';\nimport { BuildPhase, BundleDetails, BundleProgress, SnippetError } from './TerminalReporter.types';\nimport { NODE_STDLIB_MODULES } from './externals';\nimport { learnMore } from '../../../utils/link';\n\nconst MAX_PROGRESS_BAR_CHAR_WIDTH = 16;\nconst DARK_BLOCK_CHAR = '\\u2593';\nconst LIGHT_BLOCK_CHAR = '\\u2591';\n/**\n * Extends the default Metro logger and adds some additional features.\n * Also removes the giant Metro logo from the output.\n */\nexport class MetroTerminalReporter extends TerminalReporter {\n constructor(\n public projectRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n // Used for testing\n _getElapsedTime(startTime: number): number {\n return Date.now() - startTime;\n }\n /**\n * Extends the bundle progress to include the current platform that we're bundling.\n *\n * @returns `iOS path/to/bundle.js ▓▓▓▓▓░░░░░░░░░░░ 36.6% (4790/7922)`\n */\n _getBundleStatusMessage(progress: BundleProgress, phase: BuildPhase): string {\n const env = getEnvironmentForBuildDetails(progress.bundleDetails);\n const platform = env || getPlatformTagForBuildDetails(progress.bundleDetails);\n const inProgress = phase === 'in_progress';\n\n if (!inProgress) {\n const status = phase === 'done' ? `Bundling complete ` : `Bundling failed `;\n const color = phase === 'done' ? chalk.green : chalk.red;\n\n const startTime = this._bundleTimers.get(progress.bundleDetails.buildID!);\n const time = startTime != null ? chalk.dim(this._getElapsedTime(startTime) + 'ms') : '';\n // iOS Bundling complete 150ms\n return color(platform + status) + time;\n }\n\n const localPath = progress.bundleDetails.entryFile.startsWith(path.sep)\n ? path.relative(this.projectRoot, progress.bundleDetails.entryFile)\n : progress.bundleDetails.entryFile;\n\n const filledBar = Math.floor(progress.ratio * MAX_PROGRESS_BAR_CHAR_WIDTH);\n\n const _progress = inProgress\n ? chalk.green.bgGreen(DARK_BLOCK_CHAR.repeat(filledBar)) +\n chalk.bgWhite.white(LIGHT_BLOCK_CHAR.repeat(MAX_PROGRESS_BAR_CHAR_WIDTH - filledBar)) +\n chalk.bold(` ${(100 * progress.ratio).toFixed(1).padStart(4)}% `) +\n chalk.dim(\n `(${progress.transformedFileCount\n .toString()\n .padStart(progress.totalFileCount.toString().length)}/${progress.totalFileCount})`\n )\n : '';\n\n return (\n platform +\n chalk.reset.dim(`${path.dirname(localPath)}/`) +\n chalk.bold(path.basename(localPath)) +\n ' ' +\n _progress\n );\n }\n\n _logInitializing(port: number, hasReducedPerformance: boolean): void {\n // Don't print a giant logo...\n this.terminal.log('Starting Metro Bundler');\n }\n\n shouldFilterClientLog(event: {\n type: 'client_log';\n level: 'trace' | 'info' | 'warn' | 'log' | 'group' | 'groupCollapsed' | 'groupEnd' | 'debug';\n data: unknown[];\n }): boolean {\n return isAppRegistryStartupMessage(event.data);\n }\n\n /** Print the cache clear message. */\n transformCacheReset(): void {\n logWarning(\n this.terminal,\n chalk`Bundler cache is empty, rebuilding {dim (this may take a minute)}`\n );\n }\n\n /** One of the first logs that will be printed */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {\n // this.terminal.log('Dependency graph is loading...');\n if (hasReducedPerformance) {\n // Extends https://github.com/facebook/metro/blob/347b1d7ed87995d7951aaa9fd597c04b06013dac/packages/metro/src/lib/TerminalReporter.js#L283-L290\n this.terminal.log(\n chalk.red(\n [\n 'Metro is operating with reduced performance.',\n 'Please fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n _logBundlingError(error: SnippetError): void {\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.projectRoot, error);\n const cause = error.cause as undefined | { _expoImportStack?: string };\n if (moduleResolutionError) {\n let message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n if (cause?._expoImportStack) {\n message += `\\n\\n${cause?._expoImportStack}`;\n }\n return this.terminal.log(message);\n }\n if (cause?._expoImportStack) {\n error.message += `\\n\\n${cause._expoImportStack}`;\n }\n return super._logBundlingError(error);\n }\n}\n\n/**\n * Formats an error where the user is attempting to import a module from the Node.js standard library.\n * Exposed for testing.\n *\n * @param error\n * @returns error message or null if not a module resolution error\n */\nexport function formatUsingNodeStandardLibraryError(\n projectRoot: string,\n error: SnippetError\n): string | null {\n if (!error.message) {\n return null;\n }\n const { targetModuleName, originModulePath } = error;\n if (!targetModuleName || !originModulePath) {\n return null;\n }\n const relativePath = path.relative(projectRoot, originModulePath);\n\n const DOCS_PAGE_URL =\n 'https://docs.expo.dev/workflow/using-libraries/#using-third-party-libraries';\n\n if (isNodeStdLibraryModule(targetModuleName)) {\n if (originModulePath.includes('node_modules')) {\n return [\n `The package at \"${chalk.bold(\n relativePath\n )}\" attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n } else {\n return [\n `You attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\" from \"${chalk.bold(relativePath)}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n }\n }\n return `Unable to resolve \"${targetModuleName}\" from \"${relativePath}\"`;\n}\n\nexport function isNodeStdLibraryModule(moduleName: string): boolean {\n return /^node:/.test(moduleName) || NODE_STDLIB_MODULES.includes(moduleName);\n}\n\n/** If the code frame can be found then append it to the existing message. */\nfunction maybeAppendCodeFrame(message: string, rawMessage: string): string {\n const codeFrame = stripMetroInfo(rawMessage);\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\n}\n\n/**\n * Remove the Metro cache clearing steps if they exist.\n * In future versions we won't need this.\n * Returns the remaining code frame logs.\n */\nexport function stripMetroInfo(errorMessage: string): string | null {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return null;\n }\n const lines = errorMessage.split('\\n');\n const index = lines.findIndex((line) => line.includes('4. Remove the cache'));\n if (index === -1) {\n return null;\n }\n return lines.slice(index + 1).join('\\n');\n}\n\n/** @returns if the message matches the initial startup log */\nfunction isAppRegistryStartupMessage(body: any[]): boolean {\n return (\n body.length === 1 &&\n (/^Running application \"main\" with appParams:/.test(body[0]) ||\n /^Running \"main\" with \\{/.test(body[0]))\n );\n}\n\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getPlatformTagForBuildDetails(bundleDetails?: BundleDetails | null): string {\n const platform = bundleDetails?.platform ?? null;\n if (platform) {\n const formatted = { ios: 'iOS', android: 'Android', web: 'Web' }[platform] || platform;\n return `${chalk.bold(formatted)} `;\n }\n\n return '';\n}\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getEnvironmentForBuildDetails(bundleDetails?: BundleDetails | null): string {\n // Expo CLI will pass `customTransformOptions.environment = 'node'` when bundling for the server.\n const env = bundleDetails?.customTransformOptions?.environment ?? null;\n if (env === 'node') {\n return `${chalk.bold('Server')} `;\n }\n\n return '';\n}\n"],"names":["formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","MetroTerminalReporter","TerminalReporter","constructor","projectRoot","terminal","_getElapsedTime","startTime","Date","now","_getBundleStatusMessage","progress","phase","env","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","status","color","chalk","green","red","_bundleTimers","get","buildID","time","dim","localPath","entryFile","startsWith","path","sep","relative","filledBar","Math","floor","ratio","_progress","bgGreen","repeat","bgWhite","white","bold","toFixed","padStart","transformedFileCount","toString","totalFileCount","length","reset","dirname","basename","_logInitializing","port","hasReducedPerformance","log","shouldFilterClientLog","event","isAppRegistryStartupMessage","data","transformCacheReset","logWarning","dependencyGraphLoading","join","_logBundlingError","error","moduleResolutionError","cause","message","maybeAppendCodeFrame","_expoImportStack","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","includes","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","lines","split","index","findIndex","line","slice","body","formatted","ios","android","web","customTransformOptions","environment"],"mappings":"AAAA;;;;QAuIgBA,mCAAmC,GAAnCA,mCAAmC;QAwCnCC,sBAAsB,GAAtBA,sBAAsB;QAkBtBC,cAAc,GAAdA,cAAc;AAjMZ,IAAA,MAAO,kCAAP,OAAO,EAAA;AAER,IAAA,KAAM,kCAAN,MAAM,EAAA;AAEsB,IAAA,iBAAoB,WAApB,oBAAoB,CAAA;AAE7B,IAAA,UAAa,WAAb,aAAa,CAAA;AACvB,IAAA,KAAqB,WAArB,qBAAqB,CAAA;;;;;;AAE/C,MAAMC,2BAA2B,GAAG,EAAE,AAAC;AACvC,MAAMC,eAAe,GAAG,QAAQ,AAAC;AACjC,MAAMC,gBAAgB,GAAG,QAAQ,AAAC;AAK3B,MAAMC,qBAAqB,SAASC,iBAAgB,iBAAA;IACzDC,YACSC,WAAmB,EAC1BC,QAAkB,CAClB;QACA,KAAK,CAACA,QAAQ,CAAC,CAAC;aAHTD,WAAmB,GAAnBA,WAAmB;KAI3B;IAED,mBAAmB;IACnBE,eAAe,CAACC,SAAiB,EAAU;QACzC,OAAOC,IAAI,CAACC,GAAG,EAAE,GAAGF,SAAS,CAAC;KAC/B;IACD;;;;KAIG,CACHG,uBAAuB,CAACC,QAAwB,EAAEC,KAAiB,EAAU;QAC3E,MAAMC,GAAG,GAAGC,6BAA6B,CAACH,QAAQ,CAACI,aAAa,CAAC,AAAC;QAClE,MAAMC,QAAQ,GAAGH,GAAG,IAAII,6BAA6B,CAACN,QAAQ,CAACI,aAAa,CAAC,AAAC;QAC9E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,GAAuB,GAAI,IAAI,AAAC;IACjD,IAAIC,QAAQ,EAAE;QACZ,MAAM4E,SAAS,GAAG;YAAEC,GAAG,EAAE,KAAK;YAAEC,OAAO,EAAE,SAAS;YAAEC,GAAG,EAAE,KAAK;SAAE,CAAC/E,QAAQ,CAAC,IAAIA,QAAQ,AAAC;QACvF,OAAO,CAAC,EAAEK,MAAK,QAAA,CAACuB,IAAI,CAACgD,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;KACpC;IAED,OAAO,EAAE,CAAC;CACX;AACD,kEAAkE,CAClE,SAAS9E,6BAA6B,CAACC,aAAoC,EAAU;QAEvEA,GAAqC;QAArCA,IAAkD;IAD9D,iGAAiG;IACjG,MAAMF,GAAG,GAAGE,CAAAA,IAAkD,GAAlDA,aAAa,QAAwB,GAArCA,KAAAA,CAAqC,GAArCA,CAAAA,GAAqC,GAArCA,aAAa,CAAEiF,sBAAsB,SAAA,GAArCjF,KAAAA,CAAqC,GAArCA,GAAqC,CAAEkF,WAAW,AAAb,YAArClF,IAAkD,GAAI,IAAI,AAAC;IACvE,IAAIF,GAAG,KAAK,MAAM,EAAE;QAClB,OAAO,CAAC,EAAEQ,MAAK,QAAA,CAACuB,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;KACnC;IAED,OAAO,EAAE,CAAC;CACX"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { Terminal } from 'metro-core';\nimport path from 'path';\n\nimport { logWarning, TerminalReporter } from './TerminalReporter';\nimport {\n BuildPhase,\n BundleDetails,\n BundleProgress,\n SnippetError,\n TerminalReportableEvent,\n} from './TerminalReporter.types';\nimport { NODE_STDLIB_MODULES } from './externals';\nimport { learnMore } from '../../../utils/link';\n\nconst MAX_PROGRESS_BAR_CHAR_WIDTH = 16;\nconst DARK_BLOCK_CHAR = '\\u2593';\nconst LIGHT_BLOCK_CHAR = '\\u2591';\n/**\n * Extends the default Metro logger and adds some additional features.\n * Also removes the giant Metro logo from the output.\n */\nexport class MetroTerminalReporter extends TerminalReporter {\n constructor(\n public projectRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n // Used for testing\n _getElapsedTime(startTime: number): number {\n return Date.now() - startTime;\n }\n /**\n * Extends the bundle progress to include the current platform that we're bundling.\n *\n * @returns `iOS path/to/bundle.js ▓▓▓▓▓░░░░░░░░░░░ 36.6% (4790/7922)`\n */\n _getBundleStatusMessage(progress: BundleProgress, phase: BuildPhase): string {\n const env = getEnvironmentForBuildDetails(progress.bundleDetails);\n const platform = env || getPlatformTagForBuildDetails(progress.bundleDetails);\n const inProgress = phase === 'in_progress';\n\n const localPath = progress.bundleDetails.entryFile.startsWith(path.sep)\n ? path.relative(this.projectRoot, progress.bundleDetails.entryFile)\n : progress.bundleDetails.entryFile;\n\n if (!inProgress) {\n const status = phase === 'done' ? `Bundling complete ` : `Bundling failed `;\n const color = phase === 'done' ? chalk.green : chalk.red;\n\n const startTime = this._bundleTimers.get(progress.bundleDetails.buildID!);\n const time = startTime != null ? chalk.dim(this._getElapsedTime(startTime) + 'ms') : '';\n // iOS Bundling complete 150ms\n return color(platform + status) + time + chalk.reset.dim(' (' + localPath + ')');\n }\n\n const filledBar = Math.floor(progress.ratio * MAX_PROGRESS_BAR_CHAR_WIDTH);\n\n const _progress = inProgress\n ? chalk.green.bgGreen(DARK_BLOCK_CHAR.repeat(filledBar)) +\n chalk.bgWhite.white(LIGHT_BLOCK_CHAR.repeat(MAX_PROGRESS_BAR_CHAR_WIDTH - filledBar)) +\n chalk.bold(` ${(100 * progress.ratio).toFixed(1).padStart(4)}% `) +\n chalk.dim(\n `(${progress.transformedFileCount\n .toString()\n .padStart(progress.totalFileCount.toString().length)}/${progress.totalFileCount})`\n )\n : '';\n\n return (\n platform +\n chalk.reset.dim(`${path.dirname(localPath)}/`) +\n chalk.bold(path.basename(localPath)) +\n ' ' +\n _progress\n );\n }\n\n _logInitializing(port: number, hasReducedPerformance: boolean): void {\n // Don't print a giant logo...\n this.terminal.log('Starting Metro Bundler');\n }\n\n shouldFilterClientLog(event: {\n type: 'client_log';\n level: 'trace' | 'info' | 'warn' | 'log' | 'group' | 'groupCollapsed' | 'groupEnd' | 'debug';\n data: unknown[];\n }): boolean {\n return isAppRegistryStartupMessage(event.data);\n }\n\n shouldFilterBundleEvent(event: TerminalReportableEvent): boolean {\n return 'bundleDetails' in event && event.bundleDetails?.bundleType === 'map';\n }\n\n /** Print the cache clear message. */\n transformCacheReset(): void {\n logWarning(\n this.terminal,\n chalk`Bundler cache is empty, rebuilding {dim (this may take a minute)}`\n );\n }\n\n /** One of the first logs that will be printed */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {\n // this.terminal.log('Dependency graph is loading...');\n if (hasReducedPerformance) {\n // Extends https://github.com/facebook/metro/blob/347b1d7ed87995d7951aaa9fd597c04b06013dac/packages/metro/src/lib/TerminalReporter.js#L283-L290\n this.terminal.log(\n chalk.red(\n [\n 'Metro is operating with reduced performance.',\n 'Please fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n _logBundlingError(error: SnippetError): void {\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.projectRoot, error);\n const cause = error.cause as undefined | { _expoImportStack?: string };\n if (moduleResolutionError) {\n let message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n if (cause?._expoImportStack) {\n message += `\\n\\n${cause?._expoImportStack}`;\n }\n return this.terminal.log(message);\n }\n if (cause?._expoImportStack) {\n error.message += `\\n\\n${cause._expoImportStack}`;\n }\n return super._logBundlingError(error);\n }\n}\n\n/**\n * Formats an error where the user is attempting to import a module from the Node.js standard library.\n * Exposed for testing.\n *\n * @param error\n * @returns error message or null if not a module resolution error\n */\nexport function formatUsingNodeStandardLibraryError(\n projectRoot: string,\n error: SnippetError\n): string | null {\n if (!error.message) {\n return null;\n }\n const { targetModuleName, originModulePath } = error;\n if (!targetModuleName || !originModulePath) {\n return null;\n }\n const relativePath = path.relative(projectRoot, originModulePath);\n\n const DOCS_PAGE_URL =\n 'https://docs.expo.dev/workflow/using-libraries/#using-third-party-libraries';\n\n if (isNodeStdLibraryModule(targetModuleName)) {\n if (originModulePath.includes('node_modules')) {\n return [\n `The package at \"${chalk.bold(\n relativePath\n )}\" attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n } else {\n return [\n `You attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\" from \"${chalk.bold(relativePath)}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n }\n }\n return `Unable to resolve \"${targetModuleName}\" from \"${relativePath}\"`;\n}\n\nexport function isNodeStdLibraryModule(moduleName: string): boolean {\n return /^node:/.test(moduleName) || NODE_STDLIB_MODULES.includes(moduleName);\n}\n\n/** If the code frame can be found then append it to the existing message. */\nfunction maybeAppendCodeFrame(message: string, rawMessage: string): string {\n const codeFrame = stripMetroInfo(rawMessage);\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\n}\n\n/**\n * Remove the Metro cache clearing steps if they exist.\n * In future versions we won't need this.\n * Returns the remaining code frame logs.\n */\nexport function stripMetroInfo(errorMessage: string): string | null {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return null;\n }\n const lines = errorMessage.split('\\n');\n const index = lines.findIndex((line) => line.includes('4. Remove the cache'));\n if (index === -1) {\n return null;\n }\n return lines.slice(index + 1).join('\\n');\n}\n\n/** @returns if the message matches the initial startup log */\nfunction isAppRegistryStartupMessage(body: any[]): boolean {\n return (\n body.length === 1 &&\n (/^Running application \"main\" with appParams:/.test(body[0]) ||\n /^Running \"main\" with \\{/.test(body[0]))\n );\n}\n\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getPlatformTagForBuildDetails(bundleDetails?: BundleDetails | null): string {\n const platform = bundleDetails?.platform ?? null;\n if (platform) {\n const formatted = { ios: 'iOS', android: 'Android', web: 'Web' }[platform] || platform;\n return `${chalk.bold(formatted)} `;\n }\n\n return '';\n}\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getEnvironmentForBuildDetails(bundleDetails?: BundleDetails | null): string {\n // Expo CLI will pass `customTransformOptions.environment = 'node'` when bundling for the server.\n const env = bundleDetails?.customTransformOptions?.environment ?? null;\n if (env === 'node') {\n return `${chalk.bold('Server')} `;\n }\n\n return '';\n}\n"],"names":["formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","MetroTerminalReporter","TerminalReporter","constructor","projectRoot","terminal","_getElapsedTime","startTime","Date","now","_getBundleStatusMessage","progress","phase","env","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","entryFile","startsWith","path","sep","relative","status","color","chalk","green","red","_bundleTimers","get","buildID","time","dim","reset","filledBar","Math","floor","ratio","_progress","bgGreen","repeat","bgWhite","white","bold","toFixed","padStart","transformedFileCount","toString","totalFileCount","length","dirname","basename","_logInitializing","port","hasReducedPerformance","log","shouldFilterClientLog","event","isAppRegistryStartupMessage","data","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","join","_logBundlingError","error","moduleResolutionError","cause","message","maybeAppendCodeFrame","_expoImportStack","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","includes","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","lines","split","index","findIndex","line","slice","body","formatted","ios","android","web","customTransformOptions","environment"],"mappings":"AAAA;;;;QAiJgBA,mCAAmC,GAAnCA,mCAAmC;QAwCnCC,sBAAsB,GAAtBA,sBAAsB;QAkBtBC,cAAc,GAAdA,cAAc;AA3MZ,IAAA,MAAO,kCAAP,OAAO,EAAA;AAER,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AG,EAAE,KAAK;SAAE,CAACjF,QAAQ,CAAC,IAAIA,QAAQ,AAAC;QACvF,OAAO,CAAC,EAAEW,MAAK,QAAA,CAACkB,IAAI,CAACiD,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;KACpC;IAED,OAAO,EAAE,CAAC;CACX;AACD,kEAAkE,CAClE,SAAShF,6BAA6B,CAACC,aAAoC,EAAU;QAEvEA,GAAqC;QAArCA,IAAkD;IAD9D,iGAAiG;IACjG,MAAMF,GAAG,GAAGE,CAAAA,IAAkD,GAAlDA,aAAa,QAAwB,GAArCA,KAAAA,CAAqC,GAArCA,CAAAA,GAAqC,GAArCA,aAAa,CAAEmF,sBAAsB,SAAA,GAArCnF,KAAAA,CAAqC,GAArCA,GAAqC,CAAEoF,WAAW,AAAb,YAArCpF,IAAkD,GAAI,IAAI,AAAC;IACvE,IAAIF,GAAG,KAAK,MAAM,EAAE;QAClB,OAAO,CAAC,EAAEc,MAAK,QAAA,CAACkB,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;KACnC;IAED,OAAO,EAAE,CAAC;CACX"}
@@ -13,6 +13,7 @@ function _interopRequireDefault(obj) {
13
13
  default: obj
14
14
  };
15
15
  }
16
+ const debug = require("debug")("expo:metro:logger");
16
17
  function logWarning(terminal, format, ...args) {
17
18
  const str = _util.default.format(format, ...args);
18
19
  terminal.log("%s: %s", _chalk.default.yellow("warning"), str);
@@ -32,6 +33,7 @@ class TerminalReporter extends XTerminalReporter {
32
33
  * so we need to cache the details in order to print the platform info with other event types.
33
34
  */ _bundleDetails = new Map();
34
35
  /** Keep track of how long a bundle takes to complete */ _bundleTimers = new Map();
36
+ /** Keep track of bundle processes that should not be logged. */ _hiddenBundleEvents = new Set();
35
37
  _log(event) {
36
38
  switch(event.type){
37
39
  case "transform_cache_reset":
@@ -49,6 +51,9 @@ class TerminalReporter extends XTerminalReporter {
49
51
  /** Gives subclasses an easy interface for filtering out logs. Return `true` to skip. */ shouldFilterClientLog(event) {
50
52
  return false;
51
53
  }
54
+ /** Gives subclasses an easy interface for filtering out bundle events, specifically for source maps. Return `true` to skip. */ shouldFilterBundleEvent(event) {
55
+ return false;
56
+ }
52
57
  /** Cache has been reset. */ transformCacheReset() {}
53
58
  /** One of the first logs that will be printed. */ dependencyGraphLoading(hasReducedPerformance) {}
54
59
  /**
@@ -61,11 +66,23 @@ class TerminalReporter extends XTerminalReporter {
61
66
  * This function is exclusively concerned with updating the internal state.
62
67
  * No logging or status updates should be done at this point.
63
68
  */ _updateState(event) {
69
+ var ref;
64
70
  // Append the buildID to the bundleDetails.
65
71
  if (event.bundleDetails) {
66
72
  event.bundleDetails.buildID = event.buildID;
67
73
  }
68
- super._updateState(event);
74
+ var ref1;
75
+ const buildID = (ref1 = (ref = event.bundleDetails) == null ? void 0 : ref.buildID) != null ? ref1 : event.buildID;
76
+ if (buildID && !this._hiddenBundleEvents.has(buildID)) {
77
+ if (this.shouldFilterBundleEvent(event)) {
78
+ debug("skipping bundle events for", buildID, event);
79
+ this._hiddenBundleEvents.add(buildID);
80
+ } else {
81
+ super._updateState(event);
82
+ }
83
+ } else {
84
+ super._updateState(event);
85
+ }
69
86
  switch(event.type){
70
87
  case "bundle_build_done":
71
88
  case "bundle_build_failed":
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/TerminalReporter.ts"],"sourcesContent":["// This file represents an abstraction on the metro TerminalReporter.\n// We use this abstraction to safely extend the TerminalReporter for our own custom logging.\nimport chalk from 'chalk';\nimport UpstreamTerminalReporter from 'metro/src/lib/TerminalReporter';\nimport { Terminal } from 'metro-core';\nimport util from 'util';\n\nimport {\n BundleDetails,\n TerminalReportableEvent,\n TerminalReporterInterface,\n} from './TerminalReporter.types';\nimport { stripAnsi } from '../../../utils/ansi';\n\n/**\n * A standard way to log a warning to the terminal. This should not be called\n * from some arbitrary Metro logic, only from the reporters. Instead of\n * calling this, add a new type of ReportableEvent instead, and implement a\n * proper handler in the reporter(s).\n */\nexport function logWarning(terminal: Terminal, format: string, ...args: any[]): void {\n const str = util.format(format, ...args);\n terminal.log('%s: %s', chalk.yellow('warning'), str);\n}\n\n/**\n * Similar to `logWarning`, but for messages that require the user to act.\n */\nexport function logError(terminal: Terminal, format: string, ...args: any[]): void {\n terminal.log(\n '%s: %s',\n chalk.red('error'),\n // Syntax errors may have colors applied for displaying code frames\n // in various places outside of where Metro is currently running.\n // If the current terminal does not support color, we'll strip the colors\n // here.\n util.format(chalk.supportsColor ? format : stripAnsi(format), ...args)\n );\n}\n\nconst XTerminalReporter = UpstreamTerminalReporter as unknown as TerminalReporterInterface;\n\n/** Extended TerminalReporter class but with proper types and extra functionality to avoid using the `_log` method directly in subclasses. */\nexport class TerminalReporter extends XTerminalReporter implements TerminalReporterInterface {\n /**\n * A cache of { [buildID]: BundleDetails } which can be used to\n * add more contextual logs. BundleDetails is currently only sent with `bundle_build_started`\n * so we need to cache the details in order to print the platform info with other event types.\n */\n _bundleDetails: Map<string, BundleDetails> = new Map();\n\n /** Keep track of how long a bundle takes to complete */\n _bundleTimers: Map<string, number> = new Map();\n\n _log(event: TerminalReportableEvent): void {\n switch (event.type) {\n case 'transform_cache_reset':\n return this.transformCacheReset();\n case 'dep_graph_loading':\n return this.dependencyGraphLoading(event.hasReducedPerformance);\n case 'client_log':\n if (this.shouldFilterClientLog(event)) {\n return;\n }\n break;\n }\n return super._log(event);\n }\n\n /** Gives subclasses an easy interface for filtering out logs. Return `true` to skip. */\n shouldFilterClientLog(event: {\n type: 'client_log';\n level: 'trace' | 'info' | 'warn' | 'log' | 'group' | 'groupCollapsed' | 'groupEnd' | 'debug';\n data: unknown[];\n }): boolean {\n return false;\n }\n\n /** Cache has been reset. */\n transformCacheReset(): void {}\n\n /** One of the first logs that will be printed. */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {}\n\n /**\n * Custom log event representing the end of the bundling.\n *\n * @param event event object.\n * @param duration duration of the build in milliseconds.\n */\n bundleBuildEnded(event: TerminalReportableEvent, duration: number): void {}\n\n /**\n * This function is exclusively concerned with updating the internal state.\n * No logging or status updates should be done at this point.\n */\n _updateState(\n event: TerminalReportableEvent & { bundleDetails?: BundleDetails; buildID?: string }\n ) {\n // Append the buildID to the bundleDetails.\n if (event.bundleDetails) {\n event.bundleDetails.buildID = event.buildID;\n }\n\n super._updateState(event);\n switch (event.type) {\n case 'bundle_build_done':\n case 'bundle_build_failed': {\n const startTime = this._bundleTimers.get(event.buildID);\n // Observed a bug in Metro where the `bundle_build_done` is invoked twice during a static bundle\n // i.e. `expo export`.\n if (startTime == null) {\n break;\n }\n\n this.bundleBuildEnded(event, startTime ? Date.now() - startTime : 0);\n this._bundleTimers.delete(event.buildID);\n break;\n }\n case 'bundle_build_started':\n this._bundleDetails.set(event.buildID, event.bundleDetails);\n this._bundleTimers.set(event.buildID, Date.now());\n break;\n }\n }\n}\n"],"names":["logWarning","logError","terminal","format","args","str","util","log","chalk","yellow","red","supportsColor","stripAnsi","XTerminalReporter","UpstreamTerminalReporter","TerminalReporter","_bundleDetails","Map","_bundleTimers","_log","event","type","transformCacheReset","dependencyGraphLoading","hasReducedPerformance","shouldFilterClientLog","bundleBuildEnded","duration","_updateState","bundleDetails","buildID","startTime","get","Date","now","delete","set"],"mappings":"AAEA;;;;QAkBgBA,UAAU,GAAVA,UAAU;QAQVC,QAAQ,GAARA,QAAQ;AA1BN,IAAA,MAAO,kCAAP,OAAO,EAAA;AACY,IAAA,iBAAgC,kCAAhC,gCAAgC,EAAA;AAEpD,IAAA,KAAM,kCAAN,MAAM,EAAA;AAOG,IAAA,KAAqB,WAArB,qBAAqB,CAAA;;;;;;AAQxC,SAASD,UAAU,CAACE,QAAkB,EAAEC,MAAc,EAAE,GAAGC,IAAI,AAAO,EAAQ;IACnF,MAAMC,GAAG,GAAGC,KAAI,QAAA,CAACH,MAAM,CAACA,MAAM,KAAKC,IAAI,CAAC,AAAC;IACzCF,QAAQ,CAACK,GAAG,CAAC,QAAQ,EAAEC,MAAK,QAAA,CAACC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AQ,EAAE;IAE/D;;;;;KAKG,CACHE,gBAAgB,CAACN,KAA8B,EAAEO,QAAgB,EAAQ,EAAE;IAE3E;;;KAGG,CACHC,YAAY,CACVR,KAAoF,EACpF;QACA,2CAA2C;QAC3C,IAAIA,KAAK,CAACS,aAAa,EAAE;YACvBT,KAAK,CAACS,aAAa,CAACC,OAAO,GAAGV,KAAK,CAACU,OAAO,CAAC;SAC7C;QAED,KAAK,CAACF,YAAY,CAACR,KAAK,CAAC,CAAC;QAC1B,OAAQA,KAAK,CAACC,IAAI;YAChB,KAAK,mBAAmB,CAAC;YACzB,KAAK,qBAAqB;gBAAE;oBAC1B,MAAMU,SAAS,GAAG,IAAI,CAACb,aAAa,CAACc,GAAG,CAACZ,KAAK,CAACU,OAAO,CAAC,AAAC;oBACxD,gGAAgG;oBAChG,sBAAsB;oBACtB,IAAIC,SAAS,IAAI,IAAI,EAAE;wBACrB,MAAM;qBACP;oBAED,IAAI,CAACL,gBAAgB,CAACN,KAAK,EAAEW,SAAS,GAAGE,IAAI,CAACC,GAAG,EAAE,GAAGH,SAAS,GAAG,CAAC,CAAC,CAAC;oBACrE,IAAI,CAACb,aAAa,CAACiB,MAAM,CAACf,KAAK,CAACU,OAAO,CAAC,CAAC;oBACzC,MAAM;iBACP;YACD,KAAK,sBAAsB;gBACzB,IAAI,CAACd,cAAc,CAACoB,GAAG,CAAChB,KAAK,CAACU,OAAO,EAAEV,KAAK,CAACS,aAAa,CAAC,CAAC;gBAC5D,IAAI,CAACX,aAAa,CAACkB,GAAG,CAAChB,KAAK,CAACU,OAAO,EAAEG,IAAI,CAACC,GAAG,EAAE,CAAC,CAAC;gBAClD,MAAM;SACT;KACF;CACF;QAlFYnB,gBAAgB,GAAhBA,gBAAgB"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/TerminalReporter.ts"],"sourcesContent":["// This file represents an abstraction on the metro TerminalReporter.\n// We use this abstraction to safely extend the TerminalReporter for our own custom logging.\nimport chalk from 'chalk';\nimport UpstreamTerminalReporter from 'metro/src/lib/TerminalReporter';\nimport { Terminal } from 'metro-core';\nimport util from 'util';\n\nimport {\n BundleDetails,\n TerminalReportableEvent,\n TerminalReporterInterface,\n} from './TerminalReporter.types';\nimport { stripAnsi } from '../../../utils/ansi';\n\nconst debug = require('debug')('expo:metro:logger') as typeof console.log;\n\n/**\n * A standard way to log a warning to the terminal. This should not be called\n * from some arbitrary Metro logic, only from the reporters. Instead of\n * calling this, add a new type of ReportableEvent instead, and implement a\n * proper handler in the reporter(s).\n */\nexport function logWarning(terminal: Terminal, format: string, ...args: any[]): void {\n const str = util.format(format, ...args);\n terminal.log('%s: %s', chalk.yellow('warning'), str);\n}\n\n/**\n * Similar to `logWarning`, but for messages that require the user to act.\n */\nexport function logError(terminal: Terminal, format: string, ...args: any[]): void {\n terminal.log(\n '%s: %s',\n chalk.red('error'),\n // Syntax errors may have colors applied for displaying code frames\n // in various places outside of where Metro is currently running.\n // If the current terminal does not support color, we'll strip the colors\n // here.\n util.format(chalk.supportsColor ? format : stripAnsi(format), ...args)\n );\n}\n\nconst XTerminalReporter = UpstreamTerminalReporter as unknown as TerminalReporterInterface;\n\n/** Extended TerminalReporter class but with proper types and extra functionality to avoid using the `_log` method directly in subclasses. */\nexport class TerminalReporter extends XTerminalReporter implements TerminalReporterInterface {\n /**\n * A cache of { [buildID]: BundleDetails } which can be used to\n * add more contextual logs. BundleDetails is currently only sent with `bundle_build_started`\n * so we need to cache the details in order to print the platform info with other event types.\n */\n _bundleDetails: Map<string, BundleDetails> = new Map();\n\n /** Keep track of how long a bundle takes to complete */\n _bundleTimers: Map<string, number> = new Map();\n\n /** Keep track of bundle processes that should not be logged. */\n _hiddenBundleEvents: Set<string> = new Set();\n\n _log(event: TerminalReportableEvent): void {\n switch (event.type) {\n case 'transform_cache_reset':\n return this.transformCacheReset();\n case 'dep_graph_loading':\n return this.dependencyGraphLoading(event.hasReducedPerformance);\n case 'client_log':\n if (this.shouldFilterClientLog(event)) {\n return;\n }\n break;\n }\n return super._log(event);\n }\n\n /** Gives subclasses an easy interface for filtering out logs. Return `true` to skip. */\n shouldFilterClientLog(event: {\n type: 'client_log';\n level: 'trace' | 'info' | 'warn' | 'log' | 'group' | 'groupCollapsed' | 'groupEnd' | 'debug';\n data: unknown[];\n }): boolean {\n return false;\n }\n\n /** Gives subclasses an easy interface for filtering out bundle events, specifically for source maps. Return `true` to skip. */\n shouldFilterBundleEvent(event: TerminalReportableEvent): boolean {\n return false;\n }\n\n /** Cache has been reset. */\n transformCacheReset(): void {}\n\n /** One of the first logs that will be printed. */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {}\n\n /**\n * Custom log event representing the end of the bundling.\n *\n * @param event event object.\n * @param duration duration of the build in milliseconds.\n */\n bundleBuildEnded(event: TerminalReportableEvent, duration: number): void {}\n\n /**\n * This function is exclusively concerned with updating the internal state.\n * No logging or status updates should be done at this point.\n */\n _updateState(\n event: TerminalReportableEvent & { bundleDetails?: BundleDetails; buildID?: string }\n ) {\n // Append the buildID to the bundleDetails.\n if (event.bundleDetails) {\n event.bundleDetails.buildID = event.buildID;\n }\n\n const buildID = event.bundleDetails?.buildID ?? event.buildID;\n\n if (buildID && !this._hiddenBundleEvents.has(buildID)) {\n if (this.shouldFilterBundleEvent(event)) {\n debug('skipping bundle events for', buildID, event);\n this._hiddenBundleEvents.add(buildID);\n } else {\n super._updateState(event);\n }\n } else {\n super._updateState(event);\n }\n\n switch (event.type) {\n case 'bundle_build_done':\n case 'bundle_build_failed': {\n const startTime = this._bundleTimers.get(event.buildID);\n // Observed a bug in Metro where the `bundle_build_done` is invoked twice during a static bundle\n // i.e. `expo export`.\n if (startTime == null) {\n break;\n }\n\n this.bundleBuildEnded(event, startTime ? Date.now() - startTime : 0);\n this._bundleTimers.delete(event.buildID);\n break;\n }\n case 'bundle_build_started':\n this._bundleDetails.set(event.buildID, event.bundleDetails);\n this._bundleTimers.set(event.buildID, Date.now());\n break;\n }\n }\n}\n"],"names":["logWarning","logError","debug","require","terminal","format","args","str","util","log","chalk","yellow","red","supportsColor","stripAnsi","XTerminalReporter","UpstreamTerminalReporter","TerminalReporter","_bundleDetails","Map","_bundleTimers","_hiddenBundleEvents","Set","_log","event","type","transformCacheReset","dependencyGraphLoading","hasReducedPerformance","shouldFilterClientLog","shouldFilterBundleEvent","bundleBuildEnded","duration","_updateState","bundleDetails","buildID","has","add","startTime","get","Date","now","delete","set"],"mappings":"AAEA;;;;QAoBgBA,UAAU,GAAVA,UAAU;QAQVC,QAAQ,GAARA,QAAQ;AA5BN,IAAA,MAAO,kCAAP,OAAO,EAAA;AACY,IAAA,iBAAgC,kCAAhC,gCAAgC,EAAA;AAEpD,IAAA,KAAM,kCAAN,MAAM,EAAA;AAOG,IAAA,KAAqB,WAArB,qBAAqB,CAAA;;;;;;AAE/C,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,mBAAmB,CAAC,AAAsB,AAAC;AAQnE,SAASH,UAAU,CAACI,QAAkB,EAAEC,MAAc,EAAE,GAAGC,IAAI,AAAO,EAAQ;IACnF,MAAMC,GAAG,GAAGC,KAAI,QAAA,CAACH,MAAM,CAACA,MAAM,KAAKC,IAAI,CAAC,AAAC;IACzCF,QAAQ,CAACK,GAAG,CAAC,QAAQ,EAAEC,MAAK,QAAA,CAACC,MAAM,CAAC,SAAS,CAAC,EAAEJ,GAAG,CAAC,CAAC;CACtD;AAKM,SAASN,QAAQ,CAACG,QAAkB,EAAEC,MAAc,EAAE,GAAGC,IAAI,AAAO,EAAQ;IACjFF,QAAQ,CAACK,GAAG,CACV,QAAQ,EACRC,MAAK,QAAA,CAACE,GAAG,CAAC,OAAO,CAAC,EAClB,mEAAmE;IACnE,iEAAiE;IACjE,yEAAyE;IACzE,QAAQ;IACRJ,KAAI,QAAA,CAACH,MAAM,CAACK,MAAK,QAAA,CAACG,aAAa,GAAGR,MAAM,GAAGS,CAAAA,GAAAA,KAAS,AAAQ,CAAA,UAAR,CAACT,MAAM,CAAC,KAAKC,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IAAI,CAACd,aAAa,CAACuB,GAAG,CAACnB,KAAK,CAACW,OAAO,EAAEK,IAAI,CAACC,GAAG,EAAE,CAAC,CAAC;gBAClD,MAAM;SACT;KACF;CACF;QAtGYxB,gBAAgB,GAAhBA,gBAAgB"}
@@ -15,13 +15,14 @@ async function bundleApiRoute(projectRoot, filepath, options) {
15
15
  const devServerUrl = `http://localhost:${options.port}`;
16
16
  async function bundleAsync() {
17
17
  try {
18
- debug("Bundle API route:", options.appDir, filepath);
18
+ debug("Bundle API route:", options.routerRoot, filepath);
19
19
  const middleware = await (0, _getStaticRenderFunctions).requireFileContentsWithMetro(projectRoot, devServerUrl, filepath, {
20
20
  minify: options.mode === "production",
21
21
  dev: options.mode !== "production",
22
22
  // Ensure Node.js
23
23
  environment: "node",
24
- baseUrl: options.baseUrl
24
+ baseUrl: options.baseUrl,
25
+ routerRoot: options.routerRoot
25
26
  });
26
27
  return middleware;
27
28
  } catch (error) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/bundleApiRoutes.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nimport { logMetroErrorAsync } from './metroErrorInterface';\nimport { requireFileContentsWithMetro } from '../getStaticRenderFunctions';\n\nconst debug = require('debug')('expo:api-routes') as typeof console.log;\n\nconst pendingRouteOperations = new Map<string, Promise<string | null>>();\n\nexport type ApiRouteOptions = {\n mode?: string;\n appDir: string;\n port?: number;\n shouldThrow?: boolean;\n baseUrl: string;\n};\n\n// Bundle the API Route with Metro and return the string contents to be evaluated in the server.\nexport async function bundleApiRoute(\n projectRoot: string,\n filepath: string,\n options: ApiRouteOptions\n): Promise<string | null | undefined> {\n if (pendingRouteOperations.has(filepath)) {\n return pendingRouteOperations.get(filepath);\n }\n\n const devServerUrl = `http://localhost:${options.port}`;\n\n async function bundleAsync() {\n try {\n debug('Bundle API route:', options.appDir, filepath);\n\n const middleware = await requireFileContentsWithMetro(projectRoot, devServerUrl, filepath, {\n minify: options.mode === 'production',\n dev: options.mode !== 'production',\n // Ensure Node.js\n environment: 'node',\n baseUrl: options.baseUrl,\n });\n\n return middleware;\n } catch (error: any) {\n if (error instanceof Error) {\n await logMetroErrorAsync({ error, projectRoot });\n }\n if (options.shouldThrow) {\n throw error;\n }\n // TODO: improve error handling, maybe have this be a mock function which returns the static error html\n return null;\n } finally {\n // pendingRouteOperations.delete(filepath);\n }\n }\n const route = bundleAsync();\n\n pendingRouteOperations.set(filepath, route);\n return route;\n}\n\nexport async function rebundleApiRoute(\n projectRoot: string,\n filepath: string,\n options: ApiRouteOptions\n) {\n pendingRouteOperations.delete(filepath);\n return bundleApiRoute(projectRoot, filepath, options);\n}\n"],"names":["bundleApiRoute","rebundleApiRoute","debug","require","pendingRouteOperations","Map","projectRoot","filepath","options","has","get","devServerUrl","port","bundleAsync","appDir","middleware","requireFileContentsWithMetro","minify","mode","dev","environment","baseUrl","error","Error","logMetroErrorAsync","shouldThrow","route","set","delete"],"mappings":"AAOA;;;;QAgBsBA,cAAc,GAAdA,cAAc;QA2CdC,gBAAgB,GAAhBA,gBAAgB;AA3DH,IAAA,oBAAuB,WAAvB,uBAAuB,CAAA;AACb,IAAA,yBAA6B,WAA7B,6BAA6B,CAAA;AAE1E,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,iBAAiB,CAAC,AAAsB,AAAC;AAExE,MAAMC,sBAAsB,GAAG,IAAIC,GAAG,EAAkC,AAAC;AAWlE,eAAeL,cAAc,CAClCM,WAAmB,EACnBC,QAAgB,EAChBC,OAAwB,EACY;IACpC,IAAIJ,sBAAsB,CAACK,GAAG,CAACF,QAAQ,CAAC,EAAE;QACxC,OAAOH,sBAAsB,CAACM,GAAG,CAACH,QAAQ,CAAC,CAAC;KAC7C;IAED,MAAMI,YAAY,GAAG,CAAC,iBAAiB,EAAEH,OAAO,CAACI,IAAI,CAAC,CAAC,AAAC;IAExD,eAAeC,WAAW,GAAG;QAC3B,IAAI;YACFX,KAAK,CAAC,mBAAmB,EAAEM,OAAO,CAACM,MAAM,EAAEP,QAAQ,CAAC,CAAC;YAErD,MAAMQ,UAAU,GAAG,MAAMC,CAAAA,GAAAA,yBAA4B,AAMnD,CAAA,6BANmD,CAACV,WAAW,EAAEK,YAAY,EAAEJ,QAAQ,EAAE;gBACzFU,MAAM,EAAET,OAAO,CAACU,IAAI,KAAK,YAAY;gBACrCC,GAAG,EAAEX,OAAO,CAACU,IAAI,KAAK,YAAY;gBAClC,iBAAiB;gBACjBE,WAAW,EAAE,MAAM;gBACnBC,OAAO,EAAEb,OAAO,CAACa,OAAO;aACzB,CAAC,AAAC;YAEH,OAAON,UAAU,CAAC;SACnB,CAAC,OAAOO,KAAK,EAAO;YACnB,IAAIA,KAAK,YAAYC,KAAK,EAAE;gBAC1B,MAAMC,CAAAA,GAAAA,oBAAkB,AAAwB,CAAA,mBAAxB,CAAC;oBAAEF,KAAK;oBAAEhB,WAAW;iBAAE,CAAC,CAAC;aAClD;YACD,IAAIE,OAAO,CAACiB,WAAW,EAAE;gBACvB,MAAMH,KAAK,CAAC;aACb;YACD,uGAAuG;YACvG,OAAO,IAAI,CAAC;SACb,QAAS;QACR,2CAA2C;SAC5C;KACF;IACD,MAAMI,KAAK,GAAGb,WAAW,EAAE,AAAC;IAE5BT,sBAAsB,CAACuB,GAAG,CAACpB,QAAQ,EAAEmB,KAAK,CAAC,CAAC;IAC5C,OAAOA,KAAK,CAAC;CACd;AAEM,eAAezB,gBAAgB,CACpCK,WAAmB,EACnBC,QAAgB,EAChBC,OAAwB,EACxB;IACAJ,sBAAsB,CAACwB,MAAM,CAACrB,QAAQ,CAAC,CAAC;IACxC,OAAOP,cAAc,CAACM,WAAW,EAAEC,QAAQ,EAAEC,OAAO,CAAC,CAAC;CACvD"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/bundleApiRoutes.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nimport { logMetroErrorAsync } from './metroErrorInterface';\nimport { requireFileContentsWithMetro } from '../getStaticRenderFunctions';\n\nconst debug = require('debug')('expo:api-routes') as typeof console.log;\n\nconst pendingRouteOperations = new Map<string, Promise<string | null>>();\n\nexport type ApiRouteOptions = {\n mode?: string;\n routerRoot: string;\n port?: number;\n shouldThrow?: boolean;\n baseUrl: string;\n};\n\n// Bundle the API Route with Metro and return the string contents to be evaluated in the server.\nexport async function bundleApiRoute(\n projectRoot: string,\n filepath: string,\n options: ApiRouteOptions\n): Promise<string | null | undefined> {\n if (pendingRouteOperations.has(filepath)) {\n return pendingRouteOperations.get(filepath);\n }\n\n const devServerUrl = `http://localhost:${options.port}`;\n\n async function bundleAsync() {\n try {\n debug('Bundle API route:', options.routerRoot, filepath);\n\n const middleware = await requireFileContentsWithMetro(projectRoot, devServerUrl, filepath, {\n minify: options.mode === 'production',\n dev: options.mode !== 'production',\n // Ensure Node.js\n environment: 'node',\n baseUrl: options.baseUrl,\n routerRoot: options.routerRoot,\n });\n\n return middleware;\n } catch (error: any) {\n if (error instanceof Error) {\n await logMetroErrorAsync({ error, projectRoot });\n }\n if (options.shouldThrow) {\n throw error;\n }\n // TODO: improve error handling, maybe have this be a mock function which returns the static error html\n return null;\n } finally {\n // pendingRouteOperations.delete(filepath);\n }\n }\n const route = bundleAsync();\n\n pendingRouteOperations.set(filepath, route);\n return route;\n}\n\nexport async function rebundleApiRoute(\n projectRoot: string,\n filepath: string,\n options: ApiRouteOptions\n) {\n pendingRouteOperations.delete(filepath);\n return bundleApiRoute(projectRoot, filepath, options);\n}\n"],"names":["bundleApiRoute","rebundleApiRoute","debug","require","pendingRouteOperations","Map","projectRoot","filepath","options","has","get","devServerUrl","port","bundleAsync","routerRoot","middleware","requireFileContentsWithMetro","minify","mode","dev","environment","baseUrl","error","Error","logMetroErrorAsync","shouldThrow","route","set","delete"],"mappings":"AAOA;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AEhB,WAAW;iBAAE,CAAC,CAAC;aAClD;YACD,IAAIE,OAAO,CAACiB,WAAW,EAAE;gBACvB,MAAMH,KAAK,CAAC;aACb;YACD,uGAAuG;YACvG,OAAO,IAAI,CAAC;SACb,QAAS;QACR,2CAA2C;SAC5C;KACF;IACD,MAAMI,KAAK,GAAGb,WAAW,EAAE,AAAC;IAE5BT,sBAAsB,CAACuB,GAAG,CAACpB,QAAQ,EAAEmB,KAAK,CAAC,CAAC;IAC5C,OAAOA,KAAK,CAAC;CACd;AAEM,eAAezB,gBAAgB,CACpCK,WAAmB,EACnBC,QAAgB,EAChBC,OAAwB,EACxB;IACAJ,sBAAsB,CAACwB,MAAM,CAACrB,QAAQ,CAAC,CAAC;IACxC,OAAOP,cAAc,CAACM,WAAW,EAAEC,QAAQ,EAAEC,OAAO,CAAC,CAAC;CACvD"}
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", {
3
3
  value: true
4
4
  });
5
5
  exports.createFastResolver = createFastResolver;
6
+ var _fs = _interopRequireDefault(require("fs"));
6
7
  var _path = _interopRequireDefault(require("path"));
7
8
  var _createJResolver = _interopRequireDefault(require("./createJResolver"));
8
9
  var _externals = require("./externals");
@@ -16,6 +17,17 @@ class FailedToResolvePathError extends Error {
16
17
  }
17
18
  class ShimModuleError extends Error {
18
19
  }
20
+ const realpathFS = process.platform !== "win32" && _fs.default.realpathSync && typeof _fs.default.realpathSync.native === "function" ? _fs.default.realpathSync.native : _fs.default.realpathSync;
21
+ function realpathSync(x) {
22
+ try {
23
+ return realpathFS(x);
24
+ } catch (realpathErr) {
25
+ if (realpathErr.code !== "ENOENT") {
26
+ throw realpathErr;
27
+ }
28
+ }
29
+ return x;
30
+ }
19
31
  function createFastResolver({ preserveSymlinks , blockList }) {
20
32
  const cachedExtensions = new Map();
21
33
  function getAdjustedExtensions({ metroSourceExtensions , platform , isNative }) {
@@ -69,11 +81,17 @@ function createFastResolver({ preserveSymlinks , blockList }) {
69
81
  blockList,
70
82
  enablePackageExports: context.unstable_enablePackageExports,
71
83
  basedir: _path.default.dirname(context.originModulePath),
72
- paths: context.nodeModulesPaths,
84
+ paths: context.nodeModulesPaths.length ? context.nodeModulesPaths : undefined,
73
85
  extensions,
74
86
  conditions,
75
- // @ts-ignore
76
- realpathSync: context.unstable_getRealPath,
87
+ realpathSync (file) {
88
+ // @ts-expect-error: Missing on type.
89
+ const metroRealPath = context.unstable_getRealPath == null ? void 0 : context.unstable_getRealPath(file);
90
+ if (metroRealPath == null && preserveSymlinks) {
91
+ return realpathSync(file);
92
+ }
93
+ return metroRealPath != null ? metroRealPath : file;
94
+ },
77
95
  packageFilter (pkg) {
78
96
  // set the pkg.main to the first available field in context.mainFields
79
97
  for (const field of context.mainFields){
@@ -129,12 +147,11 @@ function createFastResolver({ preserveSymlinks , blockList }) {
129
147
  type: "empty"
130
148
  };
131
149
  }
132
- // TODO: Add improved error handling.
133
150
  throw new FailedToResolvePathError("The module could not be resolved because no file or module matched the pattern:\n" + ` ${(0, _formatFileCandidates).formatFileCandidates({
134
151
  type: "sourceFile",
135
152
  filePathPrefix: moduleName,
136
153
  candidateExts: extensions
137
- }, true)}\n\n`);
154
+ }, true)}\n\nFrom:\n ${context.originModulePath}\n`);
138
155
  }
139
156
  throw error;
140
157
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/createExpoMetroResolver.ts"],"sourcesContent":["/**\n * Copyright © 2023 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { Resolution, ResolutionContext } from 'metro-resolver';\nimport path from 'path';\n\nimport jestResolver from './createJResolver';\nimport { isNodeExternal } from './externals';\nimport { formatFileCandidates } from './formatFileCandidates';\n\nclass FailedToResolvePathError extends Error {}\n\nclass ShimModuleError extends Error {}\n\nexport function createFastResolver({\n preserveSymlinks,\n blockList,\n}: {\n preserveSymlinks: boolean;\n blockList: RegExp[];\n}) {\n const cachedExtensions: Map<string, readonly string[]> = new Map();\n\n function getAdjustedExtensions({\n metroSourceExtensions,\n platform,\n isNative,\n }: {\n metroSourceExtensions: readonly string[];\n platform: string | null;\n isNative: boolean;\n }): readonly string[] {\n const key = JSON.stringify({ metroSourceExtensions, platform, isNative });\n if (cachedExtensions.has(key)) {\n return cachedExtensions.get(key)!;\n }\n\n let output = metroSourceExtensions;\n if (platform) {\n const nextOutput: string[] = [];\n\n output.forEach((ext) => {\n nextOutput.push(`${platform}.${ext}`);\n if (isNative) {\n nextOutput.push(`native.${ext}`);\n }\n nextOutput.push(ext);\n });\n\n output = nextOutput;\n }\n\n output = Array.from(new Set<string>(output));\n\n // resolve expects these to start with a dot.\n output = output.map((ext) => `.${ext}`);\n\n cachedExtensions.set(key, output);\n\n return output;\n }\n\n function fastResolve(\n context: Pick<\n ResolutionContext,\n | 'unstable_enablePackageExports'\n | 'customResolverOptions'\n | 'sourceExts'\n | 'preferNativePlatform'\n | 'originModulePath'\n | 'getPackage'\n | 'nodeModulesPaths'\n | 'mainFields'\n | 'resolveAsset'\n | 'unstable_conditionNames'\n | 'unstable_conditionsByPlatform'\n >,\n moduleName: string,\n platform: string | null\n ): Resolution {\n const environment = context.customResolverOptions?.environment;\n const isServer = environment === 'node';\n\n const extensions = getAdjustedExtensions({\n metroSourceExtensions: context.sourceExts,\n platform,\n isNative: context.preferNativePlatform,\n }) as string[];\n\n let fp: string;\n\n try {\n const conditions = context.unstable_enablePackageExports\n ? [\n ...new Set([\n 'default',\n ...context.unstable_conditionNames,\n ...(platform != null ? context.unstable_conditionsByPlatform[platform] ?? [] : []),\n ]),\n ]\n : [];\n\n fp = jestResolver(moduleName, {\n blockList,\n enablePackageExports: context.unstable_enablePackageExports,\n basedir: path.dirname(context.originModulePath),\n paths: context.nodeModulesPaths as string[],\n extensions,\n conditions,\n // @ts-ignore\n realpathSync: context.unstable_getRealPath,\n packageFilter(pkg) {\n // set the pkg.main to the first available field in context.mainFields\n for (const field of context.mainFields) {\n if (\n pkg[field] &&\n // object-inspect uses browser: {} in package.json\n typeof pkg[field] === 'string'\n ) {\n return {\n ...pkg,\n main: pkg[field],\n };\n }\n }\n return pkg;\n },\n // Used to ensure files trace to packages instead of node_modules in expo/expo. This is how Metro works and\n // the app doesn't finish without it.\n preserveSymlinks,\n readPackageSync(readFileSync, pkgFile) {\n return (\n context.getPackage(pkgFile) ??\n JSON.parse(\n // @ts-expect-error\n readFileSync(pkgfile)\n )\n );\n },\n includeCoreModules: isServer,\n\n pathFilter:\n // Disable `browser` field for server environments.\n isServer\n ? undefined\n : // Enable `browser` field support\n (pkg: any, _resolvedPath: string, relativePathIn: string): string => {\n let relativePath = relativePathIn;\n if (relativePath[0] !== '.') {\n relativePath = `./${relativePath}`;\n }\n\n const replacements = pkg.browser;\n if (replacements === undefined) {\n return '';\n }\n\n // TODO: Probably use a better extension matching system here.\n // This was added for `uuid/v4` -> `./lib/rng` -> `./lib/rng-browser.js`\n const mappedPath = replacements[relativePath] ?? replacements[relativePath + '.js'];\n if (mappedPath === false) {\n throw new ShimModuleError();\n }\n return mappedPath;\n },\n });\n } catch (error: any) {\n if (error instanceof ShimModuleError) {\n return {\n type: 'empty',\n };\n }\n\n if ('code' in error && error.code === 'MODULE_NOT_FOUND') {\n if (isNodeExternal(moduleName)) {\n // In this case, mock the file to use an empty module.\n return {\n type: 'empty',\n };\n }\n\n // TODO: Add improved error handling.\n throw new FailedToResolvePathError(\n 'The module could not be resolved because no file or module matched the pattern:\\n' +\n ` ${formatFileCandidates(\n {\n type: 'sourceFile',\n filePathPrefix: moduleName,\n candidateExts: extensions,\n },\n true\n )}\\n\\n`\n );\n }\n throw error;\n }\n\n if (context.sourceExts.some((ext) => fp.endsWith(ext))) {\n return {\n type: 'sourceFile',\n filePath: fp,\n };\n }\n\n if (isNodeExternal(fp)) {\n if (isServer) {\n return {\n type: 'sourceFile',\n filePath: fp,\n };\n }\n // NOTE: This shouldn't happen, the module should throw.\n // Mock non-server built-in modules to empty.\n return {\n type: 'empty',\n };\n }\n\n // NOTE: platform extensions may not be supported on assets.\n\n if (platform === 'web') {\n // Skip multi-resolution on web/server bundles. Only consideration here is that\n // we may still need it in case the only image is a multi-resolution image.\n return {\n type: 'assetFiles',\n filePaths: [fp],\n };\n }\n\n const dirPath = path.dirname(fp);\n const extension = path.extname(fp);\n const basename = path.basename(fp, extension);\n return {\n type: 'assetFiles',\n // Support multi-resolution asset extensions...\n filePaths: context.resolveAsset(dirPath, basename, extension) ?? [fp],\n };\n }\n\n return fastResolve;\n}\n"],"names":["createFastResolver","FailedToResolvePathError","Error","ShimModuleError","preserveSymlinks","blockList","cachedExtensions","Map","getAdjustedExtensions","metroSourceExtensions","platform","isNative","key","JSON","stringify","has","get","output","nextOutput","forEach","ext","push","Array","from","Set","map","set","fastResolve","context","moduleName","environment","customResolverOptions","isServer","extensions","sourceExts","preferNativePlatform","fp","conditions","unstable_enablePackageExports","unstable_conditionNames","unstable_conditionsByPlatform","jestResolver","enablePackageExports","basedir","path","dirname","originModulePath","paths","nodeModulesPaths","realpathSync","unstable_getRealPath","packageFilter","pkg","field","mainFields","main","readPackageSync","readFileSync","pkgFile","getPackage","parse","pkgfile","includeCoreModules","pathFilter","undefined","_resolvedPath","relativePathIn","relativePath","replacements","browser","mappedPath","error","type","code","isNodeExternal","formatFileCandidates","filePathPrefix","candidateExts","some","endsWith","filePath","filePaths","dirPath","extension","extname","basename","resolveAsset"],"mappings":"AAMA;;;;QAWgBA,kBAAkB,GAAlBA,kBAAkB;AAVjB,IAAA,KAAM,kCAAN,MAAM,EAAA;AAEE,IAAA,gBAAmB,kCAAnB,mBAAmB,EAAA;AACb,IAAA,UAAa,WAAb,aAAa,CAAA;AACP,IAAA,qBAAwB,WAAxB,wBAAwB,CAAA;;;;;;AAE7D,MAAMC,wBAAwB,SAASC,KAAK;CAAG;AAE/C,MAAMC,eAAe,SAASD,KAAK;CAAG;AAE/B,SAASF,kBAAkB,CAAC,EACjCI,gBAAgB,CAAA,EAChBC,SAAS,CAAA,EAIV,EAAE;IAC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5D,IAAI9D,QAAQ,KAAK,KAAK,EAAE;YACtB,+EAA+E;YAC/E,2EAA2E;YAC3E,OAAO;gBACL8D,IAAI,EAAE,YAAY;gBAClBS,SAAS,EAAE;oBAAC7C,EAAE;iBAAC;aAChB,CAAC;SACH;QAED,MAAM8C,OAAO,GAAGtC,KAAI,QAAA,CAACC,OAAO,CAACT,EAAE,CAAC,AAAC;QACjC,MAAM+C,SAAS,GAAGvC,KAAI,QAAA,CAACwC,OAAO,CAAChD,EAAE,CAAC,AAAC;QACnC,MAAMiD,QAAQ,GAAGzC,KAAI,QAAA,CAACyC,QAAQ,CAACjD,EAAE,EAAE+C,SAAS,CAAC,AAAC;YAIjCvD,IAAkD;QAH/D,OAAO;YACL4C,IAAI,EAAE,YAAY;YAClB,+CAA+C;YAC/CS,SAAS,EAAErD,CAAAA,IAAkD,GAAlDA,OAAO,CAAC0D,YAAY,CAACJ,OAAO,EAAEG,QAAQ,EAAEF,SAAS,CAAC,YAAlDvD,IAAkD,GAAI;gBAACQ,EAAE;aAAC;SACtE,CAAC;KACH;IAED,OAAOT,WAAW,CAAC;CACpB"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/createExpoMetroResolver.ts"],"sourcesContent":["/**\n * Copyright © 2023 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport fs from 'fs';\nimport { Resolution, ResolutionContext } from 'metro-resolver';\nimport path from 'path';\n\nimport jestResolver from './createJResolver';\nimport { isNodeExternal } from './externals';\nimport { formatFileCandidates } from './formatFileCandidates';\n\nclass FailedToResolvePathError extends Error {}\n\nclass ShimModuleError extends Error {}\n\nconst realpathFS =\n process.platform !== 'win32' && fs.realpathSync && typeof fs.realpathSync.native === 'function'\n ? fs.realpathSync.native\n : fs.realpathSync;\n\nfunction realpathSync(x: string) {\n try {\n return realpathFS(x);\n } catch (realpathErr: any) {\n if (realpathErr.code !== 'ENOENT') {\n throw realpathErr;\n }\n }\n return x;\n}\n\nexport function createFastResolver({\n preserveSymlinks,\n blockList,\n}: {\n preserveSymlinks: boolean;\n blockList: RegExp[];\n}) {\n const cachedExtensions: Map<string, readonly string[]> = new Map();\n\n function getAdjustedExtensions({\n metroSourceExtensions,\n platform,\n isNative,\n }: {\n metroSourceExtensions: readonly string[];\n platform: string | null;\n isNative: boolean;\n }): readonly string[] {\n const key = JSON.stringify({ metroSourceExtensions, platform, isNative });\n if (cachedExtensions.has(key)) {\n return cachedExtensions.get(key)!;\n }\n\n let output = metroSourceExtensions;\n if (platform) {\n const nextOutput: string[] = [];\n\n output.forEach((ext) => {\n nextOutput.push(`${platform}.${ext}`);\n if (isNative) {\n nextOutput.push(`native.${ext}`);\n }\n nextOutput.push(ext);\n });\n\n output = nextOutput;\n }\n\n output = Array.from(new Set<string>(output));\n\n // resolve expects these to start with a dot.\n output = output.map((ext) => `.${ext}`);\n\n cachedExtensions.set(key, output);\n\n return output;\n }\n\n function fastResolve(\n context: Pick<\n ResolutionContext,\n | 'unstable_enablePackageExports'\n | 'customResolverOptions'\n | 'sourceExts'\n | 'preferNativePlatform'\n | 'originModulePath'\n | 'getPackage'\n | 'nodeModulesPaths'\n | 'mainFields'\n | 'resolveAsset'\n | 'unstable_conditionNames'\n | 'unstable_conditionsByPlatform'\n >,\n moduleName: string,\n platform: string | null\n ): Resolution {\n const environment = context.customResolverOptions?.environment;\n const isServer = environment === 'node';\n\n const extensions = getAdjustedExtensions({\n metroSourceExtensions: context.sourceExts,\n platform,\n isNative: context.preferNativePlatform,\n }) as string[];\n\n let fp: string;\n\n try {\n const conditions = context.unstable_enablePackageExports\n ? [\n ...new Set([\n 'default',\n ...context.unstable_conditionNames,\n ...(platform != null ? context.unstable_conditionsByPlatform[platform] ?? [] : []),\n ]),\n ]\n : [];\n\n fp = jestResolver(moduleName, {\n blockList,\n enablePackageExports: context.unstable_enablePackageExports,\n basedir: path.dirname(context.originModulePath),\n paths: context.nodeModulesPaths.length ? (context.nodeModulesPaths as string[]) : undefined,\n extensions,\n conditions,\n realpathSync(file: string): string {\n // @ts-expect-error: Missing on type.\n const metroRealPath = context.unstable_getRealPath?.(file);\n if (metroRealPath == null && preserveSymlinks) {\n return realpathSync(file);\n }\n return metroRealPath ?? file;\n },\n packageFilter(pkg) {\n // set the pkg.main to the first available field in context.mainFields\n for (const field of context.mainFields) {\n if (\n pkg[field] &&\n // object-inspect uses browser: {} in package.json\n typeof pkg[field] === 'string'\n ) {\n return {\n ...pkg,\n main: pkg[field],\n };\n }\n }\n return pkg;\n },\n // Used to ensure files trace to packages instead of node_modules in expo/expo. This is how Metro works and\n // the app doesn't finish without it.\n preserveSymlinks,\n readPackageSync(readFileSync, pkgFile) {\n return (\n context.getPackage(pkgFile) ??\n JSON.parse(\n // @ts-expect-error\n readFileSync(pkgfile)\n )\n );\n },\n includeCoreModules: isServer,\n\n pathFilter:\n // Disable `browser` field for server environments.\n isServer\n ? undefined\n : // Enable `browser` field support\n (pkg: any, _resolvedPath: string, relativePathIn: string): string => {\n let relativePath = relativePathIn;\n if (relativePath[0] !== '.') {\n relativePath = `./${relativePath}`;\n }\n\n const replacements = pkg.browser;\n if (replacements === undefined) {\n return '';\n }\n\n // TODO: Probably use a better extension matching system here.\n // This was added for `uuid/v4` -> `./lib/rng` -> `./lib/rng-browser.js`\n const mappedPath = replacements[relativePath] ?? replacements[relativePath + '.js'];\n if (mappedPath === false) {\n throw new ShimModuleError();\n }\n return mappedPath;\n },\n });\n } catch (error: any) {\n if (error instanceof ShimModuleError) {\n return {\n type: 'empty',\n };\n }\n\n if ('code' in error && error.code === 'MODULE_NOT_FOUND') {\n if (isNodeExternal(moduleName)) {\n // In this case, mock the file to use an empty module.\n return {\n type: 'empty',\n };\n }\n\n throw new FailedToResolvePathError(\n 'The module could not be resolved because no file or module matched the pattern:\\n' +\n ` ${formatFileCandidates(\n {\n type: 'sourceFile',\n filePathPrefix: moduleName,\n candidateExts: extensions,\n },\n true\n )}\\n\\nFrom:\\n ${context.originModulePath}\\n`\n );\n }\n throw error;\n }\n\n if (context.sourceExts.some((ext) => fp.endsWith(ext))) {\n return {\n type: 'sourceFile',\n filePath: fp,\n };\n }\n\n if (isNodeExternal(fp)) {\n if (isServer) {\n return {\n type: 'sourceFile',\n filePath: fp,\n };\n }\n // NOTE: This shouldn't happen, the module should throw.\n // Mock non-server built-in modules to empty.\n return {\n type: 'empty',\n };\n }\n\n // NOTE: platform extensions may not be supported on assets.\n\n if (platform === 'web') {\n // Skip multi-resolution on web/server bundles. Only consideration here is that\n // we may still need it in case the only image is a multi-resolution image.\n return {\n type: 'assetFiles',\n filePaths: [fp],\n };\n }\n\n const dirPath = path.dirname(fp);\n const extension = path.extname(fp);\n const basename = path.basename(fp, extension);\n return {\n type: 'assetFiles',\n // Support multi-resolution asset extensions...\n filePaths: context.resolveAsset(dirPath, basename, extension) ?? [fp],\n };\n }\n\n return fastResolve;\n}\n"],"names":["createFastResolver","FailedToResolvePathError","Error","ShimModuleError","realpathFS","process","platform","fs","realpathSync","native","x","realpathErr","code","preserveSymlinks","blockList","cachedExtensions","Map","getAdjustedExtensions","metroSourceExtensions","isNative","key","JSON","stringify","has","get","output","nextOutput","forEach","ext","push","Array","from","Set","map","set","fastResolve","context","moduleName","environment","customResolverOptions","isServer","extensions","sourceExts","preferNativePlatform","fp","conditions","unstable_enablePackageExports","unstable_conditionNames","unstable_conditionsByPlatform","jestResolver","enablePackageExports","basedir","path","dirname","originModulePath","paths","nodeModulesPaths","length","undefined","file","metroRealPath","unstable_getRealPath","packageFilter","pkg","field","mainFields","main","readPackageSync","readFileSync","pkgFile","getPackage","parse","pkgfile","includeCoreModules","pathFilter","_resolvedPath","relativePathIn","relativePath","replacements","browser","mappedPath","error","type","isNodeExternal","formatFileCandidates","filePathPrefix","candidateExts","some","endsWith","filePath","filePaths","dirPath","extension","extname","basename","resolveAsset"],"mappings":"AAMA;;;;QA4BgBA,kBAAkB,GAAlBA,kBAAkB;AA5BnB,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAEF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C/E,2EAA2E;YAC3E,OAAO;gBACL4E,IAAI,EAAE,YAAY;gBAClBQ,SAAS,EAAE;oBAAC9C,EAAE;iBAAC;aAChB,CAAC;SACH;QAED,MAAM+C,OAAO,GAAGvC,KAAI,QAAA,CAACC,OAAO,CAACT,EAAE,CAAC,AAAC;QACjC,MAAMgD,SAAS,GAAGxC,KAAI,QAAA,CAACyC,OAAO,CAACjD,EAAE,CAAC,AAAC;QACnC,MAAMkD,QAAQ,GAAG1C,KAAI,QAAA,CAAC0C,QAAQ,CAAClD,EAAE,EAAEgD,SAAS,CAAC,AAAC;YAIjCxD,IAAkD;QAH/D,OAAO;YACL8C,IAAI,EAAE,YAAY;YAClB,+CAA+C;YAC/CQ,SAAS,EAAEtD,CAAAA,IAAkD,GAAlDA,OAAO,CAAC2D,YAAY,CAACJ,OAAO,EAAEG,QAAQ,EAAEF,SAAS,CAAC,YAAlDxD,IAAkD,GAAI;gBAACQ,EAAE;aAAC;SACtE,CAAC;KACH;IAED,OAAOT,WAAW,CAAC;CACpB"}
@@ -52,12 +52,15 @@ const defaultResolver = (path, { enablePackageExports , blockList =[] , ...optio
52
52
  }
53
53
  return (0, _dir).fileExistsSync(file);
54
54
  },
55
- preserveSymlinks: enablePackageExports ? false : options.preserveSymlinks,
55
+ preserveSymlinks: options.preserveSymlinks,
56
56
  defaultResolver
57
57
  };
58
58
  // resolveSync dereferences symlinks to ensure we don't create a separate
59
59
  // module instance depending on how it was referenced.
60
- const result = (0, _resolve).sync(enablePackageExports ? getPathInModule(path, resolveOptions) : path, resolveOptions);
60
+ const result = (0, _resolve).sync(enablePackageExports ? getPathInModule(path, resolveOptions) : path, {
61
+ ...resolveOptions,
62
+ preserveSymlinks: !options.preserveSymlinks
63
+ });
61
64
  return result;
62
65
  };
63
66
  var _default = defaultResolver;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/createJResolver.ts"],"sourcesContent":["/**\n * Copyright © 2023 650 Industries.\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * Fork of the jest resolver but with additional settings for Metro and pnp removed.\n * https://github.com/jestjs/jest/blob/d1a2ed7fea4bdc19836274cd810c8360e3ab62f3/packages/jest-resolve/src/defaultResolver.ts#L1\n */\nimport type { JSONObject as PackageJSON } from '@expo/json-file';\nimport assert from 'assert';\nimport { dirname, isAbsolute, resolve as pathResolve } from 'path';\nimport { sync as resolveSync, SyncOpts as UpstreamResolveOptions } from 'resolve';\nimport * as resolve from 'resolve.exports';\n\nimport { directoryExistsSync, fileExistsSync } from '../../../utils/dir';\n\n/**\n * Allows transforming parsed `package.json` contents.\n *\n * @param pkg - Parsed `package.json` contents.\n * @param file - Path to `package.json` file.\n * @param dir - Directory that contains the `package.json`.\n *\n * @returns Transformed `package.json` contents.\n */\nexport type PackageFilter = (pkg: PackageJSON, file: string, dir: string) => PackageJSON;\n\n/**\n * Allows transforming a path within a package.\n *\n * @param pkg - Parsed `package.json` contents.\n * @param path - Path being resolved.\n * @param relativePath - Path relative from the `package.json` location.\n *\n * @returns Relative path that will be joined from the `package.json` location.\n */\nexport type PathFilter = (pkg: PackageJSON, path: string, relativePath: string) => string;\n\nexport type ResolverOptions = {\n /** Directory to begin resolving from. */\n basedir: string;\n /** List of export conditions. */\n conditions?: string[];\n /** Instance of default resolver. */\n defaultResolver: typeof defaultResolver;\n /** List of file extensions to search in order. */\n extensions?: string[];\n /**\n * List of directory names to be looked up for modules recursively.\n *\n * @defaultValue\n * The default is `['node_modules']`.\n */\n moduleDirectory?: string[];\n /**\n * List of `require.paths` to use if nothing is found in `node_modules`.\n *\n * @defaultValue\n * The default is `undefined`.\n */\n paths?: string[];\n /** Allows transforming parsed `package.json` contents. */\n packageFilter?: PackageFilter;\n /** Allows transforms a path within a package. */\n pathFilter?: PathFilter;\n /** Current root directory. */\n rootDir?: string;\n\n enablePackageExports?: boolean;\n\n blockList: RegExp[];\n} & Pick<\n UpstreamResolveOptions,\n 'readPackageSync' | 'moduleDirectory' | 'extensions' | 'preserveSymlinks' | 'includeCoreModules'\n>;\n\ntype UpstreamResolveOptionsWithConditions = UpstreamResolveOptions & ResolverOptions;\n\nexport type SyncResolver = (path: string, options: ResolverOptions) => string;\nexport type AsyncResolver = (path: string, options: ResolverOptions) => Promise<string>;\n\nexport type Resolver = SyncResolver | AsyncResolver;\n\nconst defaultResolver: SyncResolver = (\n path,\n { enablePackageExports, blockList = [], ...options }\n) => {\n // @ts-expect-error\n const resolveOptions: UpstreamResolveOptionsWithConditions = {\n ...options,\n\n isDirectory(file) {\n if (blockList.some((regex) => regex.test(file))) {\n return false;\n }\n return directoryExistsSync(file);\n },\n isFile(file) {\n if (blockList.some((regex) => regex.test(file))) {\n return false;\n }\n return fileExistsSync(file);\n },\n preserveSymlinks: enablePackageExports ? false : options.preserveSymlinks,\n defaultResolver,\n };\n\n // resolveSync dereferences symlinks to ensure we don't create a separate\n // module instance depending on how it was referenced.\n const result = resolveSync(\n enablePackageExports ? getPathInModule(path, resolveOptions) : path,\n resolveOptions\n );\n\n return result;\n};\n\nexport default defaultResolver;\n\n/*\n * helper functions\n */\n\nfunction getPathInModule(path: string, options: UpstreamResolveOptionsWithConditions): string {\n if (shouldIgnoreRequestForExports(path)) {\n return path;\n }\n\n const segments = path.split('/');\n\n let moduleName = segments.shift();\n\n if (moduleName) {\n if (moduleName.startsWith('@')) {\n moduleName = `${moduleName}/${segments.shift()}`;\n }\n\n // Disable package exports for babel/runtime for https://github.com/facebook/metro/issues/984/\n if (moduleName === '@babel/runtime') {\n return path;\n }\n\n // self-reference\n const closestPackageJson = findClosestPackageJson(options.basedir, options);\n if (closestPackageJson) {\n const pkg = options.readPackageSync!(options.readFileSync!, closestPackageJson);\n assert(pkg, 'package.json should be read by `readPackageSync`');\n\n if (pkg.name === moduleName) {\n const resolved = resolve.exports(\n pkg,\n (segments.join('/') || '.') as resolve.Exports.Entry,\n createResolveOptions(options.conditions)\n );\n\n if (resolved) {\n return pathResolve(dirname(closestPackageJson), resolved[0]);\n }\n\n if (pkg.exports) {\n throw new Error(\n \"`exports` exists, but no results - this is a bug in Expo CLI's Metro resolver. Please report an issue\"\n );\n }\n }\n }\n\n let packageJsonPath = '';\n\n try {\n packageJsonPath = resolveSync(`${moduleName}/package.json`, options);\n } catch {\n // ignore if package.json cannot be found\n }\n\n if (packageJsonPath && options.isFile!(packageJsonPath)) {\n const pkg = options.readPackageSync!(options.readFileSync!, packageJsonPath);\n assert(pkg, 'package.json should be read by `readPackageSync`');\n\n const resolved = resolve.exports(\n pkg,\n (segments.join('/') || '.') as resolve.Exports.Entry,\n createResolveOptions(options.conditions)\n );\n\n if (resolved) {\n return pathResolve(dirname(packageJsonPath), resolved[0]);\n }\n\n if (pkg.exports) {\n throw new Error(\n \"`exports` exists, but no results - this is a bug in Expo CLI's Metro resolver. Please report an issue\"\n );\n }\n }\n }\n\n return path;\n}\n\nfunction createResolveOptions(conditions: string[] | undefined): resolve.Options {\n return conditions\n ? { conditions, unsafe: true }\n : // no conditions were passed - let's assume this is Jest internal and it should be `require`\n { browser: false, require: true };\n}\n\n// if it's a relative import or an absolute path, imports/exports are ignored\nconst shouldIgnoreRequestForExports = (path: string) => path.startsWith('.') || isAbsolute(path);\n\n// adapted from\n// https://github.com/lukeed/escalade/blob/2477005062cdbd8407afc90d3f48f4930354252b/src/sync.js\nfunction findClosestPackageJson(\n start: string,\n options: UpstreamResolveOptions\n): string | undefined {\n let dir = pathResolve('.', start);\n if (!options.isDirectory!(dir)) {\n dir = dirname(dir);\n }\n\n while (true) {\n const pkgJsonFile = pathResolve(dir, './package.json');\n const hasPackageJson = options.isFile!(pkgJsonFile);\n\n if (hasPackageJson) {\n return pkgJsonFile;\n }\n\n const prevDir = dir;\n dir = dirname(dir);\n\n if (prevDir === dir) {\n return undefined;\n }\n }\n}\n"],"names":["resolve","defaultResolver","path","enablePackageExports","blockList","options","resolveOptions","isDirectory","file","some","regex","test","directoryExistsSync","isFile","fileExistsSync","preserveSymlinks","result","resolveSync","getPathInModule","shouldIgnoreRequestForExports","segments","split","moduleName","shift","startsWith","closestPackageJson","findClosestPackageJson","basedir","pkg","readPackageSync","readFileSync","assert","name","resolved","exports","join","createResolveOptions","conditions","pathResolve","dirname","Error","packageJsonPath","unsafe","browser","require","isAbsolute","start","dir","pkgJsonFile","hasPackageJson","prevDir","undefined"],"mappings":"AAUA;;;;;AACmB,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACiC,IAAA,KAAM,WAAN,MAAM,CAAA;AACM,IAAA,QAAS,WAAT,SAAS,CAAA;AACrEA,IAAAA,OAAO,mCAAM,iBAAiB,EAAvB;AAEiC,IAAA,IAAoB,WAApB,oBAAoB,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqExE,MAAMC,eAAe,GAAiB,CACpCC,IAAI,EACJ,EAAEC,oBAAoB,CAAA,EAAEC,SAAS,EAAG,EAAE,CAAA,EAAE,GAAGC,OAAO,EAAE,GACjD;IACH,mBAAmB;IACnB,MAAMC,cAAc,GAAyC;QAC3D,GAAGD,OAAO;QAEVE,WAAW,EAACC,IAAI,EAAE;YAChB,IAAIJ,SAAS,CAACK,IAAI,CAAC,CAACC,KAAK,GAAKA,KAAK,CAACC,IAAI,CAACH,IAAI,CAAC;YAAA,CAAC,EAAE;gBAC/C,OAAO,KAAK,CAAC;aACd;YACD,OAAOI,CAAAA,GAAAA,IAAmB,AAAM,CAAA,oBAAN,CAACJ,IAAI,CAAC,CAAC;SAClC;QACDK,MAAM,EAACL,IAAI,EAAE;YACX,IAAIJ,SAAS,CAACK,IAAI,CAAC,CAACC,KAAK,GAAKA,KAAK,CAACC,IAAI,CAACH,IAAI,CAAC;YAAA,CAAC,EAAE;gBAC/C,OAAO,KAAK,CAAC;aACd;YACD,OAAOM,CAAAA,GAAAA,IAAc,AAAM,CAAA,eAAN,CAACN,IAAI,CAAC,CAAC;SAC7B;QACDO,gBAAgB,EAAEZ,oBAAoB,GAAG,KAAK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,AAAC;QACpBA,GAAG,GAAGR,CAAAA,GAAAA,KAAO,AAAK,CAAA,QAAL,CAACQ,GAAG,CAAC,CAAC;QAEnB,IAAIG,OAAO,KAAKH,GAAG,EAAE;YACnB,OAAOI,SAAS,CAAC;SAClB;KACF;CACF"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/createJResolver.ts"],"sourcesContent":["/**\n * Copyright © 2023 650 Industries.\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * Fork of the jest resolver but with additional settings for Metro and pnp removed.\n * https://github.com/jestjs/jest/blob/d1a2ed7fea4bdc19836274cd810c8360e3ab62f3/packages/jest-resolve/src/defaultResolver.ts#L1\n */\nimport type { JSONObject as PackageJSON } from '@expo/json-file';\nimport assert from 'assert';\nimport { dirname, isAbsolute, resolve as pathResolve } from 'path';\nimport { sync as resolveSync, SyncOpts as UpstreamResolveOptions } from 'resolve';\nimport * as resolve from 'resolve.exports';\n\nimport { directoryExistsSync, fileExistsSync } from '../../../utils/dir';\n\n/**\n * Allows transforming parsed `package.json` contents.\n *\n * @param pkg - Parsed `package.json` contents.\n * @param file - Path to `package.json` file.\n * @param dir - Directory that contains the `package.json`.\n *\n * @returns Transformed `package.json` contents.\n */\ntype PackageFilter = (pkg: PackageJSON, file: string, dir: string) => PackageJSON;\n\n/**\n * Allows transforming a path within a package.\n *\n * @param pkg - Parsed `package.json` contents.\n * @param path - Path being resolved.\n * @param relativePath - Path relative from the `package.json` location.\n *\n * @returns Relative path that will be joined from the `package.json` location.\n */\ntype PathFilter = (pkg: PackageJSON, path: string, relativePath: string) => string;\n\ntype ResolverOptions = {\n /** Directory to begin resolving from. */\n basedir: string;\n /** List of export conditions. */\n conditions?: string[];\n /** Instance of default resolver. */\n defaultResolver: typeof defaultResolver;\n /** List of file extensions to search in order. */\n extensions?: string[];\n /**\n * List of directory names to be looked up for modules recursively.\n *\n * @defaultValue\n * The default is `['node_modules']`.\n */\n moduleDirectory?: string[];\n /**\n * List of `require.paths` to use if nothing is found in `node_modules`.\n *\n * @defaultValue\n * The default is `undefined`.\n */\n paths?: string[];\n /** Allows transforming parsed `package.json` contents. */\n packageFilter?: PackageFilter;\n /** Allows transforms a path within a package. */\n pathFilter?: PathFilter;\n /** Current root directory. */\n rootDir?: string;\n\n enablePackageExports?: boolean;\n\n blockList: RegExp[];\n\n getPackageForModule: import('metro-resolver').CustomResolutionContext['getPackageForModule'];\n} & Pick<\n UpstreamResolveOptions,\n | 'readPackageSync'\n | 'realpathSync'\n | 'moduleDirectory'\n | 'extensions'\n | 'preserveSymlinks'\n | 'includeCoreModules'\n>;\n\ntype UpstreamResolveOptionsWithConditions = UpstreamResolveOptions & ResolverOptions;\n\nconst defaultResolver = (\n path: string,\n {\n enablePackageExports,\n blockList = [],\n ...options\n }: Omit<ResolverOptions, 'defaultResolver' | 'getPackageForModule'>\n): string => {\n // @ts-expect-error\n const resolveOptions: UpstreamResolveOptionsWithConditions = {\n ...options,\n\n isDirectory(file) {\n if (blockList.some((regex) => regex.test(file))) {\n return false;\n }\n return directoryExistsSync(file);\n },\n isFile(file) {\n if (blockList.some((regex) => regex.test(file))) {\n return false;\n }\n return fileExistsSync(file);\n },\n preserveSymlinks: options.preserveSymlinks,\n defaultResolver,\n };\n\n // resolveSync dereferences symlinks to ensure we don't create a separate\n // module instance depending on how it was referenced.\n const result = resolveSync(enablePackageExports ? getPathInModule(path, resolveOptions) : path, {\n ...resolveOptions,\n preserveSymlinks: !options.preserveSymlinks,\n });\n\n return result;\n};\n\nexport default defaultResolver;\n\n/*\n * helper functions\n */\n\nfunction getPathInModule(path: string, options: UpstreamResolveOptionsWithConditions): string {\n if (shouldIgnoreRequestForExports(path)) {\n return path;\n }\n\n const segments = path.split('/');\n\n let moduleName = segments.shift();\n\n if (moduleName) {\n if (moduleName.startsWith('@')) {\n moduleName = `${moduleName}/${segments.shift()}`;\n }\n\n // Disable package exports for babel/runtime for https://github.com/facebook/metro/issues/984/\n if (moduleName === '@babel/runtime') {\n return path;\n }\n\n // self-reference\n const closestPackageJson = findClosestPackageJson(options.basedir, options);\n if (closestPackageJson) {\n const pkg = options.readPackageSync!(options.readFileSync!, closestPackageJson);\n assert(pkg, 'package.json should be read by `readPackageSync`');\n\n if (pkg.name === moduleName) {\n const resolved = resolve.exports(\n pkg,\n (segments.join('/') || '.') as resolve.Exports.Entry,\n createResolveOptions(options.conditions)\n );\n\n if (resolved) {\n return pathResolve(dirname(closestPackageJson), resolved[0]);\n }\n\n if (pkg.exports) {\n throw new Error(\n \"`exports` exists, but no results - this is a bug in Expo CLI's Metro resolver. Please report an issue\"\n );\n }\n }\n }\n\n let packageJsonPath = '';\n\n try {\n packageJsonPath = resolveSync(`${moduleName}/package.json`, options);\n } catch {\n // ignore if package.json cannot be found\n }\n\n if (packageJsonPath && options.isFile!(packageJsonPath)) {\n const pkg = options.readPackageSync!(options.readFileSync!, packageJsonPath);\n assert(pkg, 'package.json should be read by `readPackageSync`');\n\n const resolved = resolve.exports(\n pkg,\n (segments.join('/') || '.') as resolve.Exports.Entry,\n createResolveOptions(options.conditions)\n );\n\n if (resolved) {\n return pathResolve(dirname(packageJsonPath), resolved[0]);\n }\n\n if (pkg.exports) {\n throw new Error(\n \"`exports` exists, but no results - this is a bug in Expo CLI's Metro resolver. Please report an issue\"\n );\n }\n }\n }\n\n return path;\n}\n\nfunction createResolveOptions(conditions: string[] | undefined): resolve.Options {\n return conditions\n ? { conditions, unsafe: true }\n : // no conditions were passed - let's assume this is Jest internal and it should be `require`\n { browser: false, require: true };\n}\n\n// if it's a relative import or an absolute path, imports/exports are ignored\nconst shouldIgnoreRequestForExports = (path: string) => path.startsWith('.') || isAbsolute(path);\n\n// adapted from\n// https://github.com/lukeed/escalade/blob/2477005062cdbd8407afc90d3f48f4930354252b/src/sync.js\nfunction findClosestPackageJson(\n start: string,\n options: UpstreamResolveOptions\n): string | undefined {\n let dir = pathResolve('.', start);\n if (!options.isDirectory!(dir)) {\n dir = dirname(dir);\n }\n\n while (true) {\n const pkgJsonFile = pathResolve(dir, './package.json');\n const hasPackageJson = options.isFile!(pkgJsonFile);\n\n if (hasPackageJson) {\n return pkgJsonFile;\n }\n\n const prevDir = dir;\n dir = dirname(dir);\n\n if (prevDir === dir) {\n return undefined;\n }\n }\n}\n"],"names":["resolve","defaultResolver","path","enablePackageExports","blockList","options","resolveOptions","isDirectory","file","some","regex","test","directoryExistsSync","isFile","fileExistsSync","preserveSymlinks","result","resolveSync","getPathInModule","shouldIgnoreRequestForExports","segments","split","moduleName","shift","startsWith","closestPackageJson","findClosestPackageJson","basedir","pkg","readPackageSync","readFileSync","assert","name","resolved","exports","join","createResolveOptions","conditions","pathResolve","dirname","Error","packageJsonPath","unsafe","browser","require","isAbsolute","start","dir","pkgJsonFile","hasPackageJson","prevDir","undefined"],"mappings":"AAUA;;;;;AACmB,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACiC,IAAA,KAAM,WAAN,MAAM,CAAA;AACM,IAAA,QAAS,WAAT,SAAS,CAAA;AACrEA,IAAAA,OAAO,mCAAM,iBAAiB,EAAvB;AAEiC,IAAA,IAAoB,WAApB,oBAAoB,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuExE,MAAMC,eAAe,GAAG,CACtBC,IAAY,EACZ,EACEC,oBAAoB,CAAA,EACpBC,SAAS,EAAG,EAAE,CAAA,EACd,GAAGC,OAAO,EACuD,GACxD;IACX,mBAAmB;IACnB,MAAMC,cAAc,GAAyC;QAC3D,GAAGD,OAAO;QAEVE,WAAW,EAACC,IAAI,EAAE;YAChB,IAAIJ,SAAS,CAACK,IAAI,CAAC,CAACC,KAAK,GAAKA,KAAK,CAACC,IAAI,CAACH,IAAI,CAAC;YAAA,CAAC,EAAE;gBAC/C,OAAO,KAAK,CAAC;aACd;YACD,OAAOI,CAAAA,GAAAA,IAAmB,AAAM,CAAA,oBAAN,CAACJ,IAAI,CAAC,CAAC;SAClC;QACDK,MA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CAAA,QAAL,CAACQ,GAAG,CAAC,CAAC;KACpB;IAED,MAAO,IAAI,CAAE;QACX,MAAMC,WAAW,GAAGV,CAAAA,GAAAA,KAAW,AAAuB,CAAA,QAAvB,CAACS,GAAG,EAAE,gBAAgB,CAAC,AAAC;QACvD,MAAME,cAAc,GAAG5C,OAAO,CAACQ,MAAM,CAAEmC,WAAW,CAAC,AAAC;QAEpD,IAAIC,cAAc,EAAE;YAClB,OAAOD,WAAW,CAAC;SACpB;QAED,MAAME,OAAO,GAAGH,GAAG,AAAC;QACpBA,GAAG,GAAGR,CAAAA,GAAAA,KAAO,AAAK,CAAA,QAAL,CAACQ,GAAG,CAAC,CAAC;QAEnB,IAAIG,OAAO,KAAKH,GAAG,EAAE;YACnB,OAAOI,SAAS,CAAC;SAClB;KACF;CACF"}
@@ -60,7 +60,8 @@ function createRouteHandlerMiddleware(projectRoot, options) {
60
60
  try {
61
61
  return new _server.ExpoResponse(await (0, _metroErrorInterface).getErrorOverlayHtmlAsync({
62
62
  error,
63
- projectRoot
63
+ projectRoot,
64
+ routerRoot: options.routerRoot
64
65
  }), {
65
66
  status: 500,
66
67
  headers: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/createServerRouteMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { ExpoResponse } from '@expo/server';\nimport { createRequestHandler } from '@expo/server/build/vendor/http';\nimport requireString from 'require-from-string';\nimport resolve from 'resolve';\nimport { promisify } from 'util';\n\nimport { ForwardHtmlError } from './MetroBundlerDevServer';\nimport { bundleApiRoute } from './bundleApiRoutes';\nimport { fetchManifest } from './fetchRouterManifest';\nimport { getErrorOverlayHtmlAsync, logMetroError, logMetroErrorAsync } from './metroErrorInterface';\nimport { Log } from '../../../log';\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\nconst resolveAsync = promisify(resolve) as any as (\n id: string,\n opts: resolve.AsyncOpts\n) => Promise<string | null>;\n\nexport function createRouteHandlerMiddleware(\n projectRoot: string,\n options: {\n mode?: string;\n appDir: string;\n port?: number;\n baseUrl: string;\n getWebBundleUrl: () => string;\n getStaticPageAsync: (pathname: string) => Promise<{ content: string }>;\n }\n) {\n return createRequestHandler(\n { build: '' },\n {\n async getRoutesManifest() {\n const manifest = await fetchManifest<RegExp>(projectRoot, options);\n debug('manifest', manifest);\n // NOTE: no app dir if null\n // TODO: Redirect to 404 page\n return (\n manifest ?? {\n // Support the onboarding screen if there's no manifest\n htmlRoutes: [\n {\n file: 'index.js',\n page: '/index',\n routeKeys: {},\n namedRegex: /^\\/(?:index)?\\/?$/i,\n },\n ],\n apiRoutes: [],\n notFoundRoutes: [],\n }\n );\n },\n async getHtml(request) {\n try {\n const { content } = await options.getStaticPageAsync(request.url);\n return content;\n } catch (error: any) {\n // Forward the Metro server response as-is. It won't be pretty, but at least it will be accurate.\n if (error instanceof ForwardHtmlError) {\n return new ExpoResponse(error.html, {\n status: error.statusCode,\n headers: {\n 'Content-Type': 'text/html',\n },\n });\n }\n\n try {\n return new ExpoResponse(\n await getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n }),\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n } catch (staticError: any) {\n // Fallback error for when Expo Router is misconfigured in the project.\n return new ExpoResponse(\n '<span><h3>Internal Error:</h3><b>Project is not setup correctly for static rendering (check terminal for more info):</b><br/>' +\n error.message +\n '<br/><br/>' +\n staticError.message +\n '</span>',\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n }\n },\n logApiRouteExecutionError(error) {\n logMetroError(projectRoot, { error });\n },\n async getApiRoute(route) {\n const resolvedFunctionPath = await resolveAsync(route.page, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n });\n\n const middlewareContents = await bundleApiRoute(\n projectRoot,\n resolvedFunctionPath!,\n options\n );\n if (!middlewareContents) {\n // TODO: Error handling\n return null;\n }\n\n try {\n debug(`Bundling middleware at: ${resolvedFunctionPath}`);\n return requireString(middlewareContents);\n } catch (error: any) {\n if (error instanceof Error) {\n await logMetroErrorAsync({ projectRoot, error });\n } else {\n Log.error('Failed to load middleware: ' + error);\n }\n return new ExpoResponse(\n 'Failed to load middleware: ' + resolvedFunctionPath + '\\n\\n' + error.message,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n },\n }\n );\n}\n"],"names":["createRouteHandlerMiddleware","debug","require","resolveAsync","promisify","resolve","projectRoot","options","createRequestHandler","build","getRoutesManifest","manifest","fetchManifest","htmlRoutes","file","page","routeKeys","namedRegex","apiRoutes","notFoundRoutes","getHtml","request","content","getStaticPageAsync","url","error","ForwardHtmlError","ExpoResponse","html","status","statusCode","headers","getErrorOverlayHtmlAsync","staticError","message","logApiRouteExecutionError","logMetroError","getApiRoute","route","resolvedFunctionPath","extensions","basedir","appDir","middlewareContents","bundleApiRoute","requireString","Error","logMetroErrorAsync","Log"],"mappings":"AAMA;;;;QAmBgBA,4BAA4B,GAA5BA,4BAA4B;AAnBf,IAAA,OAAc,WAAd,cAAc,CAAA;AACN,IAAA,KAAgC,WAAhC,gCAAgC,CAAA;AAC3C,IAAA,kBAAqB,kCAArB,qBAAqB,EAAA;AAC3B,IAAA,QAAS,kCAAT,SAAS,EAAA;AACH,IAAA,KAAM,WAAN,MAAM,CAAA;AAEC,IAAA,sBAAyB,WAAzB,yBAAyB,CAAA;AAC3B,IAAA,gBAAmB,WAAnB,mBAAmB,CAAA;AACpB,IAAA,oBAAuB,WAAvB,uBAAuB,CAAA;AACuB,IAAA,oBAAuB,WAAvB,uBAAuB,CAAA;AAC/E,IAAA,IAAc,WAAd,cAAc,CAAA;;;;;;AAElC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,yBAAyB,CAAC,AAAsB,AAAC;AAEhF,MAAMC,YAAY,GAAGC,CAAA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kB,CAAC,CAAC;aAC1C,CAAC,OAAOlB,KAAK,EAAO;gBACnB,IAAIA,KAAK,YAAYqB,KAAK,EAAE;oBAC1B,MAAMC,CAAAA,GAAAA,oBAAkB,AAAwB,CAAA,mBAAxB,CAAC;wBAAEzC,WAAW;wBAAEmB,KAAK;qBAAE,CAAC,CAAC;iBAClD,MAAM;oBACLuB,IAAG,IAAA,CAACvB,KAAK,CAAC,6BAA6B,GAAGA,KAAK,CAAC,CAAC;iBAClD;gBACD,OAAO,IAAIE,OAAY,aAAA,CACrB,6BAA6B,GAAGY,oBAAoB,GAAG,MAAM,GAAGd,KAAK,CAACS,OAAO,EAC7E;oBACEL,MAAM,EAAE,GAAG;oBACXE,OAAO,EAAE;wBACP,cAAc,EAAE,WAAW;qBAC5B;iBACF,CACF,CAAC;aACH;SACF;KACF,CACF,CAAC;CACH"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/createServerRouteMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { ExpoResponse } from '@expo/server';\nimport { createRequestHandler } from '@expo/server/build/vendor/http';\nimport requireString from 'require-from-string';\nimport resolve from 'resolve';\nimport { promisify } from 'util';\n\nimport { ForwardHtmlError } from './MetroBundlerDevServer';\nimport { bundleApiRoute } from './bundleApiRoutes';\nimport { fetchManifest } from './fetchRouterManifest';\nimport { getErrorOverlayHtmlAsync, logMetroError, logMetroErrorAsync } from './metroErrorInterface';\nimport { Log } from '../../../log';\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\nconst resolveAsync = promisify(resolve) as any as (\n id: string,\n opts: resolve.AsyncOpts\n) => Promise<string | null>;\n\nexport function createRouteHandlerMiddleware(\n projectRoot: string,\n options: {\n mode?: string;\n appDir: string;\n routerRoot: string;\n port?: number;\n baseUrl: string;\n getWebBundleUrl: () => string;\n getStaticPageAsync: (pathname: string) => Promise<{ content: string }>;\n }\n) {\n return createRequestHandler(\n { build: '' },\n {\n async getRoutesManifest() {\n const manifest = await fetchManifest<RegExp>(projectRoot, options);\n debug('manifest', manifest);\n // NOTE: no app dir if null\n // TODO: Redirect to 404 page\n return (\n manifest ?? {\n // Support the onboarding screen if there's no manifest\n htmlRoutes: [\n {\n file: 'index.js',\n page: '/index',\n routeKeys: {},\n namedRegex: /^\\/(?:index)?\\/?$/i,\n },\n ],\n apiRoutes: [],\n notFoundRoutes: [],\n }\n );\n },\n async getHtml(request) {\n try {\n const { content } = await options.getStaticPageAsync(request.url);\n return content;\n } catch (error: any) {\n // Forward the Metro server response as-is. It won't be pretty, but at least it will be accurate.\n if (error instanceof ForwardHtmlError) {\n return new ExpoResponse(error.html, {\n status: error.statusCode,\n headers: {\n 'Content-Type': 'text/html',\n },\n });\n }\n\n try {\n return new ExpoResponse(\n await getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n routerRoot: options.routerRoot,\n }),\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n } catch (staticError: any) {\n // Fallback error for when Expo Router is misconfigured in the project.\n return new ExpoResponse(\n '<span><h3>Internal Error:</h3><b>Project is not setup correctly for static rendering (check terminal for more info):</b><br/>' +\n error.message +\n '<br/><br/>' +\n staticError.message +\n '</span>',\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n }\n },\n logApiRouteExecutionError(error) {\n logMetroError(projectRoot, { error });\n },\n async getApiRoute(route) {\n const resolvedFunctionPath = await resolveAsync(route.page, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n });\n\n const middlewareContents = await bundleApiRoute(\n projectRoot,\n resolvedFunctionPath!,\n options\n );\n if (!middlewareContents) {\n // TODO: Error handling\n return null;\n }\n\n try {\n debug(`Bundling middleware at: ${resolvedFunctionPath}`);\n return requireString(middlewareContents);\n } catch (error: any) {\n if (error instanceof Error) {\n await logMetroErrorAsync({ projectRoot, error });\n } else {\n Log.error('Failed to load middleware: ' + error);\n }\n return new ExpoResponse(\n 'Failed to load middleware: ' + resolvedFunctionPath + '\\n\\n' + error.message,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n },\n }\n );\n}\n"],"names":["createRouteHandlerMiddleware","debug","require","resolveAsync","promisify","resolve","projectRoot","options","createRequestHandler","build","getRoutesManifest","manifest","fetchManifest","htmlRoutes","file","page","routeKeys","namedRegex","apiRoutes","notFoundRoutes","getHtml","request","content","getStaticPageAsync","url","error","ForwardHtmlError","ExpoResponse","html","status","statusCode","headers","getErrorOverlayHtmlAsync","routerRoot","staticError","message","logApiRouteExecutionError","logMetroError","getApiRoute","route","resolvedFunctionPath","extensions","basedir","appDir","middlewareContents","bundleApiRoute","requireString","Error","logMetroErrorAsync","Log"],"mappings":"AAMA;;;;QAmBgBA,4BAA4B,GAA5BA,4BAA4B;AAnBf,IAAA,OAAc,WAAd,cAAc,CAAA;AACN,IAAA,KAAgC,WAAhC,gCAAgC,CAAA;AAC3C,IAAA,kBAAqB,kCAArB,qBAAqB,EAAA;AAC3B,IAAA,QAAS,kCAAT,SAAS,EAAA;AACH,IAAA,KAAM,WAAN,MAAM,CAAA;AAEC,IAAA,sBAAyB,WAAzB,yBAAyB,CAAA;AAC3B,IAAA,gBAAmB,WAAnB,mBAAmB,CAAA;AACpB,IAAA,oBAAuB,WAAvB,uBAAuB,CAAA;AACuB,IAAA,oBAAuB,WAAvB,uBAAuB,CAAA;AAC/E,IAAA,IAAc,WAAd,cAAc,CAAA;;;;;;AAElC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,yBAAyB,CAAC,AAAsB,AAAC;AAEhF,MAAMC,YAAY,GAAGC,CAAAA,GAAAA,KAAS,AAAS,CAAA,UAAT,CAACC,QAAO,QAAA,CAAC,AAGZ,AAAC;AAErB,SAASL,4BAA4B,CAC1CM,WAAmB,EACnBC,OAQC,EACD;IACA,OAAOC,CAAAA,GAAAA,KAA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AAA,GAAAA,oBAAkB,AAAwB,CAAA,mBAAxB,CAAC;wBAAE1C,WAAW;wBAAEmB,KAAK;qBAAE,CAAC,CAAC;iBAClD,MAAM;oBACLwB,IAAG,IAAA,CAACxB,KAAK,CAAC,6BAA6B,GAAGA,KAAK,CAAC,CAAC;iBAClD;gBACD,OAAO,IAAIE,OAAY,aAAA,CACrB,6BAA6B,GAAGa,oBAAoB,GAAG,MAAM,GAAGf,KAAK,CAACU,OAAO,EAC7E;oBACEN,MAAM,EAAE,GAAG;oBACXE,OAAO,EAAE;wBACP,cAAc,EAAE,WAAW;qBAC5B;iBACF,CACF,CAAC;aACH;SACF;KACF,CACF,CAAC;CACH"}
@@ -4,13 +4,13 @@ Object.defineProperty(exports, "__esModule", {
4
4
  });
5
5
  exports.createInspectorDeviceClass = createInspectorDeviceClass;
6
6
  var _nodeFetch = _interopRequireDefault(require("node-fetch"));
7
- var _networkResponse = require("./handlers/NetworkResponse");
8
- var _pageReload = require("./handlers/PageReload");
9
- var _vscodeDebuggerGetPossibleBreakpoints = require("./handlers/VscodeDebuggerGetPossibleBreakpoints");
10
- var _vscodeDebuggerScriptParsed = require("./handlers/VscodeDebuggerScriptParsed");
11
- var _vscodeDebuggerSetBreakpointByUrl = require("./handlers/VscodeDebuggerSetBreakpointByUrl");
12
- var _vscodeRuntimeCallFunctionOn = require("./handlers/VscodeRuntimeCallFunctionOn");
13
- var _vscodeRuntimeGetProperties = require("./handlers/VscodeRuntimeGetProperties");
7
+ var _networkResponse = require("./inspectorHandlers/NetworkResponse");
8
+ var _pageReload = require("./inspectorHandlers/PageReload");
9
+ var _vscodeDebuggerGetPossibleBreakpoints = require("./inspectorHandlers/VscodeDebuggerGetPossibleBreakpoints");
10
+ var _vscodeDebuggerScriptParsed = require("./inspectorHandlers/VscodeDebuggerScriptParsed");
11
+ var _vscodeDebuggerSetBreakpointByUrl = require("./inspectorHandlers/VscodeDebuggerSetBreakpointByUrl");
12
+ var _vscodeRuntimeCallFunctionOn = require("./inspectorHandlers/VscodeRuntimeCallFunctionOn");
13
+ var _vscodeRuntimeGetProperties = require("./inspectorHandlers/VscodeRuntimeGetProperties");
14
14
  function _interopRequireDefault(obj) {
15
15
  return obj && obj.__esModule ? obj : {
16
16
  default: obj
@@ -18,7 +18,6 @@ function _interopRequireDefault(obj) {
18
18
  }
19
19
  function createInspectorDeviceClass(metroBundler, MetroDeviceClass) {
20
20
  return class ExpoInspectorDevice extends MetroDeviceClass {
21
- /** Stores information about currently connected debugger (if any). */ _debuggerConnection = null;
22
21
  /** All handlers that should be used to intercept or reply to CDP events */ handlers = [
23
22
  // Generic handlers
24
23
  new _networkResponse.NetworkResponseHandler(),
@@ -42,35 +41,6 @@ function createInspectorDeviceClass(metroBundler, MetroDeviceClass) {
42
41
  return (ref = handler.onDebuggerMessage == null ? void 0 : handler.onDebuggerMessage(message, info)) != null ? ref : false;
43
42
  });
44
43
  }
45
- /**
46
- * Handle a new device connection with the same device identifier.
47
- * When the app and device name matches, we can reuse the debugger connection.
48
- * Else, we have to shut the debugger connection down.
49
- */ handleDuplicateDeviceConnection(newDevice) {
50
- if (this._app !== newDevice._app || this._name !== newDevice._name) {
51
- var ref;
52
- this._deviceSocket.close();
53
- (ref = this._debuggerConnection) == null ? void 0 : ref.socket.close();
54
- return;
55
- }
56
- const oldDebugger = this._debuggerConnection;
57
- this._debuggerConnection = null;
58
- if (oldDebugger) {
59
- oldDebugger.socket.removeAllListeners();
60
- this._deviceSocket.close();
61
- newDevice.handleDebuggerConnection(oldDebugger.socket, oldDebugger.pageId);
62
- }
63
- }
64
- /**
65
- * Handle a new debugger connection to this device.
66
- * This adds the `debuggerType` property to the `DebuggerInfo` object.
67
- * With that information, we can enable or disable debugger-specific handlers.
68
- */ handleDebuggerConnectionWithType(socket, pageId, debuggerType) {
69
- this.handleDebuggerConnection(socket, pageId);
70
- if (this._debuggerConnection) {
71
- this._debuggerConnection.debuggerType = debuggerType;
72
- }
73
- }
74
44
  /** Hook into the message life cycle to answer more complex CDP messages */ async _processMessageFromDevice(message, info) {
75
45
  if (!this.onDeviceMessage(message, info)) {
76
46
  await super._processMessageFromDevice(message, info);
@@ -107,4 +77,4 @@ function createInspectorDeviceClass(metroBundler, MetroDeviceClass) {
107
77
  };
108
78
  }
109
79
 
110
- //# sourceMappingURL=device.js.map
80
+ //# sourceMappingURL=InspectorDevice.js.map