@expo/cli 1.0.0-canary-20250404-3c3b5fd → 1.0.0-canary-20250701-6a945c5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -24
- package/build/bin/cli +1 -1
- package/build/metro-require/require.js +6 -4
- package/build/src/api/user/actions.js +25 -11
- package/build/src/api/user/actions.js.map +1 -1
- package/build/src/customize/templates.js +15 -1
- package/build/src/customize/templates.js.map +1 -1
- package/build/src/export/exportApp.js +26 -14
- package/build/src/export/exportApp.js.map +1 -1
- package/build/src/export/exportAsync.js +6 -0
- package/build/src/export/exportAsync.js.map +1 -1
- package/build/src/export/exportHermes.js +2 -2
- package/build/src/export/exportHermes.js.map +1 -1
- package/build/src/export/persistMetroAssets.js.map +1 -1
- package/build/src/install/checkPackages.js +22 -4
- package/build/src/install/checkPackages.js.map +1 -1
- package/build/src/install/index.js +3 -1
- package/build/src/install/index.js.map +1 -1
- package/build/src/install/resolveOptions.js +7 -2
- package/build/src/install/resolveOptions.js.map +1 -1
- package/build/src/install/utils/checkPackagesCompatibility.js +1 -1
- package/build/src/install/utils/checkPackagesCompatibility.js.map +1 -1
- package/build/src/lint/ESlintPrerequisite.js +32 -48
- package/build/src/lint/ESlintPrerequisite.js.map +1 -1
- package/build/src/lint/index.js +45 -47
- package/build/src/lint/index.js.map +1 -1
- package/build/src/lint/lintAsync.js +150 -4
- package/build/src/lint/lintAsync.js.map +1 -1
- package/build/src/lint/resolveOptions.js +115 -0
- package/build/src/lint/resolveOptions.js.map +1 -0
- package/build/src/prebuild/renameTemplateAppName.js +4 -1
- package/build/src/prebuild/renameTemplateAppName.js.map +1 -1
- package/build/src/prebuild/resolveTemplate.js +4 -4
- package/build/src/prebuild/resolveTemplate.js.map +1 -1
- package/build/src/prebuild/updatePackageJson.js +19 -9
- package/build/src/prebuild/updatePackageJson.js.map +1 -1
- package/build/src/run/android/resolveOptions.js +13 -1
- package/build/src/run/android/resolveOptions.js.map +1 -1
- package/build/src/run/android/runAndroidAsync.js +39 -17
- package/build/src/run/android/runAndroidAsync.js.map +1 -1
- package/build/src/run/ios/XcodeBuild.js +3 -3
- package/build/src/run/ios/XcodeBuild.js.map +1 -1
- package/build/src/run/ios/options/resolveOptions.js +13 -1
- package/build/src/run/ios/options/resolveOptions.js.map +1 -1
- package/build/src/run/ios/runIosAsync.js +38 -7
- package/build/src/run/ios/runIosAsync.js.map +1 -1
- package/build/src/start/doctor/SecurityBinPrerequisite.js +1 -1
- package/build/src/start/doctor/SecurityBinPrerequisite.js.map +1 -1
- package/build/src/start/doctor/apple/XcodePrerequisite.js +1 -1
- package/build/src/start/doctor/apple/XcodePrerequisite.js.map +1 -1
- package/build/src/start/doctor/dependencies/ensureDependenciesAsync.js +1 -1
- package/build/src/start/doctor/dependencies/ensureDependenciesAsync.js.map +1 -1
- package/build/src/start/doctor/dependencies/resolvePackages.js +1 -1
- package/build/src/start/doctor/dependencies/resolvePackages.js.map +1 -1
- package/build/src/start/doctor/ngrok/ExternalModule.js +1 -1
- package/build/src/start/doctor/ngrok/ExternalModule.js.map +1 -1
- package/build/src/start/index.js +1 -1
- package/build/src/start/index.js.map +1 -1
- package/build/src/start/platforms/PlatformManager.js +1 -1
- package/build/src/start/platforms/PlatformManager.js.map +1 -1
- package/build/src/start/platforms/android/AndroidPlatformManager.js +1 -1
- package/build/src/start/platforms/android/AndroidPlatformManager.js.map +1 -1
- package/build/src/start/platforms/android/getDevices.js +1 -1
- package/build/src/start/platforms/android/getDevices.js.map +1 -1
- package/build/src/start/platforms/ios/AppleDeviceManager.js +1 -1
- package/build/src/start/platforms/ios/AppleDeviceManager.js.map +1 -1
- package/build/src/start/platforms/ios/xcrun.js +1 -1
- package/build/src/start/platforms/ios/xcrun.js.map +1 -1
- package/build/src/start/project/dotExpo.js +5 -0
- package/build/src/start/project/dotExpo.js.map +1 -1
- package/build/src/start/resolveOptions.js +3 -0
- package/build/src/start/resolveOptions.js.map +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js +38 -26
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/MetroTerminalReporter.js +29 -2
- package/build/src/start/server/metro/MetroTerminalReporter.js.map +1 -1
- package/build/src/start/server/metro/createExpoFallbackResolver.js +6 -4
- package/build/src/start/server/metro/createExpoFallbackResolver.js.map +1 -1
- package/build/src/start/server/metro/createJResolver.js +2 -2
- package/build/src/start/server/metro/createJResolver.js.map +1 -1
- package/build/src/start/server/metro/createServerComponentsMiddleware.js +16 -5
- package/build/src/start/server/metro/createServerComponentsMiddleware.js.map +1 -1
- package/build/src/start/server/metro/debugging/createDebugMiddleware.js +19 -19
- package/build/src/start/server/metro/debugging/createDebugMiddleware.js.map +1 -1
- package/build/src/start/server/metro/externals.js +1 -1
- package/build/src/start/server/metro/externals.js.map +1 -1
- package/build/src/start/server/metro/instantiateMetro.js +13 -8
- package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
- package/build/src/start/server/metro/log-box/LogBoxSymbolication.js +21 -2
- package/build/src/start/server/metro/log-box/LogBoxSymbolication.js.map +1 -1
- package/build/src/start/server/metro/log-box/formatProjectFilePath.js +15 -12
- package/build/src/start/server/metro/log-box/formatProjectFilePath.js.map +1 -1
- package/build/src/start/server/metro/metroErrorInterface.js +19 -8
- package/build/src/start/server/metro/metroErrorInterface.js.map +1 -1
- package/build/src/start/server/metro/runServer-fork.js +1 -1
- package/build/src/start/server/metro/runServer-fork.js.map +1 -1
- package/build/src/start/server/metro/withMetroMultiPlatform.js +7 -12
- package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
- package/build/src/start/server/middleware/CorsMiddleware.js +1 -1
- package/build/src/start/server/middleware/CorsMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/ManifestMiddleware.js +4 -8
- package/build/src/start/server/middleware/ManifestMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/inspector/JsInspector.js +2 -25
- package/build/src/start/server/middleware/inspector/JsInspector.js.map +1 -1
- package/build/src/start/server/middleware/metroOptions.js +2 -26
- package/build/src/start/server/middleware/metroOptions.js.map +1 -1
- package/build/src/utils/build-cache-providers/helpers.js +61 -0
- package/build/src/utils/build-cache-providers/helpers.js.map +1 -0
- package/build/src/utils/build-cache-providers/index.js +283 -0
- package/build/src/utils/build-cache-providers/index.js.map +1 -0
- package/build/src/utils/codesigning.js +14 -2
- package/build/src/utils/codesigning.js.map +1 -1
- package/build/src/utils/exit.js +0 -1
- package/build/src/utils/exit.js.map +1 -1
- package/build/src/utils/ip.js +7 -104
- package/build/src/utils/ip.js.map +1 -1
- package/build/src/utils/modifyConfigAsync.js +1 -1
- package/build/src/utils/modifyConfigAsync.js.map +1 -1
- package/build/src/utils/resolveArgs.js +8 -0
- package/build/src/utils/resolveArgs.js.map +1 -1
- package/build/src/utils/scheme.js +1 -1
- package/build/src/utils/scheme.js.map +1 -1
- package/build/src/utils/telemetry/clients/FetchClient.js +2 -2
- package/build/src/utils/telemetry/clients/FetchClient.js.map +1 -1
- package/build/src/utils/telemetry/utils/context.js +1 -1
- package/build/src/utils/tsconfig/evaluateTsConfig.js +7 -2
- package/build/src/utils/tsconfig/evaluateTsConfig.js.map +1 -1
- package/build/src/utils/variadic.js +63 -6
- package/build/src/utils/variadic.js.map +1 -1
- package/package.json +20 -20
- package/static/canary/react-is/cjs/react-is.development.js +118 -185
- package/static/canary/react-is/cjs/react-is.production.js +2 -2
- package/static/canary/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js +16582 -26565
- package/static/canary/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js +3495 -3357
- package/static/canary/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js +3929 -3801
- package/static/canary/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js +16869 -27032
- package/static/canary/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-prod.js +3535 -3428
- package/static/canary/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-profiling.js +4198 -4095
- package/static/canary/scheduler/cjs/scheduler-unstable_mock.development.js +387 -684
- package/static/canary/scheduler/cjs/scheduler-unstable_mock.production.js +0 -9
- package/static/canary/scheduler/cjs/scheduler-unstable_post_task.development.js +137 -195
- package/static/canary/scheduler/cjs/scheduler-unstable_post_task.production.js +0 -5
- package/static/canary/scheduler/cjs/scheduler.development.js +339 -600
- package/static/canary/scheduler/cjs/scheduler.native.development.js +324 -512
- package/static/canary/scheduler/cjs/scheduler.native.production.js +6 -5
- package/static/canary/scheduler/cjs/scheduler.production.js +16 -17
- package/static/canary-full/react/cjs/react-compiler-runtime.development.js +13 -68
- package/static/canary-full/react/cjs/react-jsx-dev-runtime.development.js +317 -1251
- package/static/canary-full/react/cjs/react-jsx-dev-runtime.react-server.development.js +353 -1286
- package/static/canary-full/react/cjs/react-jsx-runtime.development.js +326 -1279
- package/static/canary-full/react/cjs/react-jsx-runtime.react-server.development.js +353 -1286
- package/static/canary-full/react/cjs/react.development.js +1204 -2771
- package/static/canary-full/react/cjs/react.production.js +25 -20
- package/static/canary-full/react/cjs/react.react-server.development.js +783 -2162
- package/static/canary-full/react/cjs/react.react-server.production.js +13 -63
- package/static/canary-full/react/package.json +1 -1
- package/static/canary-full/react-dom/cjs/react-dom-client.development.js +24847 -37099
- package/static/canary-full/react-dom/cjs/react-dom-client.production.js +8261 -7475
- package/static/canary-full/react-dom/cjs/react-dom-profiling.development.js +25252 -37571
- package/static/canary-full/react-dom/cjs/react-dom-profiling.profiling.js +9442 -8662
- package/static/canary-full/react-dom/cjs/react-dom-server-legacy.browser.development.js +8944 -11568
- package/static/canary-full/react-dom/cjs/react-dom-server-legacy.browser.production.js +1378 -944
- package/static/canary-full/react-dom/cjs/react-dom-server-legacy.node.development.js +8944 -11568
- package/static/canary-full/react-dom/cjs/react-dom-server-legacy.node.production.js +1386 -954
- package/static/canary-full/react-dom/cjs/react-dom-server.browser.development.js +9344 -11600
- package/static/canary-full/react-dom/cjs/react-dom-server.browser.production.js +1545 -954
- package/static/canary-full/react-dom/cjs/react-dom-server.bun.development.js +8286 -11064
- package/static/canary-full/react-dom/cjs/react-dom-server.bun.production.js +1437 -976
- package/static/canary-full/react-dom/cjs/react-dom-server.edge.development.js +9356 -11609
- package/static/canary-full/react-dom/cjs/react-dom-server.edge.production.js +1542 -970
- package/static/canary-full/react-dom/cjs/react-dom-server.node.development.js +9227 -11571
- package/static/canary-full/react-dom/cjs/react-dom-server.node.production.js +1787 -1183
- package/static/canary-full/react-dom/cjs/react-dom-test-utils.development.js +13 -59
- package/static/canary-full/react-dom/cjs/react-dom.development.js +402 -604
- package/static/canary-full/react-dom/cjs/react-dom.production.js +4 -3
- package/static/canary-full/react-dom/cjs/react-dom.react-server.development.js +322 -382
- package/static/canary-full/react-dom/cjs/react-dom.react-server.production.js +6 -7
- package/static/canary-full/react-dom/package.json +5 -5
- package/static/canary-full/react-dom/static.browser.js +1 -0
- package/static/canary-full/react-dom/static.edge.js +1 -0
- package/static/canary-full/react-dom/static.node.js +1 -0
- package/static/template/eslint.config.js +10 -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 {\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';\nimport {\n logLikeMetro,\n maybeSymbolicateAndFormatReactErrorLogAsync,\n parseErrorStringToObject,\n} from '../serverLogLikeMetro';\n\nconst debug = require('debug')('expo:metro:logger') as typeof console.log;\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 _log(event: TerminalReportableEvent): void {\n switch (event.type) {\n case 'client_log': {\n if (this.shouldFilterClientLog(event)) {\n return;\n }\n const { level } = event;\n\n if (!level) {\n break;\n }\n\n const mode = event.mode === 'NOBRIDGE' ? '' : (event.mode ?? '');\n // @ts-expect-error\n if (level === 'warn' || level === 'error') {\n // Quick check to see if an unsymbolicated stack is being logged.\n const msg = event.data.join('\\n');\n if (msg.includes('.bundle//&platform=')) {\n const parsed = parseErrorStringToObject(msg);\n if (parsed) {\n maybeSymbolicateAndFormatReactErrorLogAsync(this.projectRoot, level, parsed)\n .then((res) => {\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, mode, res);\n })\n .catch((e) => {\n // Fallback on the original error message if we can't symbolicate the stack.\n debug('Error formatting stack', e);\n\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, mode, ...event.data);\n });\n\n return;\n }\n }\n }\n\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, mode, ...event.data);\n return;\n }\n }\n return super._log(event);\n }\n\n // Used for testing\n _getElapsedTime(startTime: bigint): bigint {\n return process.hrtime.bigint() - 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 let localPath: string;\n\n if (\n typeof progress.bundleDetails?.customTransformOptions?.dom === 'string' &&\n progress.bundleDetails.customTransformOptions.dom.includes(path.sep)\n ) {\n // Because we use a generated entry file for DOM components, we need to adjust the logging path so it\n // shows a unique path for each component.\n // Here, we take the relative import path and remove all the starting slashes.\n localPath = progress.bundleDetails.customTransformOptions.dom.replace(/^(\\.?\\.[\\\\/])+/, '');\n } else {\n const inputFile = progress.bundleDetails.entryFile;\n\n localPath = path.isAbsolute(inputFile)\n ? path.relative(this.projectRoot, inputFile)\n : inputFile;\n }\n\n if (!inProgress) {\n const status = phase === 'done' ? `Bundled ` : `Bundling failed `;\n const color = phase === 'done' ? chalk.green : chalk.red;\n\n const startTime = this._bundleTimers.get(progress.bundleDetails.buildID!);\n\n let time: string = '';\n\n if (startTime != null) {\n const elapsed: bigint = this._getElapsedTime(startTime);\n const micro = Number(elapsed) / 1000;\n const converted = Number(elapsed) / 1e6;\n // If the milliseconds are < 0.5 then it will display as 0, so we display in microseconds.\n if (converted <= 0.5) {\n const tenthFractionOfMicro = ((micro * 10) / 1000).toFixed(0);\n // Format as microseconds to nearest tenth\n time = chalk.cyan.bold(`0.${tenthFractionOfMicro}ms`);\n } else {\n time = chalk.dim(converted.toFixed(0) + 'ms');\n }\n }\n\n // iOS Bundled 150ms\n const plural = progress.totalFileCount === 1 ? '' : 's';\n return (\n color(platform + status) +\n time +\n chalk.reset.dim(` ${localPath} (${progress.totalFileCount} module${plural})`)\n );\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)}${path.sep}`) +\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(chalk.dim('Starting Metro Bundler'));\n }\n\n shouldFilterClientLog(event: { type: 'client_log'; data: unknown[] }): 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('λ') + ' ';\n } else if (env === 'react-server') {\n return chalk.bold(`RSC(${getPlatformTagForBuildDetails(bundleDetails).trim()})`) + ' ';\n }\n\n if (\n bundleDetails?.customTransformOptions?.dom &&\n typeof bundleDetails?.customTransformOptions?.dom === 'string'\n ) {\n return chalk.bold(`DOM`) + ' ';\n }\n\n return '';\n}\n"],"names":["MetroTerminalReporter","formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","debug","require","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","TerminalReporter","constructor","projectRoot","terminal","_log","event","type","shouldFilterClientLog","level","mode","msg","data","join","includes","parsed","parseErrorStringToObject","maybeSymbolicateAndFormatReactErrorLogAsync","then","res","logLikeMetro","log","bind","catch","e","_getElapsedTime","startTime","process","hrtime","bigint","_getBundleStatusMessage","progress","phase","env","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","customTransformOptions","dom","path","sep","replace","inputFile","entryFile","isAbsolute","relative","status","color","chalk","green","red","_bundleTimers","get","buildID","time","elapsed","micro","Number","converted","tenthFractionOfMicro","toFixed","cyan","bold","dim","plural","totalFileCount","reset","filledBar","Math","floor","ratio","_progress","bgGreen","repeat","bgWhite","white","padStart","transformedFileCount","toString","length","dirname","basename","_logInitializing","port","hasReducedPerformance","isAppRegistryStartupMessage","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","_logBundlingError","error","moduleResolutionError","cause","message","maybeAppendCodeFrame","_expoImportStack","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","lines","split","index","findIndex","line","slice","body","formatted","ios","android","web","environment","trim"],"mappings":";;;;;;;;;;;IA6BaA,qBAAqB;eAArBA;;IAwMGC,mCAAmC;eAAnCA;;IAwCAC,sBAAsB;eAAtBA;;IAkBAC,cAAc;eAAdA;;;;gEA/RE;;;;;;;gEAED;;;;;;kCAE4B;2BAQT;sBACV;oCAKnB;;;;;;AAEP,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,MAAMC,8BAA8B;AACpC,MAAMC,kBAAkB;AACxB,MAAMC,mBAAmB;AAKlB,MAAMR,8BAA8BS,kCAAgB;IACzDC,YACE,AAAOC,WAAmB,EAC1BC,QAAkB,CAClB;QACA,KAAK,CAACA,gBAHCD,cAAAA;IAIT;IAEAE,KAAKC,KAA8B,EAAQ;QACzC,OAAQA,MAAMC,IAAI;YAChB,KAAK;gBAAc;oBACjB,IAAI,IAAI,CAACC,qBAAqB,CAACF,QAAQ;wBACrC;oBACF;oBACA,MAAM,EAAEG,KAAK,EAAE,GAAGH;oBAElB,IAAI,CAACG,OAAO;wBACV;oBACF;oBAEA,MAAMC,OAAOJ,MAAMI,IAAI,KAAK,aAAa,KAAMJ,MAAMI,IAAI,IAAI;oBAC7D,mBAAmB;oBACnB,IAAID,UAAU,UAAUA,UAAU,SAAS;wBACzC,iEAAiE;wBACjE,MAAME,MAAML,MAAMM,IAAI,CAACC,IAAI,CAAC;wBAC5B,IAAIF,IAAIG,QAAQ,CAAC,wBAAwB;4BACvC,MAAMC,SAASC,IAAAA,4CAAwB,EAACL;4BACxC,IAAII,QAAQ;gCACVE,IAAAA,+DAA2C,EAAC,IAAI,CAACd,WAAW,EAAEM,OAAOM,QAClEG,IAAI,CAAC,CAACC;oCACL,kHAAkH;oCACl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BF,aAAoC;IACzE,MAAMC,WAAWD,CAAAA,iCAAAA,cAAeC,QAAQ,KAAI;IAC5C,IAAIA,UAAU;QACZ,MAAMmF,YAAY;YAAEC,KAAK;YAAOC,SAAS;YAAWC,KAAK;QAAM,CAAC,CAACtF,SAAS,IAAIA;QAC9E,OAAO,GAAGe,gBAAK,CAACc,IAAI,CAACsD,WAAW,CAAC,CAAC;IACpC;IAEA,OAAO;AACT;AACA,gEAAgE,GAChE,SAASrF,8BAA8BC,aAAoC;QAE7DA,uCAQVA,wCACOA;IAVT,iGAAiG;IACjG,MAAMF,MAAME,CAAAA,kCAAAA,wCAAAA,cAAeK,sBAAsB,qBAArCL,sCAAuCwF,WAAW,KAAI;IAClE,IAAI1F,QAAQ,QAAQ;QAClB,OAAOkB,gBAAK,CAACc,IAAI,CAAC,OAAO;IAC3B,OAAO,IAAIhC,QAAQ,gBAAgB;QACjC,OAAOkB,gBAAK,CAACc,IAAI,CAAC,CAAC,IAAI,EAAE5B,8BAA8BF,eAAeyF,IAAI,GAAG,CAAC,CAAC,IAAI;IACrF;IAEA,IACEzF,CAAAA,kCAAAA,yCAAAA,cAAeK,sBAAsB,qBAArCL,uCAAuCM,GAAG,KAC1C,QAAON,kCAAAA,yCAAAA,cAAeK,sBAAsB,qBAArCL,uCAAuCM,GAAG,MAAK,UACtD;QACA,OAAOU,gBAAK,CAACc,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI;IAC7B;IAEA,OAAO;AACT"}
|
|
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 { env } from '../../../utils/env';\nimport { learnMore } from '../../../utils/link';\nimport {\n logLikeMetro,\n maybeSymbolicateAndFormatReactErrorLogAsync,\n parseErrorStringToObject,\n} from '../serverLogLikeMetro';\n\nconst debug = require('debug')('expo:metro:logger') as typeof console.log;\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 _log(event: TerminalReportableEvent): void {\n switch (event.type) {\n case 'unstable_server_log':\n if (typeof event.data?.[0] === 'string') {\n const message = event.data[0];\n if (message.match(/JavaScript logs have moved/)) {\n // Hide this very loud message from upstream React Native in favor of the note in the terminal UI:\n // The \"› Press j │ open debugger\"\n\n // logger?.info(\n // '\\u001B[1m\\u001B[7m💡 JavaScript logs have moved!\\u001B[22m They can now be ' +\n // 'viewed in React Native DevTools. Tip: Type \\u001B[1mj\\u001B[22m in ' +\n // 'the terminal to open (requires Google Chrome or Microsoft Edge).' +\n // '\\u001B[27m',\n // );\n return;\n }\n\n if (!env.EXPO_DEBUG) {\n // In the context of developing an iOS app or website, the MetroInspectorProxy \"connection\" logs are very confusing.\n // Here we'll hide them behind EXPO_DEBUG or DEBUG=expo:*. In the future we can reformat them to clearly indicate that the \"Connection\" is regarding the debugger.\n // These logs are also confusing because they can say \"connection established\" even when the debugger is not in a usable state. Really they belong in a UI or behind some sort of debug logging.\n if (message.match(/Connection (closed|established|failed|terminated)/i)) {\n // Skip logging.\n return;\n }\n }\n }\n break;\n case 'client_log': {\n if (this.shouldFilterClientLog(event)) {\n return;\n }\n const { level } = event;\n\n if (!level) {\n break;\n }\n\n const mode = event.mode === 'NOBRIDGE' || event.mode === 'BRIDGE' ? '' : (event.mode ?? '');\n // @ts-expect-error\n if (level === 'warn' || level === 'error') {\n // Quick check to see if an unsymbolicated stack is being logged.\n const msg = event.data.join('\\n');\n if (msg.includes('.bundle//&platform=')) {\n const parsed = parseErrorStringToObject(msg);\n\n if (parsed) {\n maybeSymbolicateAndFormatReactErrorLogAsync(this.projectRoot, level, parsed)\n .then((res) => {\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, mode, res);\n })\n .catch((e) => {\n // Fallback on the original error message if we can't symbolicate the stack.\n debug('Error formatting stack', e);\n\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, mode, ...event.data);\n });\n\n return;\n }\n }\n }\n\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, mode, ...event.data);\n return;\n }\n }\n return super._log(event);\n }\n\n // Used for testing\n _getElapsedTime(startTime: bigint): bigint {\n return process.hrtime.bigint() - 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 let localPath: string;\n\n if (\n typeof progress.bundleDetails?.customTransformOptions?.dom === 'string' &&\n progress.bundleDetails.customTransformOptions.dom.includes(path.sep)\n ) {\n // Because we use a generated entry file for DOM components, we need to adjust the logging path so it\n // shows a unique path for each component.\n // Here, we take the relative import path and remove all the starting slashes.\n localPath = progress.bundleDetails.customTransformOptions.dom.replace(/^(\\.?\\.[\\\\/])+/, '');\n } else {\n const inputFile = progress.bundleDetails.entryFile;\n\n localPath = path.isAbsolute(inputFile)\n ? path.relative(this.projectRoot, inputFile)\n : inputFile;\n }\n\n if (!inProgress) {\n const status = phase === 'done' ? `Bundled ` : `Bundling failed `;\n const color = phase === 'done' ? chalk.green : chalk.red;\n\n const startTime = this._bundleTimers.get(progress.bundleDetails.buildID!);\n\n let time: string = '';\n\n if (startTime != null) {\n const elapsed: bigint = this._getElapsedTime(startTime);\n const micro = Number(elapsed) / 1000;\n const converted = Number(elapsed) / 1e6;\n // If the milliseconds are < 0.5 then it will display as 0, so we display in microseconds.\n if (converted <= 0.5) {\n const tenthFractionOfMicro = ((micro * 10) / 1000).toFixed(0);\n // Format as microseconds to nearest tenth\n time = chalk.cyan.bold(`0.${tenthFractionOfMicro}ms`);\n } else {\n time = chalk.dim(converted.toFixed(0) + 'ms');\n }\n }\n\n // iOS Bundled 150ms\n const plural = progress.totalFileCount === 1 ? '' : 's';\n return (\n color(platform + status) +\n time +\n chalk.reset.dim(` ${localPath} (${progress.totalFileCount} module${plural})`)\n );\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)}${path.sep}`) +\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(chalk.dim('Starting Metro Bundler'));\n }\n\n shouldFilterClientLog(event: { type: 'client_log'; data: unknown[] }): 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 '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('λ') + ' ';\n } else if (env === 'react-server') {\n return chalk.bold(`RSC(${getPlatformTagForBuildDetails(bundleDetails).trim()})`) + ' ';\n }\n\n if (\n bundleDetails?.customTransformOptions?.dom &&\n typeof bundleDetails?.customTransformOptions?.dom === 'string'\n ) {\n return chalk.bold(`DOM`) + ' ';\n }\n\n return '';\n}\n"],"names":["MetroTerminalReporter","formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","debug","require","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","TerminalReporter","constructor","projectRoot","terminal","_log","event","type","data","message","match","env","EXPO_DEBUG","shouldFilterClientLog","level","mode","msg","join","includes","parsed","parseErrorStringToObject","maybeSymbolicateAndFormatReactErrorLogAsync","then","res","logLikeMetro","log","bind","catch","e","_getElapsedTime","startTime","process","hrtime","bigint","_getBundleStatusMessage","progress","phase","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","customTransformOptions","dom","path","sep","replace","inputFile","entryFile","isAbsolute","relative","status","color","chalk","green","red","_bundleTimers","get","buildID","time","elapsed","micro","Number","converted","tenthFractionOfMicro","toFixed","cyan","bold","dim","plural","totalFileCount","reset","filledBar","Math","floor","ratio","_progress","bgGreen","repeat","bgWhite","white","padStart","transformedFileCount","toString","length","dirname","basename","_logInitializing","port","hasReducedPerformance","isAppRegistryStartupMessage","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","_logBundlingError","error","moduleResolutionError","cause","maybeAppendCodeFrame","_expoImportStack","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","lines","split","index","findIndex","line","slice","body","formatted","ios","android","web","environment","trim"],"mappings":";;;;;;;;;;;IA8BaA,qBAAqB;eAArBA;;IAoOGC,mCAAmC;eAAnCA;;IAwCAC,sBA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resolver');
|
|
|
49
49
|
let filePath;
|
|
50
50
|
let packageMeta;
|
|
51
51
|
try {
|
|
52
|
-
const resolution = resolve(
|
|
52
|
+
const resolution = resolve(_path().default.join(originModuleName, 'package.json'));
|
|
53
53
|
if (resolution.type !== 'sourceFile') {
|
|
54
54
|
debug(`Fallback module resolution failed for origin module: ${originModuleName})`);
|
|
55
55
|
return null;
|
|
@@ -95,16 +95,18 @@ const debug = require('debug')('expo:start:server:metro:fallback-resolver');
|
|
|
95
95
|
moduleTestRe: dependenciesToRegex(dependencies)
|
|
96
96
|
} : null;
|
|
97
97
|
};
|
|
98
|
-
function createFallbackModuleResolver({ originModuleNames, getStrictResolver }) {
|
|
98
|
+
function createFallbackModuleResolver({ projectRoot, originModuleNames, getStrictResolver }) {
|
|
99
99
|
const _moduleDescriptionsCache = {};
|
|
100
100
|
const getModuleDescription = (immutableContext, originModuleName, platform)=>{
|
|
101
101
|
if (_moduleDescriptionsCache[originModuleName] !== undefined) {
|
|
102
102
|
return _moduleDescriptionsCache[originModuleName];
|
|
103
103
|
}
|
|
104
|
-
// Resolve the origin module itself
|
|
104
|
+
// Resolve the origin module itself via the project root rather than the file that requested the missing module
|
|
105
|
+
// The addition of `package.json` doesn't matter here. We just need a file path that'll be turned into a directory path
|
|
106
|
+
// We don't need to modify `nodeModulesPaths` since it's guaranteed to contain the project's node modules paths
|
|
105
107
|
const context = {
|
|
106
108
|
...immutableContext,
|
|
107
|
-
originModulePath:
|
|
109
|
+
originModulePath: _path().default.join(projectRoot, 'package.json')
|
|
108
110
|
};
|
|
109
111
|
return _moduleDescriptionsCache[originModuleName] = getModuleDescriptionWithResolver(context, getStrictResolver(context, platform), originModuleName);
|
|
110
112
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/createExpoFallbackResolver.ts"],"sourcesContent":["// This file creates the fallback resolver\n// The fallback resolver applies only to module imports and should be the last resolver\n// in the chain. It applies to failed Node module resolution of modules and will attempt\n// to resolve them to `expo` and `expo-router` dependencies that couldn't be resolved.\n// This resolves isolated dependency issues, where we expect dependencies of `expo`\n// and `expo-router` to be resolvable, due to hoisting, but they aren't hoisted in\n// a user's project.\n// See: https://github.com/expo/expo/pull/34286\n\nimport type { ResolutionContext } from 'metro-resolver';\nimport path from 'path';\n\nimport type { StrictResolver, StrictResolverFactory } from './withMetroMultiPlatform';\nimport type { ExpoCustomMetroResolver } from './withMetroResolvers';\n\n/** A record of dependencies that we know are only used for scripts and config-plugins\n * @privateRemarks\n * This includes dependencies we never resolve indirectly. Generally, we only want\n * to add fallback resolutions for dependencies of `expo` and `expo-router` that\n * are either transpiled into output code or resolved from other Expo packages\n * without them having direct dependencies on these dependencies.\n * Meaning: If you update this list, exclude what a user might use when they\n * forget to specify their own dependencies, rather than what we use ourselves\n * only in `expo` and `expo-router`.\n */\nconst EXCLUDE_ORIGIN_MODULES: Record<string, true | undefined> = {\n '@expo/config': true,\n '@expo/config-plugins': true,\n 'schema-utils': true, // Used by `expo-router/plugin`\n semver: true, // Used by `expo-router/doctor`\n};\n\ninterface PackageMetaPeerDependenciesMetaEntry {\n [propName: string]: unknown;\n optional?: boolean;\n}\n\ninterface PackageMeta {\n readonly [propName: string]: unknown;\n readonly name?: string;\n readonly main?: string;\n readonly exports?: any; // unused\n readonly dependencies?: Record<string, unknown>;\n readonly peerDependencies?: Record<string, unknown>;\n readonly peerDependenciesMeta?: Record<\n string,\n PackageMetaPeerDependenciesMetaEntry | undefined | null\n >;\n}\n\ninterface ModuleDescription {\n originModulePath: string;\n moduleTestRe: RegExp;\n}\n\nconst debug = require('debug')('expo:start:server:metro:fallback-resolver') as typeof console.log;\n\n/** Converts a list of module names to a regex that may either match bare module names or sub-modules of modules */\nconst dependenciesToRegex = (dependencies: string[]) =>\n new RegExp(`^(?:${dependencies.join('|')})(?:$|/)`);\n\n/** Resolves an origin module and outputs a filter regex and target path for it */\nconst getModuleDescriptionWithResolver = (\n context: ResolutionContext,\n resolve: StrictResolver,\n originModuleName: string\n): ModuleDescription | null => {\n let filePath: string | undefined;\n let packageMeta: PackageMeta | undefined | null;\n try {\n const resolution = resolve(`${originModuleName}/package.json`);\n if (resolution.type !== 'sourceFile') {\n debug(`Fallback module resolution failed for origin module: ${originModuleName})`);\n return null;\n }\n filePath = resolution.filePath;\n packageMeta = context.getPackage(filePath);\n if (!packageMeta) {\n return null;\n }\n } catch (error: any) {\n debug(\n `Fallback module resolution threw: ${error.constructor.name}. (module: ${filePath || originModuleName})`\n );\n return null;\n }\n let dependencies: string[] = [];\n if (packageMeta.dependencies) dependencies.push(...Object.keys(packageMeta.dependencies));\n if (packageMeta.peerDependencies) {\n const peerDependenciesMeta = packageMeta.peerDependenciesMeta;\n let peerDependencies = Object.keys(packageMeta.peerDependencies);\n // We explicitly include non-optional peer dependencies. Non-optional peer dependencies of\n // `expo` and `expo-router` are either expected to be accessible on a project-level, since\n // both are meant to be installed is direct dependencies, or shouldn't be accessible when\n // they're fulfilled as isolated dependencies.\n // The exception are only *optional* peer dependencies, since when they're installed\n // automatically by newer package manager behaviour, they may become isolated dependencies\n // that we still wish to access.\n if (peerDependenciesMeta) {\n peerDependencies = peerDependencies.filter((dependency) => {\n const peerMeta = peerDependenciesMeta[dependency];\n return peerMeta && typeof peerMeta === 'object' && peerMeta.optional === true;\n });\n }\n dependencies.push(...peerDependencies);\n }\n // We deduplicate the dependencies and exclude modules that we know are only used for scripts or config-plugins\n dependencies = dependencies.filter((moduleName, index, dependenciesArr) => {\n if (EXCLUDE_ORIGIN_MODULES[moduleName]) return false;\n return dependenciesArr.indexOf(moduleName) === index;\n });\n // Return test regex for dependencies and full origin module path to resolve through\n const originModulePath = path.dirname(filePath);\n return dependencies.length\n ? { originModulePath, moduleTestRe: dependenciesToRegex(dependencies) }\n : null;\n};\n\n/** Creates a fallback module resolver that resolves dependencis of modules named in `originModuleNames` via their path.\n * @remarks\n * The fallback resolver targets modules dependended on by modules named in `originModuleNames` and resolves\n * them from the module root of these origin modules instead.\n * It should only be used as a fallback after normal Node resolution (and other resolvers) have failed for:\n * - the `expo` package\n * - the `expo-router` package\n * Dependencies mentioned as either optional peer dependencies or direct dependencies by these modules may be isolated\n * and inaccessible via standard Node module resolution. This may happen when either transpilation adds these\n * dependencies to other parts of the tree (e.g. `@babel/runtime`) or when a dependency fails to hoist due to either\n * a corrupted dependency tree or when a peer dependency is fulfilled incorrectly (e.g. `expo-asset`)\n * @privateRemarks\n * This does NOT follow Node resolution and is *only* intended to provide a fallback for modules that we depend on\n * ourselves and know we can resolve (via expo or expo-router)!\n */\nexport function createFallbackModuleResolver({\n originModuleNames,\n getStrictResolver,\n}: {\n originModuleNames: string[];\n getStrictResolver: StrictResolverFactory;\n}): ExpoCustomMetroResolver {\n const _moduleDescriptionsCache: Record<string, ModuleDescription | null> = {};\n\n const getModuleDescription = (\n immutableContext: ResolutionContext,\n originModuleName: string,\n platform: string | null\n ) => {\n if (_moduleDescriptionsCache[originModuleName] !== undefined) {\n return _moduleDescriptionsCache[originModuleName];\n }\n // Resolve the origin module itself through `<module>/.`\n const context: ResolutionContext = {\n ...immutableContext,\n originModulePath: `${originModuleName}/package.json`,\n };\n return (_moduleDescriptionsCache[originModuleName] = getModuleDescriptionWithResolver(\n context,\n getStrictResolver(context, platform),\n originModuleName\n ));\n };\n\n const fileSpecifierRe = /^[\\\\/]|^\\.\\.?(?:$|[\\\\/])/i;\n\n return function requestFallbackModule(immutableContext, moduleName, platform) {\n // Early return if `moduleName` cannot be a module specifier\n // This doesn't have to be accurate as this resolver is a fallback for failed resolutions and\n // we're only doing this to avoid unnecessary resolution work\n if (fileSpecifierRe.test(moduleName)) {\n return null;\n }\n\n for (const originModuleName of originModuleNames) {\n const moduleDescription = getModuleDescription(immutableContext, originModuleName, platform);\n if (moduleDescription && moduleDescription.moduleTestRe.test(moduleName)) {\n // We instead resolve as if it was depended on by the `originModulePath` (the module named in `originModuleNames`)\n const context: ResolutionContext = {\n ...immutableContext,\n nodeModulesPaths: [moduleDescription.originModulePath],\n originModulePath: moduleDescription.originModulePath,\n };\n const res = getStrictResolver(context, platform)(moduleName);\n debug(\n `Fallback resolution for ${platform}: ${moduleName} -> from origin: ${originModuleName}`\n );\n return res;\n }\n }\n\n return null;\n };\n}\n"],"names":["createFallbackModuleResolver","EXCLUDE_ORIGIN_MODULES","semver","debug","require","dependenciesToRegex","dependencies","RegExp","join","getModuleDescriptionWithResolver","context","resolve","originModuleName","filePath","packageMeta","resolution","type","getPackage","error","constructor","name","push","Object","keys","peerDependencies","peerDependenciesMeta","filter","dependency","peerMeta","optional","moduleName","index","dependenciesArr","indexOf","originModulePath","path","dirname","length","moduleTestRe","originModuleNames","getStrictResolver","_moduleDescriptionsCache","getModuleDescription","immutableContext","platform","undefined","fileSpecifierRe","requestFallbackModule","test","moduleDescription","nodeModulesPaths","res"],"mappings":"AAAA,0CAA0C;AAC1C,uFAAuF;AACvF,wFAAwF;AACxF,sFAAsF;AACtF,mFAAmF;AACnF,kFAAkF;AAClF,oBAAoB;AACpB,+CAA+C;;;;;+BA8H/BA;;;eAAAA;;;;gEA3HC;;;;;;;;;;;AAKjB;;;;;;;;;CASC,GACD,MAAMC,yBAA2D;IAC/D,gBAAgB;IAChB,wBAAwB;IACxB,gBAAgB;IAChBC,QAAQ;AACV;AAyBA,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,iHAAiH,GACjH,MAAMC,sBAAsB,CAACC,eAC3B,IAAIC,OAAO,CAAC,IAAI,EAAED,aAAaE,IAAI,CAAC,KAAK,QAAQ,CAAC;AAEpD,gFAAgF,GAChF,MAAMC,mCAAmC,CACvCC,SACAC,SACAC;IAEA,IAAIC;IACJ,IAAIC;IACJ,IAAI;QACF,MAAMC,aAAaJ,QAAQ,GAAGC,iBAAiB,aAAa,CAAC;QAC7D,IAAIG,WAAWC,IAAI,KAAK,cAAc;YACpCb,MAAM,CAAC,qDAAqD,EAAES,iBAAiB,CAAC,CAAC;YACjF,OAAO;QACT;QACAC,WAAWE,WAAWF,QAAQ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,kBACA/B,kBACAgC;QAEA,IAAIH,wBAAwB,CAAC7B,iBAAiB,KAAKiC,WAAW;YAC5D,OAAOJ,wBAAwB,CAAC7B,iBAAiB;QACnD;QACA,wDAAwD;QACxD,MAAMF,UAA6B;YACjC,GAAGiC,gBAAgB;YACnBT,kBAAkB,GAAGtB,iBAAiB,aAAa,CAAC;QACtD;QACA,OAAQ6B,wBAAwB,CAAC7B,iBAAiB,GAAGH,iCACnDC,SACA8B,kBAAkB9B,SAASkC,WAC3BhC;IAEJ;IAEA,MAAMkC,kBAAkB;IAExB,OAAO,SAASC,sBAAsBJ,gBAAgB,EAAEb,UAAU,EAAEc,QAAQ;QAC1E,4DAA4D;QAC5D,6FAA6F;QAC7F,6DAA6D;QAC7D,IAAIE,gBAAgBE,IAAI,CAAClB,aAAa;YACpC,OAAO;QACT;QAEA,KAAK,MAAMlB,oBAAoB2B,kBAAmB;YAChD,MAAMU,oBAAoBP,qBAAqBC,kBAAkB/B,kBAAkBgC;YACnF,IAAIK,qBAAqBA,kBAAkBX,YAAY,CAACU,IAAI,CAAClB,aAAa;gBACxE,kHAAkH;gBAClH,MAAMpB,UAA6B;oBACjC,GAAGiC,gBAAgB;oBACnBO,kBAAkB;wBAACD,kBAAkBf,gBAAgB;qBAAC;oBACtDA,kBAAkBe,kBAAkBf,gBAAgB;gBACtD;gBACA,MAAMiB,MAAMX,kBAAkB9B,SAASkC,UAAUd;gBACjD3B,MACE,CAAC,wBAAwB,EAAEyC,SAAS,EAAE,EAAEd,WAAW,iBAAiB,EAAElB,kBAAkB;gBAE1F,OAAOuC;YACT;QACF;QAEA,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/createExpoFallbackResolver.ts"],"sourcesContent":["// This file creates the fallback resolver\n// The fallback resolver applies only to module imports and should be the last resolver\n// in the chain. It applies to failed Node module resolution of modules and will attempt\n// to resolve them to `expo` and `expo-router` dependencies that couldn't be resolved.\n// This resolves isolated dependency issues, where we expect dependencies of `expo`\n// and `expo-router` to be resolvable, due to hoisting, but they aren't hoisted in\n// a user's project.\n// See: https://github.com/expo/expo/pull/34286\n\nimport type { ResolutionContext } from 'metro-resolver';\nimport path from 'path';\n\nimport type { StrictResolver, StrictResolverFactory } from './withMetroMultiPlatform';\nimport type { ExpoCustomMetroResolver } from './withMetroResolvers';\n\n/** A record of dependencies that we know are only used for scripts and config-plugins\n * @privateRemarks\n * This includes dependencies we never resolve indirectly. Generally, we only want\n * to add fallback resolutions for dependencies of `expo` and `expo-router` that\n * are either transpiled into output code or resolved from other Expo packages\n * without them having direct dependencies on these dependencies.\n * Meaning: If you update this list, exclude what a user might use when they\n * forget to specify their own dependencies, rather than what we use ourselves\n * only in `expo` and `expo-router`.\n */\nconst EXCLUDE_ORIGIN_MODULES: Record<string, true | undefined> = {\n '@expo/config': true,\n '@expo/config-plugins': true,\n 'schema-utils': true, // Used by `expo-router/plugin`\n semver: true, // Used by `expo-router/doctor`\n};\n\ninterface PackageMetaPeerDependenciesMetaEntry {\n [propName: string]: unknown;\n optional?: boolean;\n}\n\ninterface PackageMeta {\n readonly [propName: string]: unknown;\n readonly name?: string;\n readonly main?: string;\n readonly exports?: any; // unused\n readonly dependencies?: Record<string, unknown>;\n readonly peerDependencies?: Record<string, unknown>;\n readonly peerDependenciesMeta?: Record<\n string,\n PackageMetaPeerDependenciesMetaEntry | undefined | null\n >;\n}\n\ninterface ModuleDescription {\n originModulePath: string;\n moduleTestRe: RegExp;\n}\n\nconst debug = require('debug')('expo:start:server:metro:fallback-resolver') as typeof console.log;\n\n/** Converts a list of module names to a regex that may either match bare module names or sub-modules of modules */\nconst dependenciesToRegex = (dependencies: string[]) =>\n new RegExp(`^(?:${dependencies.join('|')})(?:$|/)`);\n\n/** Resolves an origin module and outputs a filter regex and target path for it */\nconst getModuleDescriptionWithResolver = (\n context: ResolutionContext,\n resolve: StrictResolver,\n originModuleName: string\n): ModuleDescription | null => {\n let filePath: string | undefined;\n let packageMeta: PackageMeta | undefined | null;\n try {\n const resolution = resolve(path.join(originModuleName, 'package.json'));\n if (resolution.type !== 'sourceFile') {\n debug(`Fallback module resolution failed for origin module: ${originModuleName})`);\n return null;\n }\n filePath = resolution.filePath;\n packageMeta = context.getPackage(filePath);\n if (!packageMeta) {\n return null;\n }\n } catch (error: any) {\n debug(\n `Fallback module resolution threw: ${error.constructor.name}. (module: ${filePath || originModuleName})`\n );\n return null;\n }\n let dependencies: string[] = [];\n if (packageMeta.dependencies) dependencies.push(...Object.keys(packageMeta.dependencies));\n if (packageMeta.peerDependencies) {\n const peerDependenciesMeta = packageMeta.peerDependenciesMeta;\n let peerDependencies = Object.keys(packageMeta.peerDependencies);\n // We explicitly include non-optional peer dependencies. Non-optional peer dependencies of\n // `expo` and `expo-router` are either expected to be accessible on a project-level, since\n // both are meant to be installed is direct dependencies, or shouldn't be accessible when\n // they're fulfilled as isolated dependencies.\n // The exception are only *optional* peer dependencies, since when they're installed\n // automatically by newer package manager behaviour, they may become isolated dependencies\n // that we still wish to access.\n if (peerDependenciesMeta) {\n peerDependencies = peerDependencies.filter((dependency) => {\n const peerMeta = peerDependenciesMeta[dependency];\n return peerMeta && typeof peerMeta === 'object' && peerMeta.optional === true;\n });\n }\n dependencies.push(...peerDependencies);\n }\n // We deduplicate the dependencies and exclude modules that we know are only used for scripts or config-plugins\n dependencies = dependencies.filter((moduleName, index, dependenciesArr) => {\n if (EXCLUDE_ORIGIN_MODULES[moduleName]) return false;\n return dependenciesArr.indexOf(moduleName) === index;\n });\n // Return test regex for dependencies and full origin module path to resolve through\n const originModulePath = path.dirname(filePath);\n return dependencies.length\n ? { originModulePath, moduleTestRe: dependenciesToRegex(dependencies) }\n : null;\n};\n\n/** Creates a fallback module resolver that resolves dependencis of modules named in `originModuleNames` via their path.\n * @remarks\n * The fallback resolver targets modules dependended on by modules named in `originModuleNames` and resolves\n * them from the module root of these origin modules instead.\n * It should only be used as a fallback after normal Node resolution (and other resolvers) have failed for:\n * - the `expo` package\n * - the `expo-router` package\n * Dependencies mentioned as either optional peer dependencies or direct dependencies by these modules may be isolated\n * and inaccessible via standard Node module resolution. This may happen when either transpilation adds these\n * dependencies to other parts of the tree (e.g. `@babel/runtime`) or when a dependency fails to hoist due to either\n * a corrupted dependency tree or when a peer dependency is fulfilled incorrectly (e.g. `expo-asset`)\n * @privateRemarks\n * This does NOT follow Node resolution and is *only* intended to provide a fallback for modules that we depend on\n * ourselves and know we can resolve (via expo or expo-router)!\n */\nexport function createFallbackModuleResolver({\n projectRoot,\n originModuleNames,\n getStrictResolver,\n}: {\n projectRoot: string;\n originModuleNames: string[];\n getStrictResolver: StrictResolverFactory;\n}): ExpoCustomMetroResolver {\n const _moduleDescriptionsCache: Record<string, ModuleDescription | null> = {};\n\n const getModuleDescription = (\n immutableContext: ResolutionContext,\n originModuleName: string,\n platform: string | null\n ) => {\n if (_moduleDescriptionsCache[originModuleName] !== undefined) {\n return _moduleDescriptionsCache[originModuleName];\n }\n // Resolve the origin module itself via the project root rather than the file that requested the missing module\n // The addition of `package.json` doesn't matter here. We just need a file path that'll be turned into a directory path\n // We don't need to modify `nodeModulesPaths` since it's guaranteed to contain the project's node modules paths\n const context: ResolutionContext = {\n ...immutableContext,\n originModulePath: path.join(projectRoot, 'package.json'),\n };\n return (_moduleDescriptionsCache[originModuleName] = getModuleDescriptionWithResolver(\n context,\n getStrictResolver(context, platform),\n originModuleName\n ));\n };\n\n const fileSpecifierRe = /^[\\\\/]|^\\.\\.?(?:$|[\\\\/])/i;\n\n return function requestFallbackModule(immutableContext, moduleName, platform) {\n // Early return if `moduleName` cannot be a module specifier\n // This doesn't have to be accurate as this resolver is a fallback for failed resolutions and\n // we're only doing this to avoid unnecessary resolution work\n if (fileSpecifierRe.test(moduleName)) {\n return null;\n }\n\n for (const originModuleName of originModuleNames) {\n const moduleDescription = getModuleDescription(immutableContext, originModuleName, platform);\n if (moduleDescription && moduleDescription.moduleTestRe.test(moduleName)) {\n // We instead resolve as if it was depended on by the `originModulePath` (the module named in `originModuleNames`)\n const context: ResolutionContext = {\n ...immutableContext,\n nodeModulesPaths: [moduleDescription.originModulePath],\n originModulePath: moduleDescription.originModulePath,\n };\n const res = getStrictResolver(context, platform)(moduleName);\n debug(\n `Fallback resolution for ${platform}: ${moduleName} -> from origin: ${originModuleName}`\n );\n return res;\n }\n }\n\n return null;\n };\n}\n"],"names":["createFallbackModuleResolver","EXCLUDE_ORIGIN_MODULES","semver","debug","require","dependenciesToRegex","dependencies","RegExp","join","getModuleDescriptionWithResolver","context","resolve","originModuleName","filePath","packageMeta","resolution","path","type","getPackage","error","constructor","name","push","Object","keys","peerDependencies","peerDependenciesMeta","filter","dependency","peerMeta","optional","moduleName","index","dependenciesArr","indexOf","originModulePath","dirname","length","moduleTestRe","projectRoot","originModuleNames","getStrictResolver","_moduleDescriptionsCache","getModuleDescription","immutableContext","platform","undefined","fileSpecifierRe","requestFallbackModule","test","moduleDescription","nodeModulesPaths","res"],"mappings":"AAAA,0CAA0C;AAC1C,uFAAuF;AACvF,wFAAwF;AACxF,sFAAsF;AACtF,mFAAmF;AACnF,kFAAkF;AAClF,oBAAoB;AACpB,+CAA+C;;;;;+BA8H/BA;;;eAAAA;;;;gEA3HC;;;;;;;;;;;AAKjB;;;;;;;;;CASC,GACD,MAAMC,yBAA2D;IAC/D,gBAAgB;IAChB,wBAAwB;IACxB,gBAAgB;IAChBC,QAAQ;AACV;AAyBA,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,iHAAiH,GACjH,MAAMC,sBAAsB,CAACC,eAC3B,IAAIC,OAAO,CAAC,IAAI,EAAED,aAAaE,IAAI,CAAC,KAAK,QAAQ,CAAC;AAEpD,gFAAgF,GAChF,MAAMC,mCAAmC,CACvCC,SACAC,SACAC;IAEA,IAAIC;IACJ,IAAIC;IACJ,IAAI;QACF,MAAMC,aAAaJ,QAAQK,eAAI,CAACR,IAAI,CAACI,kBAAkB;QACvD,IAAIG,WAAWE,IAAI,KAAK,cAAc;YACpCd,MAAM,CAAC,q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ageJson), resolved[0]);
|
|
143
143
|
}
|
|
144
144
|
if (pkg.exports) {
|
|
145
|
-
throw new Error("`exports` exists, but no results - this is a bug in Expo CLI's Metro resolver.
|
|
145
|
+
throw new Error("`exports` exists, but no results - this is a bug in Expo CLI's Metro resolver. Report an issue: https://github.com/expo/expo/issues");
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
148
|
}
|
|
@@ -162,7 +162,7 @@ const _default = defaultResolver;
|
|
|
162
162
|
return (0, _path().resolve)((0, _path().dirname)(packageJsonPath), resolved[0]);
|
|
163
163
|
}
|
|
164
164
|
if (pkg.exports) {
|
|
165
|
-
throw new Error("`exports` exists, but no results - this is a bug in Expo CLI's Metro resolver.
|
|
165
|
+
throw new Error("`exports` exists, but no results - this is a bug in Expo CLI's Metro resolver. Report an issue: https://github.com/expo/expo/issues");
|
|
166
166
|
}
|
|
167
167
|
return path;
|
|
168
168
|
}
|
|
@@ -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\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 &\n ResolverOptions & {\n pathExists: (file: string) => boolean;\n };\n\nconst defaultResolver = (\n path: string,\n {\n enablePackageExports,\n blockList = [],\n ...options\n }: Omit<ResolverOptions, 'defaultResolver' | 'getPackageForModule'> & {\n isDirectory: (file: string) => boolean;\n isFile: (file: string) => boolean;\n pathExists: (file: string) => boolean;\n }\n): string => {\n // @ts-expect-error\n const resolveOptions: UpstreamResolveOptionsWithConditions = {\n ...options,\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 return path;\n }\n\n if (moduleName.startsWith('@')) {\n moduleName = `${moduleName}/${segments.shift()}`;\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 // Added support for the package.json \"imports\" field (#-prefixed paths)\n if (path.startsWith('#')) {\n const resolved = resolve.imports(pkg, path, createResolveOptions(options.conditions));\n if (resolved) {\n // TODO: Should we attempt to resolve every path in the array?\n return pathResolve(dirname(closestPackageJson), resolved[0]);\n }\n // NOTE: resolve.imports would have thrown by this point.\n return path;\n }\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) {\n return path;\n }\n\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 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: UpstreamResolveOptionsWithConditions\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.pathExists!(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":["defaultResolver","path","enablePackageExports","blockList","options","resolveOptions","preserveSymlinks","result","resolveSync","getPathInModule","shouldIgnoreRequestForExports","segments","split","moduleName","shift","startsWith","closestPackageJson","findClosestPackageJson","basedir","pkg","readPackageSync","readFileSync","assert","resolved","resolve","imports","createResolveOptions","conditions","pathResolve","dirname","name","exports","join","Error","packageJsonPath","unsafe","browser","require","isAbsolute","start","dir","isDirectory","pkgJsonFile","hasPackageJson","pathExists","prevDir","undefined"],"mappings":"AAAA;;;;;;;;;CASC;;;;+BA4GD;;;eAAA;;;;gEA1GmB;;;;;;;yBACyC;;;;;;;yBACY;;;;;;;iEAC/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EzB,MAAMA,kBAAkB,CACtBC,MACA,EACEC,oBAAoB,EACpBC,YAAY,EAAE,EACd,GAAGC,SAKJ;I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AAO,EAACW;IAChB;IAEA,MAAO,KAAM;QACX,MAAME,cAAcd,IAAAA,eAAW,EAACY,KAAK;QACrC,MAAMG,iBAAiBvC,QAAQwC,UAAU,CAAEF;QAE3C,IAAIC,gBAAgB;YAClB,OAAOD;QACT;QAEA,MAAMG,UAAUL;QAChBA,MAAMX,IAAAA,eAAO,EAACW;QAEd,IAAIK,YAAYL,KAAK;YACnB,OAAOM;QACT;IACF;AACF"}
|
|
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\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 &\n ResolverOptions & {\n pathExists: (file: string) => boolean;\n };\n\nconst defaultResolver = (\n path: string,\n {\n enablePackageExports,\n blockList = [],\n ...options\n }: Omit<ResolverOptions, 'defaultResolver' | 'getPackageForModule'> & {\n isDirectory: (file: string) => boolean;\n isFile: (file: string) => boolean;\n pathExists: (file: string) => boolean;\n }\n): string => {\n // @ts-expect-error\n const resolveOptions: UpstreamResolveOptionsWithConditions = {\n ...options,\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 return path;\n }\n\n if (moduleName.startsWith('@')) {\n moduleName = `${moduleName}/${segments.shift()}`;\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 // Added support for the package.json \"imports\" field (#-prefixed paths)\n if (path.startsWith('#')) {\n const resolved = resolve.imports(pkg, path, createResolveOptions(options.conditions));\n if (resolved) {\n // TODO: Should we attempt to resolve every path in the array?\n return pathResolve(dirname(closestPackageJson), resolved[0]);\n }\n // NOTE: resolve.imports would have thrown by this point.\n return path;\n }\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. Report an issue: https://github.com/expo/expo/issues\"\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) {\n return path;\n }\n\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. Report an issue: https://github.com/expo/expo/issues\"\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: UpstreamResolveOptionsWithConditions\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.pathExists!(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":["defaultResolver","path","enablePackageExports","blockList","options","resolveOptions","preserveSymlinks","result","resolveSync","getPathInModule","shouldIgnoreRequestForExports","segments","split","moduleName","shift","startsWith","closestPackageJson","findClosestPackageJson","basedir","pkg","readPackageSync","readFileSync","assert","resolved","resolve","imports","createResolveOptions","conditions","pathResolve","dirname","name","exports","join","Error","packageJsonPath","unsafe","browser","require","isAbsolute","start","dir","isDirectory","pkgJsonFile","hasPackageJson","pathExists","prevDir","undefined"],"mappings":"AAAA;;;;;;;;;CASC;;;;+BA4GD;;;eAAA;;;;gEA1GmB;;;;;;;yBACyC;;;;;;;yBACY;;;;;;;iEAC/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EzB,MAAMA,kBAAkB,CACtBC,MACA,EACEC,oBAAoB,EACpBC,YAAY,EAAE,EACd,GAAGC,SAKJ;IAED,mBAAmB;IACnB,MAAMC,iBAAuD;QAC3D,GAAGD,OAAO;QACVE,kBAAkBF,QAAQE,gBAAgB;QAC1CN;IACF;IAEA,yEAAyE;IACzE,sDAAsD;IACtD,MAAMO,SAASC,IAAAA,eAAW,EAACN,uBAAuBO,gBAAgBR,MAAMI,kBAAkBJ,MAAM;QAC9F,GAAGI,cAAc;QACjBC,kBAAkB,CAACF,QAAQE,gBAAgB;IAC7C;I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|
|
@@ -182,8 +182,10 @@ function createServerComponentsMiddleware(projectRoot, { rscPath, instanceMetroO
|
|
|
182
182
|
targetDomain: 'server',
|
|
183
183
|
contents: wrapBundle(contents.src)
|
|
184
184
|
});
|
|
185
|
+
// Match babel plugin.
|
|
186
|
+
const publicModuleId = './' + (0, _filePath.toPosixPath)(_path().default.relative(projectRoot, entryPoint));
|
|
185
187
|
// Import relative to `dist/server/_expo/rsc/web/router.js`
|
|
186
|
-
manifest[
|
|
188
|
+
manifest[publicModuleId] = [
|
|
187
189
|
String(relativeName),
|
|
188
190
|
outputName
|
|
189
191
|
];
|
|
@@ -276,13 +278,14 @@ function createServerComponentsMiddleware(projectRoot, { rscPath, instanceMetroO
|
|
|
276
278
|
const { mode, minify = false, isExporting, baseUrl, routerRoot, asyncRoutes, preserveEnvVars, reactCompiler, lazy } = instanceMetroOptions;
|
|
277
279
|
(0, _assert().default)(isExporting != null && baseUrl != null && mode != null && routerRoot != null && asyncRoutes != null, `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`);
|
|
278
280
|
return (file, isServer)=>{
|
|
281
|
+
const filePath = _path().default.join(projectRoot, file.startsWith('file://') ? fileURLToFilePath(file) : file);
|
|
279
282
|
if (isExporting) {
|
|
280
283
|
(0, _assert().default)(context.ssrManifest, 'SSR manifest must exist when exporting');
|
|
281
|
-
const relativeFilePath = (0, _filePath.toPosixPath)(_path().default.relative(serverRoot,
|
|
284
|
+
const relativeFilePath = (0, _filePath.toPosixPath)(_path().default.relative(serverRoot, filePath));
|
|
282
285
|
(0, _assert().default)(context.ssrManifest.has(relativeFilePath), `SSR manifest is missing client boundary "${relativeFilePath}"`);
|
|
283
286
|
const chunk = context.ssrManifest.get(relativeFilePath);
|
|
284
287
|
return {
|
|
285
|
-
id: String(createModuleId(
|
|
288
|
+
id: String(createModuleId(filePath, {
|
|
286
289
|
platform: context.platform,
|
|
287
290
|
environment: 'client'
|
|
288
291
|
})),
|
|
@@ -317,7 +320,6 @@ function createServerComponentsMiddleware(projectRoot, { rscPath, instanceMetroO
|
|
|
317
320
|
// TICKLE: Handshake 1
|
|
318
321
|
searchParams.set('xRSC', '1');
|
|
319
322
|
clientReferenceUrl.search = searchParams.toString();
|
|
320
|
-
const filePath = file.startsWith('file://') ? fileURLToFilePath(file) : file;
|
|
321
323
|
const relativeFilePath = _path().default.relative(serverRoot, filePath);
|
|
322
324
|
clientReferenceUrl.pathname = relativeFilePath;
|
|
323
325
|
// Ensure url.pathname ends with '.bundle'
|
|
@@ -474,7 +476,16 @@ const getFullUrl = (url)=>{
|
|
|
474
476
|
}
|
|
475
477
|
};
|
|
476
478
|
const fileURLToFilePath = (fileURL)=>{
|
|
477
|
-
|
|
479
|
+
try {
|
|
480
|
+
return _url().default.fileURLToPath(fileURL);
|
|
481
|
+
} catch (error) {
|
|
482
|
+
if (error instanceof TypeError) {
|
|
483
|
+
throw Error(`Invalid URL: ${fileURL}`, {
|
|
484
|
+
cause: error
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
throw error;
|
|
488
|
+
}
|
|
478
489
|
};
|
|
479
490
|
const encodeInput = (input)=>{
|
|
480
491
|
if (input === '') {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/createServerComponentsMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport { getRscMiddleware } from '@expo/server/build/middleware/rsc';\nimport assert from 'assert';\nimport { EntriesDev } from 'expo-router/build/rsc/server';\nimport path from 'path';\nimport url from 'url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n ExpoMetroOptions,\n getMetroOptionsFromUrl,\n} from '../middleware/metroOptions';\n\nconst debug = require('debug')('expo:rsc') as typeof console.log;\n\ntype SSRLoadModuleArtifactsFunc = (\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>\n) => Promise<{ artifacts: SerialAsset[]; src: string }>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\nconst getMetroServerRootMemo = memoize(getMetroServerRoot);\n\nexport function createServerComponentsMiddleware(\n projectRoot: string,\n {\n rscPath,\n instanceMetroOptions,\n ssrLoadModule,\n ssrLoadModuleArtifacts,\n useClientRouter,\n createModuleId,\n routerOptions,\n }: {\n rscPath: string;\n instanceMetroOptions: Partial<ExpoMetroOptions>;\n ssrLoadModule: SSRLoadModuleFunc;\n ssrLoadModuleArtifacts: SSRLoadModuleArtifactsFunc;\n useClientRouter: boolean;\n createModuleId: (\n filePath: string,\n context: { platform: string; environment: string }\n ) => string | number;\n routerOptions: Record<string, any>;\n }\n) {\n const routerModule = useClientRouter\n ? 'expo-router/build/rsc/router/noopRouter'\n : 'expo-router/build/rsc/router/expo-definedRouter';\n\n const rscMiddleware = getRscMiddleware({\n config: {},\n // Disabled in development\n baseUrl: '',\n rscPath,\n onError: console.error,\n renderRsc: async (args) => {\n // In development we should add simulated versions of common production headers.\n if (args.headers['x-real-ip'] == null) {\n args.headers['x-real-ip'] = getIpAddress();\n }\n if (args.headers['x-forwarded-for'] == null) {\n args.headers['x-forwarded-for'] = args.headers['x-real-ip'];\n }\n if (args.headers['x-forwarded-proto'] == null) {\n args.headers['x-forwarded-proto'] = 'http';\n }\n\n // Dev server-only implementation.\n try {\n return await renderRscToReadableStream({\n ...args,\n headers: new Headers(args.headers),\n body: args.body!,\n routerOptions,\n });\n } catch (error: any) {\n // If you get a codeFrame error during SSR like when using a Class component in React Server Components, then this\n // will throw with:\n // {\n // rawObject: {\n // type: 'TransformError',\n // lineNumber: 0,\n // errors: [ [Object] ],\n // name: 'SyntaxError',\n // message: '...',\n // }\n // }\n\n // TODO: Revisit all error handling now that we do direct metro bundling...\n await logMetroError(projectRoot, { error });\n\n if (error[IS_METRO_BUNDLE_ERROR_SYMBOL]) {\n throw new Response(JSON.stringify(error), {\n status: isPossiblyUnableToResolveError(error) ? 404 : 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n const sanitizedServerMessage = stripAnsi(error.message) ?? error.message;\n throw new Response(sanitizedServerMessage, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n }\n },\n });\n\n let rscPathPrefix = rscPath;\n if (rscPathPrefix !== '/') {\n rscPathPrefix += '/';\n }\n\n async function exportServerActionsAsync(\n {\n platform,\n entryPoints,\n domRoot,\n }: { platform: string; entryPoints: string[]; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n clientBoundaries: string[];\n manifest: Record<string, [string, string]>;\n }> {\n const uniqueEntryPoints = [...new Set(entryPoints)];\n // TODO: Support multiple entry points in a single split server bundle...\n const manifest: Record<string, [string, string]> = {};\n const nestedClientBoundaries: string[] = [];\n const nestedServerBoundaries: string[] = [];\n const processedEntryPoints = new Set<string>();\n async function processEntryPoint(entryPoint: string) {\n processedEntryPoints.add(entryPoint);\n\n const contents = await ssrLoadModuleArtifacts(entryPoint, {\n environment: 'react-server',\n platform,\n // Ignore the metro runtime to avoid overwriting the original in the API route.\n modulesOnly: true,\n // Required\n runModule: true,\n // Required to ensure assets load as client boundaries.\n domRoot,\n });\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactClientReferences) {\n nestedClientBoundaries.push(...reactClientReferences!);\n }\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactServerReferences) {\n nestedServerBoundaries.push(...reactServerReferences!);\n }\n\n // Naive check to ensure the module runtime is not included in the server action bundle.\n if (contents.src.includes('The experimental Metro feature')) {\n throw new Error(\n 'Internal error: module runtime should not be included in server action bundles: ' +\n entryPoint\n );\n }\n\n const relativeName = createModuleId(entryPoint, {\n platform,\n environment: 'react-server',\n });\n const safeName = path.basename(contents.artifacts.find((a) => a.type === 'js')!.filename!);\n\n const outputName = `_expo/rsc/${platform}/${safeName}`;\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(outputName, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[entryPoint] = [String(relativeName), outputName];\n }\n\n async function processEntryPoints(entryPoints: string[], recursions = 0) {\n // Arbitrary recursion limit to prevent infinite loops.\n if (recursions > 10) {\n throw new Error('Recursion limit exceeded while processing server boundaries');\n }\n\n for (const entryPoint of entryPoints) {\n await processEntryPoint(entryPoint);\n }\n\n // When a server action has other server actions inside of it, we need to process those as well to ensure all entry points are in the manifest and accounted for.\n let uniqueNestedServerBoundaries = [...new Set(nestedServerBoundaries)];\n // Filter out values that have already been processed.\n uniqueNestedServerBoundaries = uniqueNestedServerBoundaries.filter(\n (value) => !processedEntryPoints.has(value)\n );\n if (uniqueNestedServerBoundaries.length) {\n debug('bundling nested server action boundaries', uniqueNestedServerBoundaries);\n return processEntryPoints(uniqueNestedServerBoundaries, recursions + 1);\n }\n }\n\n await processEntryPoints(uniqueEntryPoints);\n\n // Save the SSR manifest so we can perform more replacements in the server renderer and with server actions.\n files.set(`_expo/rsc/${platform}/action-manifest.js`, {\n targetDomain: 'server',\n contents: 'module.exports = ' + JSON.stringify(manifest),\n });\n\n return { manifest, clientBoundaries: nestedClientBoundaries };\n }\n\n async function getExpoRouterClientReferencesAsync(\n { platform, domRoot }: { platform: string; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n reactClientReferences: string[];\n reactServerReferences: string[];\n cssModules: SerialAsset[];\n }> {\n const contents = await ssrLoadModuleArtifacts(routerModule, {\n environment: 'react-server',\n platform,\n modulesOnly: true,\n domRoot,\n });\n\n // Extract the global CSS modules that are imported from the router.\n // These will be injected in the head of the HTML document for the website.\n const cssModules = contents.artifacts.filter((a) => a.type.startsWith('css'));\n\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactServerReferences) {\n throw new Error(\n 'Static server action references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactServerReferences);\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactClientReferences) {\n throw new Error(\n 'Static client references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactClientReferences);\n\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(`_expo/rsc/${platform}/router.js`, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n return { reactClientReferences, reactServerReferences, cssModules };\n }\n\n const routerCache = new Map<string, EntriesDev>();\n\n async function getExpoRouterRscEntriesGetterAsync({\n platform,\n routerOptions,\n }: {\n platform: string;\n routerOptions: Record<string, any>;\n }) {\n await ensureMemo();\n // We can only cache this if we're using the client router since it doesn't change or use HMR\n if (routerCache.has(platform) && useClientRouter) {\n return routerCache.get(platform)!;\n }\n\n const router = await ssrLoadModule<\n typeof import('expo-router/build/rsc/router/expo-definedRouter')\n >(\n routerModule,\n {\n environment: 'react-server',\n modulesOnly: true,\n platform,\n },\n {\n hot: !useClientRouter,\n }\n );\n\n const entries = router.default({\n redirects: routerOptions?.redirects,\n rewrites: routerOptions?.rewrites,\n });\n\n routerCache.set(platform, entries);\n return entries;\n }\n\n function getResolveClientEntry(context: {\n platform: string;\n engine?: 'hermes' | null;\n ssrManifest?: Map<string, string>;\n }): (\n file: string,\n isServer: boolean\n ) => {\n id: string;\n chunks: string[];\n } {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n const {\n mode,\n minify = false,\n isExporting,\n baseUrl,\n routerRoot,\n asyncRoutes,\n preserveEnvVars,\n reactCompiler,\n lazy,\n } = instanceMetroOptions;\n\n assert(\n isExporting != null &&\n baseUrl != null &&\n mode != null &&\n routerRoot != null &&\n asyncRoutes != null,\n `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`\n );\n\n return (file: string, isServer: boolean) => {\n if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n const relativeFilePath = toPosixPath(path.relative(serverRoot, file));\n\n assert(\n context.ssrManifest.has(relativeFilePath),\n `SSR manifest is missing client boundary \"${relativeFilePath}\"`\n );\n\n const chunk = context.ssrManifest.get(relativeFilePath);\n\n return {\n id: String(createModuleId(file, { platform: context.platform, environment: 'client' })),\n chunks: chunk != null ? [chunk] : [],\n };\n }\n\n const environment = isServer ? 'react-server' : 'client';\n const searchParams = createBundleUrlSearchParams({\n mainModuleName: '',\n platform: context.platform,\n mode,\n minify,\n lazy,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n reactCompiler: !!reactCompiler,\n engine: context.engine ?? undefined,\n bytecode: false,\n clientBoundaries: [],\n inlineSourceMap: false,\n environment,\n modulesOnly: true,\n runModule: false,\n });\n\n searchParams.set('resolver.clientboundary', String(true));\n\n const clientReferenceUrl = new URL('http://a');\n\n // TICKLE: Handshake 1\n searchParams.set('xRSC', '1');\n\n clientReferenceUrl.search = searchParams.toString();\n\n const filePath = file.startsWith('file://') ? fileURLToFilePath(file) : file;\n\n const relativeFilePath = path.relative(serverRoot, filePath);\n\n clientReferenceUrl.pathname = relativeFilePath;\n\n // Ensure url.pathname ends with '.bundle'\n if (!clientReferenceUrl.pathname.endsWith('.bundle')) {\n clientReferenceUrl.pathname += '.bundle';\n }\n\n // Return relative URLs to help Android fetch from wherever it was loaded from since it doesn't support localhost.\n const chunkName = clientReferenceUrl.pathname + clientReferenceUrl.search;\n\n return {\n id: String(createModuleId(filePath, { platform: context.platform, environment })),\n chunks: [chunkName],\n };\n };\n }\n\n const rscRendererCache = new Map<string, typeof import('expo-router/build/rsc/rsc-renderer')>();\n\n let ensurePromise: Promise<any> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n const runtime = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'metro-runtime/src/modules/empty-module.js',\n {\n environment: 'react-server',\n platform: 'web',\n }\n );\n return runtime;\n }\n const ensureMemo = () => {\n ensurePromise ??= ensureSSRReady();\n return ensurePromise;\n };\n\n async function getRscRendererAsync(platform: string) {\n await ensureMemo();\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRendererCache.has(platform)) {\n return rscRendererCache.get(platform)!;\n }\n\n // TODO: Extract CSS Modules / Assets from the bundler process\n const renderer = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'expo-router/build/rsc/rsc-renderer',\n {\n environment: 'react-server',\n platform,\n }\n );\n\n rscRendererCache.set(platform, renderer);\n return renderer;\n }\n\n const rscRenderContext = new Map<string, any>();\n\n function getRscRenderContext(platform: string) {\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRenderContext.has(platform)) {\n return rscRenderContext.get(platform)!;\n }\n\n const context = {};\n\n rscRenderContext.set(platform, context);\n return context;\n }\n\n async function renderRscToReadableStream(\n {\n input,\n headers,\n method,\n platform,\n body,\n engine,\n contentType,\n ssrManifest,\n decodedBody,\n routerOptions,\n }: {\n input: string;\n headers: Headers;\n method: 'POST' | 'GET';\n platform: string;\n body?: ReadableStream<Uint8Array>;\n engine?: 'hermes' | null;\n contentType?: string;\n ssrManifest?: Map<string, string>;\n decodedBody?: unknown;\n routerOptions: Record<string, any>;\n },\n isExporting: boolean | undefined = instanceMetroOptions.isExporting\n ) {\n assert(\n isExporting != null,\n 'The server must be started before calling renderRscToReadableStream.'\n );\n\n if (method === 'POST') {\n assert(body, 'Server request must be provided when method is POST (server actions)');\n }\n\n const context = getRscRenderContext(platform);\n\n context['__expo_requestHeaders'] = headers;\n\n const { renderRsc } = await getRscRendererAsync(platform);\n\n return renderRsc(\n {\n body,\n decodedBody,\n context,\n config: {},\n input,\n contentType,\n },\n {\n isExporting,\n entries: await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions }),\n resolveClientEntry: getResolveClientEntry({ platform, engine, ssrManifest }),\n async loadServerModuleRsc(urlFragment) {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n debug('[SSR] loadServerModuleRsc:', urlFragment);\n\n const options = getMetroOptionsFromUrl(urlFragment);\n\n return ssrLoadModule(path.join(serverRoot, options.mainModuleName), options, {\n hot: true,\n });\n },\n }\n );\n }\n\n return {\n // Get the static client boundaries (no dead code elimination allowed) for the production export.\n getExpoRouterClientReferencesAsync,\n exportServerActionsAsync,\n\n async exportRoutesAsync(\n {\n platform,\n ssrManifest,\n routerOptions,\n }: {\n platform: string;\n ssrManifest: Map<string, string>;\n routerOptions: Record<string, any>;\n },\n files: ExportAssetMap\n ) {\n // TODO: When we add web SSR support, we need to extract CSS Modules / Assets from the bundler process to prevent FLOUC.\n const { getBuildConfig } = (\n await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions })\n ).default;\n\n // Get all the routes to render.\n const buildConfig = await getBuildConfig!(async () =>\n // TODO: Rework prefetching code to use Metro runtime.\n []\n );\n\n await Promise.all(\n Array.from(buildConfig).map(async ({ entries }) => {\n for (const { input, isStatic } of entries || []) {\n if (!isStatic) {\n debug('Skipping static export for route', { input });\n continue;\n }\n const destRscFile = path.join('_flight', platform, encodeInput(input));\n\n const pipe = await renderRscToReadableStream(\n {\n input,\n method: 'GET',\n platform,\n headers: new Headers(),\n ssrManifest,\n routerOptions,\n },\n true\n );\n\n const rsc = await streamToStringAsync(pipe);\n debug('RSC Payload', { platform, input, rsc });\n\n files.set(destRscFile, {\n contents: rsc,\n targetDomain: 'client',\n rscId: input,\n });\n }\n })\n );\n },\n\n middleware: createBuiltinAPIRequestHandler(\n // Match `/_flight/[platform]/[...path]`\n (req) => {\n return getFullUrl(req.url).pathname.startsWith(rscPathPrefix);\n },\n rscMiddleware\n ),\n onReloadRscEvent: (platform: string) => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n rscRendererCache.delete(platform);\n routerCache.delete(platform);\n },\n };\n}\n\nconst getFullUrl = (url: string) => {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'http://localhost:0');\n }\n};\n\nexport const fileURLToFilePath = (fileURL: string) => {\n return url.fileURLToPath(fileURL);\n};\n\nconst encodeInput = (input: string) => {\n if (input === '') {\n return 'index.txt';\n }\n if (input === 'index') {\n throw new Error('Input should not be `index`');\n }\n if (input.startsWith('/')) {\n throw new Error('Input should not start with `/`');\n }\n if (input.endsWith('/')) {\n throw new Error('Input should not end with `/`');\n }\n return input + '.txt';\n};\n\nfunction wrapBundle(str: string) {\n // Skip the metro runtime so debugging is a bit easier.\n // Replace the __r() call with an export statement.\n // Use gm to apply to the last require line. This is needed when the bundle has side-effects.\n return str.replace(/^(__r\\(.*\\);)$/gm, 'module.exports = $1');\n}\n"],"names":["createServerComponentsMiddleware","fileURLToFilePath","debug","require","getMetroServerRootMemo","memoize","getMetroServerRoot","projectRoot","rscPath","instanceMetroOptions","ssrLoadModule","ssrLoadModuleArtifacts","useClientRouter","createModuleId","routerOptions","routerModule","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","IS_METRO_BUNDLE_ERROR_SYMBOL","Response","JSON","stringify","status","isPossiblyUnableToResolveError","sanitizedServerMessage","stripAnsi","message","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","nestedServerBoundaries","processedEntryPoints","processEntryPoint","entryPoint","contents","add","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","reactServerReferences","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","String","processEntryPoints","recursions","uniqueNestedServerBoundaries","value","has","length","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","routerCache","Map","getExpoRouterRscEntriesGetterAsync","ensureMemo","get","router","hot","entries","default","redirects","rewrites","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","ssrManifest","relativeFilePath","toPosixPath","relative","chunk","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","filePath","pathname","endsWith","chunkName","rscRendererCache","ensurePromise","ensureSSRReady","runtime","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","join","exportRoutesAsync","getBuildConfig","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","delete","fileURL","fileURLToPath","str","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAuCeA,gCAAgC;eAAhCA;;IAslBHC,iBAAiB;eAAjBA;;;;yBA5nBsB;;;;;;;yBAEF;;;;;;;gEACd;;;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B;AACzC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/createServerComponentsMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport { getRscMiddleware } from '@expo/server/build/middleware/rsc';\nimport assert from 'assert';\nimport { EntriesDev } from 'expo-router/build/rsc/server';\nimport path from 'path';\nimport url from 'url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n ExpoMetroOptions,\n getMetroOptionsFromUrl,\n} from '../middleware/metroOptions';\n\nconst debug = require('debug')('expo:rsc') as typeof console.log;\n\ntype SSRLoadModuleArtifactsFunc = (\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>\n) => Promise<{ artifacts: SerialAsset[]; src: string }>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\nconst getMetroServerRootMemo = memoize(getMetroServerRoot);\n\nexport function createServerComponentsMiddleware(\n projectRoot: string,\n {\n rscPath,\n instanceMetroOptions,\n ssrLoadModule,\n ssrLoadModuleArtifacts,\n useClientRouter,\n createModuleId,\n routerOptions,\n }: {\n rscPath: string;\n instanceMetroOptions: Partial<ExpoMetroOptions>;\n ssrLoadModule: SSRLoadModuleFunc;\n ssrLoadModuleArtifacts: SSRLoadModuleArtifactsFunc;\n useClientRouter: boolean;\n createModuleId: (\n filePath: string,\n context: { platform: string; environment: string }\n ) => string | number;\n routerOptions: Record<string, any>;\n }\n) {\n const routerModule = useClientRouter\n ? 'expo-router/build/rsc/router/noopRouter'\n : 'expo-router/build/rsc/router/expo-definedRouter';\n\n const rscMiddleware = getRscMiddleware({\n config: {},\n // Disabled in development\n baseUrl: '',\n rscPath,\n onError: console.error,\n renderRsc: async (args) => {\n // In development we should add simulated versions of common production headers.\n if (args.headers['x-real-ip'] == null) {\n args.headers['x-real-ip'] = getIpAddress();\n }\n if (args.headers['x-forwarded-for'] == null) {\n args.headers['x-forwarded-for'] = args.headers['x-real-ip'];\n }\n if (args.headers['x-forwarded-proto'] == null) {\n args.headers['x-forwarded-proto'] = 'http';\n }\n\n // Dev server-only implementation.\n try {\n return await renderRscToReadableStream({\n ...args,\n headers: new Headers(args.headers),\n body: args.body!,\n routerOptions,\n });\n } catch (error: any) {\n // If you get a codeFrame error during SSR like when using a Class component in React Server Components, then this\n // will throw with:\n // {\n // rawObject: {\n // type: 'TransformError',\n // lineNumber: 0,\n // errors: [ [Object] ],\n // name: 'SyntaxError',\n // message: '...',\n // }\n // }\n\n // TODO: Revisit all error handling now that we do direct metro bundling...\n await logMetroError(projectRoot, { error });\n\n if (error[IS_METRO_BUNDLE_ERROR_SYMBOL]) {\n throw new Response(JSON.stringify(error), {\n status: isPossiblyUnableToResolveError(error) ? 404 : 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n const sanitizedServerMessage = stripAnsi(error.message) ?? error.message;\n throw new Response(sanitizedServerMessage, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n }\n },\n });\n\n let rscPathPrefix = rscPath;\n if (rscPathPrefix !== '/') {\n rscPathPrefix += '/';\n }\n\n async function exportServerActionsAsync(\n {\n platform,\n entryPoints,\n domRoot,\n }: { platform: string; entryPoints: string[]; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n clientBoundaries: string[];\n manifest: Record<string, [string, string]>;\n }> {\n const uniqueEntryPoints = [...new Set(entryPoints)];\n // TODO: Support multiple entry points in a single split server bundle...\n const manifest: Record<string, [string, string]> = {};\n const nestedClientBoundaries: string[] = [];\n const nestedServerBoundaries: string[] = [];\n const processedEntryPoints = new Set<string>();\n async function processEntryPoint(entryPoint: string) {\n processedEntryPoints.add(entryPoint);\n\n const contents = await ssrLoadModuleArtifacts(entryPoint, {\n environment: 'react-server',\n platform,\n // Ignore the metro runtime to avoid overwriting the original in the API route.\n modulesOnly: true,\n // Required\n runModule: true,\n // Required to ensure assets load as client boundaries.\n domRoot,\n });\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactClientReferences) {\n nestedClientBoundaries.push(...reactClientReferences!);\n }\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactServerReferences) {\n nestedServerBoundaries.push(...reactServerReferences!);\n }\n\n // Naive check to ensure the module runtime is not included in the server action bundle.\n if (contents.src.includes('The experimental Metro feature')) {\n throw new Error(\n 'Internal error: module runtime should not be included in server action bundles: ' +\n entryPoint\n );\n }\n\n const relativeName = createModuleId(entryPoint, {\n platform,\n environment: 'react-server',\n });\n const safeName = path.basename(contents.artifacts.find((a) => a.type === 'js')!.filename!);\n\n const outputName = `_expo/rsc/${platform}/${safeName}`;\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(outputName, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n // Match babel plugin.\n const publicModuleId = './' + toPosixPath(path.relative(projectRoot, entryPoint));\n\n // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[publicModuleId] = [String(relativeName), outputName];\n }\n\n async function processEntryPoints(entryPoints: string[], recursions = 0) {\n // Arbitrary recursion limit to prevent infinite loops.\n if (recursions > 10) {\n throw new Error('Recursion limit exceeded while processing server boundaries');\n }\n\n for (const entryPoint of entryPoints) {\n await processEntryPoint(entryPoint);\n }\n\n // When a server action has other server actions inside of it, we need to process those as well to ensure all entry points are in the manifest and accounted for.\n let uniqueNestedServerBoundaries = [...new Set(nestedServerBoundaries)];\n // Filter out values that have already been processed.\n uniqueNestedServerBoundaries = uniqueNestedServerBoundaries.filter(\n (value) => !processedEntryPoints.has(value)\n );\n if (uniqueNestedServerBoundaries.length) {\n debug('bundling nested server action boundaries', uniqueNestedServerBoundaries);\n return processEntryPoints(uniqueNestedServerBoundaries, recursions + 1);\n }\n }\n\n await processEntryPoints(uniqueEntryPoints);\n\n // Save the SSR manifest so we can perform more replacements in the server renderer and with server actions.\n files.set(`_expo/rsc/${platform}/action-manifest.js`, {\n targetDomain: 'server',\n contents: 'module.exports = ' + JSON.stringify(manifest),\n });\n\n return { manifest, clientBoundaries: nestedClientBoundaries };\n }\n\n async function getExpoRouterClientReferencesAsync(\n { platform, domRoot }: { platform: string; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n reactClientReferences: string[];\n reactServerReferences: string[];\n cssModules: SerialAsset[];\n }> {\n const contents = await ssrLoadModuleArtifacts(routerModule, {\n environment: 'react-server',\n platform,\n modulesOnly: true,\n domRoot,\n });\n\n // Extract the global CSS modules that are imported from the router.\n // These will be injected in the head of the HTML document for the website.\n const cssModules = contents.artifacts.filter((a) => a.type.startsWith('css'));\n\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactServerReferences) {\n throw new Error(\n 'Static server action references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactServerReferences);\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactClientReferences) {\n throw new Error(\n 'Static client references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactClientReferences);\n\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(`_expo/rsc/${platform}/router.js`, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n return { reactClientReferences, reactServerReferences, cssModules };\n }\n\n const routerCache = new Map<string, EntriesDev>();\n\n async function getExpoRouterRscEntriesGetterAsync({\n platform,\n routerOptions,\n }: {\n platform: string;\n routerOptions: Record<string, any>;\n }) {\n await ensureMemo();\n // We can only cache this if we're using the client router since it doesn't change or use HMR\n if (routerCache.has(platform) && useClientRouter) {\n return routerCache.get(platform)!;\n }\n\n const router = await ssrLoadModule<\n typeof import('expo-router/build/rsc/router/expo-definedRouter')\n >(\n routerModule,\n {\n environment: 'react-server',\n modulesOnly: true,\n platform,\n },\n {\n hot: !useClientRouter,\n }\n );\n\n const entries = router.default({\n redirects: routerOptions?.redirects,\n rewrites: routerOptions?.rewrites,\n });\n\n routerCache.set(platform, entries);\n return entries;\n }\n\n function getResolveClientEntry(context: {\n platform: string;\n engine?: 'hermes' | null;\n ssrManifest?: Map<string, string>;\n }): (\n file: string,\n isServer: boolean\n ) => {\n id: string;\n chunks: string[];\n } {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n const {\n mode,\n minify = false,\n isExporting,\n baseUrl,\n routerRoot,\n asyncRoutes,\n preserveEnvVars,\n reactCompiler,\n lazy,\n } = instanceMetroOptions;\n\n assert(\n isExporting != null &&\n baseUrl != null &&\n mode != null &&\n routerRoot != null &&\n asyncRoutes != null,\n `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`\n );\n\n return (file: string, isServer: boolean) => {\n const filePath = path.join(\n projectRoot,\n file.startsWith('file://') ? fileURLToFilePath(file) : file\n );\n\n if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n\n const relativeFilePath = toPosixPath(path.relative(serverRoot, filePath));\n\n assert(\n context.ssrManifest.has(relativeFilePath),\n `SSR manifest is missing client boundary \"${relativeFilePath}\"`\n );\n\n const chunk = context.ssrManifest.get(relativeFilePath);\n\n return {\n id: String(\n createModuleId(filePath, { platform: context.platform, environment: 'client' })\n ),\n chunks: chunk != null ? [chunk] : [],\n };\n }\n\n const environment = isServer ? 'react-server' : 'client';\n const searchParams = createBundleUrlSearchParams({\n mainModuleName: '',\n platform: context.platform,\n mode,\n minify,\n lazy,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n reactCompiler: !!reactCompiler,\n engine: context.engine ?? undefined,\n bytecode: false,\n clientBoundaries: [],\n inlineSourceMap: false,\n environment,\n modulesOnly: true,\n runModule: false,\n });\n\n searchParams.set('resolver.clientboundary', String(true));\n\n const clientReferenceUrl = new URL('http://a');\n\n // TICKLE: Handshake 1\n searchParams.set('xRSC', '1');\n\n clientReferenceUrl.search = searchParams.toString();\n\n const relativeFilePath = path.relative(serverRoot, filePath);\n\n clientReferenceUrl.pathname = relativeFilePath;\n\n // Ensure url.pathname ends with '.bundle'\n if (!clientReferenceUrl.pathname.endsWith('.bundle')) {\n clientReferenceUrl.pathname += '.bundle';\n }\n\n // Return relative URLs to help Android fetch from wherever it was loaded from since it doesn't support localhost.\n const chunkName = clientReferenceUrl.pathname + clientReferenceUrl.search;\n\n return {\n id: String(createModuleId(filePath, { platform: context.platform, environment })),\n chunks: [chunkName],\n };\n };\n }\n\n const rscRendererCache = new Map<string, typeof import('expo-router/build/rsc/rsc-renderer')>();\n\n let ensurePromise: Promise<any> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n const runtime = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'metro-runtime/src/modules/empty-module.js',\n {\n environment: 'react-server',\n platform: 'web',\n }\n );\n return runtime;\n }\n const ensureMemo = () => {\n ensurePromise ??= ensureSSRReady();\n return ensurePromise;\n };\n\n async function getRscRendererAsync(platform: string) {\n await ensureMemo();\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRendererCache.has(platform)) {\n return rscRendererCache.get(platform)!;\n }\n\n // TODO: Extract CSS Modules / Assets from the bundler process\n const renderer = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'expo-router/build/rsc/rsc-renderer',\n {\n environment: 'react-server',\n platform,\n }\n );\n\n rscRendererCache.set(platform, renderer);\n return renderer;\n }\n\n const rscRenderContext = new Map<string, any>();\n\n function getRscRenderContext(platform: string) {\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRenderContext.has(platform)) {\n return rscRenderContext.get(platform)!;\n }\n\n const context = {};\n\n rscRenderContext.set(platform, context);\n return context;\n }\n\n async function renderRscToReadableStream(\n {\n input,\n headers,\n method,\n platform,\n body,\n engine,\n contentType,\n ssrManifest,\n decodedBody,\n routerOptions,\n }: {\n input: string;\n headers: Headers;\n method: 'POST' | 'GET';\n platform: string;\n body?: ReadableStream<Uint8Array>;\n engine?: 'hermes' | null;\n contentType?: string;\n ssrManifest?: Map<string, string>;\n decodedBody?: unknown;\n routerOptions: Record<string, any>;\n },\n isExporting: boolean | undefined = instanceMetroOptions.isExporting\n ) {\n assert(\n isExporting != null,\n 'The server must be started before calling renderRscToReadableStream.'\n );\n\n if (method === 'POST') {\n assert(body, 'Server request must be provided when method is POST (server actions)');\n }\n\n const context = getRscRenderContext(platform);\n\n context['__expo_requestHeaders'] = headers;\n\n const { renderRsc } = await getRscRendererAsync(platform);\n\n return renderRsc(\n {\n body,\n decodedBody,\n context,\n config: {},\n input,\n contentType,\n },\n {\n isExporting,\n entries: await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions }),\n resolveClientEntry: getResolveClientEntry({ platform, engine, ssrManifest }),\n async loadServerModuleRsc(urlFragment) {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n debug('[SSR] loadServerModuleRsc:', urlFragment);\n\n const options = getMetroOptionsFromUrl(urlFragment);\n\n return ssrLoadModule(\n path.join(serverRoot, options.mainModuleName),\n\n options,\n {\n hot: true,\n }\n );\n },\n }\n );\n }\n\n return {\n // Get the static client boundaries (no dead code elimination allowed) for the production export.\n getExpoRouterClientReferencesAsync,\n exportServerActionsAsync,\n\n async exportRoutesAsync(\n {\n platform,\n ssrManifest,\n routerOptions,\n }: {\n platform: string;\n ssrManifest: Map<string, string>;\n routerOptions: Record<string, any>;\n },\n files: ExportAssetMap\n ) {\n // TODO: When we add web SSR support, we need to extract CSS Modules / Assets from the bundler process to prevent FLOUC.\n const { getBuildConfig } = (\n await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions })\n ).default;\n\n // Get all the routes to render.\n const buildConfig = await getBuildConfig!(async () =>\n // TODO: Rework prefetching code to use Metro runtime.\n []\n );\n\n await Promise.all(\n Array.from(buildConfig).map(async ({ entries }) => {\n for (const { input, isStatic } of entries || []) {\n if (!isStatic) {\n debug('Skipping static export for route', { input });\n continue;\n }\n const destRscFile = path.join('_flight', platform, encodeInput(input));\n\n const pipe = await renderRscToReadableStream(\n {\n input,\n method: 'GET',\n platform,\n headers: new Headers(),\n ssrManifest,\n routerOptions,\n },\n true\n );\n\n const rsc = await streamToStringAsync(pipe);\n debug('RSC Payload', { platform, input, rsc });\n\n files.set(destRscFile, {\n contents: rsc,\n targetDomain: 'client',\n rscId: input,\n });\n }\n })\n );\n },\n\n middleware: createBuiltinAPIRequestHandler(\n // Match `/_flight/[platform]/[...path]`\n (req) => {\n return getFullUrl(req.url).pathname.startsWith(rscPathPrefix);\n },\n rscMiddleware\n ),\n onReloadRscEvent: (platform: string) => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n rscRendererCache.delete(platform);\n routerCache.delete(platform);\n },\n };\n}\n\nconst getFullUrl = (url: string) => {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'http://localhost:0');\n }\n};\n\nexport const fileURLToFilePath = (fileURL: string) => {\n try {\n return url.fileURLToPath(fileURL);\n } catch (error) {\n if (error instanceof TypeError) {\n throw Error(`Invalid URL: ${fileURL}`, { cause: error });\n }\n throw error;\n }\n};\n\nconst encodeInput = (input: string) => {\n if (input === '') {\n return 'index.txt';\n }\n if (input === 'index') {\n throw new Error('Input should not be `index`');\n }\n if (input.startsWith('/')) {\n throw new Error('Input should not start with `/`');\n }\n if (input.endsWith('/')) {\n throw new Error('Input should not end with `/`');\n }\n return input + '.txt';\n};\n\nfunction wrapBundle(str: string) {\n // Skip the metro runtime so debugging is a bit easier.\n // Replace the __r() call with an export statement.\n // Use gm to apply to the last require line. This is needed when the bundle has side-effects.\n return str.replace(/^(__r\\(.*\\);)$/gm, 'module.exports = $1');\n}\n"],"names":["createServerComponentsMiddleware","fileURLToFilePath","debug","require","getMetroServerRootMemo","memoize","getMetroServerRoot","projectRoot","rscPath","instanceMetroOptions","ssrLoadModule","ssrLoadModuleArtifacts","useClientRouter","createModuleId","routerOptions","routerModule","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","IS_METRO_BUNDLE_ERROR_SYMBOL","Response","JSON","stringify","status","isPossiblyUnableToResolveError","sanitizedServerMessage","stripAnsi","message","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","nestedServerBoundaries","processedEntryPoints","processEntryPoint","entryPoint","contents","add","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","reactServerReferences","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","publicModuleId","toPosixPath","relative","String","processEntryPoints","recursions","uniqueNestedServerBoundaries","value","has","length","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","routerCache","Map","getExpoRouterRscEntriesGetterAsync","ensureMemo","get","router","hot","entries","default","redirects","rewrites","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","filePath","join","ssrManifest","relativeFilePath","chunk","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","pathname","endsWith","chunkName","rscRendererCache","ensurePromise","ensureSSRReady","runtime","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","exportRoutesAsync","getBuildConfig","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","delete","fileURL","fileURLToPath","TypeError","cause","str","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAuCeA,gCAAgC;eAAhCA;;IAomBHC,iBAAiB;eAAjBA;;;;yBA1oBsB;;;;;;;yBAEF;;;;;;;gEACd;;;;;;;gEAEF;;;;;;;gEACD;;;;;;qCAE4C;qCACb;sBAErB;0BACE;oBACJ;oBACK;wBACO;gDACW;8BAKxC;;;;;;AAEP,MAAMC,QAAQC,QAAQ,SAAS;AAa/B,MAAMC,yBAAyBC,IAAAA,WAAO,EAACC,2BAAkB;AAElD,SAASN,iCACdO,WAAmB,EACnB,EACEC,OAAO,EACPC,oBAAoB,EACpBC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,EACfC,cAAc,EACdC,aAAa,EAYd;IAED,MAAMC,eAAeH,kBACjB,4CACA;IAEJ,MAAMI,gBAAgBC,IAAAA,uBAAgB,EAAC;QACrCC,QAAQ,CAAC;QACT,0BAA0B;QAC1BC,SAAS;QACTX;QACAY,SAASC,QAAQC,KAAK;QACtBC,WAAW,OAAOC;YAChB,gFAAgF;YAChF,IAAIA,KAAKC,OAAO,CAAC,YAAY,IAAI,MAAM;gBACrCD,KAAKC,O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AEtC,QAAQ,CAAC5C,UAAU,CAACvD;QACjD,GACAxB;QAEFkK,kBAAkB,CAACxI;YACjB,+FAA+F;YAE/FoG,iBAAiBqC,MAAM,CAACzI;YACxBsD,YAAYmF,MAAM,CAACzI;QACrB;IACF;AACF;AAEA,MAAMsI,aAAa,CAACC;IAClB,IAAI;QACF,OAAO,IAAIzC,IAAIyC;IACjB,EAAE,OAAM;QACN,OAAO,IAAIzC,IAAIyC,KAAK;IACtB;AACF;AAEO,MAAMhL,oBAAoB,CAACmL;IAChC,IAAI;QACF,OAAOH,cAAG,CAACI,aAAa,CAACD;IAC3B,EAAE,OAAO9J,OAAO;QACd,IAAIA,iBAAiBgK,WAAW;YAC9B,MAAM/G,MAAM,CAAC,aAAa,EAAE6G,SAAS,EAAE;gBAAEG,OAAOjK;YAAM;QACxD;QACA,MAAMA;IACR;AACF;AAEA,MAAMkJ,cAAc,CAAClB;IACnB,IAAIA,UAAU,IAAI;QAChB,OAAO;IACT;IACA,IAAIA,UAAU,SAAS;QACrB,MAAM,IAAI/E,MAAM;IAClB;IACA,IAAI+E,MAAMvD,UAAU,CAAC,MAAM;QACzB,MAAM,IAAIxB,MAAM;IAClB;IACA,IAAI+E,MAAMV,QAAQ,CAAC,MAAM;QACvB,MAAM,IAAIrE,MAAM;IAClB;IACA,OAAO+E,QAAQ;AACjB;AAEA,SAASrE,WAAWuG,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAIC,OAAO,CAAC,oBAAoB;AACzC"}
|
|
@@ -8,13 +8,6 @@ Object.defineProperty(exports, "createDebugMiddleware", {
|
|
|
8
8
|
return createDebugMiddleware;
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
|
-
function _chalk() {
|
|
12
|
-
const data = /*#__PURE__*/ _interop_require_default(require("chalk"));
|
|
13
|
-
_chalk = function() {
|
|
14
|
-
return data;
|
|
15
|
-
};
|
|
16
|
-
return data;
|
|
17
|
-
}
|
|
18
11
|
function _ws() {
|
|
19
12
|
const data = require("ws");
|
|
20
13
|
_ws = function() {
|
|
@@ -23,16 +16,10 @@ function _ws() {
|
|
|
23
16
|
return data;
|
|
24
17
|
}
|
|
25
18
|
const _createHandlersFactory = require("./createHandlersFactory");
|
|
26
|
-
const _log = require("../../../../log");
|
|
27
19
|
const _env = require("../../../../utils/env");
|
|
28
20
|
const _NetworkResponse = require("./messageHandlers/NetworkResponse");
|
|
29
|
-
function _interop_require_default(obj) {
|
|
30
|
-
return obj && obj.__esModule ? obj : {
|
|
31
|
-
default: obj
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
21
|
const debug = require('debug')('expo:metro:debugging:middleware');
|
|
35
|
-
function createDebugMiddleware(metroBundler) {
|
|
22
|
+
function createDebugMiddleware(metroBundler, reporter) {
|
|
36
23
|
// Load the React Native debugging tools from project
|
|
37
24
|
// TODO: check if this works with isolated modules
|
|
38
25
|
const { createDevMiddleware } = require('@react-native/dev-middleware');
|
|
@@ -42,8 +29,14 @@ function createDebugMiddleware(metroBundler) {
|
|
|
42
29
|
scheme: 'http',
|
|
43
30
|
hostType: 'localhost'
|
|
44
31
|
}),
|
|
45
|
-
logger: createLogger(
|
|
32
|
+
logger: createLogger(reporter),
|
|
46
33
|
unstable_customInspectorMessageHandler: (0, _createHandlersFactory.createHandlersFactory)(),
|
|
34
|
+
// TODO: Forward all events to the shared Metro log reporter. Do this when we have opinions on how all logs should be presented.
|
|
35
|
+
// unstable_eventReporter: {
|
|
36
|
+
// logEvent(event) {
|
|
37
|
+
// reporter.update(event);
|
|
38
|
+
// },
|
|
39
|
+
// },
|
|
47
40
|
unstable_experiments: {
|
|
48
41
|
// Enable the Network tab in React Native DevTools
|
|
49
42
|
enableNetworkInspector: true,
|
|
@@ -59,13 +52,20 @@ function createDebugMiddleware(metroBundler) {
|
|
|
59
52
|
debugWebsocketEndpoints: websocketEndpoints
|
|
60
53
|
};
|
|
61
54
|
}
|
|
62
|
-
function createLogger(
|
|
55
|
+
function createLogger(reporter) {
|
|
63
56
|
return {
|
|
64
|
-
info: (
|
|
65
|
-
warn: (
|
|
66
|
-
error: (
|
|
57
|
+
info: makeLogger(reporter, 'info'),
|
|
58
|
+
warn: makeLogger(reporter, 'warn'),
|
|
59
|
+
error: makeLogger(reporter, 'error')
|
|
67
60
|
};
|
|
68
61
|
}
|
|
62
|
+
function makeLogger(reporter, level) {
|
|
63
|
+
return (...data)=>reporter.update({
|
|
64
|
+
type: 'unstable_server_log',
|
|
65
|
+
level,
|
|
66
|
+
data
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
69
|
/**
|
|
70
70
|
* This adds a dedicated websocket connection that handles Network-related CDP events.
|
|
71
71
|
* It's a temporary solution until Fusebox either implements the Network CDP domain,
|