/** * Metro configuration for an `@effect/ui-native` app. * * **Details** * * Metro doesn't tree-shake, so a release bundle would carry every module * `effect` and `effect/ui` could need. {@link withEffectUi} pre-bundles * release builds with Vite, which does, and hands Metro the result with * React Native left out for Metro to resolve. In development Metro serves * the sources, and edits reach the app through Fast Refresh. * * **Example** (Configuring Metro) * * ```ts * // metro.config.js * const { getDefaultConfig } = require("expo/metro-config") * const { NativeMetro } = require("@effect/ui-native/node") * * module.exports = NativeMetro.withEffectUi(getDefaultConfig(__dirname)) * ``` * * @stability experimental * @since 4.2.0 */ import * as Crypto from "node:crypto" import * as Fs from "node:fs" import * as Module from "node:module" import * as Path from "node:path" import { fileURLToPath, pathToFileURL } from "node:url" import { cacheDir, prebundle } from "./internal/prebundle.ts" import { installTextDecoder } from "./internal/textDecoder.ts" import type { Settings } from "./internal/transformer.ts" /** * The parts of a Metro config {@link withEffectUi} reads and changes. * * @stability experimental * @category models * @since 4.2.0 */ export interface MetroConfig { readonly projectRoot: string readonly resolver?: { readonly unstable_conditionNames?: ReadonlyArray | undefined readonly sourceExts?: ReadonlyArray | undefined readonly assetExts?: ReadonlyArray | undefined readonly resolverMainFields?: ReadonlyArray | undefined readonly resolveRequest?: ResolveRequest | null | undefined readonly [key: string]: unknown } | undefined readonly serializer?: { readonly getModulesRunBeforeMainModule?: | ((entryFilePath: string) => ReadonlyArray) | undefined readonly getPolyfills?: | (( options: { readonly platform: string | null } ) => ReadonlyArray) | undefined readonly [key: string]: unknown } | undefined readonly transformer?: { readonly babelTransformerPath?: string | undefined readonly [key: string]: unknown } | undefined readonly server?: { readonly unstable_serverRoot?: string | null | undefined readonly [key: string]: unknown } | undefined readonly [key: string]: unknown } /** * Options accepted by {@link withEffectUi}. * * @stability experimental * @category models * @since 4.2.0 */ export interface Options { /** The module the bundle starts at. By default, the CLI's `--entry-file`, or else the `main` of the app's `package.json`. */ readonly entry?: string | undefined /** * Whether a release build is pre-bundled with Vite. `true` by default; with * `false`, Metro bundles the sources. */ readonly prebundle?: boolean | undefined /** The platforms a release build is pre-bundled for. `["android", "ios"]` by default; a react-native-macos app adds `"macos"`. */ readonly platforms?: ReadonlyArray | undefined /** * Modules the pre-bundle leaves to Metro, besides `react-native`, `expo` * and their scoped and prefixed packages. Leave out any other package with * native code. Static imports of assets in `resolver.assetExts` are left to * Metro automatically. */ readonly external?: ReadonlyArray | undefined } /** * Metro's `resolver.resolveRequest`. The context is Metro's own, which an * app's resolver types with Metro's types. * * @stability experimental * @category models * @since 4.2.0 */ export type ResolveRequest = ( // oxlint-disable-next-line no-explicit-any context: any, moduleName: string, platform: string | null ) => { readonly type: string readonly filePath?: string readonly filePaths?: ReadonlyArray } const own = (file: string) => { const self = fileURLToPath(import.meta.url) return Fs.realpathSync( Path.join(Path.dirname(self), file + Path.extname(self)) ) } // The value of the CLI flag `name`, as `--name value` or `--name=value`. const flag = (name: string): string | undefined => { const argv = process.argv for (let i = 0; i < argv.length; i++) { if (argv[i] === name) return argv[i + 1] if (argv[i]!.startsWith(name + "=")) return argv[i]!.slice(name.length + 1) } } // `react-native bundle` sets NODE_ENV only once it has loaded this config, // so a bundle it makes with `--dev false` is a release too. const isRelease = () => process.env.NODE_ENV === "production" || flag("--dev") === "false" const reactNativeMinor = (root: string): number | undefined => { try { const require = Module.createRequire(Path.join(root, "package.json")) const { version } = require("react-native/package.json") const [major, minor] = String(version).split(".").map(Number) return major === 0 ? minor : Infinity } catch { return undefined } } const assetRegistry = /^(react-native(?:-[^/]+)?)\/asset-registry$/ // The kit imports `react-native/asset-registry`, which React Native before // 0.87 lacks; those have the file it exports. const withAssetRegistry = ( config: Config ): Config => { const upstream = config.resolver?.resolveRequest return { ...config, resolver: { ...config.resolver, resolveRequest: (context, moduleName, platform) => { const resolve = upstream ?? context.resolveRequest try { return resolve(context, moduleName, platform) } catch (error) { if (!assetRegistry.test(moduleName)) throw error return resolve( context, moduleName.replace( assetRegistry, "$1/Libraries/Image/AssetRegistry" ), platform ) } } } satisfies MetroConfig["resolver"] } } // Writes `code` to the cache directory, leaving an unchanged file, and // with it Metro's cache of the file, alone. const writeCache = (root: string, name: string, code: string): string => { const dir = cacheDir(root) const file = Path.join(dir, name) Fs.mkdirSync(dir, { recursive: true }) if (!Fs.existsSync(file) || Fs.readFileSync(file, "utf8") !== code) { Fs.writeFileSync(file, code) } return file } // The Hermes of React Native before 0.88 has no TextDecoder, which // `effect`'s encoding modules construct as they load. const withTextDecoder = ( config: Config ): Config => { const minor = reactNativeMinor(config.projectRoot) if (minor === undefined || minor >= 88) return config const file = writeCache( config.projectRoot, "text-decoder.js", `(${installTextDecoder})(globalThis);\n` ) const before = config.serializer?.getPolyfills return { ...config, serializer: { ...config.serializer, getPolyfills: (options) => [...(before?.(options) ?? []), file] } satisfies MetroConfig["serializer"] } } const mainOf = (root: string): string => { const pkg = JSON.parse( Fs.readFileSync(Path.join(root, "package.json"), "utf8") ) if (typeof pkg.main !== "string") { throw new Error( `[@effect/ui-native] ${root}/package.json has no "main", so pass the entry to withEffectUi` ) } return pkg.main } /** * Configures Metro for an `@effect/ui-native` app, and pre-bundles a * release build. Use the result as the export of `metro.config.js`. * * **Details** * * A release build is one with `NODE_ENV=production`, as `expo export`, * `expo run:android --variant release` and EAS Build set, or one that * `react-native bundle` makes with `--dev false`, as Gradle's and Xcode's * release builds do. For one, Vite bundles the entry with the `production` * condition, leaving out React Native, Expo and static asset imports * (`resolver.assetExts`), and Metro bundles the result in place of the * entry. Other packages with native code go in `external`. Use static * `import` for assets rather than `require`: pre-bundling rejects `require` * of an asset. * * The app's own `resolver.resolveRequest` also resolves the imports Vite * bundles, so a release gets the modules development does. It is given the * resolver config, `dev`, `originModulePath` and `platform`, and its * `context.resolveRequest` hands the import, under the name and origin it is * given, back to Vite. It may resolve to a source file, asset files, or an * empty module; anything else fails the build, and belongs in `external`. Vite * resolves a handed-back import only after the app's resolver returns, and * only for the build's platform, so a resolver that reads its result, or * hands it back for another platform, fails the build too. * * In development the entry's sources are served as they are, and the * refresh runtime is run before them, so that an edit to a module whose * exports are all components swaps them in place without losing state. * * React Native 0.83 to 0.87 work too: `react-native/asset-registry` falls * back to the file versions before 0.87 have, and a UTF-8 `TextDecoder` runs * before the bundle where Hermes lacks one. With React Native's own Babel * preset rather than Expo's, add * `@babel/plugin-transform-export-namespace-from` to the app's Babel * config: `effect` and `effect/ui` use `export * as`. * * @stability experimental * @category constructors * @since 4.2.0 */ export const withEffectUi = async ( config: Config | Promise, options?: Options | undefined ): Promise => { const resolved = await config return withTextDecoder(withAssetRegistry( isRelease() ? await release(resolved, options) : development(resolved) )) } const release = async ( resolved: Config, options: Options | undefined ): Promise => { const root = resolved.projectRoot const conditions = resolved.resolver?.unstable_conditionNames ?? [] const resolver = { ...resolved.resolver, unstable_conditionNames: conditions.includes("production") ? conditions : [...conditions, "production"] } if (options?.prebundle === false) return { ...resolved, resolver } const cli = flag("--entry-file") const entry = options?.entry !== undefined ? Path.resolve(root, options.entry) : cli !== undefined // Metro resolves it from its server root, not the working directory. ? Path.resolve(resolved.server?.unstable_serverRoot ?? root, cli) : Path.resolve(root, mainOf(root)) // Metro reads its files when it starts, so every platform is built now. const bundles = Object.fromEntries( await Promise.all( (options?.platforms ?? ["android", "ios"]).map(async (platform) => [ platform, await prebundle(resolved, platform, entry, options?.external ?? []) ] as const ) ) ) const settings: Settings = { upstream: Module.createRequire(Path.join(root, "package.json")).resolve( resolved.transformer?.babelTransformerPath ?? "metro-babel-transformer" ), bundles: Object.fromEntries( Object.entries(bundles).map(([platform, { entry, file }]) => [ platform, { entry, file } ]) ) } // Metro's workers load the transformer by path, so each config has its // own file with its settings, named by them. const code = `import { make } from ${JSON.stringify(pathToFileURL(own("./internal/transformer")).href)} export const { transform, getCacheKey } = make(${JSON.stringify(settings)}) ` const transformer = writeCache( root, `transformer.${Crypto.createHash("sha1").update(code).digest("hex").slice(0, 16)}.mjs`, code ) const upstream = resolved.resolver?.resolveRequest return { ...resolved, resolver: { ...resolver, // Restore importers for deferred assets. resolveRequest: (context, moduleName, platform) => { const asset = context.dev || platform === null ? undefined : bundles[platform]?.assets.get(moduleName) if (asset === undefined) { return (upstream ?? context.resolveRequest)( context, moduleName, platform ) } const resolve = asset.runUpstream && upstream != null ? upstream : context.resolveRequest return resolve( { ...context, originModulePath: asset.origin }, asset.moduleName, platform ) } } satisfies MetroConfig["resolver"], // Swaps the entry for its pre-bundle, however the CLI hands it to Metro. transformer: { ...resolved.transformer, babelTransformerPath: transformer } } } const development = (resolved: Config): Config => { const before = resolved.serializer?.getModulesRunBeforeMainModule const refresh = own("../internal/devOn") return { ...resolved, serializer: { ...resolved.serializer, getModulesRunBeforeMainModule: (entryFilePath: string) => [ ...(before?.(entryFilePath) ?? []), refresh ] } } }