diff --git a/packages/cli-config/src/__tests__/loadTypeScriptConfig-test.ts b/packages/cli-config/src/__tests__/loadTypeScriptConfig-test.ts new file mode 100644 index 000000000..dd0e7eadd --- /dev/null +++ b/packages/cli-config/src/__tests__/loadTypeScriptConfig-test.ts @@ -0,0 +1,98 @@ +import {defaultLoaders, defaultLoadersSync} from 'cosmiconfig'; +import { + loadTypeScriptConfig, + loadTypeScriptConfigSync, +} from '../loadTypeScriptConfig'; + +jest.mock('cosmiconfig', () => ({ + defaultLoaders: {'.ts': jest.fn(), '.js': jest.fn()}, + defaultLoadersSync: {'.ts': jest.fn(), '.js': jest.fn()}, +})); + +const tsLoader = defaultLoaders['.ts'] as jest.Mock; +const jsLoader = defaultLoaders['.js'] as jest.Mock; +const tsLoaderSync = defaultLoadersSync['.ts'] as jest.Mock; +const jsLoaderSync = defaultLoadersSync['.js'] as jest.Mock; + +const FILE = '/project/react-native.config.ts'; +const config = {assets: ['./fonts']}; +const typescript7Error = new TypeError( + `TypeScript Error in ${FILE}:\ntypescript.findConfigFile is not a function`, +); + +function setNativeTypeScript(value: unknown) { + Object.defineProperty(process.features, 'typescript', { + value, + configurable: true, + }); +} + +beforeEach(() => { + jest.resetAllMocks(); + setNativeTypeScript('strip'); +}); + +describe('loadTypeScriptConfig', () => { + it('uses the typescript loader when it works', async () => { + tsLoader.mockResolvedValue(config); + + await expect(loadTypeScriptConfig(FILE, '')).resolves.toBe(config); + expect(jsLoader).not.toHaveBeenCalled(); + }); + + it('loads the file natively when typescript has no compiler API', async () => { + tsLoader.mockRejectedValue(typescript7Error); + jsLoader.mockResolvedValue(config); + + await expect(loadTypeScriptConfig(FILE, '')).resolves.toBe(config); + expect(jsLoader).toHaveBeenCalledWith(FILE, ''); + }); + + it('does not hide other typescript errors', async () => { + const syntaxError = new SyntaxError("TypeScript Error: ';' expected"); + tsLoader.mockRejectedValue(syntaxError); + + await expect(loadTypeScriptConfig(FILE, '')).rejects.toBe(syntaxError); + expect(jsLoader).not.toHaveBeenCalled(); + }); + + it('explains what to do when Node cannot load TypeScript', async () => { + setNativeTypeScript(undefined); + tsLoader.mockRejectedValue(typescript7Error); + jsLoader.mockRejectedValue(new SyntaxError('Unexpected token')); + + await expect(loadTypeScriptConfig(FILE, '')).rejects.toThrow( + /cannot load TypeScript files natively/, + ); + }); + + it('explains that Node does not load TypeScript from node_modules', async () => { + const nodeModulesError = Object.assign(new Error('unsupported'), { + code: 'ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING', + }); + tsLoader.mockRejectedValue(typescript7Error); + jsLoader.mockRejectedValue(nodeModulesError); + + await expect(loadTypeScriptConfig(FILE, '')).rejects.toThrow( + /does not load TypeScript files from node_modules/, + ); + }); +}); + +describe('loadTypeScriptConfigSync', () => { + it('uses the typescript loader when it works', () => { + tsLoaderSync.mockReturnValue(config); + + expect(loadTypeScriptConfigSync(FILE, '')).toBe(config); + expect(jsLoaderSync).not.toHaveBeenCalled(); + }); + + it('loads the file natively and unwraps the default export', () => { + tsLoaderSync.mockImplementation(() => { + throw typescript7Error; + }); + jsLoaderSync.mockReturnValue({__esModule: true, default: config}); + + expect(loadTypeScriptConfigSync(FILE, '')).toBe(config); + }); +}); diff --git a/packages/cli-config/src/loadTypeScriptConfig.ts b/packages/cli-config/src/loadTypeScriptConfig.ts new file mode 100644 index 000000000..203cbc457 --- /dev/null +++ b/packages/cli-config/src/loadTypeScriptConfig.ts @@ -0,0 +1,71 @@ +import {defaultLoaders, defaultLoadersSync} from 'cosmiconfig'; +import type {Loader, LoaderSync} from 'cosmiconfig'; + +/** + * cosmiconfig 9 compiles `.ts` files with the `typescript` package of the + * project. TypeScript 7 no longer ships that compiler API, so the default + * loader throws `typescript.findConfigFile is not a function`. In that case we + * let Node load the file with its own TypeScript support instead. + */ +const MISSING_COMPILER_API = + /typescript\.(findConfigFile|readConfigFile|transpileModule)|ts\.(findConfigFile|readConfigFile|transpileModule)/; + +function isMissingCompilerApi(error: unknown): boolean { + const message = (error as Error | undefined)?.message ?? ''; + return ( + /is not a function/.test(message) && MISSING_COMPILER_API.test(message) + ); +} + +function explainNativeLoadError(filepath: string, error: unknown): unknown { + // `process.features.typescript` is only set on Node.js versions that can + // strip types, so on older ones the file just fails to parse. + if (!(process.features as {typescript?: unknown}).typescript) { + return new Error( + `Failed to load ${filepath}: the installed "typescript" package cannot compile it and this version of Node.js (${process.version}) cannot load TypeScript files natively. Use Node.js 22.18 or newer, or write the configuration as react-native.config.js.`, + ); + } + if ( + (error as NodeJS.ErrnoException)?.code === + 'ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING' + ) { + return new Error( + `Failed to load ${filepath}: Node.js does not load TypeScript files from node_modules and the installed "typescript" package cannot compile it. Ask the package author to ship react-native.config.js, or use a version of "typescript" that provides the compiler API.`, + ); + } + return error; +} + +function unwrapDefaultExport(mod: any) { + return mod && mod.__esModule ? mod.default : mod; +} + +export const loadTypeScriptConfig: Loader = async (filepath, content) => { + try { + return await defaultLoaders['.ts'](filepath, content); + } catch (error) { + if (!isMissingCompilerApi(error)) { + throw error; + } + try { + return await defaultLoaders['.js'](filepath, content); + } catch (nativeError) { + throw explainNativeLoadError(filepath, nativeError); + } + } +}; + +export const loadTypeScriptConfigSync: LoaderSync = (filepath, content) => { + try { + return defaultLoadersSync['.ts'](filepath, content); + } catch (error) { + if (!isMissingCompilerApi(error)) { + throw error; + } + try { + return unwrapDefaultExport(defaultLoadersSync['.js'](filepath, content)); + } catch (nativeError) { + throw explainNativeLoadError(filepath, nativeError); + } + } +}; diff --git a/packages/cli-config/src/readConfigFromDisk.ts b/packages/cli-config/src/readConfigFromDisk.ts index b972a35ec..cf387540d 100644 --- a/packages/cli-config/src/readConfigFromDisk.ts +++ b/packages/cli-config/src/readConfigFromDisk.ts @@ -8,6 +8,10 @@ import type { } from '@react-native-community/cli-types'; import {logger, inlineString} from '@react-native-community/cli-tools'; import pico from 'picocolors'; +import { + loadTypeScriptConfig, + loadTypeScriptConfigSync, +} from './loadTypeScriptConfig'; /** * Places to look for the configuration file. @@ -43,6 +47,7 @@ export async function readConfigFromDiskAsync( const explorer = cosmiconfig('react-native', { stopDir: rootFolder, searchPlaces, + loaders: {'.ts': loadTypeScriptConfig}, }); const searchResult = await explorer.search(rootFolder); @@ -58,6 +63,7 @@ export function readConfigFromDisk(rootFolder: string): UserConfig { const explorer = cosmiconfigSync('react-native', { stopDir: rootFolder, searchPlaces: searchPlacesForCJS, + loaders: {'.ts': loadTypeScriptConfigSync}, }); const searchResult = explorer.search(rootFolder); @@ -100,6 +106,7 @@ export async function readDependencyConfigFromDiskAsync( const explorer = cosmiconfig('react-native', { stopDir: rootFolder, searchPlaces, + loaders: {'.ts': loadTypeScriptConfig}, }); const searchResult = await explorer.search(rootFolder); @@ -118,6 +125,7 @@ export function readDependencyConfigFromDisk( const explorer = cosmiconfigSync('react-native', { stopDir: rootFolder, searchPlaces: searchPlacesForCJS, + loaders: {'.ts': loadTypeScriptConfigSync}, }); const searchResult = explorer.search(rootFolder);