@expo/cli 55.0.0-canary-20251210-1f163e3 → 55.0.0-canary-20251211-7da85ea

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.
@@ -92,7 +92,10 @@ function withWebPolyfills(config, { getMetroBundler }) {
92
92
  const virtualModuleId = `\0polyfill:external-require`;
93
93
  (0, _metroVirtualModules.getMetroBundlerWithVirtualModules)(getMetroBundler()).setVirtualModule(virtualModuleId, (()=>{
94
94
  if (ctx.platform === 'web') {
95
- return `global.$$require_external = typeof require !== "undefined" ? require : () => null;`;
95
+ // NOTE(@hassankhan): We need to wrap require in an arrow function rather than assigning
96
+ // it directly because `workerd` loses its `this` context when `require` is dereferenced
97
+ // and called later.
98
+ return `global.$$require_external = typeof require !== "undefined" ? (m) => require(m) : () => null;`;
96
99
  } else {
97
100
  // Wrap in try/catch to support Android.
98
101
  return 'try { global.$$require_external = typeof expo === "undefined" ? require : (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} } catch { global.$$require_external = (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} }';
@@ -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 type { ExpoConfig, Platform } from '@expo/config';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ConfigT } from '@expo/metro/metro-config';\nimport type {\n Resolution,\n ResolutionContext,\n CustomResolutionContext,\n} from '@expo/metro/metro-resolver';\nimport { resolve as resolver } from '@expo/metro/metro-resolver';\nimport type { SourceFileResolution } from '@expo/metro/metro-resolver/types';\nimport fs from 'fs';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport {\n createAutolinkingModuleResolverInput,\n createAutolinkingModuleResolver,\n AutolinkingModuleResolverInput,\n} from './createExpoAutolinkingResolver';\nimport { createFallbackModuleResolver } from './createExpoFallbackResolver';\nimport { FailedToResolveNativeOnlyModuleError } from './errors/FailedToResolveNativeOnlyModuleError';\nimport { isNodeExternal, shouldCreateVirtualShim } from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { getMetroBundlerWithVirtualModules } from './metroVirtualModules';\nimport { withMetroErrorReportingResolver } from './withMetroErrorReportingResolver';\nimport { withMetroMutatedResolverContext, withMetroResolvers } from './withMetroResolvers';\nimport { withMetroSupervisingTransformWorker } from './withMetroSupervisingTransformWorker';\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 { isServerEnvironment } from '../middleware/metroOptions';\nimport { PlatformBundlers } from '../platformBundlers';\n\nexport type StrictResolver = (moduleName: string) => Resolution;\nexport type StrictResolverFactory = (\n context: ResolutionContext,\n platform: string | null\n) => StrictResolver;\n\nconst ASSET_REGISTRY_SRC = `const assets=[];module.exports={registerAsset:s=>assets.push(s),getAssetByID:s=>assets[s-1]};`;\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\n\nfunction withWebPolyfills(\n config: ConfigT,\n {\n getMetroBundler,\n }: {\n getMetroBundler: () => Bundler;\n }\n): 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 const virtualEnvVarId = `\\0polyfill:environment-variables`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualEnvVarId,\n (() => {\n return `//`;\n })()\n );\n\n const virtualModuleId = `\\0polyfill:external-require`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n (() => {\n if (ctx.platform === 'web') {\n return `global.$$require_external = typeof require !== \"undefined\" ? require : () => null;`;\n } else {\n // Wrap in try/catch to support Android.\n return 'try { global.$$require_external = typeof expo === \"undefined\" ? require : (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} } catch { global.$$require_external = (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} }';\n }\n })()\n );\n\n const virtualModulesPolyfills = [virtualModuleId, virtualEnvVarId];\n\n if (ctx.platform === 'web') {\n try {\n const rnGetPolyfills: () => string[] = require('react-native/rn-get-polyfills');\n return [\n ...virtualModulesPolyfills,\n // Ensure that the error-guard polyfill is included in the web polyfills to\n // make metro-runtime work correctly.\n // TODO: This module is pretty big for a function that simply re-throws an error that doesn't need to be caught.\n // NOTE(@kitten): This is technically the public API to get polyfills rather than resolving directly into\n // `@react-native/js-polyfills`. We should really just start vendoring these, but for now, this exclusion works\n ...rnGetPolyfills().filter((x: string) => !x.includes('/console')),\n ];\n } catch (error: any) {\n if ('code' in error && error.code === 'MODULE_NOT_FOUND') {\n // If react-native is not installed, because we're targeting web, we still continue\n // This should be rare, but we add it so we don't unnecessarily have a fixed peer dependency on react-native\n debug(\n 'Skipping react-native/rn-get-polyfills from getPolyfills. react-native is not installed.'\n );\n return virtualModulesPolyfills;\n } else {\n throw error;\n }\n }\n }\n\n // Generally uses `@expo/metro-config`'s `getPolyfills` function, unless overridden\n const polyfills = originalGetPolyfills(ctx);\n return [\n ...polyfills,\n ...virtualModulesPolyfills,\n // Removed on server platforms during the transform.\n require.resolve('expo/virtual/streams.js'),\n ];\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 autolinkingModuleResolverInput,\n isTsconfigPathsEnabled,\n isExporting,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n tsconfig: TsConfigPaths | null;\n autolinkingModuleResolverInput?: AutolinkingModuleResolverInput;\n isTsconfigPathsEnabled?: boolean;\n isExporting?: boolean;\n isReactServerComponentsEnabled?: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isReactServerComponentsEnabled) {\n Log.warn(`React Server Components (beta) is enabled.`);\n }\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 'react-native/Libraries/Image/resolveAssetSource': 'expo-asset/build/resolveAssetSource',\n },\n };\n\n let _universalAliases: [RegExp, string][] | null;\n\n function getUniversalAliases() {\n if (_universalAliases) {\n return _universalAliases;\n }\n\n _universalAliases = [];\n\n // This package is currently always installed as it is included in the `expo` package.\n if (resolveFrom.silent(config.projectRoot, '@expo/vector-icons')) {\n debug('Enabling alias: react-native-vector-icons -> @expo/vector-icons');\n _universalAliases.push([/^react-native-vector-icons(\\/.*)?/, '@expo/vector-icons$1']);\n }\n if (isReactServerComponentsEnabled) {\n if (resolveFrom.silent(config.projectRoot, 'expo-router/rsc')) {\n debug('Enabling bridge alias: expo-router -> expo-router/rsc');\n _universalAliases.push([/^expo-router$/, 'expo-router/rsc']);\n // Bridge the internal entry point which is a standalone import to ensure package.json resolution works as expected.\n _universalAliases.push([/^expo-router\\/entry-classic$/, 'expo-router/rsc/entry']);\n }\n }\n return _universalAliases;\n }\n\n // used to resolve externals in `requestCustomExternals` from the project root\n const projectRootOriginPath = path.join(config.projectRoot, 'package.json');\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 =\n isTsconfigPathsEnabled && (tsconfig?.paths || tsconfig?.baseUrl != null)\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!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 ?? config.projectRoot,\n hasBaseUrl: !!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 getStrictResolver: StrictResolverFactory = (\n { resolveRequest, ...context },\n platform\n ): StrictResolver => {\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 // TODO: This is a hack to get resolveWeak working.\n const idFactory = (config.serializer?.createModuleIdFactory?.() ??\n ((id: number | string, context: { platform: string; environment?: string }): number | string =>\n id)) as (\n id: number | string,\n context: { platform: string; environment?: string }\n ) => number | string;\n\n // We're manually resolving the `asyncRequireModulePath` since it's a module request\n // However, in isolated installations it might not resolve from all paths, so we're resolving\n // it from the project root manually\n let _asyncRequireModuleResolvedPath: string | null | undefined;\n const getAsyncRequireModule = () => {\n if (_asyncRequireModuleResolvedPath === undefined) {\n _asyncRequireModuleResolvedPath =\n resolveFrom.silent(config.projectRoot, config.transformer.asyncRequireModulePath) ?? null;\n }\n return _asyncRequireModuleResolvedPath\n ? ({ type: 'sourceFile', filePath: _asyncRequireModuleResolvedPath } as const)\n : null;\n };\n\n const getAssetRegistryModule = () => {\n const virtualModuleId = `\\0polyfill:assets-registry`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n ASSET_REGISTRY_SRC\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n } as const;\n };\n\n // If Node.js pass-through, then remap to a module like `module.exports = $$require_external(<module>)`.\n // If module should be shimmed, remap to an empty module.\n const externals: {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => boolean;\n replace: 'empty' | 'node' | 'weak';\n }[] = [\n {\n match: (context: ResolutionContext, moduleName: string) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for Node.js environments.\n !isServerEnvironment(context.customResolverOptions?.environment)\n ) {\n return false;\n }\n\n if (context.customResolverOptions?.environment === 'react-server') {\n // Ensure these non-react-server modules are excluded when bundling for React Server Components in development.\n return /^(source-map-support(\\/.*)?|@babel\\/runtime\\/.+|debug|metro-runtime\\/src\\/modules\\/HMRClient|metro|acorn-loose|acorn|chalk|ws|ansi-styles|supports-color|color-convert|has-flag|utf-8-validate|color-name|react-refresh\\/runtime|@remix-run\\/node\\/.+)$/.test(\n moduleName\n );\n }\n\n // TODO: Windows doesn't support externals somehow.\n if (process.platform === 'win32') {\n return /^(source-map-support(\\/.*)?)$/.test(moduleName);\n }\n\n // Extern these modules in standard Node.js environments in development to prevent API routes side-effects\n // from leaking into the dev server process.\n return /^(source-map-support(\\/.*)?|react|@radix-ui\\/.+|@babel\\/runtime\\/.+|react-dom(\\/.+)?|debug|acorn-loose|acorn|css-in-js-utils\\/lib\\/.+|hyphenate-style-name|color|color-string|color-convert|color-name|fontfaceobserver|fast-deep-equal|query-string|escape-string-regexp|invariant|postcss-value-parser|memoize-one|nullthrows|strict-uri-encode|decode-uri-component|split-on-first|filter-obj|warn-once|simple-swizzle|is-arrayish|inline-style-prefixer\\/.+)$/.test(\n moduleName\n );\n },\n replace: 'node',\n },\n // Externals to speed up async split chunks by extern-ing common packages that appear in the root client chunk.\n {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for client environments.\n isServerEnvironment(context.customResolverOptions?.environment) ||\n // Only enable for client boundaries\n !context.customResolverOptions.clientboundary\n ) {\n return false;\n }\n\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return false;\n }\n\n const isExternal = // Extern these modules in standard Node.js environments.\n /^(deprecated-react-native-prop-types|react|react\\/jsx-dev-runtime|scheduler|react-native|react-dom(\\/.+)?|metro-runtime(\\/.+)?)$/.test(\n moduleName\n ) ||\n // TODO: Add more\n /^@babel\\/runtime\\/helpers\\/(wrapNativeSuper)$/.test(moduleName);\n\n return isExternal;\n },\n replace: 'weak',\n },\n ];\n\n const metroConfigWithCustomResolver = withMetroResolvers(config, [\n // Mock out production react imports in development.\n function requestDevMockProdReact(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // This resolution is dev-only to prevent bundling the production React packages in development.\n if (!context.dev) return null;\n\n if (\n // Match react-native renderers.\n (platform !== 'web' &&\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/]react-native[\\\\/]/) &&\n moduleName.match(/([\\\\/]ReactFabric|ReactNativeRenderer)-prod/)) ||\n // Match react production imports.\n (moduleName.match(/\\.production(\\.min)?\\.js$/) &&\n // Match if the import originated from a react package.\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/](react[-\\\\/]|scheduler[\\\\/])/))\n ) {\n debug(`Skipping production module: ${moduleName}`);\n // /Users/path/to/expo/node_modules/react/index.js ./cjs/react.production.min.js\n // /Users/path/to/expo/node_modules/react/jsx-dev-runtime.js ./cjs/react-jsx-dev-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n // /Users/path/to/expo/node_modules/react-refresh/runtime.js ./cjs/react-refresh-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/scheduler/index.native.js ./cjs/scheduler.native.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n return {\n type: 'empty',\n };\n }\n return null;\n },\n // tsconfig paths\n function requestTsconfigPaths(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n return (\n tsConfigResolve?.(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n getOptionalResolver(context, platform)\n ) ?? null\n );\n },\n\n // Node.js externals support\n function requestNodeExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n const moduleId = isNodeExternal(moduleName);\n if (!moduleId) {\n return null;\n }\n\n if (\n // In browser runtimes, we want to either resolve a local node module by the same name, or shim the module to\n // prevent crashing when Node.js built-ins are imported.\n !isServer\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\n if (!result && platform !== 'web') {\n // Preserve previous behavior where native throws an error on node.js internals.\n return null;\n }\n\n return (\n result ?? {\n // In this case, mock the file to use an empty module.\n type: 'empty',\n }\n );\n }\n const contents = `module.exports=$$require_external('node:${moduleId}');`;\n debug(`Virtualizing Node.js \"${moduleId}\"`);\n const virtualModuleId = `\\0node:${moduleId}`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n },\n\n // Custom externals support\n function requestCustomExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return null;\n }\n // Skip applying JS externals for CSS files.\n if (/\\.(s?css|sass)$/.test(context.originModulePath)) {\n return null;\n }\n\n for (const external of externals) {\n if (external.match(context, moduleName, platform)) {\n if (external.replace === 'empty') {\n debug(`Redirecting external \"${moduleName}\" to \"${external.replace}\"`);\n return {\n type: external.replace,\n };\n } else if (external.replace === 'weak') {\n // TODO: Make this use require.resolveWeak again. Previously this was just resolving to the same path.\n const realModule = getStrictResolver(context, platform)(moduleName);\n const realPath = realModule.type === 'sourceFile' ? realModule.filePath : moduleName;\n const opaqueId = idFactory(realPath, {\n platform: platform!,\n environment: context.customResolverOptions?.environment,\n });\n const contents =\n typeof opaqueId === 'number'\n ? `module.exports=/*${moduleName}*/__r(${opaqueId})`\n : `module.exports=/*${moduleName}*/__r(${JSON.stringify(opaqueId)})`;\n // const contents = `module.exports=/*${moduleName}*/__r(require.resolveWeak('${moduleName}'))`;\n // const generatedModuleId = fastHashMemoized(contents);\n const virtualModuleId = `\\0weak:${opaqueId}`;\n debug('Virtualizing module:', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else if (external.replace === 'node') {\n // TODO(@kitten): Temporary workaround. Our externals logic here isn't generic and only works\n // for development and not exports. We never intend to use it in exported production bundles,\n // however, this is still a dangerous implementation. To protect us from externalizing modules\n // that aren't available to the app, we force any resolution to happen via the project root\n const projectRootContext: ResolutionContext = {\n ...context,\n nodeModulesPaths: [],\n originModulePath: projectRootOriginPath,\n disableHierarchicalLookup: false,\n };\n const externModule = getStrictResolver(projectRootContext, platform)(moduleName);\n if (externModule.type !== 'sourceFile') {\n return null;\n }\n const contents = `module.exports=$$require_external('${moduleName}')`;\n const virtualModuleId = `\\0node:${moduleName}`;\n debug('Virtualizing Node.js (custom):', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else {\n external.replace satisfies never;\n }\n }\n }\n return null;\n },\n\n // Basic moduleId aliases\n function requestAlias(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 return getStrictResolver(context, platform)(redirectedModuleName);\n }\n\n for (const [matcher, alias] of getUniversalAliases()) {\n const match = moduleName.match(matcher);\n if (match) {\n const aliasedModule = alias.replace(\n /\\$(\\d+)/g,\n (_, index) => match[parseInt(index, 10)] ?? ''\n );\n const doResolve = getStrictResolver(context, platform);\n debug(`Alias \"${moduleName}\" to \"${aliasedModule}\"`);\n return doResolve(aliasedModule);\n }\n }\n\n return null;\n },\n\n // Polyfill for asset registry (assetRegistryPath) and async require module (asyncRequireModulePath)\n function requestStableConfigModules(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n if (moduleName === config.transformer.asyncRequireModulePath) {\n return getAsyncRequireModule();\n }\n\n // TODO(@kitten): Compare against `config.transformer.assetRegistryPath`\n if (/^@react-native\\/assets-registry\\/registry(\\.js)?$/.test(moduleName)) {\n return getAssetRegistryModule();\n }\n\n if (\n platform === 'web' &&\n context.originModulePath.match(/node_modules[\\\\/]react-native-web[\\\\/]/) &&\n moduleName.includes('/modules/AssetRegistry')\n ) {\n return getAssetRegistryModule();\n }\n\n return null;\n },\n\n createAutolinkingModuleResolver(autolinkingModuleResolverInput, {\n getStrictResolver,\n }),\n\n // TODO: Reduce these as much as possible in the future.\n // Complex post-resolution rewrites.\n function requestPostRewrites(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const doResolve = getStrictResolver(context, platform);\n\n const result = doResolve(moduleName);\n\n if (result.type !== 'sourceFile') {\n return result;\n }\n\n const normalizedPath = normalizeSlashes(result.filePath);\n\n const doReplace = (from: string, to: string | undefined, options?: { throws?: boolean }) =>\n doReplaceHelper(from, to, {\n normalizedPath,\n doResolve,\n ...options,\n });\n const doReplaceStrict = (from: string, to: string | undefined) =>\n doReplace(from, to, { throws: true });\n\n if (env.EXPO_UNSTABLE_WEB_MODAL) {\n const webModalModule = doReplace(\n 'expo-router/build/layouts/_web-modal.js',\n 'expo-router/build/layouts/ExperimentalModalStack.js'\n );\n if (webModalModule) {\n debug('Using `_unstable-web-modal` implementation.');\n return webModalModule;\n }\n }\n\n if (platform === 'web') {\n if (result.filePath.includes('node_modules')) {\n // Disallow importing confusing native modules on web\n if (\n [\n 'react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore',\n 'react-native/Libraries/Utilities/codegenNativeCommands',\n 'react-native/Libraries/Utilities/codegenNativeComponent',\n ].some((matcher) =>\n // Support absolute and modules with .js extensions.\n moduleName.includes(matcher)\n )\n ) {\n throw new FailedToResolveNativeOnlyModuleError(\n moduleName,\n path.relative(config.projectRoot, context.originModulePath)\n );\n }\n\n // Replace with static shims\n\n // Drop everything up until the `node_modules` folder.\n const normalName = normalizedPath.replace(/.*node_modules\\//, '');\n\n const shimFile = shouldCreateVirtualShim(normalName);\n if (shimFile) {\n const virtualId = `\\0shim:${normalName}`;\n const bundler = getMetroBundlerWithVirtualModules(getMetroBundler());\n if (!bundler.hasVirtualModule(virtualId)) {\n bundler.setVirtualModule(virtualId, fs.readFileSync(shimFile, 'utf8'));\n }\n debug(`Redirecting module \"${result.filePath}\" to shim`);\n\n return {\n ...result,\n filePath: virtualId,\n };\n }\n }\n } else {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n // Shim out React Native native runtime globals in server mode for native.\n if (isServer) {\n const emptyModule = doReplace('react-native/Libraries/Core/InitializeCore.js', undefined);\n if (emptyModule) {\n debug('Shimming out InitializeCore for React Native in native SSR bundle');\n return emptyModule;\n }\n }\n\n const hmrModule = doReplaceStrict(\n 'react-native/Libraries/Utilities/HMRClient.js',\n 'expo/src/async-require/hmr.ts'\n );\n if (hmrModule) return hmrModule;\n\n if (env.EXPO_UNSTABLE_LOG_BOX) {\n const logBoxModule = doReplace(\n 'react-native/Libraries/LogBox/LogBoxInspectorContainer.js',\n '@expo/log-box/swap-rn-logbox.js'\n );\n if (logBoxModule) return logBoxModule;\n\n const logBoxParserModule = doReplace(\n 'react-native/Libraries/LogBox/Data/parseLogBoxLog.js',\n '@expo/log-box/swap-rn-logbox-parser.js'\n );\n if (logBoxParserModule) return logBoxParserModule;\n }\n }\n\n return result;\n },\n\n // If at this point, we haven't resolved a module yet, if it's a module specifier for a known dependency\n // of either `expo` or `expo-router`, attempt to resolve it from these origin modules instead\n createFallbackModuleResolver({\n projectRoot: config.projectRoot,\n originModuleNames: ['expo', 'expo-router'],\n getStrictResolver,\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 = asWritable({\n ...immutableContext,\n preferNativePlatform: platform !== 'web',\n });\n\n if (isServerEnvironment(context.customResolverOptions?.environment)) {\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_conditionsByPlatform = {};\n\n const isReactServerComponents =\n context.customResolverOptions?.environment === 'react-server';\n\n if (isReactServerComponents) {\n // NOTE: Align the behavior across server and client. This is a breaking change so we'll just roll it out with React Server Components.\n // This ensures that react-server and client code both resolve `module` and `main` in the same order.\n if (platform === 'web') {\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 = ['module', 'main'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'module', 'main'];\n }\n } else {\n if (platform === 'web') {\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 // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'main', 'module'];\n }\n }\n\n // Enable react-server import conditions.\n if (context.customResolverOptions?.environment === 'react-server') {\n context.unstable_conditionNames = ['node', 'react-server', 'workerd'];\n } else {\n context.unstable_conditionNames = ['node'];\n }\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 return context;\n }\n );\n\n return withMetroErrorReportingResolver(\n withMetroSupervisingTransformWorker(metroConfigWithCustomContext)\n );\n}\n\nfunction doReplaceHelper(\n from: string,\n to: string | undefined,\n {\n throws = false,\n normalizedPath,\n doResolve,\n }: {\n throws?: boolean;\n normalizedPath: string;\n doResolve: StrictResolver;\n }\n): SourceFileResolution | { type: 'empty' } | undefined {\n if (!normalizedPath.endsWith(from)) {\n return undefined;\n }\n\n if (to === undefined) {\n return {\n type: 'empty',\n };\n }\n\n try {\n const hmrModule = doResolve(to);\n if (hmrModule.type === 'sourceFile') {\n debug(`Using \\`${to}\\` implementation.`);\n return hmrModule;\n }\n } catch (resolutionError) {\n if (throws) {\n throw new Error(`Failed to replace ${from} with ${to}. Resolution of ${to} failed.`, {\n cause: resolutionError,\n });\n }\n\n debug(`Failed to resolve ${to} when swapping from ${from}: ${resolutionError}`);\n }\n return undefined;\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 exp,\n platformBundlers,\n isTsconfigPathsEnabled,\n isAutolinkingResolverEnabled,\n isExporting,\n\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n config: ConfigT;\n exp: ExpoConfig;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n isAutolinkingResolverEnabled?: boolean;\n isExporting?: boolean;\n\n isReactServerComponentsEnabled: boolean;\n isNamedRequiresEnabled: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n // Change the default metro-runtime to a custom one that supports bundle splitting.\n // NOTE(@kitten): This is now always active and EXPO_USE_METRO_REQUIRE / isNamedRequiresEnabled is disregarded\n const metroDefaults: typeof import('@expo/metro/metro-config/defaults/defaults') = require('@expo/metro/metro-config/defaults/defaults');\n asWritable(metroDefaults).moduleSystem = require.resolve('@expo/cli/build/metro-require/require');\n\n if (!config.projectRoot) {\n asWritable(config).projectRoot = projectRoot;\n }\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 // This is used for running Expo CLI in development against projects outside the monorepo.\n if (!isDirectoryIn(__dirname, projectRoot)) {\n const watchFolders = (config.watchFolders as string[]) || [];\n asWritable(config).watchFolders = watchFolders;\n\n watchFolders.push(path.join(require.resolve('metro-runtime/package.json'), '../..'));\n watchFolders.push(\n path.join(require.resolve('@expo/metro-config/package.json'), '../..'),\n // For virtual modules\n path.join(require.resolve('expo/package.json'), '..')\n );\n }\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(\n ([platform, bundler]) => bundler === 'metro' && exp.platforms?.includes(platform as Platform)\n )\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n asWritable(config.resolver).platforms = expoConfigPlatforms;\n\n config = withWebPolyfills(config, { getMetroBundler });\n\n let autolinkingModuleResolverInput: AutolinkingModuleResolverInput | undefined;\n if (isAutolinkingResolverEnabled) {\n autolinkingModuleResolverInput = await createAutolinkingModuleResolverInput({\n platforms: expoConfigPlatforms,\n projectRoot,\n });\n }\n\n return withExtendedResolver(config, {\n autolinkingModuleResolverInput,\n tsconfig,\n isExporting,\n isTsconfigPathsEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n });\n}\n\nfunction isDirectoryIn(targetPath: string, rootPath: string) {\n return targetPath.startsWith(rootPath) && targetPath.length >= rootPath.length;\n}\n"],"names":["getNodejsExtensions","shouldAliasModule","withExtendedResolver","withMetroMultiPlatformAsync","ASSET_REGISTRY_SRC","debug","require","asWritable","input","withWebPolyfills","config","getMetroBundler","originalGetPolyfills","serializer","getPolyfills","bind","ctx","virtualEnvVarId","getMetroBundlerWithVirtualModules","setVirtualModule","virtualModuleId","platform","virtualModulesPolyfills","rnGetPolyfills","filter","x","includes","error","code","polyfills","resolve","normalizeSlashes","p","replace","srcExts","mjsExts","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","autolinkingModuleResolverInput","isTsconfigPathsEnabled","isExporting","isReactServerComponentsEnabled","Log","warn","aliases","web","_universalAliases","getUniversalAliases","resolveFrom","silent","projectRoot","push","projectRootOriginPath","path","join","preferredMainFields","tsConfigResolve","paths","baseUrl","resolveWithTsConfigPaths","hasBaseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","getStrictResolver","resolveRequest","context","doResolve","moduleName","resolver","getOptionalResolver","optionalResolve","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","idFactory","createModuleIdFactory","id","_asyncRequireModuleResolvedPath","getAsyncRequireModule","undefined","transformer","asyncRequireModulePath","type","filePath","getAssetRegistryModule","externals","match","customResolverOptions","exporting","isServerEnvironment","environment","process","clientboundary","endsWith","isExternal","metroConfigWithCustomResolver","withMetroResolvers","requestDevMockProdReact","dev","originModulePath","requestTsconfigPaths","requestNodeExternals","isServer","moduleId","isNodeExternal","result","contents","requestCustomExternals","external","realModule","realPath","opaqueId","JSON","stringify","projectRootContext","nodeModulesPaths","disableHierarchicalLookup","externModule","requestAlias","redirectedModuleName","matcher","alias","aliasedModule","_","parseInt","requestStableConfigModules","createAutolinkingModuleResolver","requestPostRewrites","normalizedPath","doReplace","from","to","options","doReplaceHelper","doReplaceStrict","throws","env","EXPO_UNSTABLE_WEB_MODAL","webModalModule","some","FailedToResolveNativeOnlyModuleError","relative","normalName","shimFile","shouldCreateVirtualShim","virtualId","bundler","hasVirtualModule","fs","readFileSync","emptyModule","hmrModule","EXPO_UNSTABLE_LOG_BOX","logBoxModule","logBoxParserModule","createFallbackModuleResolver","originModuleNames","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","sourceExts","unstable_enablePackageExports","unstable_conditionsByPlatform","isReactServerComponents","mainFields","unstable_conditionNames","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","withMetroSupervisingTransformWorker","resolutionError","Error","cause","output","exp","platformBundlers","isAutolinkingResolverEnabled","metroDefaults","moduleSystem","EXPO_PUBLIC_PROJECT_ROOT","isDirectoryIn","__dirname","watchFolders","expoConfigPlatforms","entries","platforms","map","Array","isArray","Set","concat","createAutolinkingModuleResolverInput","targetPath","rootPath","startsWith"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IA2IeA,mBAAmB;eAAnBA;;IA6tBAC,iBAAiB;eAAjBA;;IAxsBAC,oBAAoB;eAApBA;;IAwtBMC,2BAA2B;eAA3BA;;;;yBA/2Bc;;;;;;;gEAErB;;;;;;;gEACE;;;;;;;gEACO;;;;;;+CAMjB;4CACsC;sDACQ;2BACG;6BACe;qCACrB;iDACF;oCACoB;qDAChB;qBAChC;8BACS;qBACT;sBACa;6BACH;mCACwB;0CACb;8BACL;;;;;;AASpC,MAAMC,qBAAqB,CAAC,6FAA6F,CAAC;AAE1H,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,SAASC,WAAcC,KAAQ;IAC7B,OAAOA;AACT;AAEA,SAASC,iBACPC,MAAe,EACf,EACEC,eAAe,EAGhB;IAED,MAAMC,uBAAuBF,OAAOG,UAAU,CAACC,YAAY,GACvDJ,OAAOG,UAAU,CAAC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AQ;QAAEC;IAAgB;IAEpD,IAAIkC;IACJ,IAAIoJ,8BAA8B;QAChCpJ,iCAAiC,MAAMmK,IAAAA,mEAAoC,EAAC;YAC1EN,WAAWF;YACX/I;QACF;IACF;IAEA,OAAOvD,qBAAqBQ,QAAQ;QAClCmC;QACAD;QACAG;QACAD;QACAE;QACArC;IACF;AACF;AAEA,SAAS0L,cAAcY,UAAkB,EAAEC,QAAgB;IACzD,OAAOD,WAAWE,UAAU,CAACD,aAAaD,WAAWpI,MAAM,IAAIqI,SAASrI,MAAM;AAChF"}
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 type { ExpoConfig, Platform } from '@expo/config';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ConfigT } from '@expo/metro/metro-config';\nimport type {\n Resolution,\n ResolutionContext,\n CustomResolutionContext,\n} from '@expo/metro/metro-resolver';\nimport { resolve as resolver } from '@expo/metro/metro-resolver';\nimport type { SourceFileResolution } from '@expo/metro/metro-resolver/types';\nimport fs from 'fs';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport {\n createAutolinkingModuleResolverInput,\n createAutolinkingModuleResolver,\n AutolinkingModuleResolverInput,\n} from './createExpoAutolinkingResolver';\nimport { createFallbackModuleResolver } from './createExpoFallbackResolver';\nimport { FailedToResolveNativeOnlyModuleError } from './errors/FailedToResolveNativeOnlyModuleError';\nimport { isNodeExternal, shouldCreateVirtualShim } from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { getMetroBundlerWithVirtualModules } from './metroVirtualModules';\nimport { withMetroErrorReportingResolver } from './withMetroErrorReportingResolver';\nimport { withMetroMutatedResolverContext, withMetroResolvers } from './withMetroResolvers';\nimport { withMetroSupervisingTransformWorker } from './withMetroSupervisingTransformWorker';\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 { isServerEnvironment } from '../middleware/metroOptions';\nimport { PlatformBundlers } from '../platformBundlers';\n\nexport type StrictResolver = (moduleName: string) => Resolution;\nexport type StrictResolverFactory = (\n context: ResolutionContext,\n platform: string | null\n) => StrictResolver;\n\nconst ASSET_REGISTRY_SRC = `const assets=[];module.exports={registerAsset:s=>assets.push(s),getAssetByID:s=>assets[s-1]};`;\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\n\nfunction withWebPolyfills(\n config: ConfigT,\n {\n getMetroBundler,\n }: {\n getMetroBundler: () => Bundler;\n }\n): 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 const virtualEnvVarId = `\\0polyfill:environment-variables`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualEnvVarId,\n (() => {\n return `//`;\n })()\n );\n\n const virtualModuleId = `\\0polyfill:external-require`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n (() => {\n if (ctx.platform === 'web') {\n // NOTE(@hassankhan): We need to wrap require in an arrow function rather than assigning\n // it directly because `workerd` loses its `this` context when `require` is dereferenced\n // and called later.\n return `global.$$require_external = typeof require !== \"undefined\" ? (m) => require(m) : () => null;`;\n } else {\n // Wrap in try/catch to support Android.\n return 'try { global.$$require_external = typeof expo === \"undefined\" ? require : (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} } catch { global.$$require_external = (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} }';\n }\n })()\n );\n\n const virtualModulesPolyfills = [virtualModuleId, virtualEnvVarId];\n\n if (ctx.platform === 'web') {\n try {\n const rnGetPolyfills: () => string[] = require('react-native/rn-get-polyfills');\n return [\n ...virtualModulesPolyfills,\n // Ensure that the error-guard polyfill is included in the web polyfills to\n // make metro-runtime work correctly.\n // TODO: This module is pretty big for a function that simply re-throws an error that doesn't need to be caught.\n // NOTE(@kitten): This is technically the public API to get polyfills rather than resolving directly into\n // `@react-native/js-polyfills`. We should really just start vendoring these, but for now, this exclusion works\n ...rnGetPolyfills().filter((x: string) => !x.includes('/console')),\n ];\n } catch (error: any) {\n if ('code' in error && error.code === 'MODULE_NOT_FOUND') {\n // If react-native is not installed, because we're targeting web, we still continue\n // This should be rare, but we add it so we don't unnecessarily have a fixed peer dependency on react-native\n debug(\n 'Skipping react-native/rn-get-polyfills from getPolyfills. react-native is not installed.'\n );\n return virtualModulesPolyfills;\n } else {\n throw error;\n }\n }\n }\n\n // Generally uses `@expo/metro-config`'s `getPolyfills` function, unless overridden\n const polyfills = originalGetPolyfills(ctx);\n return [\n ...polyfills,\n ...virtualModulesPolyfills,\n // Removed on server platforms during the transform.\n require.resolve('expo/virtual/streams.js'),\n ];\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 autolinkingModuleResolverInput,\n isTsconfigPathsEnabled,\n isExporting,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n tsconfig: TsConfigPaths | null;\n autolinkingModuleResolverInput?: AutolinkingModuleResolverInput;\n isTsconfigPathsEnabled?: boolean;\n isExporting?: boolean;\n isReactServerComponentsEnabled?: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isReactServerComponentsEnabled) {\n Log.warn(`React Server Components (beta) is enabled.`);\n }\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 'react-native/Libraries/Image/resolveAssetSource': 'expo-asset/build/resolveAssetSource',\n },\n };\n\n let _universalAliases: [RegExp, string][] | null;\n\n function getUniversalAliases() {\n if (_universalAliases) {\n return _universalAliases;\n }\n\n _universalAliases = [];\n\n // This package is currently always installed as it is included in the `expo` package.\n if (resolveFrom.silent(config.projectRoot, '@expo/vector-icons')) {\n debug('Enabling alias: react-native-vector-icons -> @expo/vector-icons');\n _universalAliases.push([/^react-native-vector-icons(\\/.*)?/, '@expo/vector-icons$1']);\n }\n if (isReactServerComponentsEnabled) {\n if (resolveFrom.silent(config.projectRoot, 'expo-router/rsc')) {\n debug('Enabling bridge alias: expo-router -> expo-router/rsc');\n _universalAliases.push([/^expo-router$/, 'expo-router/rsc']);\n // Bridge the internal entry point which is a standalone import to ensure package.json resolution works as expected.\n _universalAliases.push([/^expo-router\\/entry-classic$/, 'expo-router/rsc/entry']);\n }\n }\n return _universalAliases;\n }\n\n // used to resolve externals in `requestCustomExternals` from the project root\n const projectRootOriginPath = path.join(config.projectRoot, 'package.json');\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 =\n isTsconfigPathsEnabled && (tsconfig?.paths || tsconfig?.baseUrl != null)\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!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 ?? config.projectRoot,\n hasBaseUrl: !!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 getStrictResolver: StrictResolverFactory = (\n { resolveRequest, ...context },\n platform\n ): StrictResolver => {\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 // TODO: This is a hack to get resolveWeak working.\n const idFactory = (config.serializer?.createModuleIdFactory?.() ??\n ((id: number | string, context: { platform: string; environment?: string }): number | string =>\n id)) as (\n id: number | string,\n context: { platform: string; environment?: string }\n ) => number | string;\n\n // We're manually resolving the `asyncRequireModulePath` since it's a module request\n // However, in isolated installations it might not resolve from all paths, so we're resolving\n // it from the project root manually\n let _asyncRequireModuleResolvedPath: string | null | undefined;\n const getAsyncRequireModule = () => {\n if (_asyncRequireModuleResolvedPath === undefined) {\n _asyncRequireModuleResolvedPath =\n resolveFrom.silent(config.projectRoot, config.transformer.asyncRequireModulePath) ?? null;\n }\n return _asyncRequireModuleResolvedPath\n ? ({ type: 'sourceFile', filePath: _asyncRequireModuleResolvedPath } as const)\n : null;\n };\n\n const getAssetRegistryModule = () => {\n const virtualModuleId = `\\0polyfill:assets-registry`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n ASSET_REGISTRY_SRC\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n } as const;\n };\n\n // If Node.js pass-through, then remap to a module like `module.exports = $$require_external(<module>)`.\n // If module should be shimmed, remap to an empty module.\n const externals: {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => boolean;\n replace: 'empty' | 'node' | 'weak';\n }[] = [\n {\n match: (context: ResolutionContext, moduleName: string) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for Node.js environments.\n !isServerEnvironment(context.customResolverOptions?.environment)\n ) {\n return false;\n }\n\n if (context.customResolverOptions?.environment === 'react-server') {\n // Ensure these non-react-server modules are excluded when bundling for React Server Components in development.\n return /^(source-map-support(\\/.*)?|@babel\\/runtime\\/.+|debug|metro-runtime\\/src\\/modules\\/HMRClient|metro|acorn-loose|acorn|chalk|ws|ansi-styles|supports-color|color-convert|has-flag|utf-8-validate|color-name|react-refresh\\/runtime|@remix-run\\/node\\/.+)$/.test(\n moduleName\n );\n }\n\n // TODO: Windows doesn't support externals somehow.\n if (process.platform === 'win32') {\n return /^(source-map-support(\\/.*)?)$/.test(moduleName);\n }\n\n // Extern these modules in standard Node.js environments in development to prevent API routes side-effects\n // from leaking into the dev server process.\n return /^(source-map-support(\\/.*)?|react|@radix-ui\\/.+|@babel\\/runtime\\/.+|react-dom(\\/.+)?|debug|acorn-loose|acorn|css-in-js-utils\\/lib\\/.+|hyphenate-style-name|color|color-string|color-convert|color-name|fontfaceobserver|fast-deep-equal|query-string|escape-string-regexp|invariant|postcss-value-parser|memoize-one|nullthrows|strict-uri-encode|decode-uri-component|split-on-first|filter-obj|warn-once|simple-swizzle|is-arrayish|inline-style-prefixer\\/.+)$/.test(\n moduleName\n );\n },\n replace: 'node',\n },\n // Externals to speed up async split chunks by extern-ing common packages that appear in the root client chunk.\n {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for client environments.\n isServerEnvironment(context.customResolverOptions?.environment) ||\n // Only enable for client boundaries\n !context.customResolverOptions.clientboundary\n ) {\n return false;\n }\n\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return false;\n }\n\n const isExternal = // Extern these modules in standard Node.js environments.\n /^(deprecated-react-native-prop-types|react|react\\/jsx-dev-runtime|scheduler|react-native|react-dom(\\/.+)?|metro-runtime(\\/.+)?)$/.test(\n moduleName\n ) ||\n // TODO: Add more\n /^@babel\\/runtime\\/helpers\\/(wrapNativeSuper)$/.test(moduleName);\n\n return isExternal;\n },\n replace: 'weak',\n },\n ];\n\n const metroConfigWithCustomResolver = withMetroResolvers(config, [\n // Mock out production react imports in development.\n function requestDevMockProdReact(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // This resolution is dev-only to prevent bundling the production React packages in development.\n if (!context.dev) return null;\n\n if (\n // Match react-native renderers.\n (platform !== 'web' &&\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/]react-native[\\\\/]/) &&\n moduleName.match(/([\\\\/]ReactFabric|ReactNativeRenderer)-prod/)) ||\n // Match react production imports.\n (moduleName.match(/\\.production(\\.min)?\\.js$/) &&\n // Match if the import originated from a react package.\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/](react[-\\\\/]|scheduler[\\\\/])/))\n ) {\n debug(`Skipping production module: ${moduleName}`);\n // /Users/path/to/expo/node_modules/react/index.js ./cjs/react.production.min.js\n // /Users/path/to/expo/node_modules/react/jsx-dev-runtime.js ./cjs/react-jsx-dev-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n // /Users/path/to/expo/node_modules/react-refresh/runtime.js ./cjs/react-refresh-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/scheduler/index.native.js ./cjs/scheduler.native.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n return {\n type: 'empty',\n };\n }\n return null;\n },\n // tsconfig paths\n function requestTsconfigPaths(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n return (\n tsConfigResolve?.(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n getOptionalResolver(context, platform)\n ) ?? null\n );\n },\n\n // Node.js externals support\n function requestNodeExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n const moduleId = isNodeExternal(moduleName);\n if (!moduleId) {\n return null;\n }\n\n if (\n // In browser runtimes, we want to either resolve a local node module by the same name, or shim the module to\n // prevent crashing when Node.js built-ins are imported.\n !isServer\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\n if (!result && platform !== 'web') {\n // Preserve previous behavior where native throws an error on node.js internals.\n return null;\n }\n\n return (\n result ?? {\n // In this case, mock the file to use an empty module.\n type: 'empty',\n }\n );\n }\n const contents = `module.exports=$$require_external('node:${moduleId}');`;\n debug(`Virtualizing Node.js \"${moduleId}\"`);\n const virtualModuleId = `\\0node:${moduleId}`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n },\n\n // Custom externals support\n function requestCustomExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return null;\n }\n // Skip applying JS externals for CSS files.\n if (/\\.(s?css|sass)$/.test(context.originModulePath)) {\n return null;\n }\n\n for (const external of externals) {\n if (external.match(context, moduleName, platform)) {\n if (external.replace === 'empty') {\n debug(`Redirecting external \"${moduleName}\" to \"${external.replace}\"`);\n return {\n type: external.replace,\n };\n } else if (external.replace === 'weak') {\n // TODO: Make this use require.resolveWeak again. Previously this was just resolving to the same path.\n const realModule = getStrictResolver(context, platform)(moduleName);\n const realPath = realModule.type === 'sourceFile' ? realModule.filePath : moduleName;\n const opaqueId = idFactory(realPath, {\n platform: platform!,\n environment: context.customResolverOptions?.environment,\n });\n const contents =\n typeof opaqueId === 'number'\n ? `module.exports=/*${moduleName}*/__r(${opaqueId})`\n : `module.exports=/*${moduleName}*/__r(${JSON.stringify(opaqueId)})`;\n // const contents = `module.exports=/*${moduleName}*/__r(require.resolveWeak('${moduleName}'))`;\n // const generatedModuleId = fastHashMemoized(contents);\n const virtualModuleId = `\\0weak:${opaqueId}`;\n debug('Virtualizing module:', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else if (external.replace === 'node') {\n // TODO(@kitten): Temporary workaround. Our externals logic here isn't generic and only works\n // for development and not exports. We never intend to use it in exported production bundles,\n // however, this is still a dangerous implementation. To protect us from externalizing modules\n // that aren't available to the app, we force any resolution to happen via the project root\n const projectRootContext: ResolutionContext = {\n ...context,\n nodeModulesPaths: [],\n originModulePath: projectRootOriginPath,\n disableHierarchicalLookup: false,\n };\n const externModule = getStrictResolver(projectRootContext, platform)(moduleName);\n if (externModule.type !== 'sourceFile') {\n return null;\n }\n const contents = `module.exports=$$require_external('${moduleName}')`;\n const virtualModuleId = `\\0node:${moduleName}`;\n debug('Virtualizing Node.js (custom):', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else {\n external.replace satisfies never;\n }\n }\n }\n return null;\n },\n\n // Basic moduleId aliases\n function requestAlias(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 return getStrictResolver(context, platform)(redirectedModuleName);\n }\n\n for (const [matcher, alias] of getUniversalAliases()) {\n const match = moduleName.match(matcher);\n if (match) {\n const aliasedModule = alias.replace(\n /\\$(\\d+)/g,\n (_, index) => match[parseInt(index, 10)] ?? ''\n );\n const doResolve = getStrictResolver(context, platform);\n debug(`Alias \"${moduleName}\" to \"${aliasedModule}\"`);\n return doResolve(aliasedModule);\n }\n }\n\n return null;\n },\n\n // Polyfill for asset registry (assetRegistryPath) and async require module (asyncRequireModulePath)\n function requestStableConfigModules(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n if (moduleName === config.transformer.asyncRequireModulePath) {\n return getAsyncRequireModule();\n }\n\n // TODO(@kitten): Compare against `config.transformer.assetRegistryPath`\n if (/^@react-native\\/assets-registry\\/registry(\\.js)?$/.test(moduleName)) {\n return getAssetRegistryModule();\n }\n\n if (\n platform === 'web' &&\n context.originModulePath.match(/node_modules[\\\\/]react-native-web[\\\\/]/) &&\n moduleName.includes('/modules/AssetRegistry')\n ) {\n return getAssetRegistryModule();\n }\n\n return null;\n },\n\n createAutolinkingModuleResolver(autolinkingModuleResolverInput, {\n getStrictResolver,\n }),\n\n // TODO: Reduce these as much as possible in the future.\n // Complex post-resolution rewrites.\n function requestPostRewrites(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const doResolve = getStrictResolver(context, platform);\n\n const result = doResolve(moduleName);\n\n if (result.type !== 'sourceFile') {\n return result;\n }\n\n const normalizedPath = normalizeSlashes(result.filePath);\n\n const doReplace = (from: string, to: string | undefined, options?: { throws?: boolean }) =>\n doReplaceHelper(from, to, {\n normalizedPath,\n doResolve,\n ...options,\n });\n const doReplaceStrict = (from: string, to: string | undefined) =>\n doReplace(from, to, { throws: true });\n\n if (env.EXPO_UNSTABLE_WEB_MODAL) {\n const webModalModule = doReplace(\n 'expo-router/build/layouts/_web-modal.js',\n 'expo-router/build/layouts/ExperimentalModalStack.js'\n );\n if (webModalModule) {\n debug('Using `_unstable-web-modal` implementation.');\n return webModalModule;\n }\n }\n\n if (platform === 'web') {\n if (result.filePath.includes('node_modules')) {\n // Disallow importing confusing native modules on web\n if (\n [\n 'react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore',\n 'react-native/Libraries/Utilities/codegenNativeCommands',\n 'react-native/Libraries/Utilities/codegenNativeComponent',\n ].some((matcher) =>\n // Support absolute and modules with .js extensions.\n moduleName.includes(matcher)\n )\n ) {\n throw new FailedToResolveNativeOnlyModuleError(\n moduleName,\n path.relative(config.projectRoot, context.originModulePath)\n );\n }\n\n // Replace with static shims\n\n // Drop everything up until the `node_modules` folder.\n const normalName = normalizedPath.replace(/.*node_modules\\//, '');\n\n const shimFile = shouldCreateVirtualShim(normalName);\n if (shimFile) {\n const virtualId = `\\0shim:${normalName}`;\n const bundler = getMetroBundlerWithVirtualModules(getMetroBundler());\n if (!bundler.hasVirtualModule(virtualId)) {\n bundler.setVirtualModule(virtualId, fs.readFileSync(shimFile, 'utf8'));\n }\n debug(`Redirecting module \"${result.filePath}\" to shim`);\n\n return {\n ...result,\n filePath: virtualId,\n };\n }\n }\n } else {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n // Shim out React Native native runtime globals in server mode for native.\n if (isServer) {\n const emptyModule = doReplace('react-native/Libraries/Core/InitializeCore.js', undefined);\n if (emptyModule) {\n debug('Shimming out InitializeCore for React Native in native SSR bundle');\n return emptyModule;\n }\n }\n\n const hmrModule = doReplaceStrict(\n 'react-native/Libraries/Utilities/HMRClient.js',\n 'expo/src/async-require/hmr.ts'\n );\n if (hmrModule) return hmrModule;\n\n if (env.EXPO_UNSTABLE_LOG_BOX) {\n const logBoxModule = doReplace(\n 'react-native/Libraries/LogBox/LogBoxInspectorContainer.js',\n '@expo/log-box/swap-rn-logbox.js'\n );\n if (logBoxModule) return logBoxModule;\n\n const logBoxParserModule = doReplace(\n 'react-native/Libraries/LogBox/Data/parseLogBoxLog.js',\n '@expo/log-box/swap-rn-logbox-parser.js'\n );\n if (logBoxParserModule) return logBoxParserModule;\n }\n }\n\n return result;\n },\n\n // If at this point, we haven't resolved a module yet, if it's a module specifier for a known dependency\n // of either `expo` or `expo-router`, attempt to resolve it from these origin modules instead\n createFallbackModuleResolver({\n projectRoot: config.projectRoot,\n originModuleNames: ['expo', 'expo-router'],\n getStrictResolver,\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 = asWritable({\n ...immutableContext,\n preferNativePlatform: platform !== 'web',\n });\n\n if (isServerEnvironment(context.customResolverOptions?.environment)) {\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_conditionsByPlatform = {};\n\n const isReactServerComponents =\n context.customResolverOptions?.environment === 'react-server';\n\n if (isReactServerComponents) {\n // NOTE: Align the behavior across server and client. This is a breaking change so we'll just roll it out with React Server Components.\n // This ensures that react-server and client code both resolve `module` and `main` in the same order.\n if (platform === 'web') {\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 = ['module', 'main'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'module', 'main'];\n }\n } else {\n if (platform === 'web') {\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 // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'main', 'module'];\n }\n }\n\n // Enable react-server import conditions.\n if (context.customResolverOptions?.environment === 'react-server') {\n context.unstable_conditionNames = ['node', 'react-server', 'workerd'];\n } else {\n context.unstable_conditionNames = ['node'];\n }\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 return context;\n }\n );\n\n return withMetroErrorReportingResolver(\n withMetroSupervisingTransformWorker(metroConfigWithCustomContext)\n );\n}\n\nfunction doReplaceHelper(\n from: string,\n to: string | undefined,\n {\n throws = false,\n normalizedPath,\n doResolve,\n }: {\n throws?: boolean;\n normalizedPath: string;\n doResolve: StrictResolver;\n }\n): SourceFileResolution | { type: 'empty' } | undefined {\n if (!normalizedPath.endsWith(from)) {\n return undefined;\n }\n\n if (to === undefined) {\n return {\n type: 'empty',\n };\n }\n\n try {\n const hmrModule = doResolve(to);\n if (hmrModule.type === 'sourceFile') {\n debug(`Using \\`${to}\\` implementation.`);\n return hmrModule;\n }\n } catch (resolutionError) {\n if (throws) {\n throw new Error(`Failed to replace ${from} with ${to}. Resolution of ${to} failed.`, {\n cause: resolutionError,\n });\n }\n\n debug(`Failed to resolve ${to} when swapping from ${from}: ${resolutionError}`);\n }\n return undefined;\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 exp,\n platformBundlers,\n isTsconfigPathsEnabled,\n isAutolinkingResolverEnabled,\n isExporting,\n\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n config: ConfigT;\n exp: ExpoConfig;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n isAutolinkingResolverEnabled?: boolean;\n isExporting?: boolean;\n\n isReactServerComponentsEnabled: boolean;\n isNamedRequiresEnabled: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n // Change the default metro-runtime to a custom one that supports bundle splitting.\n // NOTE(@kitten): This is now always active and EXPO_USE_METRO_REQUIRE / isNamedRequiresEnabled is disregarded\n const metroDefaults: typeof import('@expo/metro/metro-config/defaults/defaults') = require('@expo/metro/metro-config/defaults/defaults');\n asWritable(metroDefaults).moduleSystem = require.resolve('@expo/cli/build/metro-require/require');\n\n if (!config.projectRoot) {\n asWritable(config).projectRoot = projectRoot;\n }\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 // This is used for running Expo CLI in development against projects outside the monorepo.\n if (!isDirectoryIn(__dirname, projectRoot)) {\n const watchFolders = (config.watchFolders as string[]) || [];\n asWritable(config).watchFolders = watchFolders;\n\n watchFolders.push(path.join(require.resolve('metro-runtime/package.json'), '../..'));\n watchFolders.push(\n path.join(require.resolve('@expo/metro-config/package.json'), '../..'),\n // For virtual modules\n path.join(require.resolve('expo/package.json'), '..')\n );\n }\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(\n ([platform, bundler]) => bundler === 'metro' && exp.platforms?.includes(platform as Platform)\n )\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n asWritable(config.resolver).platforms = expoConfigPlatforms;\n\n config = withWebPolyfills(config, { getMetroBundler });\n\n let autolinkingModuleResolverInput: AutolinkingModuleResolverInput | undefined;\n if (isAutolinkingResolverEnabled) {\n autolinkingModuleResolverInput = await createAutolinkingModuleResolverInput({\n platforms: expoConfigPlatforms,\n projectRoot,\n });\n }\n\n return withExtendedResolver(config, {\n autolinkingModuleResolverInput,\n tsconfig,\n isExporting,\n isTsconfigPathsEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n });\n}\n\nfunction isDirectoryIn(targetPath: string, rootPath: string) {\n return targetPath.startsWith(rootPath) && targetPath.length >= rootPath.length;\n}\n"],"names":["getNodejsExtensions","shouldAliasModule","withExtendedResolver","withMetroMultiPlatformAsync","ASSET_REGISTRY_SRC","debug","require","asWritable","input","withWebPolyfills","config","getMetroBundler","originalGetPolyfills","serializer","getPolyfills","bind","ctx","virtualEnvVarId","getMetroBundlerWithVirtualModules","setVirtualModule","virtualModuleId","platform","virtualModulesPolyfills","rnGetPolyfills","filter","x","includes","error","code","polyfills","resolve","normalizeSlashes","p","replace","srcExts","mjsExts","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","autolinkingModuleResolverInput","isTsconfigPathsEnabled","isExporting","isReactServerComponentsEnabled","Log","warn","aliases","web","_universalAliases","getUniversalAliases","resolveFrom","silent","projectRoot","push","projectRootOriginPath","path","join","preferredMainFields","tsConfigResolve","paths","baseUrl","resolveWithTsConfigPaths","hasBaseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","getStrictResolver","resolveRequest","context","doResolve","moduleName","resolver","getOptionalResolver","optionalResolve","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","idFactory","createModuleIdFactory","id","_asyncRequireModuleResolvedPath","getAsyncRequireModule","undefined","transformer","asyncRequireModulePath","type","filePath","getAssetRegistryModule","externals","match","customResolverOptions","exporting","isServerEnvironment","environment","process","clientboundary","endsWith","isExternal","metroConfigWithCustomResolver","withMetroResolvers","requestDevMockProdReact","dev","originModulePath","requestTsconfigPaths","requestNodeExternals","isServer","moduleId","isNodeExternal","result","contents","requestCustomExternals","external","realModule","realPath","opaqueId","JSON","stringify","projectRootContext","nodeModulesPaths","disableHierarchicalLookup","externModule","requestAlias","redirectedModuleName","matcher","alias","aliasedModule","_","parseInt","requestStableConfigModules","createAutolinkingModuleResolver","requestPostRewrites","normalizedPath","doReplace","from","to","options","doReplaceHelper","doReplaceStrict","throws","env","EXPO_UNSTABLE_WEB_MODAL","webModalModule","some","FailedToResolveNativeOnlyModuleError","relative","normalName","shimFile","shouldCreateVirtualShim","virtualId","bundler","hasVirtualModule","fs","readFileSync","emptyModule","hmrModule","EXPO_UNSTABLE_LOG_BOX","logBoxModule","logBoxParserModule","createFallbackModuleResolver","originModuleNames","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","sourceExts","unstable_enablePackageExports","unstable_conditionsByPlatform","isReactServerComponents","mainFields","unstable_conditionNames","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","withMetroSupervisingTransformWorker","resolutionError","Error","cause","output","exp","platformBundlers","isAutolinkingResolverEnabled","metroDefaults","moduleSystem","EXPO_PUBLIC_PROJECT_ROOT","isDirectoryIn","__dirname","watchFolders","expoConfigPlatforms","entries","platforms","map","Array","isArray","Set","concat","createAutolinkingModuleResolverInput","targetPath","rootPath","startsWith"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IA8IeA,mBAAmB;eAAnBA;;IA6tBAC,iBAAiB;eAAjBA;;IAxsBAC,oBAAoB;eAApBA;;IAwtBMC,2BAA2B;eAA3BA;;;;yBAl3Bc;;;;;;;gEAErB;;;;;;;gEACE;;;;;;;gEACO;;;;;;+CAMjB;4CACsC;sDACQ;2BACG;6BACe;qCACrB;iDACF;oCACoB;qDAChB;qBAChC;8BACS;qBACT;sBACa;6BACH;mCACwB;0CACb;8BACL;;;;;;AASpC,MAAMC,qBAAqB,CAAC,6FAA6F,CAAC;AAE1H,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,SAASC,WAAcC,KAAQ;IAC7B,OAAOA;AACT;AAEA,SAASC,iBACPC,MAAe,EACf,EACEC,eAAe,EAGhB;IAED,MAAMC,uBAAuBF,OAAOG,UAAU,CAACC,YAAY,GACvDJ,OAAOG,UAAU,CAACC,YAAY,CAACC,IAAI,CAACL,OAAOG,UAAU,IACrD,IAAM,EAAE;IAEZ,MAAMC,eAAe,CAACE;QACpB,MAAMC,kBAAkB,CAAC,gCAAgC,CAAC;QAE1DC,IAAAA,sDAAiC,EAACP,mBAAmBQ,gBAAgB,CACnEF,iBACA,AAAC,CAAA;YACC,OAAO,CAAC,EAAE,CAAC;QACb,CAAA;QAGF,MAAMG,kBAAkB,CAAC,2BAA2B,CAAC;QAErDF,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AkB,EAAEC,QAAgB;IACzD,OAAOD,WAAWE,UAAU,CAACD,aAAaD,WAAWpI,MAAM,IAAIqI,SAASrI,MAAM;AAChF"}
@@ -2,38 +2,69 @@
2
2
  Object.defineProperty(exports, "__esModule", {
3
3
  value: true
4
4
  });
5
- Object.defineProperty(exports, "createCorsMiddleware", {
6
- enumerable: true,
7
- get: function() {
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ _isLocalHostname: function() {
13
+ return _isLocalHostname;
14
+ },
15
+ createCorsMiddleware: function() {
8
16
  return createCorsMiddleware;
9
17
  }
10
18
  });
11
- const DEFAULT_ALLOWED_CORS_HOSTNAMES = [
12
- 'localhost',
13
- 'chrome-devtools-frontend.appspot.com',
19
+ const DEFAULT_ALLOWED_CORS_HOSTS = [
14
20
  'devtools'
15
21
  ];
22
+ const _isLocalHostname = (hostname)=>{
23
+ if (hostname === 'localhost') {
24
+ return true;
25
+ }
26
+ let maybeIp = hostname;
27
+ const ipv6To4Prefix = '::ffff:';
28
+ if (maybeIp.startsWith(ipv6To4Prefix)) {
29
+ maybeIp = maybeIp.slice(ipv6To4Prefix.length);
30
+ }
31
+ if (maybeIp === '::1') {
32
+ return true;
33
+ } else if (/^127(?:.\d+){3}$/.test(maybeIp)) {
34
+ return maybeIp.split('.').every((part)=>{
35
+ const num = parseInt(part, 10);
36
+ return num >= 0 && num <= 255;
37
+ });
38
+ } else {
39
+ return false;
40
+ }
41
+ };
16
42
  function createCorsMiddleware(exp) {
17
43
  var _exp_extra_router, _exp_extra, _exp_extra_router1, _exp_extra1;
18
- const allowedHostnames = [
19
- ...DEFAULT_ALLOWED_CORS_HOSTNAMES
44
+ const allowedHosts = [
45
+ ...DEFAULT_ALLOWED_CORS_HOSTS
20
46
  ];
21
47
  // Support for expo-router API routes
22
48
  if ((_exp_extra = exp.extra) == null ? void 0 : (_exp_extra_router = _exp_extra.router) == null ? void 0 : _exp_extra_router.headOrigin) {
23
- allowedHostnames.push(new URL(exp.extra.router.headOrigin).hostname);
49
+ allowedHosts.push(new URL(exp.extra.router.headOrigin).host);
24
50
  }
25
51
  if ((_exp_extra1 = exp.extra) == null ? void 0 : (_exp_extra_router1 = _exp_extra1.router) == null ? void 0 : _exp_extra_router1.origin) {
26
- allowedHostnames.push(new URL(exp.extra.router.origin).hostname);
52
+ allowedHosts.push(new URL(exp.extra.router.origin).host);
27
53
  }
28
54
  return (req, res, next)=>{
29
55
  if (typeof req.headers.origin === 'string') {
30
56
  const { host, hostname } = new URL(req.headers.origin);
31
57
  const isSameOrigin = host === req.headers.host;
32
- if (!isSameOrigin && !allowedHostnames.includes(hostname)) {
58
+ const isLocalhost = _isLocalHostname(hostname);
59
+ const isAllowedHost = allowedHosts.includes(host) || isLocalhost;
60
+ if (!isSameOrigin && !isAllowedHost) {
33
61
  next(new Error(`Unauthorized request from ${req.headers.origin}. ` + 'This may happen because of a conflicting browser extension to intercept HTTP requests. ' + 'Disable browser extensions or use incognito mode and try again.'));
34
62
  return;
63
+ } else if (!isLocalhost && isAllowedHost) {
64
+ // Skipped for localhost to only allow requests from this dev-sever and not escalate
65
+ // the cross-origin resource sharing that's allowed beyond the browser's defaults
66
+ res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
35
67
  }
36
- res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
37
68
  maybePreventMetroResetCorsHeader(req, res);
38
69
  }
39
70
  // Block MIME-type sniffing.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/middleware/CorsMiddleware.ts"],"sourcesContent":["import type { ExpoConfig } from '@expo/config';\n\nimport type { ServerRequest, ServerResponse } from './server.types';\n\nconst DEFAULT_ALLOWED_CORS_HOSTNAMES = [\n 'localhost',\n 'chrome-devtools-frontend.appspot.com', // Support remote Chrome DevTools frontend\n 'devtools', // Support local Chrome DevTools `devtools://devtools`\n];\n\nexport function createCorsMiddleware(exp: ExpoConfig) {\n const allowedHostnames = [...DEFAULT_ALLOWED_CORS_HOSTNAMES];\n // Support for expo-router API routes\n if (exp.extra?.router?.headOrigin) {\n allowedHostnames.push(new URL(exp.extra.router.headOrigin).hostname);\n }\n if (exp.extra?.router?.origin) {\n allowedHostnames.push(new URL(exp.extra.router.origin).hostname);\n }\n\n return (req: ServerRequest, res: ServerResponse, next: (err?: Error) => void) => {\n if (typeof req.headers.origin === 'string') {\n const { host, hostname } = new URL(req.headers.origin);\n const isSameOrigin = host === req.headers.host;\n if (!isSameOrigin && !allowedHostnames.includes(hostname)) {\n next(\n new Error(\n `Unauthorized request from ${req.headers.origin}. ` +\n 'This may happen because of a conflicting browser extension to intercept HTTP requests. ' +\n 'Disable browser extensions or use incognito mode and try again.'\n )\n );\n return;\n }\n\n res.setHeader('Access-Control-Allow-Origin', req.headers.origin);\n maybePreventMetroResetCorsHeader(req, res);\n }\n\n // Block MIME-type sniffing.\n res.setHeader('X-Content-Type-Options', 'nosniff');\n\n next();\n };\n}\n\n// When accessing source maps,\n// metro will overwrite the `Access-Control-Allow-Origin` header with hardcoded `devtools://devtools` value.\n// https://github.com/facebook/metro/blob/a7f8955e6d2424b0d5f73d4bcdaf22560e1d5f27/packages/metro/src/Server.js#L540\n// This is a workaround to prevent this behavior.\nfunction maybePreventMetroResetCorsHeader(req: ServerRequest, res: ServerResponse) {\n const pathname = req.url ? new URL(req.url, `http://${req.headers.host}`).pathname : '';\n if (pathname.endsWith('.map')) {\n const setHeader = res.setHeader.bind(res);\n res.setHeader = (key, ...args) => {\n if (key !== 'Access-Control-Allow-Origin') {\n setHeader(key, ...args);\n }\n return res;\n };\n }\n}\n"],"names":["createCorsMiddleware","DEFAULT_ALLOWED_CORS_HOSTNAMES","exp","allowedHostnames","extra","router","headOrigin","push","URL","hostname","origin","req","res","next","headers","host","isSameOrigin","includes","Error","setHeader","maybePreventMetroResetCorsHeader","pathname","url","endsWith","bind","key","args"],"mappings":";;;;+BAUgBA;;;eAAAA;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/E,MAAMS,WAAWV,IAAIW,GAAG,GAAG,IAAId,IAAIG,IAAIW,GAAG,EAAE,CAAC,OAAO,EAAEX,IAAIG,OAAO,CAACC,IAAI,EAAE,EAAEM,QAAQ,GAAG;IACrF,IAAIA,SAASE,QAAQ,CAAC,SAAS;QAC7B,MAAMJ,YAAYP,IAAIO,SAAS,CAACK,IAAI,CAACZ;QACrCA,IAAIO,SAAS,GAAG,CAACM,KAAK,GAAGC;YACvB,IAAID,QAAQ,+BAA+B;gBACzCN,UAAUM,QAAQC;YACpB;YACA,OAAOd;QACT;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../src/start/server/middleware/CorsMiddleware.ts"],"sourcesContent":["import type { ExpoConfig } from '@expo/config';\n\nimport type { ServerRequest, ServerResponse } from './server.types';\n\nconst DEFAULT_ALLOWED_CORS_HOSTS = [\n 'devtools', // Support local Chrome DevTools `devtools://devtools`\n];\n\n/** Check if hostname matches \"localhost\" exactly, the local IPv6,\n * a local IPV4 in the 127.0.0.0/8 range, or an IPv6-to-4 range\n * (starting with ::ffff: and ending in an IPv4) */\nexport const _isLocalHostname = (hostname: string) => {\n if (hostname === 'localhost') {\n return true;\n }\n let maybeIp = hostname;\n const ipv6To4Prefix = '::ffff:';\n if (maybeIp.startsWith(ipv6To4Prefix)) {\n maybeIp = maybeIp.slice(ipv6To4Prefix.length);\n }\n if (maybeIp === '::1') {\n return true;\n } else if (/^127(?:.\\d+){3}$/.test(maybeIp)) {\n return maybeIp.split('.').every((part) => {\n const num = parseInt(part, 10);\n return num >= 0 && num <= 255;\n });\n } else {\n return false;\n }\n};\n\nexport function createCorsMiddleware(exp: ExpoConfig) {\n const allowedHosts = [...DEFAULT_ALLOWED_CORS_HOSTS];\n // Support for expo-router API routes\n if (exp.extra?.router?.headOrigin) {\n allowedHosts.push(new URL(exp.extra.router.headOrigin).host);\n }\n if (exp.extra?.router?.origin) {\n allowedHosts.push(new URL(exp.extra.router.origin).host);\n }\n\n return (req: ServerRequest, res: ServerResponse, next: (err?: Error) => void) => {\n if (typeof req.headers.origin === 'string') {\n const { host, hostname } = new URL(req.headers.origin);\n const isSameOrigin = host === req.headers.host;\n const isLocalhost = _isLocalHostname(hostname);\n const isAllowedHost = allowedHosts.includes(host) || isLocalhost;\n if (!isSameOrigin && !isAllowedHost) {\n next(\n new Error(\n `Unauthorized request from ${req.headers.origin}. ` +\n 'This may happen because of a conflicting browser extension to intercept HTTP requests. ' +\n 'Disable browser extensions or use incognito mode and try again.'\n )\n );\n return;\n } else if (!isLocalhost && isAllowedHost) {\n // Skipped for localhost to only allow requests from this dev-sever and not escalate\n // the cross-origin resource sharing that's allowed beyond the browser's defaults\n res.setHeader('Access-Control-Allow-Origin', req.headers.origin);\n }\n\n maybePreventMetroResetCorsHeader(req, res);\n }\n\n // Block MIME-type sniffing.\n res.setHeader('X-Content-Type-Options', 'nosniff');\n\n next();\n };\n}\n\n// When accessing source maps,\n// metro will overwrite the `Access-Control-Allow-Origin` header with hardcoded `devtools://devtools` value.\n// https://github.com/facebook/metro/blob/a7f8955e6d2424b0d5f73d4bcdaf22560e1d5f27/packages/metro/src/Server.js#L540\n// This is a workaround to prevent this behavior.\nfunction maybePreventMetroResetCorsHeader(req: ServerRequest, res: ServerResponse) {\n const pathname = req.url ? new URL(req.url, `http://${req.headers.host}`).pathname : '';\n if (pathname.endsWith('.map')) {\n const setHeader = res.setHeader.bind(res);\n res.setHeader = (key, ...args) => {\n if (key !== 'Access-Control-Allow-Origin') {\n setHeader(key, ...args);\n }\n return res;\n };\n }\n}\n"],"names":["_isLocalHostname","createCorsMiddleware","DEFAULT_ALLOWED_CORS_HOSTS","hostname","maybeIp","ipv6To4Prefix","startsWith","slice","length","test","split","every","part","num","parseInt","exp","allowedHosts","extra","router","headOrigin","push","URL","host","origin","req","res","next","headers","isSameOrigin","isLocalhost","isAllowedHost","includes","Error","setHeader","maybePreventMetroResetCorsHeader","pathname","url","endsWith","bind","key","args"],"mappings":";;;;;;;;;;;IAWaA,gBAAg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IAAIG,OAAO,CAACL,IAAI;YAC9C,MAAMO,cAAc7B,iBAAiBG;YACrC,MAAM2B,gBAAgBd,aAAae,QAAQ,CAACT,SAASO;YACrD,IAAI,CAACD,gBAAgB,CAACE,eAAe;gBACnCJ,KACE,IAAIM,MACF,CAAC,0BAA0B,EAAER,IAAIG,OAAO,CAACJ,MAAM,CAAC,EAAE,CAAC,GACjD,4FACA;gBAGN;YACF,OAAO,IAAI,CAACM,eAAeC,eAAe;gBACxC,oFAAoF;gBACpF,iFAAiF;gBACjFL,IAAIQ,SAAS,CAAC,+BAA+BT,IAAIG,OAAO,CAACJ,MAAM;YACjE;YAEAW,iCAAiCV,KAAKC;QACxC;QAEA,4BAA4B;QAC5BA,IAAIQ,SAAS,CAAC,0BAA0B;QAExCP;IACF;AACF;AAEA,8BAA8B;AAC9B,4GAA4G;AAC5G,oHAAoH;AACpH,iDAAiD;AACjD,SAASQ,iCAAiCV,GAAkB,EAAEC,GAAmB;IAC/E,MAAMU,WAAWX,IAAIY,GAAG,GAAG,IAAIf,IAAIG,IAAIY,GAAG,EAAE,CAAC,OAAO,EAAEZ,IAAIG,OAAO,CAACL,IAAI,EAAE,EAAEa,QAAQ,GAAG;IACrF,IAAIA,SAASE,QAAQ,CAAC,SAAS;QAC7B,MAAMJ,YAAYR,IAAIQ,SAAS,CAACK,IAAI,CAACb;QACrCA,IAAIQ,SAAS,GAAG,CAACM,KAAK,GAAGC;YACvB,IAAID,QAAQ,+BAA+B;gBACzCN,UAAUM,QAAQC;YACpB;YACA,OAAOf;QACT;IACF;AACF"}
@@ -34,18 +34,50 @@ function _interop_require_default(obj) {
34
34
  };
35
35
  }
36
36
  const debug = require('debug')('expo:start:server:middleware:createFile');
37
+ const ROUTER_INDEX_CONTENTS = `import { StyleSheet, Text, View } from "react-native";
38
+
39
+ export default function Page() {
40
+ return (
41
+ <View style={styles.container}>
42
+ <View style={styles.main}>
43
+ <Text style={styles.title}>Hello World</Text>
44
+ <Text style={styles.subtitle}>This is the first page of your app.</Text>
45
+ </View>
46
+ </View>
47
+ );
48
+ }
49
+
50
+ const styles = StyleSheet.create({
51
+ container: {
52
+ flex: 1,
53
+ alignItems: "center",
54
+ padding: 24,
55
+ },
56
+ main: {
57
+ flex: 1,
58
+ justifyContent: "center",
59
+ maxWidth: 960,
60
+ marginHorizontal: "auto",
61
+ },
62
+ title: {
63
+ fontSize: 64,
64
+ fontWeight: "bold",
65
+ },
66
+ subtitle: {
67
+ fontSize: 36,
68
+ color: "#38434D",
69
+ },
70
+ });
71
+ `;
37
72
  class CreateFileMiddleware extends _ExpoMiddleware.ExpoMiddleware {
38
- constructor(projectRoot){
39
- super(projectRoot, [
73
+ constructor(options){
74
+ super(options.projectRoot, [
40
75
  '/_expo/touch'
41
- ]), this.projectRoot = projectRoot;
76
+ ]), this.options = options;
42
77
  }
43
- resolvePath(inputPath) {
44
- return this.resolveExtension(_path().default.join(this.projectRoot, inputPath));
45
- }
46
- resolveExtension(inputPath) {
47
- let resolvedPath = inputPath;
48
- const extension = _path().default.extname(inputPath);
78
+ resolveExtension(basePath, relativePath) {
79
+ let resolvedPath = relativePath;
80
+ const extension = _path().default.extname(relativePath);
49
81
  if (extension === '.js') {
50
82
  // Automatically convert JS files to TS files when added to a project
51
83
  // with TypeScript.
@@ -54,7 +86,7 @@ class CreateFileMiddleware extends _ExpoMiddleware.ExpoMiddleware {
54
86
  resolvedPath = resolvedPath.replace(/\.js$/, '.tsx');
55
87
  }
56
88
  }
57
- return resolvedPath;
89
+ return _path().default.join(basePath, resolvedPath);
58
90
  }
59
91
  async parseRawBody(req) {
60
92
  const rawBody = await new Promise((resolve, reject)=>{
@@ -69,19 +101,26 @@ class CreateFileMiddleware extends _ExpoMiddleware.ExpoMiddleware {
69
101
  reject(err);
70
102
  });
71
103
  });
72
- const properties = JSON.parse(rawBody);
73
- this.assertTouchFileBody(properties);
74
- return properties;
75
- }
76
- assertTouchFileBody(body) {
104
+ const body = JSON.parse(rawBody);
77
105
  if (typeof body !== 'object' || body == null) {
78
106
  throw new Error('Expected object');
107
+ } else if (typeof body.type !== 'string') {
108
+ throw new Error('Expected "type" in body to be string');
79
109
  }
80
- if (typeof body.path !== 'string') {
81
- throw new Error('Expected "path" in body to be string');
110
+ switch(body.type){
111
+ case 'router_index':
112
+ return body;
113
+ default:
114
+ throw new Error('Unknown "type" passed in body');
82
115
  }
83
- if (typeof body.contents !== 'string') {
84
- throw new Error('Expected "contents" in body to be string');
116
+ }
117
+ makeOutputForInput(input) {
118
+ switch(input.type){
119
+ case 'router_index':
120
+ return {
121
+ absolutePath: this.resolveExtension(this.options.appDir, 'index.js'),
122
+ contents: ROUTER_INDEX_CONTENTS
123
+ };
85
124
  }
86
125
  }
87
126
  async handleRequestAsync(req, res) {
@@ -100,18 +139,18 @@ class CreateFileMiddleware extends _ExpoMiddleware.ExpoMiddleware {
100
139
  return;
101
140
  }
102
141
  debug(`Requested: %O`, properties);
103
- const resolvedPath = properties.absolutePath ? this.resolveExtension(_path().default.resolve(properties.absolutePath)) : this.resolvePath(properties.path);
104
- if (_fs().default.existsSync(resolvedPath)) {
142
+ const file = this.makeOutputForInput(properties);
143
+ if (_fs().default.existsSync(file.absolutePath)) {
105
144
  res.statusCode = 409;
106
145
  res.end('File already exists.');
107
146
  return;
108
147
  }
109
- debug(`Resolved path:`, resolvedPath);
148
+ debug(`Resolved path:`, file.absolutePath);
110
149
  try {
111
- await _fs().default.promises.mkdir(_path().default.dirname(resolvedPath), {
150
+ await _fs().default.promises.mkdir(_path().default.dirname(file.absolutePath), {
112
151
  recursive: true
113
152
  });
114
- await _fs().default.promises.writeFile(resolvedPath, properties.contents, 'utf8');
153
+ await _fs().default.promises.writeFile(file.absolutePath, file.contents, 'utf8');
115
154
  } catch (e) {
116
155
  debug('Error writing file', e);
117
156
  res.statusCode = 500;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/middleware/CreateFileMiddleware.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 path from 'path';\n\nimport { ExpoMiddleware } from './ExpoMiddleware';\nimport { ServerRequest, ServerResponse } from './server.types';\n\nconst debug = require('debug')('expo:start:server:middleware:createFile') as typeof console.log;\n\nexport type TouchFileBody = {\n /** @deprecated */\n path: string;\n absolutePath?: string;\n contents: string;\n};\n\n/**\n * Middleware for creating a file given a `POST` request with\n * `{ contents: string, path: string }` in the body.\n */\nexport class CreateFileMiddleware extends ExpoMiddleware {\n constructor(protected projectRoot: string) {\n super(projectRoot, ['/_expo/touch']);\n }\n\n protected resolvePath(inputPath: string): string {\n return this.resolveExtension(path.join(this.projectRoot, inputPath));\n }\n\n protected resolveExtension(inputPath: string): string {\n let resolvedPath = inputPath;\n const extension = path.extname(inputPath);\n if (extension === '.js') {\n // Automatically convert JS files to TS files when added to a project\n // with TypeScript.\n const tsconfigPath = path.join(this.projectRoot, 'tsconfig.json');\n if (fs.existsSync(tsconfigPath)) {\n resolvedPath = resolvedPath.replace(/\\.js$/, '.tsx');\n }\n }\n\n return resolvedPath;\n }\n\n protected async parseRawBody(req: ServerRequest): Promise<TouchFileBody> {\n const rawBody = await new Promise<string>((resolve, reject) => {\n let body = '';\n req.on('data', (chunk) => {\n body += chunk.toString();\n });\n req.on('end', () => {\n resolve(body);\n });\n req.on('error', (err) => {\n reject(err);\n });\n });\n\n const properties = JSON.parse(rawBody);\n this.assertTouchFileBody(properties);\n\n return properties;\n }\n\n private assertTouchFileBody(body: any): asserts body is TouchFileBody {\n if (typeof body !== 'object' || body == null) {\n throw new Error('Expected object');\n }\n if (typeof body.path !== 'string') {\n throw new Error('Expected \"path\" in body to be string');\n }\n if (typeof body.contents !== 'string') {\n throw new Error('Expected \"contents\" in body to be string');\n }\n }\n\n async handleRequestAsync(req: ServerRequest, res: ServerResponse): Promise<void> {\n if (req.method !== 'POST') {\n res.statusCode = 405;\n res.end('Method Not Allowed');\n return;\n }\n\n let properties: TouchFileBody;\n\n try {\n properties = await this.parseRawBody(req);\n } catch (e) {\n debug('Error parsing request body', e);\n res.statusCode = 400;\n res.end('Bad Request');\n return;\n }\n\n debug(`Requested: %O`, properties);\n\n const resolvedPath = properties.absolutePath\n ? this.resolveExtension(path.resolve(properties.absolutePath))\n : this.resolvePath(properties.path);\n\n if (fs.existsSync(resolvedPath)) {\n res.statusCode = 409;\n res.end('File already exists.');\n return;\n }\n\n debug(`Resolved path:`, resolvedPath);\n\n try {\n await fs.promises.mkdir(path.dirname(resolvedPath), { recursive: true });\n await fs.promises.writeFile(resolvedPath, properties.contents, 'utf8');\n } catch (e) {\n debug('Error writing file', e);\n res.statusCode = 500;\n res.end('Error writing file.');\n return;\n }\n\n debug(`File created`);\n res.statusCode = 200;\n res.end('OK');\n }\n}\n"],"names":["CreateFileMiddleware","debug","require","ExpoMiddleware","constructor","projectRoot","resolvePath","inputPath","resolveExtension","path","join","resolvedPath","extension","extname","tsconfigPath","fs","existsSync","replace","parseRawBody","req","rawBody","Promise","resolve","reject","body","on","chunk","toString","err","properties","JSON","parse","assertTouchFileBody","Error","contents","handleRequestAsync","res","method","statusCode","end","e","absolutePath","promises","mkdir","dirname","recursive","writeFile"],"mappings":"AAAA;;;;;CAKC;;;;+BAoBYA;;;eAAAA;;;;gEAnBE;;;;;;;gEACE;;;;;;gCAEc;;;;;;AAG/B,MAAMC,QAAQC,QAAQ,SAAS;AAaxB,MAAMF,6BAA6BG,8BAAc;IACtDC,YAAY,AAAUC,WAAmB,CAAE;QACzC,KAAK,CAACA,aAAa;YAAC;SAAe,QADfA,cAAAA;IAEtB;IAEUC,YAAYC,SAAiB,EAAU;QAC/C,OAAO,IAAI,CAACC,gBAAgB,CAACC,eAAI,CAACC,IAAI,CAAC,IAAI,CAACL,WAAW,EAAEE;IAC3D;IAEUC,iBAAiBD,SAAiB,EAAU;QACpD,IAAII,eAAeJ;QACnB,MAAMK,YAAYH,eAAI,CAACI,OAAO,CAACN;QAC/B,IA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CAAC,aAAa,CAAC,EAAE4B;QAEvB,MAAMlB,eAAekB,WAAWY,YAAY,GACxC,IAAI,CAACjC,gBAAgB,CAACC,eAAI,CAACa,OAAO,CAACO,WAAWY,YAAY,KAC1D,IAAI,CAACnC,WAAW,CAACuB,WAAWpB,IAAI;QAEpC,IAAIM,aAAE,CAACC,UAAU,CAACL,eAAe;YAC/ByB,IAAIE,UAAU,GAAG;YACjBF,IAAIG,GAAG,CAAC;YACR;QACF;QAEAtC,MAAM,CAAC,cAAc,CAAC,EAAEU;QAExB,IAAI;YACF,MAAMI,aAAE,CAAC2B,QAAQ,CAACC,KAAK,CAAClC,eAAI,CAACmC,OAAO,CAACjC,eAAe;gBAAEkC,WAAW;YAAK;YACtE,MAAM9B,aAAE,CAAC2B,QAAQ,CAACI,SAAS,CAACnC,cAAckB,WAAWK,QAAQ,EAAE;QACjE,EAAE,OAAOM,GAAG;YACVvC,MAAM,sBAAsBuC;YAC5BJ,IAAIE,UAAU,GAAG;YACjBF,IAAIG,GAAG,CAAC;YACR;QACF;QAEAtC,MAAM,CAAC,YAAY,CAAC;QACpBmC,IAAIE,UAAU,GAAG;QACjBF,IAAIG,GAAG,CAAC;IACV;AACF"}
1
+ {"version":3,"sources":["../../../../../src/start/server/middleware/CreateFileMiddleware.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 path from 'path';\n\nimport { ExpoMiddleware } from './ExpoMiddleware';\nimport { ServerRequest, ServerResponse } from './server.types';\n\nconst debug = require('debug')('expo:start:server:middleware:createFile') as typeof console.log;\n\ninterface TouchFileInput {\n type: 'router_index';\n}\n\ninterface TouchFileOutput {\n absolutePath: string;\n contents: string;\n}\n\nconst ROUTER_INDEX_CONTENTS = `import { StyleSheet, Text, View } from \"react-native\";\n\nexport default function Page() {\n return (\n <View style={styles.container}>\n <View style={styles.main}>\n <Text style={styles.title}>Hello World</Text>\n <Text style={styles.subtitle}>This is the first page of your app.</Text>\n </View>\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n alignItems: \"center\",\n padding: 24,\n },\n main: {\n flex: 1,\n justifyContent: \"center\",\n maxWidth: 960,\n marginHorizontal: \"auto\",\n },\n title: {\n fontSize: 64,\n fontWeight: \"bold\",\n },\n subtitle: {\n fontSize: 36,\n color: \"#38434D\",\n },\n});\n`;\n\ninterface CreateFileMiddlewareOptions {\n /** The absolute metro or server root, used to calculate the relative dom entry path */\n metroRoot: string;\n /** The absolute project root, used to resolve the `expo/dom/entry.js` path */\n projectRoot: string;\n /** The expo-router root */\n appDir: string;\n}\n\n/**\n * Middleware for creating a file given a `POST` request with\n * `{ contents: string, path: string }` in the body.\n */\nexport class CreateFileMiddleware extends ExpoMiddleware {\n constructor(protected options: CreateFileMiddlewareOptions) {\n super(options.projectRoot, ['/_expo/touch']);\n }\n\n protected resolveExtension(basePath: string, relativePath: string): string {\n let resolvedPath = relativePath;\n const extension = path.extname(relativePath);\n if (extension === '.js') {\n // Automatically convert JS files to TS files when added to a project\n // with TypeScript.\n const tsconfigPath = path.join(this.projectRoot, 'tsconfig.json');\n if (fs.existsSync(tsconfigPath)) {\n resolvedPath = resolvedPath.replace(/\\.js$/, '.tsx');\n }\n }\n return path.join(basePath, resolvedPath);\n }\n\n protected async parseRawBody(req: ServerRequest): Promise<TouchFileInput> {\n const rawBody = await new Promise<string>((resolve, reject) => {\n let body = '';\n req.on('data', (chunk) => {\n body += chunk.toString();\n });\n req.on('end', () => {\n resolve(body);\n });\n req.on('error', (err) => {\n reject(err);\n });\n });\n\n const body = JSON.parse(rawBody);\n if (typeof body !== 'object' || body == null) {\n throw new Error('Expected object');\n } else if (typeof body.type !== 'string') {\n throw new Error('Expected \"type\" in body to be string');\n }\n\n switch (body.type) {\n case 'router_index':\n return body;\n default:\n throw new Error('Unknown \"type\" passed in body');\n }\n }\n\n private makeOutputForInput(input: TouchFileInput): TouchFileOutput {\n switch (input.type) {\n case 'router_index':\n return {\n absolutePath: this.resolveExtension(this.options.appDir, 'index.js'),\n contents: ROUTER_INDEX_CONTENTS,\n };\n }\n }\n\n async handleRequestAsync(req: ServerRequest, res: ServerResponse): Promise<void> {\n if (req.method !== 'POST') {\n res.statusCode = 405;\n res.end('Method Not Allowed');\n return;\n }\n\n let properties: TouchFileInput;\n try {\n properties = await this.parseRawBody(req);\n } catch (e) {\n debug('Error parsing request body', e);\n res.statusCode = 400;\n res.end('Bad Request');\n return;\n }\n\n debug(`Requested: %O`, properties);\n\n const file = this.makeOutputForInput(properties);\n if (fs.existsSync(file.absolutePath)) {\n res.statusCode = 409;\n res.end('File already exists.');\n return;\n }\n\n debug(`Resolved path:`, file.absolutePath);\n\n try {\n await fs.promises.mkdir(path.dirname(file.absolutePath), { recursive: true });\n await fs.promises.writeFile(file.absolutePath, file.contents, 'utf8');\n } catch (e) {\n debug('Error writing file', e);\n res.statusCode = 500;\n res.end('Error writing file.');\n return;\n }\n\n debug(`File created`);\n res.statusCode = 200;\n res.end('OK');\n }\n}\n"],"names":["CreateFileMiddleware","debug","require","ROUTER_INDEX_CONTENTS","ExpoMiddleware","constructor","options","projectRoot","resolveExtension","basePath","relativePath","resolvedPath","extension","path","extname","tsconfigPath","join","fs","existsSync","replace","parseRawBody","req","rawBody","Promise","resolve","reject","body","on","chunk","toString","err","JSON","parse","Error","type","makeOutputForInput","input","absolutePath","appDir","contents","handleRequestAsync","res","method","statusCode","end","properties","e","file","promises","mkdir","dirname","recursive","writeFile"],"mappings":"AAAA;;;;;CAKC;;;;+BAmEYA;;;eAAAA;;;;gEAlEE;;;;;;;gEACE;;;;;;gCAEc;;;;;;AAG/B,MAAMC,QAAQC,QAAQ,SAAS;AAW/B,MAAMC,wBAAwB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkC/B,CAAC;AAeM,MAAMH,6BAA6BI,8BAAc;IACtDC,YAAY,AAAUC,OAAoC,CAAE;QA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