@expo/cli 0.13.2 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/bin/cli +30 -27
- package/build/bin/cli.map +1 -1
- package/build/src/api/getVersions.js.map +1 -1
- package/build/src/api/rest/cache/response.js.map +1 -1
- package/build/src/api/rest/client.js +2 -2
- package/build/src/api/rest/client.js.map +1 -1
- package/build/src/config/configAsync.js +1 -1
- package/build/src/config/configAsync.js.map +1 -1
- package/build/src/config/index.js +2 -2
- package/build/src/config/index.js.map +1 -1
- package/build/src/customize/generate.js +1 -1
- package/build/src/customize/generate.js.map +1 -1
- package/build/src/customize/typescript.js +6 -4
- package/build/src/customize/typescript.js.map +1 -1
- package/build/src/export/createMetadataJson.js +3 -2
- package/build/src/export/createMetadataJson.js.map +1 -1
- package/build/src/export/embed/exportEmbedAsync.js +44 -17
- package/build/src/export/embed/exportEmbedAsync.js.map +1 -1
- package/build/src/export/embed/index.js +4 -4
- package/build/src/export/embed/index.js.map +1 -1
- package/build/src/export/embed/resolveOptions.js +3 -3
- package/build/src/export/embed/resolveOptions.js.map +1 -1
- package/build/src/export/exportApp.js +74 -83
- package/build/src/export/exportApp.js.map +1 -1
- package/build/src/export/exportAssets.js +81 -21
- package/build/src/export/exportAssets.js.map +1 -1
- package/build/src/export/exportHermes.js +24 -14
- package/build/src/export/exportHermes.js.map +1 -1
- package/build/src/export/exportStaticAsync.js +109 -58
- package/build/src/export/exportStaticAsync.js.map +1 -1
- package/build/src/export/favicon.js +2 -2
- package/build/src/export/favicon.js.map +1 -1
- package/build/src/export/fork-bundleAsync.js +56 -23
- package/build/src/export/fork-bundleAsync.js.map +1 -1
- package/build/src/export/index.js +11 -9
- package/build/src/export/index.js.map +1 -1
- package/build/src/export/metroAssetLocalPath.js +101 -0
- package/build/src/export/metroAssetLocalPath.js.map +1 -0
- package/build/src/export/persistMetroAssets.js +94 -21
- package/build/src/export/persistMetroAssets.js.map +1 -1
- package/build/src/export/resolveOptions.js +1 -1
- package/build/src/export/resolveOptions.js.map +1 -1
- package/build/src/export/saveAssets.js +9 -48
- package/build/src/export/saveAssets.js.map +1 -1
- package/build/src/export/web/exportWebAsync.js +1 -1
- package/build/src/export/web/exportWebAsync.js.map +1 -1
- package/build/src/export/web/index.js +2 -2
- package/build/src/export/web/index.js.map +1 -1
- package/build/src/export/writeContents.js +6 -3
- package/build/src/export/writeContents.js.map +1 -1
- package/build/src/install/applyPlugins.js +52 -0
- package/build/src/install/applyPlugins.js.map +1 -0
- package/build/src/install/checkPackages.js +2 -2
- package/build/src/install/checkPackages.js.map +1 -1
- package/build/src/install/fixPackages.js +84 -0
- package/build/src/install/fixPackages.js.map +1 -0
- package/build/src/install/installAsync.js +32 -61
- package/build/src/install/installAsync.js.map +1 -1
- package/build/src/install/installExpoPackage.js +79 -0
- package/build/src/install/installExpoPackage.js.map +1 -0
- package/build/src/login/index.js +1 -1
- package/build/src/login/index.js.map +1 -1
- package/build/src/logout/index.js +1 -1
- package/build/src/logout/index.js.map +1 -1
- package/build/src/prebuild/clearNativeFolder.js +1 -1
- package/build/src/prebuild/clearNativeFolder.js.map +1 -1
- package/build/src/prebuild/configureProjectAsync.js +3 -3
- package/build/src/prebuild/configureProjectAsync.js.map +1 -1
- package/build/src/prebuild/copyTemplateFiles.js +21 -30
- package/build/src/prebuild/copyTemplateFiles.js.map +1 -1
- package/build/src/prebuild/index.js +3 -3
- package/build/src/prebuild/index.js.map +1 -1
- package/build/src/prebuild/prebuildAsync.js +39 -17
- package/build/src/prebuild/prebuildAsync.js.map +1 -1
- package/build/src/prebuild/resolveOptions.js +2 -2
- package/build/src/prebuild/resolveOptions.js.map +1 -1
- package/build/src/prebuild/updateFromTemplate.js +6 -6
- package/build/src/prebuild/updateFromTemplate.js.map +1 -1
- package/build/src/prebuild/updatePackageJson.js +49 -36
- package/build/src/prebuild/updatePackageJson.js.map +1 -1
- package/build/src/prebuild/validateTemplatePlatforms.js +2 -2
- package/build/src/prebuild/validateTemplatePlatforms.js.map +1 -1
- package/build/src/register/index.js +1 -1
- package/build/src/register/index.js.map +1 -1
- package/build/src/run/android/index.js +2 -2
- package/build/src/run/android/index.js.map +1 -1
- package/build/src/run/ios/appleDevice/AppleDevice.js +35 -2
- package/build/src/run/ios/appleDevice/AppleDevice.js.map +1 -1
- package/build/src/run/ios/index.js +2 -2
- package/build/src/run/ios/index.js.map +1 -1
- package/build/src/start/doctor/dependencies/getVersionedPackages.js +12 -4
- package/build/src/start/doctor/dependencies/getVersionedPackages.js.map +1 -1
- package/build/src/start/doctor/dependencies/validateDependenciesVersions.js +20 -3
- package/build/src/start/doctor/dependencies/validateDependenciesVersions.js.map +1 -1
- package/build/src/start/index.js +3 -3
- package/build/src/start/index.js.map +1 -1
- package/build/src/start/interface/interactiveActions.js +30 -11
- package/build/src/start/interface/interactiveActions.js.map +1 -1
- package/build/src/start/server/BundlerDevServer.js +14 -10
- package/build/src/start/server/BundlerDevServer.js.map +1 -1
- package/build/src/start/server/DevServerManager.js +6 -1
- package/build/src/start/server/DevServerManager.js.map +1 -1
- package/build/src/start/server/DevToolsPluginManager.js +63 -0
- package/build/src/start/server/DevToolsPluginManager.js.map +1 -0
- package/build/src/start/server/getStaticRenderFunctions.js +21 -20
- package/build/src/start/server/getStaticRenderFunctions.js.map +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js +67 -64
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/bundleApiRoutes.js +4 -19
- package/build/src/start/server/metro/bundleApiRoutes.js.map +1 -1
- package/build/src/start/server/metro/createExpoMetroResolver.js +187 -0
- package/build/src/start/server/metro/createExpoMetroResolver.js.map +1 -0
- package/build/src/start/server/metro/createJResolver.js +149 -0
- package/build/src/start/server/metro/createJResolver.js.map +1 -0
- package/build/src/start/server/metro/createServerRouteMiddleware.js +13 -1
- package/build/src/start/server/metro/createServerRouteMiddleware.js.map +1 -1
- package/build/src/start/server/metro/externals.js +25 -3
- package/build/src/start/server/metro/externals.js.map +1 -1
- package/build/src/start/server/metro/fetchRouterManifest.js.map +1 -1
- package/build/src/start/server/metro/formatFileCandidates.js +72 -0
- package/build/src/start/server/metro/formatFileCandidates.js.map +1 -0
- package/build/src/start/server/metro/inspector-proxy/device.js +3 -1
- package/build/src/start/server/metro/inspector-proxy/device.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerGetPossibleBreakpoints.js +3 -4
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerGetPossibleBreakpoints.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeRuntimeCallFunctionOn.js +24 -0
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeRuntimeCallFunctionOn.js.map +1 -0
- package/build/src/start/server/metro/inspector-proxy/handlers/utils.js +11 -0
- package/build/src/start/server/metro/inspector-proxy/handlers/utils.js.map +1 -0
- package/build/src/start/server/metro/inspector-proxy/index.js +10 -7
- package/build/src/start/server/metro/inspector-proxy/index.js.map +1 -1
- package/build/src/start/server/metro/instantiateMetro.js +37 -16
- package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
- package/build/src/start/server/metro/metroErrorInterface.js +3 -2
- package/build/src/start/server/metro/metroErrorInterface.js.map +1 -1
- package/build/src/start/server/metro/router.js +6 -3
- package/build/src/start/server/metro/router.js.map +1 -1
- package/build/src/start/server/metro/runServer-fork.js +19 -10
- package/build/src/start/server/metro/runServer-fork.js.map +1 -1
- package/build/src/start/server/metro/serializeHtml.js +43 -0
- package/build/src/start/server/metro/serializeHtml.js.map +1 -0
- package/build/src/start/server/metro/waitForMetroToObserveTypeScriptFile.js +1 -2
- package/build/src/start/server/metro/waitForMetroToObserveTypeScriptFile.js.map +1 -1
- package/build/src/start/server/metro/withMetroMultiPlatform.js +268 -191
- package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
- package/build/src/start/server/metro/withMetroResolvers.js +114 -40
- package/build/src/start/server/metro/withMetroResolvers.js.map +1 -1
- package/build/src/start/server/middleware/DevToolsPluginMiddleware.js +61 -0
- package/build/src/start/server/middleware/DevToolsPluginMiddleware.js.map +1 -0
- package/build/src/start/server/middleware/ExpoMiddleware.js +2 -2
- package/build/src/start/server/middleware/ExpoMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/ManifestMiddleware.js +45 -68
- package/build/src/start/server/middleware/ManifestMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/inspector/JsInspector.js +1 -1
- package/build/src/start/server/middleware/inspector/JsInspector.js.map +1 -1
- package/build/src/start/server/middleware/inspector/LaunchBrowser.js +30 -26
- package/build/src/start/server/middleware/inspector/LaunchBrowser.js.map +1 -1
- package/build/src/start/server/middleware/inspector/LaunchBrowser.types.js +7 -7
- package/build/src/start/server/middleware/inspector/LaunchBrowser.types.js.map +1 -1
- package/build/src/start/server/middleware/inspector/LaunchBrowserImplLinux.js +5 -2
- package/build/src/start/server/middleware/inspector/LaunchBrowserImplLinux.js.map +1 -1
- package/build/src/start/server/middleware/inspector/LaunchBrowserImplMacOS.js +3 -2
- package/build/src/start/server/middleware/inspector/LaunchBrowserImplMacOS.js.map +1 -1
- package/build/src/start/server/middleware/inspector/LaunchBrowserImplWindows.js +8 -7
- package/build/src/start/server/middleware/inspector/LaunchBrowserImplWindows.js.map +1 -1
- package/build/src/start/server/middleware/metroOptions.js +123 -0
- package/build/src/start/server/middleware/metroOptions.js.map +1 -0
- package/build/src/start/server/middleware/resolveAssets.js.map +1 -1
- package/build/src/start/server/type-generation/__typetests__/fixtures/basic.js.map +1 -1
- package/build/src/start/server/type-generation/expo-env.js +1 -1
- package/build/src/start/server/type-generation/expo-env.js.map +1 -1
- package/build/src/start/server/type-generation/routes.js +1 -0
- package/build/src/start/server/type-generation/routes.js.map +1 -1
- package/build/src/utils/analytics/getMetroDebugProperties.js +1 -2
- package/build/src/utils/analytics/getMetroDebugProperties.js.map +1 -1
- package/build/src/utils/analytics/getMetroProperties.js +1 -2
- package/build/src/utils/analytics/getMetroProperties.js.map +1 -1
- package/build/src/utils/analytics/rudderstackClient.js +2 -2
- package/build/src/utils/args.js +4 -2
- package/build/src/utils/args.js.map +1 -1
- package/build/src/utils/cocoapods.js +2 -1
- package/build/src/utils/cocoapods.js.map +1 -1
- package/build/src/utils/dir.js +18 -8
- package/build/src/utils/dir.js.map +1 -1
- package/build/src/utils/env.js +6 -0
- package/build/src/utils/env.js.map +1 -1
- package/build/src/utils/getOrPromptApplicationId.js +2 -4
- package/build/src/utils/getOrPromptApplicationId.js.map +1 -1
- package/build/src/utils/prompts.js +1 -28
- package/build/src/utils/prompts.js.map +1 -1
- package/build/src/whoami/index.js +1 -1
- package/build/src/whoami/index.js.map +1 -1
- package/package.json +16 -16
- package/static/shims/react-native-web/dist/cjs/exports/AppRegistry/AppContainer.js +13 -0
- package/static/shims/react-native-web/dist/cjs/exports/BackHandler/index.js +10 -0
- package/static/shims/react-native-web/dist/exports/AppRegistry/AppContainer.js +12 -0
- package/static/shims/react-native-web/dist/exports/BackHandler/index.js +7 -0
- package/build/src/export/createBundles.js +0 -37
- package/build/src/export/createBundles.js.map +0 -1
- package/build/src/start/server/metro/resolveFromProject.js +0 -90
- package/build/src/start/server/metro/resolveFromProject.js.map +0 -1
- package/build/src/start/server/middleware/resolveEntryPoint.js +0 -42
- package/build/src/start/server/middleware/resolveEntryPoint.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.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 chalk from 'chalk';\nimport fs from 'fs';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext } from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport {\n EXTERNAL_REQUIRE_NATIVE_POLYFILL,\n EXTERNAL_REQUIRE_POLYFILL,\n getNodeExternalModuleId,\n isNodeExternal,\n setupNodeExternals,\n} from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { importMetroResolverFromProject } from './resolveFromProject';\nimport { getAppRouterRelativeEntryPath } from './router';\nimport { withMetroResolvers } from './withMetroResolvers';\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { learnMore } from '../../../utils/link';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { WebSupportProjectPrerequisite } from '../../doctor/web/WebSupportProjectPrerequisite';\nimport { PlatformBundlers } from '../platformBundlers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(config: ConfigT, projectRoot: string): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform: string | null }): readonly string[] => {\n if (ctx.platform === 'web') {\n return [\n // NOTE: We might need this for all platforms\n path.join(projectRoot, EXTERNAL_REQUIRE_POLYFILL),\n // TODO: runtime polyfills, i.e. Fast Refresh, error overlay, React Dev Tools...\n ];\n }\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n\n return [...polyfills, EXTERNAL_REQUIRE_NATIVE_POLYFILL];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function getNodejsExtensions(srcExts: readonly string[]): string[] {\n const mjsExts = srcExts.filter((ext) => /mjs$/.test(ext));\n const nodejsSourceExtensions = srcExts.filter((ext) => !/mjs$/.test(ext));\n // find index of last `*.js` extension\n const jsIndex = nodejsSourceExtensions.reduce((index, ext, i) => {\n return /jsx?$/.test(ext) ? i : index;\n }, -1);\n\n // insert `*.mjs` extensions after `*.js` extensions\n nodejsSourceExtensions.splice(jsIndex + 1, 0, ...mjsExts);\n\n return nodejsSourceExtensions;\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n projectRoot,\n tsconfig,\n platforms,\n isTsconfigPathsEnabled,\n }: {\n projectRoot: string;\n tsconfig: TsConfigPaths | null;\n platforms: string[];\n isTsconfigPathsEnabled?: boolean;\n }\n) {\n // Get the `transformer.assetRegistryPath`\n // this needs to be unified since you can't dynamically\n // swap out the transformer based on platform.\n const assetRegistryPath = fs.realpathSync(\n // This is the native asset registry alias for native.\n path.resolve(resolveFrom(projectRoot, 'react-native/Libraries/Image/AssetRegistry'))\n // NOTE(EvanBacon): This is the newer import but it doesn't work in the expo/expo monorepo.\n // path.resolve(resolveFrom(projectRoot, '@react-native/assets/registry.js'))\n );\n\n let reactNativeWebAppContainer: string | null = null;\n try {\n reactNativeWebAppContainer = fs.realpathSync(\n // This is the native asset registry alias for native.\n path.resolve(resolveFrom(projectRoot, 'expo-router/build/fork/react-native-web-container'))\n // NOTE(EvanBacon): This is the newer import but it doesn't work in the expo/expo monorepo.\n // path.resolve(resolveFrom(projectRoot, '@react-native/assets/registry.js'))\n );\n } catch {}\n\n const isWebEnabled = platforms.includes('web');\n\n const { resolve } = importMetroResolverFromProject(projectRoot);\n\n const extraNodeModules: { [key: string]: Record<string, string> } = {};\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n 'react-native/index': 'react-native-web',\n },\n };\n\n if (isWebEnabled) {\n // Allow `react-native-web` to be optional when web is not enabled but path aliases is.\n extraNodeModules['web'] = {\n 'react-native': path.resolve(require.resolve('react-native-web/package.json'), '..'),\n };\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve = tsconfig?.paths\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl,\n })\n : null;\n\n if (isTsconfigPathsEnabled && isInteractive()) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(projectRoot, ['./tsconfig.json', './jsconfig.json']);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n\n let nodejsSourceExtensions: string[] | null = null;\n\n return withMetroResolvers(config, projectRoot, [\n // Add a resolver to alias the web asset resolver.\n (immutableContext: ResolutionContext, moduleName: string, platform: string | null) => {\n let context = {\n ...immutableContext,\n } as Mutable<ResolutionContext> & {\n mainFields: string[];\n customResolverOptions?: Record<string, string>;\n };\n\n const environment = context.customResolverOptions?.environment;\n const isNode = environment === 'node';\n\n // TODO: We need to prevent the require.context from including API routes as these use externals.\n // Should be fine after async routes lands.\n if (isNode) {\n const moduleId = isNodeExternal(moduleName);\n if (moduleId) {\n moduleName = getNodeExternalModuleId(context.originModulePath, moduleId);\n debug(`Redirecting Node.js external \"${moduleId}\" to \"${moduleName}\"`);\n }\n\n // Adjust nodejs source extensions to sort mjs after js, including platform variants.\n if (nodejsSourceExtensions === null) {\n nodejsSourceExtensions = getNodejsExtensions(context.sourceExts);\n }\n context.sourceExts = nodejsSourceExtensions;\n }\n\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n moduleName = aliases[platform][moduleName];\n }\n\n // TODO: We may be able to remove this in the future, it's doing no harm\n // by staying here.\n // Conditionally remap `react-native` to `react-native-web`\n if (platform && platform in extraNodeModules) {\n context.extraNodeModules = {\n ...extraNodeModules[platform],\n ...context.extraNodeModules,\n };\n }\n\n if (tsconfig?.baseUrl && isTsconfigPathsEnabled) {\n context = {\n ...context,\n nodeModulesPaths: [\n ...immutableContext.nodeModulesPaths,\n // add last to ensure node modules are resolved first\n tsconfig.baseUrl,\n ],\n };\n }\n\n let mainFields: string[] = context.mainFields;\n\n if (isNode) {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n mainFields = ['main', 'module'];\n } else if (env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE) {\n mainFields = context.mainFields;\n } else if (platform && platform in preferredMainFields) {\n mainFields = preferredMainFields[platform];\n }\n function doResolve(moduleName: string): Resolution | null {\n return resolve(\n {\n ...context,\n resolveRequest: undefined,\n mainFields,\n\n // Passing `mainFields` directly won't be considered (in certain version of Metro)\n // we need to extend the `getPackageMainPath` directly to\n // use platform specific `mainFields`.\n // @ts-ignore\n getPackageMainPath(packageJsonPath) {\n // @ts-expect-error: mainFields is not on type\n const package_ = context.moduleCache.getPackage(packageJsonPath);\n return package_.getMain(mainFields);\n },\n },\n moduleName,\n platform\n );\n }\n\n function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n }\n\n let result: Resolution | null = null;\n\n // React Native uses `event-target-shim` incorrectly and this causes the native runtime\n // to fail to load. This is a temporary workaround until we can fix this upstream.\n // https://github.com/facebook/react-native/pull/38628\n if (\n moduleName.includes('event-target-shim') &&\n context.originModulePath.includes(path.sep + 'react-native' + path.sep)\n ) {\n context.sourceExts = context.sourceExts.filter((f) => !f.includes('mjs'));\n debug('Skip mjs support for event-target-shim in:', context.originModulePath);\n }\n\n if (tsConfigResolve) {\n result = tsConfigResolve(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n optionalResolve\n );\n }\n\n if (\n // is web\n platform === 'web' &&\n // Not server runtime\n !isNode &&\n // Is Node.js built-in\n isNodeExternal(moduleName)\n ) {\n // Perform optional resolve first. If the module doesn't exist (no module in the node_modules)\n // then we can mock the file to use an empty module.\n result ??= optionalResolve(moduleName);\n\n if (!result) {\n // In this case, mock the file to use an empty module.\n return {\n type: 'empty',\n };\n }\n }\n\n result ??= doResolve(moduleName);\n\n if (result) {\n // Replace the web resolver with the original one.\n // This is basically an alias for web-only.\n if (shouldAliasAssetRegistryForWeb(platform, result)) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = assetRegistryPath;\n }\n\n // React Native Web adds a couple extra divs for no reason, these\n // make static rendering much harder as we expect the root element to be `<html>`.\n // This resolution will alias to a simple in-out component to avoid React Native web.\n if (\n // Only apply the transform if expo-router is present.\n reactNativeWebAppContainer &&\n shouldAliasModule(\n {\n platform,\n result,\n },\n {\n platform: 'web',\n output: 'react-native-web/dist/exports/AppRegistry/AppContainer.js',\n }\n )\n ) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = reactNativeWebAppContainer;\n }\n }\n return result;\n },\n ]);\n}\n\n/** @returns `true` if the incoming resolution should be swapped on web. */\nexport function shouldAliasAssetRegistryForWeb(\n platform: string | null,\n result: Resolution\n): boolean {\n return (\n platform === 'web' &&\n result?.type === 'sourceFile' &&\n typeof result?.filePath === 'string' &&\n normalizeSlashes(result.filePath).endsWith(\n 'react-native-web/dist/modules/AssetRegistry/index.js'\n )\n );\n}\n/** @returns `true` if the incoming resolution should be swapped. */\nexport function shouldAliasModule(\n input: {\n platform: string | null;\n result: Resolution;\n },\n alias: { platform: string; output: string }\n): boolean {\n return (\n input.platform === alias.platform &&\n input.result?.type === 'sourceFile' &&\n typeof input.result?.filePath === 'string' &&\n normalizeSlashes(input.result.filePath).endsWith(alias.output)\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n webOutput,\n routerDirectory,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n webOutput?: 'single' | 'static' | 'server';\n routerDirectory: string;\n }\n) {\n // Auto pick app entry for router.\n process.env.EXPO_ROUTER_APP_ROOT = getAppRouterRelativeEntryPath(projectRoot, routerDirectory);\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n if (['static', 'server'].includes(webOutput ?? '')) {\n // Enable static rendering in runtime space.\n process.env.EXPO_PUBLIC_USE_STATIC = '1';\n }\n\n // Ensure the cache is invalidated if these values change.\n // @ts-expect-error\n config.transformer._expoRouterRootDirectory = process.env.EXPO_ROUTER_APP_ROOT;\n // @ts-expect-error\n config.transformer._expoRouterWebRendering = webOutput;\n // TODO: import mode\n\n if (platformBundlers.web === 'metro') {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n }\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n Log.warn(\n chalk.yellow`Experimental path aliases feature is enabled. ` +\n learnMore('https://docs.expo.dev/guides/typescript/#path-aliases')\n );\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n await setupNodeExternals(projectRoot);\n\n return withMetroMultiPlatform(projectRoot, {\n config,\n platformBundlers,\n tsconfig,\n isTsconfigPathsEnabled,\n });\n}\n\nfunction withMetroMultiPlatform(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n tsconfig,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n tsconfig: TsConfigPaths | null;\n }\n) {\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(([, bundler]) => bundler === 'metro')\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n if (expoConfigPlatforms.includes('web')) {\n config = withWebPolyfills(config, projectRoot);\n }\n\n return withExtendedResolver(config, {\n projectRoot,\n tsconfig,\n isTsconfigPathsEnabled,\n platforms: expoConfigPlatforms,\n });\n}\n"],"names":["getNodejsExtensions","withExtendedResolver","shouldAliasAssetRegistryForWeb","shouldAliasModule","withMetroMultiPlatformAsync","debug","require","withWebPolyfills","config","projectRoot","originalGetPolyfills","serializer","getPolyfills","bind","ctx","platform","path","join","EXTERNAL_REQUIRE_POLYFILL","polyfills","EXTERNAL_REQUIRE_NATIVE_POLYFILL","normalizeSlashes","p","replace","srcExts","mjsExts","filter","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","platforms","isTsconfigPathsEnabled","assetRegistryPath","fs","realpathSync","resolve","resolveFrom","reactNativeWebAppContainer","isWebEnabled","includes","importMetroResolverFromProject","extraNodeModules","aliases","web","preferredMainFields","tsConfigResolve","paths","resolveWithTsConfigPaths","baseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","withMetroResolvers","immutableContext","moduleName","context","environment","customResolverOptions","isNode","moduleId","isNodeExternal","getNodeExternalModuleId","originModulePath","sourceExts","nodeModulesPaths","mainFields","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","doResolve","resolveRequest","undefined","getPackageMainPath","packageJsonPath","package_","moduleCache","getPackage","getMain","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","result","sep","f","type","filePath","output","endsWith","input","alias","platformBundlers","webOutput","routerDirectory","process","EXPO_ROUTER_APP_ROOT","getAppRouterRelativeEntryPath","EXPO_PUBLIC_PROJECT_ROOT","EXPO_PUBLIC_USE_STATIC","transformer","_expoRouterRootDirectory","_expoRouterWebRendering","WebSupportProjectPrerequisite","assertAsync","Log","warn","chalk","yellow","learnMore","setupNodeExternals","withMetroMultiPlatform","expoConfigPlatforms","entries","bundler","map","Array","isArray","resolver","Set","concat"],"mappings":"AAMA;;;;QAiEgBA,mBAAmB,GAAnBA,mBAAmB;QAqBnBC,oBAAoB,GAApBA,oBAAoB;QA2RpBC,8BAA8B,GAA9BA,8BAA8B;QAc9BC,iBAAiB,GAAjBA,iBAAiB;QAgBXC,2BAA2B,GAA3BA,2BAA2B;AA/Y/B,IAAA,MAAO,kCAAP,OAAO,EAAA;AACV,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAGF,IAAA,KAAM,kCAAN,MAAM,EAAA;AACC,IAAA,YAAc,kCAAd,cAAc,EAAA;AAQ/B,IAAA,UAAa,WAAb,aAAa,CAAA;AACmD,IAAA,YAAe,WAAf,eAAe,CAAA;AACvC,IAAA,mBAAsB,WAAtB,sBAAsB,CAAA;AACvB,IAAA,OAAU,WAAV,UAAU,CAAA;AACrB,IAAA,mBAAsB,WAAtB,sBAAsB,CAA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AA,CAAC,CAC5CC,GAAG,CAAC,CAAC,CAAClH,QAAQ,CAAC,GAAKA,QAAQ;IAAA,CAAC,AAAC;IAEjC,IAAImH,KAAK,CAACC,OAAO,CAAC3H,MAAM,CAAC4H,QAAQ,CAAChG,SAAS,CAAC,EAAE;QAC5C0F,mBAAmB,GAAG;eAAI,IAAIO,GAAG,CAACP,mBAAmB,CAACQ,MAAM,CAAC9H,MAAM,CAAC4H,QAAQ,CAAChG,SAAS,CAAC,CAAC;SAAC,CAAC;KAC3F;IAED,yCAAyC;IACzC5B,MAAM,CAAC4H,QAAQ,CAAChG,SAAS,GAAG0F,mBAAmB,CAAC;IAEhD,IAAIA,mBAAmB,CAACjF,QAAQ,CAAC,KAAK,CAAC,EAAE;QACvCrC,MAAM,GAAGD,gBAAgB,CAACC,MAAM,EAAEC,WAAW,CAAC,CAAC;KAChD;IAED,OAAOR,oBAAoB,CAACO,MAAM,EAAE;QAClCC,WAAW;QACX0B,QAAQ;QACRE,sBAAsB;QACtBD,SAAS,EAAE0F,mBAAmB;KAC/B,CAAC,CAAC;CACJ"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport fs from 'fs';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext, CustomResolutionContext } from 'metro-resolver';\nimport * as metroResolver from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { createFastResolver } from './createExpoMetroResolver';\nimport {\n EXTERNAL_REQUIRE_NATIVE_POLYFILL,\n EXTERNAL_REQUIRE_POLYFILL,\n METRO_SHIMS_FOLDER,\n getNodeExternalModuleId,\n isNodeExternal,\n setupNodeExternals,\n setupShimFiles,\n} from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { getAppRouterRelativeEntryPath } from './router';\nimport {\n withMetroErrorReportingResolver,\n withMetroMutatedResolverContext,\n withMetroResolvers,\n} from './withMetroResolvers';\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { WebSupportProjectPrerequisite } from '../../doctor/web/WebSupportProjectPrerequisite';\nimport { PlatformBundlers } from '../platformBundlers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(config: ConfigT): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform: string | null }): readonly string[] => {\n if (ctx.platform === 'web') {\n return [\n // NOTE: We might need this for all platforms\n path.join(config.projectRoot, EXTERNAL_REQUIRE_POLYFILL),\n // TODO: runtime polyfills, i.e. Fast Refresh, error overlay, React Dev Tools...\n ];\n }\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n\n return [...polyfills, path.join(config.projectRoot, EXTERNAL_REQUIRE_NATIVE_POLYFILL)];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function getNodejsExtensions(srcExts: readonly string[]): string[] {\n const mjsExts = srcExts.filter((ext) => /mjs$/.test(ext));\n const nodejsSourceExtensions = srcExts.filter((ext) => !/mjs$/.test(ext));\n // find index of last `*.js` extension\n const jsIndex = nodejsSourceExtensions.reduce((index, ext, i) => {\n return /jsx?$/.test(ext) ? i : index;\n }, -1);\n\n // insert `*.mjs` extensions after `*.js` extensions\n nodejsSourceExtensions.splice(jsIndex + 1, 0, ...mjsExts);\n\n return nodejsSourceExtensions;\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n tsconfig,\n platforms,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n }: {\n tsconfig: TsConfigPaths | null;\n platforms: string[];\n isTsconfigPathsEnabled?: boolean;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n }\n) {\n if (isFastResolverEnabled) {\n Log.warn(`Experimental bundling features are enabled.`);\n }\n\n // Get the `transformer.assetRegistryPath`\n // this needs to be unified since you can't dynamically\n // swap out the transformer based on platform.\n const assetRegistryPath = fs.realpathSync(\n path.resolve(resolveFrom(config.projectRoot, '@react-native/assets-registry/registry.js'))\n );\n\n const defaultResolver = metroResolver.resolve;\n const resolver = isFastResolverEnabled\n ? createFastResolver({\n preserveSymlinks: config.resolver?.unstable_enableSymlinks ?? false,\n blockList: Array.isArray(config.resolver?.blockList)\n ? config.resolver?.blockList\n : [config.resolver?.blockList],\n })\n : defaultResolver;\n\n const extraNodeModules: { [key: string]: Record<string, string> } = {};\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n 'react-native/index': 'react-native-web',\n },\n };\n\n // TODO: We can probably drop this resolution hack.\n const isWebEnabled = platforms.includes('web');\n if (isWebEnabled) {\n // Allow `react-native-web` to be optional when web is not enabled but path aliases is.\n extraNodeModules['web'] = {\n 'react-native': path.resolve(require.resolve('react-native-web/package.json'), '..'),\n };\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve = tsconfig?.paths\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl,\n })\n : null;\n\n // TODO: Move this to be a transform key for invalidation.\n if (!isExporting && isInteractive()) {\n if (isTsconfigPathsEnabled) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(config.projectRoot, [\n './tsconfig.json',\n './jsconfig.json',\n ]);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(config.projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n }\n\n let nodejsSourceExtensions: string[] | null = null;\n\n const shimsFolder = path.join(config.projectRoot, METRO_SHIMS_FOLDER);\n\n function getStrictResolver(\n { resolveRequest, ...context }: ResolutionContext,\n platform: string | null\n ) {\n return function doResolve(moduleName: string): Resolution {\n return resolver(context, moduleName, platform);\n };\n }\n\n function getOptionalResolver(context: ResolutionContext, platform: string | null) {\n const doResolve = getStrictResolver(context, platform);\n return function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n };\n }\n\n const metroConfigWithCustomResolver = withMetroResolvers(config, [\n // tsconfig paths\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n return (\n tsConfigResolve?.(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n getOptionalResolver(context, platform)\n ) ?? null\n );\n },\n\n // Node.js built-ins get empty externals on web\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n if (\n isFastResolverEnabled ||\n // is web\n platform !== 'web' ||\n // Skip when targeting server runtimes\n context.customResolverOptions?.environment === 'node' ||\n // This transform only applies to Node.js built-ins\n !isNodeExternal(moduleName)\n ) {\n return null;\n }\n\n // Perform optional resolve first. If the module doesn't exist (no module in the node_modules)\n // then we can mock the file to use an empty module.\n const result = getOptionalResolver(context, platform)(moduleName);\n return (\n result ?? {\n // In this case, mock the file to use an empty module.\n type: 'empty',\n }\n );\n },\n\n // Node.js externals support\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n if (\n // is web\n platform !== 'web' ||\n // Only apply to server runtimes\n context.customResolverOptions?.environment !== 'node'\n ) {\n return null;\n }\n\n const moduleId = isNodeExternal(moduleName);\n if (!moduleId) {\n return null;\n }\n const redirectedModuleName = getNodeExternalModuleId(context.originModulePath, moduleId);\n debug(`Redirecting Node.js external \"${moduleId}\" to \"${redirectedModuleName}\"`);\n const doResolve = getStrictResolver(context, platform);\n return doResolve(redirectedModuleName);\n },\n\n // Basic moduleId aliases\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n const redirectedModuleName = aliases[platform][moduleName];\n const doResolve = getStrictResolver(context, platform);\n return doResolve(redirectedModuleName);\n }\n\n return null;\n },\n\n // HACK(EvanBacon):\n // React Native uses `event-target-shim` incorrectly and this causes the native runtime\n // to fail to load. This is a temporary workaround until we can fix this upstream.\n // https://github.com/facebook/react-native/pull/38628\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n if (platform !== 'web' && moduleName === 'event-target-shim') {\n debug('For event-target-shim to use js:', context.originModulePath);\n const doResolve = getStrictResolver(context, platform);\n return doResolve('event-target-shim/dist/event-target-shim.js');\n }\n\n return null;\n },\n\n // TODO: Reduce these as much as possible in the future.\n // Complex post-resolution rewrites.\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n const doResolve = getStrictResolver(context, platform);\n\n const result = doResolve(moduleName);\n\n if (result.type !== 'sourceFile') {\n return result;\n }\n\n // Replace the web resolver with the original one.\n // This is basically an alias for web-only.\n // TODO: Drop this in favor of the standalone asset registry module.\n if (shouldAliasAssetRegistryForWeb(platform, result)) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = assetRegistryPath;\n }\n\n if (platform === 'web' && result.filePath.includes('node_modules')) {\n // Replace with static shims\n\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const shimPath = path.join(shimsFolder, normalName);\n if (fs.existsSync(shimPath)) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = shimPath;\n }\n }\n\n return result;\n },\n ]);\n\n // Ensure we mutate the resolution context to include the custom resolver options for server and web.\n const metroConfigWithCustomContext = withMetroMutatedResolverContext(\n metroConfigWithCustomResolver,\n (\n immutableContext: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ): CustomResolutionContext => {\n const context = {\n ...immutableContext,\n } as Mutable<ResolutionContext> & {\n mainFields: string[];\n customResolverOptions?: Record<string, string>;\n };\n\n if (context.customResolverOptions?.environment === 'node') {\n // Adjust nodejs source extensions to sort mjs after js, including platform variants.\n if (nodejsSourceExtensions === null) {\n nodejsSourceExtensions = getNodejsExtensions(context.sourceExts);\n }\n context.sourceExts = nodejsSourceExtensions;\n\n context.unstable_enablePackageExports = true;\n context.unstable_conditionNames = ['node', 'require'];\n context.unstable_conditionsByPlatform = {};\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['main', 'module'];\n } else {\n // Non-server changes\n\n if (!env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE && platform && platform in preferredMainFields) {\n context.mainFields = preferredMainFields[platform];\n }\n }\n\n // TODO: We may be able to remove this in the future, it's doing no harm\n // by staying here.\n // Conditionally remap `react-native` to `react-native-web`\n if (platform && platform in extraNodeModules) {\n context.extraNodeModules = {\n ...extraNodeModules[platform],\n ...context.extraNodeModules,\n };\n }\n\n if (tsconfig?.baseUrl && isTsconfigPathsEnabled) {\n const nodeModulesPaths: string[] = [...immutableContext.nodeModulesPaths];\n\n if (isFastResolverEnabled) {\n // add last to ensure node modules are resolved first\n nodeModulesPaths.push(\n path.isAbsolute(tsconfig.baseUrl)\n ? tsconfig.baseUrl\n : path.join(config.projectRoot, tsconfig.baseUrl)\n );\n } else {\n // add last to ensure node modules are resolved first\n nodeModulesPaths.push(tsconfig.baseUrl);\n }\n\n context.nodeModulesPaths = nodeModulesPaths;\n }\n\n // TODO: We can drop this in the next version upgrade (SDK 50).\n const mainFields: string[] = context.mainFields;\n\n return {\n ...context,\n preferNativePlatform: platform !== 'web',\n // Passing `mainFields` directly won't be considered (in certain version of Metro)\n // we need to extend the `getPackageMainPath` directly to\n // use platform specific `mainFields`.\n // @ts-ignore\n getPackageMainPath(packageJsonPath) {\n // @ts-expect-error: mainFields is not on type\n const package_ = context.moduleCache.getPackage(packageJsonPath);\n return package_.getMain(mainFields);\n },\n };\n }\n );\n\n return withMetroErrorReportingResolver(metroConfigWithCustomContext);\n}\n\n/** @returns `true` if the incoming resolution should be swapped on web. */\nexport function shouldAliasAssetRegistryForWeb(\n platform: string | null,\n result: Resolution\n): boolean {\n return (\n platform === 'web' &&\n result?.type === 'sourceFile' &&\n typeof result?.filePath === 'string' &&\n normalizeSlashes(result.filePath).endsWith(\n 'react-native-web/dist/modules/AssetRegistry/index.js'\n )\n );\n}\n/** @returns `true` if the incoming resolution should be swapped. */\nexport function shouldAliasModule(\n input: {\n platform: string | null;\n result: Resolution;\n },\n alias: { platform: string; output: string }\n): boolean {\n return (\n input.platform === alias.platform &&\n input.result?.type === 'sourceFile' &&\n typeof input.result?.filePath === 'string' &&\n normalizeSlashes(input.result.filePath).endsWith(alias.output)\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n webOutput,\n routerDirectory,\n isFastResolverEnabled,\n isExporting,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n webOutput?: 'single' | 'static' | 'server';\n routerDirectory: string;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n }\n) {\n if (!config.projectRoot) {\n // @ts-expect-error: read-only types\n config.projectRoot = projectRoot;\n }\n // Auto pick app entry for router.\n process.env.EXPO_ROUTER_APP_ROOT = getAppRouterRelativeEntryPath(projectRoot, routerDirectory);\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n if (['static', 'server'].includes(webOutput ?? '')) {\n // Enable static rendering in runtime space.\n process.env.EXPO_PUBLIC_USE_STATIC = '1';\n }\n\n // This is used for running Expo CLI in development against projects outside the monorepo.\n if (!isDirectoryIn(__dirname, projectRoot)) {\n if (!config.watchFolders) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders = [];\n }\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('metro-runtime/package.json'), '../..'));\n }\n\n // Ensure the cache is invalidated if these values change.\n // @ts-expect-error\n config.transformer._expoRouterRootDirectory = process.env.EXPO_ROUTER_APP_ROOT;\n // @ts-expect-error\n config.transformer._expoRouterWebRendering = webOutput;\n // TODO: import mode\n\n if (platformBundlers.web === 'metro') {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n }\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n await setupShimFiles(projectRoot);\n await setupNodeExternals(projectRoot);\n\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(([, bundler]) => bundler === 'metro')\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n config = withWebPolyfills(config);\n\n return withExtendedResolver(config, {\n tsconfig,\n isExporting,\n isTsconfigPathsEnabled,\n platforms: expoConfigPlatforms,\n isFastResolverEnabled,\n });\n}\n\nfunction isDirectoryIn(a: string, b: string) {\n return b.startsWith(a) && b.length > a.length;\n}\n"],"names":["getNodejsExtensions","withExtendedResolver","shouldAliasAssetRegistryForWeb","shouldAliasModule","withMetroMultiPlatformAsync","metroResolver","debug","require","withWebPolyfills","config","originalGetPolyfills","serializer","getPolyfills","bind","ctx","platform","path","join","projectRoot","EXTERNAL_REQUIRE_POLYFILL","polyfills","EXTERNAL_REQUIRE_NATIVE_POLYFILL","normalizeSlashes","p","replace","srcExts","mjsExts","filter","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","platforms","isTsconfigPathsEnabled","isFastResolverEnabled","isExporting","Log","warn","assetRegistryPath","fs","realpathSync","resolve","resolveFrom","defaultResolver","resolver","createFastResolver","preserveSymlinks","unstable_enableSymlinks","blockList","Array","isArray","extraNodeModules","aliases","web","isWebEnabled","includes","preferredMainFields","tsConfigResolve","paths","resolveWithTsConfigPaths","baseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","shimsFolder","METRO_SHIMS_FOLDER","getStrictResolver","resolveRequest","context","doResolve","moduleName","getOptionalResolver","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","metroConfigWithCustomResolver","withMetroResolvers","originModulePath","customResolverOptions","environment","isNodeExternal","result","type","moduleId","redirectedModuleName","getNodeExternalModuleId","filePath","normalName","shimPath","existsSync","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","sourceExts","unstable_enablePackageExports","unstable_conditionNames","unstable_conditionsByPlatform","mainFields","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","nodeModulesPaths","push","isAbsolute","preferNativePlatform","getPackageMainPath","packageJsonPath","package_","moduleCache","getPackage","getMain","withMetroErrorReportingResolver","endsWith","input","alias","output","platformBundlers","webOutput","routerDirectory","process","EXPO_ROUTER_APP_ROOT","getAppRouterRelativeEntryPath","EXPO_PUBLIC_PROJECT_ROOT","EXPO_PUBLIC_USE_STATIC","isDirectoryIn","__dirname","watchFolders","transformer","_expoRouterRootDirectory","_expoRouterWebRendering","WebSupportProjectPrerequisite","assertAsync","setupShimFiles","setupNodeExternals","expoConfigPlatforms","entries","bundler","map","Set","concat","a","b","startsWith"],"mappings":"AAMA;;;;QAsEgBA,mBAAmB,GAAnBA,mBAAmB;QAqBnBC,oBAAoB,GAApBA,oBAAoB;QA0VpBC,8BAA8B,GAA9BA,8BAA8B;QAc9BC,iBAAiB,GAAjBA,iBAAiB;QAgBXC,2BAA2B,GAA3BA,2BAA2B;AAndlC,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAGPC,IAAAA,aAAa,mCAAM,gBAAgB,EAAtB;AACR,IAAA,KAAM,kCAAN,MAAM,EAAA;AACC,IAAA,YAAc,kCAAd,cAAc,EAAA;AAEH,IAAA,wBAA2B,WAA3B,2BAA2B,CAAA;AASvD,IAAA,UAAa,WAAb,aAAa,CAAA;AACmD,IAAA,YAAe,WAAf,eAAe,CAAA;AACxC,IAAA,OAAU,WAAV,UAAU,CAAA;AAKjD,IAAA,mBAAsB,WAAtB,sBAA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;IAEhD5I,MAAM,GAAGD,gBAAgB,CAACC,MAAM,CAAC,CAAC;IAElC,OAAOR,oBAAoB,CAACQ,MAAM,EAAE;QAClC2B,QAAQ;QACRI,WAAW;QACXF,sBAAsB;QACtBD,SAAS,EAAEgH,mBAAmB;QAC9B9G,qBAAqB;KACtB,CAAC,CAAC;CACJ;AAED,SAASoG,aAAa,CAACgB,CAAS,EAAEC,CAAS,EAAE;IAC3C,OAAOA,CAAC,CAACC,UAAU,CAACF,CAAC,CAAC,IAAIC,CAAC,CAACjF,MAAM,GAAGgF,CAAC,CAAChF,MAAM,CAAC;CAC/C"}
|
|
@@ -4,21 +4,43 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
4
4
|
});
|
|
5
5
|
exports.getDefaultMetroResolver = getDefaultMetroResolver;
|
|
6
6
|
exports.withMetroResolvers = withMetroResolvers;
|
|
7
|
+
exports.withMetroMutatedResolverContext = withMetroMutatedResolverContext;
|
|
8
|
+
exports.withMetroErrorReportingResolver = withMetroErrorReportingResolver;
|
|
7
9
|
var _chalk = _interopRequireDefault(require("chalk"));
|
|
10
|
+
var metroResolver = _interopRequireWildcard(require("metro-resolver"));
|
|
8
11
|
var _path = _interopRequireDefault(require("path"));
|
|
9
12
|
var _metroErrors = require("./metroErrors");
|
|
10
|
-
var _resolveFromProject = require("./resolveFromProject");
|
|
11
13
|
var _env = require("../../../utils/env");
|
|
12
14
|
function _interopRequireDefault(obj) {
|
|
13
15
|
return obj && obj.__esModule ? obj : {
|
|
14
16
|
default: obj
|
|
15
17
|
};
|
|
16
18
|
}
|
|
19
|
+
function _interopRequireWildcard(obj) {
|
|
20
|
+
if (obj && obj.__esModule) {
|
|
21
|
+
return obj;
|
|
22
|
+
} else {
|
|
23
|
+
var newObj = {};
|
|
24
|
+
if (obj != null) {
|
|
25
|
+
for(var key in obj){
|
|
26
|
+
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
27
|
+
var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
|
|
28
|
+
if (desc.get || desc.set) {
|
|
29
|
+
Object.defineProperty(newObj, key, desc);
|
|
30
|
+
} else {
|
|
31
|
+
newObj[key] = obj[key];
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
newObj.default = obj;
|
|
37
|
+
return newObj;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
17
40
|
const debug = require("debug")("expo:metro:withMetroResolvers");
|
|
18
41
|
function getDefaultMetroResolver(projectRoot) {
|
|
19
|
-
const { resolve } = (0, _resolveFromProject).importMetroResolverFromProject(projectRoot);
|
|
20
42
|
return (context, moduleName, platform)=>{
|
|
21
|
-
return resolve(context, moduleName, platform);
|
|
43
|
+
return metroResolver.resolve(context, moduleName, platform);
|
|
22
44
|
};
|
|
23
45
|
}
|
|
24
46
|
function optionsKeyForContext(context) {
|
|
@@ -27,13 +49,82 @@ function optionsKeyForContext(context) {
|
|
|
27
49
|
// Compound key for the resolver cache
|
|
28
50
|
return (ref = JSON.stringify((_customResolverOptions = context.customResolverOptions) != null ? _customResolverOptions : {}, canonicalize)) != null ? ref : "";
|
|
29
51
|
}
|
|
30
|
-
function withMetroResolvers(config,
|
|
31
|
-
var
|
|
32
|
-
debug(`Appending ${resolvers.length} custom resolvers to Metro config. (has custom resolver: ${!!((
|
|
33
|
-
const
|
|
52
|
+
function withMetroResolvers(config, resolvers) {
|
|
53
|
+
var ref, ref1;
|
|
54
|
+
debug(`Appending ${resolvers.length} custom resolvers to Metro config. (has custom resolver: ${!!((ref = config.resolver) == null ? void 0 : ref.resolveRequest)})`);
|
|
55
|
+
// const hasUserDefinedResolver = !!config.resolver?.resolveRequest;
|
|
56
|
+
// const defaultResolveRequest = getDefaultMetroResolver(projectRoot);
|
|
57
|
+
const originalResolveRequest = (ref1 = config.resolver) == null ? void 0 : ref1.resolveRequest;
|
|
58
|
+
return {
|
|
59
|
+
...config,
|
|
60
|
+
resolver: {
|
|
61
|
+
...config.resolver,
|
|
62
|
+
resolveRequest (context, moduleName1, platform1) {
|
|
63
|
+
const upstreamResolveRequest = context.resolveRequest;
|
|
64
|
+
const universalContext = {
|
|
65
|
+
...context,
|
|
66
|
+
resolveRequest (ctx, moduleName, platform) {
|
|
67
|
+
for (const resolver of resolvers){
|
|
68
|
+
try {
|
|
69
|
+
const res = resolver(ctx, moduleName, platform);
|
|
70
|
+
if (res) {
|
|
71
|
+
return res;
|
|
72
|
+
}
|
|
73
|
+
} catch (error) {
|
|
74
|
+
// If the error is directly related to a resolver not being able to resolve a module, then
|
|
75
|
+
// we can ignore the error and try the next resolver. Otherwise, we should throw the error.
|
|
76
|
+
const isResolutionError = (0, _metroErrors).isFailedToResolveNameError(error) || (0, _metroErrors).isFailedToResolvePathError(error);
|
|
77
|
+
if (!isResolutionError) {
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
debug(`Custom resolver threw: ${error.constructor.name}. (module: ${moduleName}, platform: ${platform})`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
// If we haven't returned by now, use the original resolver or upstream resolver.
|
|
84
|
+
return upstreamResolveRequest(ctx, moduleName, platform);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
// If the user defined a resolver, run it first and depend on the documented
|
|
88
|
+
// chaining logic: https://facebook.github.io/metro/docs/resolution/#resolution-algorithm
|
|
89
|
+
//
|
|
90
|
+
// config.resolver.resolveRequest = (context, moduleName, platform) => {
|
|
91
|
+
//
|
|
92
|
+
// // Do work...
|
|
93
|
+
//
|
|
94
|
+
// return context.resolveRequest(context, moduleName, platform);
|
|
95
|
+
// };
|
|
96
|
+
const firstResolver = originalResolveRequest != null ? originalResolveRequest : universalContext.resolveRequest;
|
|
97
|
+
return firstResolver(universalContext, moduleName1, platform1);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function withMetroMutatedResolverContext(config, getContext) {
|
|
103
|
+
var ref2;
|
|
104
|
+
const defaultResolveRequest = getDefaultMetroResolver(config.projectRoot);
|
|
105
|
+
const originalResolveRequest = (ref2 = config.resolver) == null ? void 0 : ref2.resolveRequest;
|
|
106
|
+
return {
|
|
107
|
+
...config,
|
|
108
|
+
resolver: {
|
|
109
|
+
...config.resolver,
|
|
110
|
+
resolveRequest (context, moduleName, platform) {
|
|
111
|
+
const universalContext = getContext(context, moduleName, platform);
|
|
112
|
+
var ref;
|
|
113
|
+
const firstResolver = (ref = originalResolveRequest != null ? originalResolveRequest : universalContext.resolveRequest) != null ? ref : defaultResolveRequest;
|
|
114
|
+
return firstResolver(universalContext, moduleName, platform);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function withMetroErrorReportingResolver(config) {
|
|
120
|
+
var ref4;
|
|
121
|
+
if (!_env.env.EXPO_METRO_UNSTABLE_ERRORS) {
|
|
122
|
+
return config;
|
|
123
|
+
}
|
|
124
|
+
const originalResolveRequest = (ref4 = config.resolver) == null ? void 0 : ref4.resolveRequest;
|
|
34
125
|
function mutateResolutionError(error, context, moduleName, platform) {
|
|
35
126
|
var ref;
|
|
36
|
-
if (!
|
|
127
|
+
if (!platform) {
|
|
37
128
|
debug("Cannot mutate resolution error");
|
|
38
129
|
return error;
|
|
39
130
|
}
|
|
@@ -67,8 +158,8 @@ function withMetroResolvers(config, projectRoot, resolvers) {
|
|
|
67
158
|
const pad = (num)=>{
|
|
68
159
|
return new Array(num).fill(" ").join("");
|
|
69
160
|
};
|
|
70
|
-
var
|
|
71
|
-
const root = (ref3 = (
|
|
161
|
+
var ref3;
|
|
162
|
+
const root = (ref3 = (ref = config.server) == null ? void 0 : ref.unstable_serverRoot) != null ? ref3 : config.projectRoot;
|
|
72
163
|
const recurseBackWithLimit = (req, limit, count = 0)=>{
|
|
73
164
|
const results = {
|
|
74
165
|
origin: req.origin,
|
|
@@ -142,7 +233,7 @@ function withMetroResolvers(config, projectRoot, resolvers) {
|
|
|
142
233
|
...config.resolver,
|
|
143
234
|
resolveRequest (context, moduleName, platform) {
|
|
144
235
|
const storeResult = (res)=>{
|
|
145
|
-
if (!
|
|
236
|
+
if (!platform) return;
|
|
146
237
|
const key = optionsKeyForContext(context);
|
|
147
238
|
if (!depGraph.has(key)) depGraph.set(key, new Map());
|
|
148
239
|
const mapByTarget = depGraph.get(key);
|
|
@@ -156,39 +247,22 @@ function withMetroResolvers(config, projectRoot, resolvers) {
|
|
|
156
247
|
request: moduleName
|
|
157
248
|
});
|
|
158
249
|
};
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
250
|
+
// If the user defined a resolver, run it first and depend on the documented
|
|
251
|
+
// chaining logic: https://facebook.github.io/metro/docs/resolution/#resolution-algorithm
|
|
252
|
+
//
|
|
253
|
+
// config.resolver.resolveRequest = (context, moduleName, platform) => {
|
|
254
|
+
//
|
|
255
|
+
// // Do work...
|
|
256
|
+
//
|
|
257
|
+
// return context.resolveRequest(context, moduleName, platform);
|
|
258
|
+
// };
|
|
163
259
|
try {
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
const resolution = resolver(universalContext, moduleName, platform);
|
|
167
|
-
if (resolution) {
|
|
168
|
-
storeResult(resolution);
|
|
169
|
-
return resolution;
|
|
170
|
-
}
|
|
171
|
-
} catch (error) {
|
|
172
|
-
// If no user-defined resolver, use Expo's default behavior.
|
|
173
|
-
// This prevents extraneous resolution attempts on failure.
|
|
174
|
-
if (!config.resolver.resolveRequest) {
|
|
175
|
-
throw error;
|
|
176
|
-
}
|
|
177
|
-
// If the error is directly related to a resolver not being able to resolve a module, then
|
|
178
|
-
// we can ignore the error and try the next resolver. Otherwise, we should throw the error.
|
|
179
|
-
const isResolutionError = (0, _metroErrors).isFailedToResolveNameError(error) || (0, _metroErrors).isFailedToResolvePathError(error);
|
|
180
|
-
if (!isResolutionError) {
|
|
181
|
-
throw error;
|
|
182
|
-
}
|
|
183
|
-
debug(`Custom resolver threw: ${error.constructor.name}. (module: ${moduleName}, platform: ${platform})`);
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
// If we haven't returned by now, use the original resolver or upstream resolver.
|
|
187
|
-
const res = originalResolveRequest(universalContext, moduleName, platform);
|
|
260
|
+
const firstResolver = originalResolveRequest != null ? originalResolveRequest : context.resolveRequest;
|
|
261
|
+
const res = firstResolver(context, moduleName, platform);
|
|
188
262
|
storeResult(res);
|
|
189
263
|
return res;
|
|
190
264
|
} catch (error) {
|
|
191
|
-
throw mutateResolutionError(error,
|
|
265
|
+
throw mutateResolutionError(error, context, moduleName, platform);
|
|
192
266
|
}
|
|
193
267
|
}
|
|
194
268
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/withMetroResolvers.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 chalk from 'chalk';\nimport { ConfigT as MetroConfig } from 'metro-config';\nimport { ResolutionContext } from 'metro-resolver';\nimport path from 'path';\n\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { importMetroResolverFromProject } from './resolveFromProject';\nimport { env } from '../../../utils/env';\n\nconst debug = require('debug')('expo:metro:withMetroResolvers') as typeof console.log;\n\nexport type MetroResolver = NonNullable<MetroConfig['resolver']['resolveRequest']>;\n\n/** Expo Metro Resolvers can return `null` to skip without throwing an error. Metro Resolvers will throw either a `FailedToResolveNameError` or `FailedToResolvePathError`. */\nexport type ExpoCustomMetroResolver = (\n ...args: Parameters<MetroResolver>\n) => ReturnType<MetroResolver> | null;\n\n/** @returns `MetroResolver` utilizing the upstream `resolve` method. */\nexport function getDefaultMetroResolver(projectRoot: string): MetroResolver {\n const { resolve } = importMetroResolverFromProject(projectRoot);\n return (context: ResolutionContext, moduleName: string, platform: string | null) => {\n return resolve(context, moduleName, platform);\n };\n}\n\nfunction optionsKeyForContext(context: ResolutionContext) {\n const canonicalize = require('metro-core/src/canonicalize');\n\n // Compound key for the resolver cache\n return JSON.stringify(context.customResolverOptions ?? {}, canonicalize) ?? '';\n}\n\n/**\n * Extend the Metro config `resolver.resolveRequest` method with additional resolvers that can\n * exit early by returning a `Resolution` or skip to the next resolver by returning `null`.\n *\n * @param config Metro config.\n * @param projectRoot path to the project root used to resolve the default Metro resolver.\n * @param resolvers custom MetroResolver to chain.\n * @returns a new `MetroConfig` with the `resolver.resolveRequest` method chained.\n */\nexport function withMetroResolvers(\n config: MetroConfig,\n projectRoot: string,\n resolvers: ExpoCustomMetroResolver[]\n): MetroConfig {\n debug(\n `Appending ${\n resolvers.length\n } custom resolvers to Metro config. (has custom resolver: ${!!config.resolver?.resolveRequest})`\n );\n const originalResolveRequest =\n config.resolver?.resolveRequest || getDefaultMetroResolver(projectRoot);\n\n function mutateResolutionError(\n error: Error,\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n if (!env.EXPO_METRO_UNSTABLE_ERRORS || !platform) {\n debug('Cannot mutate resolution error');\n return error;\n }\n\n const mapByOrigin = depGraph.get(optionsKeyForContext(context));\n const mapByPlatform = mapByOrigin?.get(platform);\n\n if (!mapByPlatform) {\n return error;\n }\n\n // collect all references inversely using some expensive lookup\n\n const getReferences = (origin: string) => {\n const inverseOrigin: { origin: string; previous: string; request: string }[] = [];\n\n if (!mapByPlatform) {\n return inverseOrigin;\n }\n\n for (const [originKey, mapByTarget] of mapByPlatform) {\n // search comparing origin to path\n\n const found = [...mapByTarget.values()].find((resolution) => resolution.path === origin);\n if (found) {\n inverseOrigin.push({\n origin,\n previous: originKey,\n request: found.request,\n });\n }\n }\n\n return inverseOrigin;\n };\n\n const pad = (num: number) => {\n return new Array(num).fill(' ').join('');\n };\n\n const root = config.server?.unstable_serverRoot ?? config.projectRoot ?? projectRoot;\n\n type InverseDepResult = {\n origin: string;\n request: string;\n previous: InverseDepResult[];\n };\n const recurseBackWithLimit = (\n req: { origin: string; request: string },\n limit: number,\n count: number = 0\n ) => {\n const results: InverseDepResult = {\n origin: req.origin,\n request: req.request,\n previous: [],\n };\n\n if (count >= limit) {\n return results;\n }\n\n const inverse = getReferences(req.origin);\n for (const match of inverse) {\n // Use more qualified name if possible\n // results.origin = match.origin;\n // Found entry point\n if (req.origin === match.previous) {\n continue;\n }\n results.previous.push(\n recurseBackWithLimit({ origin: match.previous, request: match.request }, limit, count + 1)\n );\n }\n return results;\n };\n\n const inverseTree = recurseBackWithLimit(\n { origin: context.originModulePath, request: moduleName },\n // TODO: Do we need to expose this?\n 35\n );\n\n if (inverseTree.previous.length > 0) {\n debug('Found inverse graph:', JSON.stringify(inverseTree, null, 2));\n let extraMessage = chalk.bold('Import stack:');\n const printRecursive = (tree: InverseDepResult, depth: number = 0) => {\n let filename = path.relative(root, tree.origin);\n if (filename.match(/\\?ctx=[\\w\\d]+$/)) {\n filename = filename.replace(/\\?ctx=[\\w\\d]+$/, chalk.dim(' (require.context)'));\n } else {\n let formattedRequest = chalk.green(`\"${tree.request}\"`);\n\n if (\n // If bundling for web and the import is pulling internals from outside of react-native\n // then mark it as an invalid import.\n platform === 'web' &&\n !/^(node_modules\\/)?react-native\\//.test(filename) &&\n tree.request.match(/^react-native\\/.*/)\n ) {\n formattedRequest =\n formattedRequest +\n chalk`\\n {yellow Importing react-native internals is not supported on web.}`;\n }\n\n filename = filename + chalk`\\n{gray |} {cyan import} ${formattedRequest}\\n`;\n }\n let line = '\\n' + pad(depth) + chalk.gray(' ') + filename;\n if (filename.match(/node_modules/)) {\n line = chalk.gray(\n // Bold the node module name\n line.replace(/node_modules\\/([^/]+)/, (_match, p1) => {\n return 'node_modules/' + chalk.bold(p1);\n })\n );\n }\n extraMessage += line;\n for (const child of tree.previous) {\n printRecursive(\n child,\n // Only add depth if there are multiple children\n tree.previous.length > 1 ? depth + 1 : depth\n );\n }\n };\n printRecursive(inverseTree);\n\n // @ts-expect-error\n error._expoImportStack = extraMessage;\n } else {\n debug('Found no inverse tree for:', context.originModulePath);\n }\n\n return error;\n }\n\n const depGraph: Map<\n // custom options\n string,\n Map<\n // platform\n string,\n Map<\n // origin module name\n string,\n Set<{\n // required module name\n path: string;\n // This isn't entirely accurate since a module can be imported multiple times in a file,\n // and use different names. But it's good enough for now.\n request: string;\n }>\n >\n >\n > = new Map();\n\n return {\n ...config,\n resolver: {\n ...config.resolver,\n resolveRequest(context, moduleName, platform) {\n const storeResult = (res: NonNullable<ReturnType<ExpoCustomMetroResolver>>) => {\n if (!env.EXPO_METRO_UNSTABLE_ERRORS || !platform) return;\n\n const key = optionsKeyForContext(context);\n if (!depGraph.has(key)) depGraph.set(key, new Map());\n const mapByTarget = depGraph.get(key);\n if (!mapByTarget!.has(platform)) mapByTarget!.set(platform, new Map());\n const mapByPlatform = mapByTarget!.get(platform);\n if (!mapByPlatform!.has(context.originModulePath))\n mapByPlatform!.set(context.originModulePath, new Set());\n const setForModule = mapByPlatform!.get(context.originModulePath)!;\n\n const qualifiedModuleName = res?.type === 'sourceFile' ? res.filePath : moduleName;\n setForModule.add({ path: qualifiedModuleName, request: moduleName });\n };\n\n const universalContext = {\n ...context,\n preferNativePlatform: platform !== 'web',\n };\n\n try {\n for (const resolver of resolvers) {\n try {\n const resolution = resolver(universalContext, moduleName, platform);\n if (resolution) {\n storeResult(resolution);\n return resolution;\n }\n } catch (error: any) {\n // If no user-defined resolver, use Expo's default behavior.\n // This prevents extraneous resolution attempts on failure.\n if (!config.resolver.resolveRequest) {\n throw error;\n }\n\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n debug(\n `Custom resolver threw: ${error.constructor.name}. (module: ${moduleName}, platform: ${platform})`\n );\n }\n }\n // If we haven't returned by now, use the original resolver or upstream resolver.\n const res = originalResolveRequest(universalContext, moduleName, platform);\n storeResult(res);\n return res;\n } catch (error: any) {\n throw mutateResolutionError(error, universalContext, moduleName, platform);\n }\n },\n },\n };\n}\n"],"names":["getDefaultMetroResolver","withMetroResolvers","debug","require","projectRoot","resolve","importMetroResolverFromProject","context","moduleName","platform","optionsKeyForContext","canonicalize","JSON","stringify","customResolverOptions","config","resolvers","length","resolver","resolveRequest","originalResolveRequest","mutateResolutionError","error","env","EXPO_METRO_UNSTABLE_ERRORS","mapByOrigin","depGraph","get","mapByPlatform","getReferences","origin","inverseOrigin","originKey","mapByTarget","found","values","find","resolution","path","push","previous","request","pad","num","Array","fill","join","root","server","unstable_serverRoot","recurseBackWithLimit","req","limit","count","results","inverse","match","inverseTree","originModulePath","extraMessage","chalk","bold","printRecursive","tree","depth","filename","relative","replace","dim","formattedRequest","green","test","line","gray","_match","p1","child","_expoImportStack","Map","storeResult","res","key","has","set","Set","setForModule","qualifiedModuleName","type","filePath","add","universalContext","preferNativePlatform","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","constructor","name"],"mappings":"AAMA;;;;QAmBgBA,uBAAuB,GAAvBA,uBAAuB;QAuBvBC,kBAAkB,GAAlBA,kBAAkB;AA1ChB,IAAA,MAAO,kCAAP,OAAO,EAAA;AAGR,IAAA,KAAM,kCAAN,MAAM,EAAA;AAEgD,IAAA,YAAe,WAAf,eAAe,CAAA;AACvC,IAAA,mBAAsB,WAAtB,sBAAsB,CAAA;AACjD,IAAA,IAAoB,WAApB,oBAAoB,CAAA;;;;;;AAExC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,+BAA+B,CAAC,AAAsB,AAAC;AAU/E,SAASH,uBAAuB,CAACI,WAAmB,EAAiB;IAC1E,MAAM,EAAEC,OAAO,CAAA,EAAE,GAAGC,CAAAA,GAAAA,mBAA8B,AAAa,CAAA,+BAAb,CAACF,WAAW,CAAC,AAAC;IAChE,OAAO,CAACG,OAA0B,EAAEC,UAAkB,EAAEC,QAAuB,GAAK;QAClF,OAAOJ,OAAO,CAACE,OAAO,EAA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AAAA,YAA0B,AAAO,CAAA,2BAAP,CAACvE,KAAK,CAAC,IAAIwE,CAAAA,GAAAA,YAA0B,AAAO,CAAA,2BAAP,CAACxE,KAAK,CAAC,AAAC;4BACzE,IAAI,CAACsE,iBAAiB,EAAE;gCACtB,MAAMtE,KAAK,CAAC;6BACb;4BACDpB,KAAK,CACH,CAAC,uBAAuB,EAAEoB,KAAK,CAACyE,WAAW,CAACC,IAAI,CAAC,WAAW,EAAExF,UAAU,CAAC,YAAY,EAAEC,QAAQ,CAAC,CAAC,CAAC,CACnG,CAAC;yBACH;qBACF;oBACD,iFAAiF;oBACjF,MAAMuE,GAAG,GAAG5D,sBAAsB,CAACsE,gBAAgB,EAAElF,UAAU,EAAEC,QAAQ,CAAC,AAAC;oBAC3EsE,WAAW,CAACC,GAAG,CAAC,CAAC;oBACjB,OAAOA,GAAG,CAAC;iBACZ,CAAC,OAAO1D,KAAK,EAAO;oBACnB,MAAMD,qBAAqB,CAACC,KAAK,EAAEoE,gBAAgB,EAAElF,UAAU,EAAEC,QAAQ,CAAC,CAAC;iBAC5E;aACF;SACF;KACF,CAAC;CACH"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/withMetroResolvers.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 chalk from 'chalk';\nimport { ConfigT as MetroConfig } from 'metro-config';\nimport type { ResolutionContext, CustomResolutionContext } from 'metro-resolver';\nimport * as metroResolver from 'metro-resolver';\nimport path from 'path';\n\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { env } from '../../../utils/env';\n\nconst debug = require('debug')('expo:metro:withMetroResolvers') as typeof console.log;\n\nexport type MetroResolver = NonNullable<MetroConfig['resolver']['resolveRequest']>;\n\n/** Expo Metro Resolvers can return `null` to skip without throwing an error. Metro Resolvers will throw either a `FailedToResolveNameError` or `FailedToResolvePathError`. */\nexport type ExpoCustomMetroResolver = (\n ...args: Parameters<MetroResolver>\n) => ReturnType<MetroResolver> | null;\n\n/** @returns `MetroResolver` utilizing the upstream `resolve` method. */\nexport function getDefaultMetroResolver(projectRoot: string): MetroResolver {\n return (context: ResolutionContext, moduleName: string, platform: string | null) => {\n return metroResolver.resolve(context, moduleName, platform);\n };\n}\n\nfunction optionsKeyForContext(context: ResolutionContext) {\n const canonicalize = require('metro-core/src/canonicalize');\n\n // Compound key for the resolver cache\n return JSON.stringify(context.customResolverOptions ?? {}, canonicalize) ?? '';\n}\n\n/**\n * Extend the Metro config `resolver.resolveRequest` method with additional resolvers that can\n * exit early by returning a `Resolution` or skip to the next resolver by returning `null`.\n *\n * @param config Metro config.\n * @param resolvers custom MetroResolver to chain.\n * @returns a new `MetroConfig` with the `resolver.resolveRequest` method chained.\n */\nexport function withMetroResolvers(\n config: MetroConfig,\n resolvers: ExpoCustomMetroResolver[]\n): MetroConfig {\n debug(\n `Appending ${\n resolvers.length\n } custom resolvers to Metro config. (has custom resolver: ${!!config.resolver?.resolveRequest})`\n );\n // const hasUserDefinedResolver = !!config.resolver?.resolveRequest;\n // const defaultResolveRequest = getDefaultMetroResolver(projectRoot);\n const originalResolveRequest = config.resolver?.resolveRequest;\n\n return {\n ...config,\n resolver: {\n ...config.resolver,\n resolveRequest(context, moduleName, platform) {\n const upstreamResolveRequest = context.resolveRequest;\n\n const universalContext = {\n ...context,\n resolveRequest(\n ctx: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n for (const resolver of resolvers) {\n try {\n const res = resolver(ctx, moduleName, platform);\n if (res) {\n return res;\n }\n } catch (error: any) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n debug(\n `Custom resolver threw: ${error.constructor.name}. (module: ${moduleName}, platform: ${platform})`\n );\n }\n }\n // If we haven't returned by now, use the original resolver or upstream resolver.\n return upstreamResolveRequest(ctx, moduleName, platform);\n },\n };\n\n // If the user defined a resolver, run it first and depend on the documented\n // chaining logic: https://facebook.github.io/metro/docs/resolution/#resolution-algorithm\n //\n // config.resolver.resolveRequest = (context, moduleName, platform) => {\n //\n // // Do work...\n //\n // return context.resolveRequest(context, moduleName, platform);\n // };\n const firstResolver = originalResolveRequest ?? universalContext.resolveRequest;\n return firstResolver(universalContext, moduleName, platform);\n },\n },\n };\n}\n\n/**\n * Hook into the Metro resolver chain and mutate the context so users can resolve against our custom assumptions.\n * For example, this will set `preferNativePlatform` to false when bundling for web.\n * */\nexport function withMetroMutatedResolverContext(\n config: MetroConfig,\n getContext: (\n ctx: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ) => CustomResolutionContext\n): MetroConfig {\n const defaultResolveRequest = getDefaultMetroResolver(config.projectRoot);\n const originalResolveRequest = config.resolver?.resolveRequest;\n\n return {\n ...config,\n resolver: {\n ...config.resolver,\n resolveRequest(context, moduleName, platform) {\n const universalContext = getContext(context, moduleName, platform);\n const firstResolver =\n originalResolveRequest ?? universalContext.resolveRequest ?? defaultResolveRequest;\n return firstResolver(universalContext, moduleName, platform);\n },\n },\n };\n}\n\nexport function withMetroErrorReportingResolver(config: MetroConfig): MetroConfig {\n if (!env.EXPO_METRO_UNSTABLE_ERRORS) {\n return config;\n }\n\n const originalResolveRequest = config.resolver?.resolveRequest;\n\n function mutateResolutionError(\n error: Error,\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n if (!platform) {\n debug('Cannot mutate resolution error');\n return error;\n }\n\n const mapByOrigin = depGraph.get(optionsKeyForContext(context));\n const mapByPlatform = mapByOrigin?.get(platform);\n\n if (!mapByPlatform) {\n return error;\n }\n\n // collect all references inversely using some expensive lookup\n\n const getReferences = (origin: string) => {\n const inverseOrigin: { origin: string; previous: string; request: string }[] = [];\n\n if (!mapByPlatform) {\n return inverseOrigin;\n }\n\n for (const [originKey, mapByTarget] of mapByPlatform) {\n // search comparing origin to path\n\n const found = [...mapByTarget.values()].find((resolution) => resolution.path === origin);\n if (found) {\n inverseOrigin.push({\n origin,\n previous: originKey,\n request: found.request,\n });\n }\n }\n\n return inverseOrigin;\n };\n\n const pad = (num: number) => {\n return new Array(num).fill(' ').join('');\n };\n\n const root = config.server?.unstable_serverRoot ?? config.projectRoot;\n\n type InverseDepResult = {\n origin: string;\n request: string;\n previous: InverseDepResult[];\n };\n const recurseBackWithLimit = (\n req: { origin: string; request: string },\n limit: number,\n count: number = 0\n ) => {\n const results: InverseDepResult = {\n origin: req.origin,\n request: req.request,\n previous: [],\n };\n\n if (count >= limit) {\n return results;\n }\n\n const inverse = getReferences(req.origin);\n for (const match of inverse) {\n // Use more qualified name if possible\n // results.origin = match.origin;\n // Found entry point\n if (req.origin === match.previous) {\n continue;\n }\n results.previous.push(\n recurseBackWithLimit({ origin: match.previous, request: match.request }, limit, count + 1)\n );\n }\n return results;\n };\n\n const inverseTree = recurseBackWithLimit(\n { origin: context.originModulePath, request: moduleName },\n // TODO: Do we need to expose this?\n 35\n );\n\n if (inverseTree.previous.length > 0) {\n debug('Found inverse graph:', JSON.stringify(inverseTree, null, 2));\n let extraMessage = chalk.bold('Import stack:');\n const printRecursive = (tree: InverseDepResult, depth: number = 0) => {\n let filename = path.relative(root, tree.origin);\n if (filename.match(/\\?ctx=[\\w\\d]+$/)) {\n filename = filename.replace(/\\?ctx=[\\w\\d]+$/, chalk.dim(' (require.context)'));\n } else {\n let formattedRequest = chalk.green(`\"${tree.request}\"`);\n\n if (\n // If bundling for web and the import is pulling internals from outside of react-native\n // then mark it as an invalid import.\n platform === 'web' &&\n !/^(node_modules\\/)?react-native\\//.test(filename) &&\n tree.request.match(/^react-native\\/.*/)\n ) {\n formattedRequest =\n formattedRequest +\n chalk`\\n {yellow Importing react-native internals is not supported on web.}`;\n }\n\n filename = filename + chalk`\\n{gray |} {cyan import} ${formattedRequest}\\n`;\n }\n let line = '\\n' + pad(depth) + chalk.gray(' ') + filename;\n if (filename.match(/node_modules/)) {\n line = chalk.gray(\n // Bold the node module name\n line.replace(/node_modules\\/([^/]+)/, (_match, p1) => {\n return 'node_modules/' + chalk.bold(p1);\n })\n );\n }\n extraMessage += line;\n for (const child of tree.previous) {\n printRecursive(\n child,\n // Only add depth if there are multiple children\n tree.previous.length > 1 ? depth + 1 : depth\n );\n }\n };\n printRecursive(inverseTree);\n\n // @ts-expect-error\n error._expoImportStack = extraMessage;\n } else {\n debug('Found no inverse tree for:', context.originModulePath);\n }\n\n return error;\n }\n\n const depGraph: Map<\n // custom options\n string,\n Map<\n // platform\n string,\n Map<\n // origin module name\n string,\n Set<{\n // required module name\n path: string;\n // This isn't entirely accurate since a module can be imported multiple times in a file,\n // and use different names. But it's good enough for now.\n request: string;\n }>\n >\n >\n > = new Map();\n\n return {\n ...config,\n resolver: {\n ...config.resolver,\n resolveRequest(context, moduleName, platform) {\n const storeResult = (res: NonNullable<ReturnType<ExpoCustomMetroResolver>>) => {\n if (!platform) return;\n\n const key = optionsKeyForContext(context);\n if (!depGraph.has(key)) depGraph.set(key, new Map());\n const mapByTarget = depGraph.get(key);\n if (!mapByTarget!.has(platform)) mapByTarget!.set(platform, new Map());\n const mapByPlatform = mapByTarget!.get(platform);\n if (!mapByPlatform!.has(context.originModulePath))\n mapByPlatform!.set(context.originModulePath, new Set());\n const setForModule = mapByPlatform!.get(context.originModulePath)!;\n\n const qualifiedModuleName = res?.type === 'sourceFile' ? res.filePath : moduleName;\n setForModule.add({ path: qualifiedModuleName, request: moduleName });\n };\n\n // If the user defined a resolver, run it first and depend on the documented\n // chaining logic: https://facebook.github.io/metro/docs/resolution/#resolution-algorithm\n //\n // config.resolver.resolveRequest = (context, moduleName, platform) => {\n //\n // // Do work...\n //\n // return context.resolveRequest(context, moduleName, platform);\n // };\n try {\n const firstResolver = originalResolveRequest ?? context.resolveRequest;\n const res = firstResolver(context, moduleName, platform);\n storeResult(res);\n return res;\n } catch (error: any) {\n throw mutateResolutionError(error, context, moduleName, platform);\n }\n },\n },\n };\n}\n"],"names":["getDefaultMetroResolver","withMetroResolvers","withMetroMutatedResolverContext","withMetroErrorReportingResolver","metroResolver","debug","require","projectRoot","context","moduleName","platform","resolve","optionsKeyForContext","canonicalize","JSON","stringify","customResolverOptions","config","resolvers","length","resolver","resolveRequest","originalResolveRequest","upstreamResolveRequest","universalContext","ctx","res","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","constructor","name","firstResolver","getContext","defaultResolveRequest","env","EXPO_METRO_UNSTABLE_ERRORS","mutateResolutionError","mapByOrigin","depGraph","get","mapByPlatform","getReferences","origin","inverseOrigin","originKey","mapByTarget","found","values","find","resolution","path","push","previous","request","pad","num","Array","fill","join","root","server","unstable_serverRoot","recurseBackWithLimit","req","limit","count","results","inverse","match","inverseTree","originModulePath","extraMessage","chalk","bold","printRecursive","tree","depth","filename","relative","replace","dim","formattedRequest","green","test","line","gray","_match","p1","child","_expoImportStack","Map","storeResult","key","has","set","Set","setForModule","qualifiedModuleName","type","filePath","add"],"mappings":"AAMA;;;;QAmBgBA,uBAAuB,GAAvBA,uBAAuB;QAqBvBC,kBAAkB,GAAlBA,kBAAkB;QAuElBC,+BAA+B,GAA/BA,+BAA+B;QAyB/BC,+BAA+B,GAA/BA,+BAA+B;AAxI7B,IAAA,MAAO,kCAAP,OAAO,EAAA;AAGbC,IAAAA,aAAa,mCAAM,gBAAgB,EAAtB;AACR,IAAA,KAAM,kCAAN,MAAM,EAAA;AAEgD,IAAA,YAAe,WAAf,eAAe,CAAA;AAClE,IAAA,IAAoB,WAApB,oBAAoB,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAExC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,+BAA+B,CAAC,AAAsB,AAAC;AAU/E,SAASN,uBAAuB,CAACO,WAAmB,EAAiB;IAC1E,OAAO,CAACC,OAA0B,EAAEC,UAAkB,EAAEC,QAAuB,GAAK;QAClF,OAA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BAAgB,CAAC,EAC/C9B,aAAa,CAAEsD,GAAG,CAACxF,OAAO,CAACgE,gBAAgB,EAAE,IAAIyB,GAAG,EAAE,CAAC,CAAC;oBAC1D,MAAMC,YAAY,GAAGxD,aAAa,CAAED,GAAG,CAACjC,OAAO,CAACgE,gBAAgB,CAAC,AAAC,AAAC;oBAEnE,MAAM2B,mBAAmB,GAAGzE,CAAAA,GAAG,QAAM,GAATA,KAAAA,CAAS,GAATA,GAAG,CAAE0E,IAAI,CAAA,KAAK,YAAY,GAAG1E,GAAG,CAAC2E,QAAQ,GAAG5F,UAAU,AAAC;oBACnFyF,YAAY,CAACI,GAAG,CAAC;wBAAElD,IAAI,EAAE+C,mBAAmB;wBAAE5C,OAAO,EAAE9C,UAAU;qBAAE,CAAC,CAAC;iBACtE,AAAC;gBAEF,4EAA4E;gBAC5E,yFAAyF;gBACzF,EAAE;gBACF,wEAAwE;gBACxE,EAAE;gBACF,iBAAiB;gBACjB,EAAE;gBACF,iEAAiE;gBACjE,KAAK;gBACL,IAAI;oBACF,MAAMwB,aAAa,GAAGX,sBAAsB,WAAtBA,sBAAsB,GAAId,OAAO,CAACa,cAAc,AAAC;oBACvE,MAAMK,GAAG,GAAGO,aAAa,CAACzB,OAAO,EAAEC,UAAU,EAAEC,QAAQ,CAAC,AAAC;oBACzDmF,WAAW,CAACnE,GAAG,CAAC,CAAC;oBACjB,OAAOA,GAAG,CAAC;iBACZ,CAAC,OAAOC,KAAK,EAAO;oBACnB,MAAMW,qBAAqB,CAACX,KAAK,EAAEnB,OAAO,EAAEC,UAAU,EAAEC,QAAQ,CAAC,CAAC;iBACnE;aACF;SACF;KACF,CAAC;CACH"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
Object.defineProperty(exports, "DevToolsPluginEndpoint", {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
get: function() {
|
|
8
|
+
return _devToolsPluginManager.DevToolsPluginEndpoint;
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
var _assert = _interopRequireDefault(require("assert"));
|
|
12
|
+
var _send = _interopRequireDefault(require("send"));
|
|
13
|
+
var _expoMiddleware = require("./ExpoMiddleware");
|
|
14
|
+
var _devToolsPluginManager = require("../DevToolsPluginManager");
|
|
15
|
+
function _interopRequireDefault(obj) {
|
|
16
|
+
return obj && obj.__esModule ? obj : {
|
|
17
|
+
default: obj
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
class DevToolsPluginMiddleware extends _expoMiddleware.ExpoMiddleware {
|
|
21
|
+
constructor(projectRoot, pluginManager){
|
|
22
|
+
super(projectRoot, [
|
|
23
|
+
_devToolsPluginManager.DevToolsPluginEndpoint
|
|
24
|
+
]);
|
|
25
|
+
this.pluginManager = pluginManager;
|
|
26
|
+
}
|
|
27
|
+
shouldHandleRequest(req) {
|
|
28
|
+
var ref;
|
|
29
|
+
if (!((ref = req.url) == null ? void 0 : ref.startsWith(_devToolsPluginManager.DevToolsPluginEndpoint))) {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
async handleRequestAsync(req, res) {
|
|
35
|
+
(0, _assert).default(req.headers.host, "Request headers must include host");
|
|
36
|
+
var _url;
|
|
37
|
+
const { pathname } = new URL((_url = req.url) != null ? _url : "/", `http://${req.headers.host}`);
|
|
38
|
+
const pluginName = this.queryPossiblePluginName(pathname.substring(_devToolsPluginManager.DevToolsPluginEndpoint.length + 1));
|
|
39
|
+
const webpageRoot = await this.pluginManager.queryPluginWebpageRootAsync(pluginName);
|
|
40
|
+
if (!webpageRoot) {
|
|
41
|
+
res.statusCode = 404;
|
|
42
|
+
res.end();
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const pathInPluginRoot = pathname.substring(_devToolsPluginManager.DevToolsPluginEndpoint.length + pluginName.length + 1) || "/";
|
|
46
|
+
(0, _send).default(req, pathInPluginRoot, {
|
|
47
|
+
root: webpageRoot
|
|
48
|
+
}).pipe(res);
|
|
49
|
+
}
|
|
50
|
+
queryPossiblePluginName(pathname) {
|
|
51
|
+
const parts = pathname.split("/");
|
|
52
|
+
if (parts[0][0] === "@" && parts.length > 1) {
|
|
53
|
+
// Scoped package name
|
|
54
|
+
return `${parts[0]}/${parts[1]}`;
|
|
55
|
+
}
|
|
56
|
+
return parts[0];
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
exports.DevToolsPluginMiddleware = DevToolsPluginMiddleware;
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=DevToolsPluginMiddleware.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/DevToolsPluginMiddleware.ts"],"sourcesContent":["import assert from 'assert';\nimport send from 'send';\n\nimport { ExpoMiddleware } from './ExpoMiddleware';\nimport { ServerRequest, ServerResponse } from './server.types';\nimport DevToolsPluginManager, { DevToolsPluginEndpoint } from '../DevToolsPluginManager';\n\nexport { DevToolsPluginEndpoint };\n\nexport class DevToolsPluginMiddleware extends ExpoMiddleware {\n constructor(\n projectRoot: string,\n private readonly pluginManager: DevToolsPluginManager\n ) {\n super(projectRoot, [DevToolsPluginEndpoint]);\n }\n\n override shouldHandleRequest(req: ServerRequest): boolean {\n if (!req.url?.startsWith(DevToolsPluginEndpoint)) {\n return false;\n }\n return true;\n }\n\n async handleRequestAsync(req: ServerRequest, res: ServerResponse): Promise<void> {\n assert(req.headers.host, 'Request headers must include host');\n const { pathname } = new URL(req.url ?? '/', `http://${req.headers.host}`);\n const pluginName = this.queryPossiblePluginName(\n pathname.substring(DevToolsPluginEndpoint.length + 1)\n );\n const webpageRoot = await this.pluginManager.queryPluginWebpageRootAsync(pluginName);\n if (!webpageRoot) {\n res.statusCode = 404;\n res.end();\n return;\n }\n\n const pathInPluginRoot =\n pathname.substring(DevToolsPluginEndpoint.length + pluginName.length + 1) || '/';\n send(req, pathInPluginRoot, { root: webpageRoot }).pipe(res);\n }\n\n private queryPossiblePluginName(pathname: string): string {\n const parts = pathname.split('/');\n if (parts[0][0] === '@' && parts.length > 1) {\n // Scoped package name\n return `${parts[0]}/${parts[1]}`;\n }\n return parts[0];\n }\n}\n"],"names":["DevToolsPluginEndpoint","DevToolsPluginMiddleware","ExpoMiddleware","constructor","projectRoot","pluginManager","shouldHandleRequest","req","url","startsWith","handleRequestAsync","res","assert","headers","host","pathname","URL","pluginName","queryPossiblePluginName","substring","length","webpageRoot","queryPluginWebpageRootAsync","statusCode","end","pathInPluginRoot","send","root","pipe","parts","split"],"mappings":"AAAA;;;;+BAOSA,wBAAsB;;;eAAtBA,sBAAsB,uBAAA;;;AAPZ,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACV,IAAA,KAAM,kCAAN,MAAM,EAAA;AAEQ,IAAA,eAAkB,WAAlB,kBAAkB,CAAA;AAEa,IAAA,sBAA0B,WAA1B,0BAA0B,CAAA;;;;;;AAIjF,MAAMC,wBAAwB,SAASC,eAAc,eAAA;IAC1DC,YACEC,WAAmB,EACFC,aAAoC,CACrD;QACA,KAAK,CAACD,WAAW,EAAE;YAACJ,sBAAsB,uBAAA;SAAC,CAAC,CAAC;aAF5BK,aAAoC,GAApCA,aAAoC;KAGtD;IAED,AAASC,mBAAmB,CAACC,GAAkB,EAAW;YACnDA,GAAO;QAAZ,IAAI,EAACA,CAAAA,GAAO,GAAPA,GAAG,CAACC,GAAG,SAAY,GAAnBD,KAAAA,CAAmB,GAAnBA,GAAO,CAAEE,UAAU,CAACT,sBAAsB,uBAAA,CAAC,CAAA,EAAE;YAChD,OAAO,KAAK,CAAC;SACd;QACD,OAAO,IAAI,CAAC;KACb;IAED,MAAMU,kBAAkB,CAACH,GAAkB,EAAEI,GAAmB,EAAiB;QAC/EC,CAAAA,GAAAA,OAAM,AAAuD,CAAA,QAAvD,CAACL,GAAG,CAACM,OAAO,CAACC,IAAI,EAA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,CAAC,CAAC,CAAC,CAAC;SAClC;QACD,OAAOA,KAAK,CAAC,CAAC,CAAC,CAAC;KACjB;CACF;QAzCY5B,wBAAwB,GAAxBA,wBAAwB"}
|
|
@@ -34,7 +34,7 @@ class ExpoMiddleware {
|
|
|
34
34
|
/**
|
|
35
35
|
* Returns true when the middleware should handle the incoming server request.
|
|
36
36
|
* Exposed for testing.
|
|
37
|
-
*/
|
|
37
|
+
*/ shouldHandleRequest(req) {
|
|
38
38
|
if (!req.url) {
|
|
39
39
|
return false;
|
|
40
40
|
}
|
|
@@ -63,7 +63,7 @@ class ExpoMiddleware {
|
|
|
63
63
|
}
|
|
64
64
|
};
|
|
65
65
|
const middleware = async (req, res, next)=>{
|
|
66
|
-
if (!this.
|
|
66
|
+
if (!this.shouldHandleRequest(req)) {
|
|
67
67
|
return next();
|
|
68
68
|
}
|
|
69
69
|
return internalMiddleware(req, res, next);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/ExpoMiddleware.ts"],"sourcesContent":["import { parse } from 'url';\n\nimport { ServerNext, ServerRequest, ServerResponse } from './server.types';\nimport * as Log from '../../../log';\n\n/** Base middleware creator for Expo dev servers. */\nexport abstract class ExpoMiddleware {\n constructor(\n protected projectRoot: string,\n protected supportedPaths: string[]\n ) {}\n\n /**\n * Returns true when the middleware should handle the incoming server request.\n * Exposed for testing.\n */\n
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/ExpoMiddleware.ts"],"sourcesContent":["import { parse } from 'url';\n\nimport { ServerNext, ServerRequest, ServerResponse } from './server.types';\nimport * as Log from '../../../log';\n\n/** Base middleware creator for Expo dev servers. */\nexport abstract class ExpoMiddleware {\n constructor(\n protected projectRoot: string,\n protected supportedPaths: string[]\n ) {}\n\n /**\n * Returns true when the middleware should handle the incoming server request.\n * Exposed for testing.\n */\n public shouldHandleRequest(req: ServerRequest): boolean {\n if (!req.url) {\n return false;\n }\n const parsed = parse(req.url);\n // Strip the query params\n if (!parsed.pathname) {\n return false;\n }\n\n return this.supportedPaths.includes(parsed.pathname);\n }\n\n abstract handleRequestAsync(\n req: ServerRequest,\n res: ServerResponse,\n next: ServerNext\n ): Promise<void>;\n\n /** Create a server middleware handler. */\n public getHandler() {\n const internalMiddleware = async (\n req: ServerRequest,\n res: ServerResponse,\n next: ServerNext\n ) => {\n try {\n return await this.handleRequestAsync(req, res, next);\n } catch (error: any) {\n Log.exception(error);\n // 5xx = Server Error HTTP code\n res.statusCode = 500;\n if (typeof error === 'object' && error !== null) {\n res.end(\n JSON.stringify({\n error: error.toString(),\n })\n );\n } else {\n res.end(`Unexpected error: ${error}`);\n }\n }\n };\n const middleware = async (req: ServerRequest, res: ServerResponse, next: ServerNext) => {\n if (!this.shouldHandleRequest(req)) {\n return next();\n }\n return internalMiddleware(req, res, next);\n };\n\n middleware.internal = internalMiddleware;\n\n return middleware;\n }\n}\n\nexport function disableResponseCache(res: ServerResponse): ServerResponse {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, must-revalidate');\n res.setHeader('Expires', '-1');\n res.setHeader('Pragma', 'no-cache');\n return res;\n}\n"],"names":["disableResponseCache","Log","ExpoMiddleware","constructor","projectRoot","supportedPaths","shouldHandleRequest","req","url","parsed","parse","pathname","includes","getHandler","internalMiddleware","res","next","handleRequestAsync","error","exception","statusCode","end","JSON","stringify","toString","middleware","internal","setHeader"],"mappings":"AAAA;;;;QAwEgBA,oBAAoB,GAApBA,oBAAoB;AAxEd,IAAA,IAAK,WAAL,KAAK,CAAA;AAGfC,IAAAA,GAAG,mCAAM,cAAc,EAApB;;;;;;;;;;;;;;;;;;;;;;AAGR,MAAeC,cAAc;IAClCC,YACYC,WAAmB,EACnBC,cAAwB,CAClC;aAFUD,WAAmB,GAAnBA,WAAmB;aACnBC,cAAwB,GAAxBA,cAAwB;KAChC;IAEJ;;;KAGG,CACH,AAAOC,mBAAmB,CAACC,GAAkB,EAAW;QACtD,IAAI,CAACA,GAAG,CAACC,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