@teardown/metro-config 2.0.87 → 2.0.89

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bun.js ADDED
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ /**
3
+ * Bun-specific Metro configuration utilities.
4
+ *
5
+ * Handles blocking of .bun directories which can cause Metro resolution issues.
6
+ */
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.BUN_BLOCK_PATTERN = void 0;
12
+ exports.createBunAwareResolver = createBunAwareResolver;
13
+ exports.getBlockList = getBlockList;
14
+ const node_fs_1 = require("node:fs");
15
+ const node_path_1 = __importDefault(require("node:path"));
16
+ const workspace_1 = require("./workspace");
17
+ /**
18
+ * Block pattern for .bun directories.
19
+ * Metro's blockList prevents processing of matched paths.
20
+ */
21
+ exports.BUN_BLOCK_PATTERN = /.*[/\\]\.bun[/\\].*/;
22
+ /**
23
+ * Try to resolve a module using an existing resolver.
24
+ * Returns null if no resolver provided or resolution fails.
25
+ */
26
+ function tryExistingResolver(existingResolver, context, moduleName, platform) {
27
+ if (!existingResolver) {
28
+ return null;
29
+ }
30
+ return existingResolver(context, moduleName, platform);
31
+ }
32
+ /**
33
+ * Find an alternative path for a module when the resolved path contains .bun.
34
+ * Searches through available module paths, skipping any that are in .bun directories.
35
+ */
36
+ function findAlternativePathForBun(moduleName, modulesPaths) {
37
+ for (const modulesPath of modulesPaths) {
38
+ if (modulesPath.includes("/.bun/"))
39
+ continue;
40
+ const packagePath = node_path_1.default.join(modulesPath, moduleName);
41
+ if (!(0, node_fs_1.existsSync)(packagePath))
42
+ continue;
43
+ const mainFile = resolvePackageMain(packagePath);
44
+ if (mainFile) {
45
+ return { type: "sourceFile", filePath: mainFile };
46
+ }
47
+ }
48
+ return null;
49
+ }
50
+ /**
51
+ * Create a custom resolver that filters out .bun paths during module resolution.
52
+ *
53
+ * Note: The primary mechanism for blocking .bun directories is the blockList pattern.
54
+ * This resolver provides an additional layer of protection by finding alternative
55
+ * paths when a resolution from an existing custom resolver points to .bun.
56
+ *
57
+ * IMPORTANT: This resolver returns null when it doesn't handle resolution, signaling
58
+ * Metro to use its default resolution. Do NOT call context.resolveRequest as that
59
+ * points to the outermost resolver (e.g., Uniwind) and creates infinite loops.
60
+ *
61
+ * @param projectRoot - The project root directory
62
+ * @param existingResolver - Optional existing resolver from the config that should be preserved.
63
+ */
64
+ function createBunAwareResolver(projectRoot, existingResolver) {
65
+ const modulesPaths = (0, workspace_1.getModulesPaths)(projectRoot);
66
+ return (context, moduleName, platform) => {
67
+ const result = tryExistingResolver(existingResolver, context, moduleName, platform);
68
+ // If no result from existing resolver, return null to let Metro use its default
69
+ // Do NOT call context.resolveRequest - it points to the outermost resolver
70
+ if (!result) {
71
+ return null;
72
+ }
73
+ // If resolved path contains .bun, try to find alternative
74
+ if (result.filePath?.includes("/.bun/")) {
75
+ const alternative = findAlternativePathForBun(moduleName, modulesPaths);
76
+ if (alternative) {
77
+ return alternative;
78
+ }
79
+ }
80
+ return result;
81
+ };
82
+ }
83
+ /**
84
+ * Resolve the main entry point of a package.
85
+ */
86
+ function resolvePackageMain(packagePath) {
87
+ const packageJsonPath = node_path_1.default.join(packagePath, "package.json");
88
+ if ((0, node_fs_1.existsSync)(packageJsonPath)) {
89
+ try {
90
+ const pkg = JSON.parse((0, node_fs_1.readFileSync)(packageJsonPath, "utf8"));
91
+ const main = pkg.main || pkg.module || "index.js";
92
+ const mainPath = node_path_1.default.join(packagePath, main);
93
+ if ((0, node_fs_1.existsSync)(mainPath)) {
94
+ return mainPath;
95
+ }
96
+ // Try with .js extension
97
+ const mainPathJs = `${mainPath}.js`;
98
+ if ((0, node_fs_1.existsSync)(mainPathJs)) {
99
+ return mainPathJs;
100
+ }
101
+ }
102
+ catch {
103
+ // Ignore parse errors
104
+ }
105
+ }
106
+ // Fallback to index.js
107
+ const indexPath = node_path_1.default.join(packagePath, "index.js");
108
+ if ((0, node_fs_1.existsSync)(indexPath)) {
109
+ return indexPath;
110
+ }
111
+ return null;
112
+ }
113
+ /**
114
+ * Get blockList patterns for Metro config.
115
+ * Includes .bun directory blocking.
116
+ */
117
+ function getBlockList(existingBlockList) {
118
+ const blockListArray = Array.isArray(existingBlockList)
119
+ ? existingBlockList
120
+ : existingBlockList
121
+ ? [existingBlockList]
122
+ : [];
123
+ return [...blockListArray, exports.BUN_BLOCK_PATTERN];
124
+ }
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ /**
3
+ * Dev Client Metro Configuration
4
+ *
5
+ * Provides Metro configuration for injecting the dev client launcher
6
+ * before the main application entry point. This enables expo-dev-client-like
7
+ * behavior for bare React Native apps.
8
+ *
9
+ * @packageDocumentation
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.withTeardownDevClient = withTeardownDevClient;
13
+ /**
14
+ * Get the path to the bootstrap module
15
+ */
16
+ function getBootstrapModulePath(projectRoot, customPath) {
17
+ if (customPath) {
18
+ return customPath;
19
+ }
20
+ // Resolve @teardown/dev-client/bootstrap from the project
21
+ try {
22
+ return require.resolve("@teardown/dev-client/bootstrap", {
23
+ paths: [projectRoot],
24
+ });
25
+ }
26
+ catch {
27
+ // Fallback - the module should be resolvable at runtime
28
+ return "@teardown/dev-client/bootstrap";
29
+ }
30
+ }
31
+ /**
32
+ * Wrap Metro config with dev client launcher support.
33
+ *
34
+ * This injects a bootstrap module that runs before the main entry point,
35
+ * allowing the dev client launcher to show before the app loads.
36
+ * The bootstrap module:
37
+ * - Patches AppRegistry.registerComponent to capture app registrations
38
+ * - Shows a launcher UI before the main app
39
+ * - Automatically wraps the app with DevClientProvider when launched
40
+ *
41
+ * @param config - Metro configuration
42
+ * @param options - Dev client options
43
+ * @returns Enhanced Metro configuration
44
+ *
45
+ * @example
46
+ * ```js
47
+ * // metro.config.js
48
+ * const { withTeardown, withTeardownDevClient } = require('@teardown/metro-config');
49
+ * const { getDefaultConfig } = require('@react-native/metro-config');
50
+ *
51
+ * let config = getDefaultConfig(__dirname);
52
+ * config = withTeardown(config);
53
+ * config = withTeardownDevClient(config);
54
+ *
55
+ * module.exports = config;
56
+ * ```
57
+ */
58
+ function withTeardownDevClient(config, options = {}) {
59
+ const { enabled = true, bootstrapModule, verbose = false } = options;
60
+ // Don't modify config if disabled
61
+ if (!enabled) {
62
+ if (verbose) {
63
+ console.log("[teardown/dev-client] Dev client disabled");
64
+ }
65
+ return config;
66
+ }
67
+ const projectRoot = config.projectRoot || process.cwd();
68
+ const bootstrapPath = getBootstrapModulePath(projectRoot, bootstrapModule);
69
+ if (verbose) {
70
+ console.log("[teardown/dev-client] Enabling dev client launcher");
71
+ console.log(`[teardown/dev-client] Bootstrap module: ${bootstrapPath}`);
72
+ }
73
+ // Get existing getModulesRunBeforeMainModule function
74
+ const existingGetModules = config.serializer?.getModulesRunBeforeMainModule;
75
+ return {
76
+ ...config,
77
+ serializer: {
78
+ ...config.serializer,
79
+ /**
80
+ * Returns modules to run before the main entry point.
81
+ * We prepend our bootstrap module to intercept app registration.
82
+ */
83
+ getModulesRunBeforeMainModule: (entryFilePath) => {
84
+ // Get any existing modules
85
+ const existing = existingGetModules?.(entryFilePath) ?? [];
86
+ // Add our bootstrap module at the beginning
87
+ return [bootstrapPath, ...existing];
88
+ },
89
+ },
90
+ };
91
+ }
package/dist/index.js ADDED
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ /**
3
+ * @teardown/metro-config
4
+ *
5
+ * Metro configuration wrapper that provides:
6
+ * - Rust-powered transforms via Facetpack (36x faster than Babel)
7
+ * - Automatic monorepo/workspace detection and configuration
8
+ * - Bun-specific handling (blocks .bun directories)
9
+ *
10
+ * @example
11
+ * ```js
12
+ * // metro.config.js
13
+ * const { withTeardown } = require('@teardown/metro-config')
14
+ * const { getDefaultConfig } = require('@react-native/metro-config')
15
+ *
16
+ * module.exports = withTeardown(getDefaultConfig(__dirname))
17
+ * ```
18
+ *
19
+ * @packageDocumentation
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.isInMonorepo = exports.getWorkspaceRoot = exports.getWatchFolders = exports.getRelativeProjectRoot = exports.getModulesPaths = exports.getMetroServerRoot = exports.parseTsConfigPaths = exports.createTsConfigPathsResolver = exports.withTeardownDevClient = exports.getBlockList = exports.BUN_BLOCK_PATTERN = exports.getStoredOptions = void 0;
23
+ exports.withTeardown = withTeardown;
24
+ const facetpack_1 = require("@ecrindigital/facetpack");
25
+ Object.defineProperty(exports, "getStoredOptions", { enumerable: true, get: function () { return facetpack_1.getStoredOptions; } });
26
+ const bun_1 = require("./bun");
27
+ const tsconfig_paths_1 = require("./tsconfig-paths");
28
+ const workspace_1 = require("./workspace");
29
+ /**
30
+ * Wraps a Metro configuration with Teardown's enhancements.
31
+ *
32
+ * This function applies:
33
+ * - Facetpack for Rust-powered transforms (36x faster)
34
+ * - Automatic monorepo detection and watch folder configuration
35
+ * - Bun-specific handling (.bun directory blocking)
36
+ * - Proper nodeModulesPaths for monorepo resolution
37
+ *
38
+ * @param config - Base Metro configuration
39
+ * @param options - Optional configuration options
40
+ * @returns Enhanced Metro configuration
41
+ *
42
+ * @example
43
+ * ```js
44
+ * // Basic usage - all monorepo handling is automatic
45
+ * const { withTeardown } = require('@teardown/metro-config')
46
+ * const { getDefaultConfig } = require('@react-native/metro-config')
47
+ *
48
+ * module.exports = withTeardown(getDefaultConfig(__dirname))
49
+ * ```
50
+ *
51
+ * @example
52
+ * ```js
53
+ * // With options
54
+ * const { withTeardown } = require('@teardown/metro-config')
55
+ * const { getDefaultConfig } = require('@react-native/metro-config')
56
+ *
57
+ * module.exports = withTeardown(getDefaultConfig(__dirname), {
58
+ * verbose: true,
59
+ * projectRoot: __dirname, // explicitly set project root
60
+ * })
61
+ * ```
62
+ */
63
+ function withTeardown(config, options = {}) {
64
+ const { verbose, projectRoot: explicitProjectRoot, tsconfigPaths = true, ...facetpackOptions } = options;
65
+ // Determine project root
66
+ const projectRoot = explicitProjectRoot || config.projectRoot || process.cwd();
67
+ if (verbose) {
68
+ console.log("[teardown/metro-config] Applying Teardown configuration...");
69
+ console.log(`[teardown/metro-config] Project root: ${projectRoot}`);
70
+ }
71
+ // Check if in monorepo
72
+ const inMonorepo = (0, workspace_1.isInMonorepo)(projectRoot);
73
+ if (verbose && inMonorepo) {
74
+ const workspaceRoot = (0, workspace_1.getWorkspaceRoot)(projectRoot);
75
+ console.log(`[teardown/metro-config] Monorepo detected: ${workspaceRoot}`);
76
+ }
77
+ // Get monorepo-aware watch folders
78
+ const additionalWatchFolders = (0, workspace_1.getWatchFolders)(projectRoot);
79
+ const existingWatchFolders = config.watchFolders || [];
80
+ // Get monorepo-aware node modules paths
81
+ const modulesPaths = (0, workspace_1.getModulesPaths)(projectRoot);
82
+ const existingNodeModulesPaths = config.resolver?.nodeModulesPaths || [];
83
+ // Get block list with .bun blocking
84
+ const blockList = (0, bun_1.getBlockList)(config.resolver?.blockList);
85
+ // Get any existing custom resolver from the config
86
+ const existingResolver = config.resolver?.resolveRequest;
87
+ // Create resolver chain: tsconfig paths -> bun-aware -> existing/default
88
+ // The bun-aware resolver handles .bun path filtering
89
+ const bunAwareResolver = (0, bun_1.createBunAwareResolver)(projectRoot, existingResolver);
90
+ // Apply tsconfig paths resolver on top (so it runs first)
91
+ const chainedResolver = tsconfigPaths
92
+ ? (0, tsconfig_paths_1.createTsConfigPathsResolver)(projectRoot, bunAwareResolver, verbose)
93
+ : bunAwareResolver;
94
+ // Wrap with null-safe handling so external plugins (like Uniwind) don't receive null
95
+ // When our resolver chain returns null, use Metro's internal resolver as fallback
96
+ const nullSafeResolver = (context, moduleName, platform) => {
97
+ const result = chainedResolver(context, moduleName, platform);
98
+ if (result === null) {
99
+ return context.resolveRequest(context, moduleName, platform);
100
+ }
101
+ return result;
102
+ };
103
+ // Build enhanced config
104
+ const enhancedConfig = {
105
+ ...config,
106
+ projectRoot,
107
+ watchFolders: [...new Set([...existingWatchFolders, ...additionalWatchFolders])],
108
+ resolver: {
109
+ ...config.resolver,
110
+ blockList,
111
+ nodeModulesPaths: [...new Set([...modulesPaths, ...existingNodeModulesPaths])],
112
+ resolveRequest: nullSafeResolver,
113
+ },
114
+ };
115
+ // Set unstable_serverRoot for monorepo web support
116
+ if (inMonorepo) {
117
+ const serverRoot = (0, workspace_1.getMetroServerRoot)(projectRoot);
118
+ enhancedConfig.unstable_serverRoot = serverRoot;
119
+ // Add relative project root to transformer cache key for cache collision prevention
120
+ const relativeRoot = (0, workspace_1.getRelativeProjectRoot)(projectRoot);
121
+ if (relativeRoot) {
122
+ const existingCacheKey = config.transformer?.customTransformOptions || {};
123
+ enhancedConfig.transformer = {
124
+ ...config.transformer,
125
+ customTransformOptions: {
126
+ ...existingCacheKey,
127
+ _teardownRelativeProjectRoot: relativeRoot,
128
+ },
129
+ };
130
+ }
131
+ }
132
+ if (verbose) {
133
+ const watchFoldersCount = enhancedConfig.watchFolders?.length || 0;
134
+ const nodeModulesPathsCount = enhancedConfig.resolver?.nodeModulesPaths?.length || 0;
135
+ console.log(`[teardown/metro-config] Watch folders: ${watchFoldersCount}`);
136
+ console.log(`[teardown/metro-config] Node modules paths: ${nodeModulesPathsCount}`);
137
+ }
138
+ // Apply Facetpack for Rust-powered transforms
139
+ const finalConfig = (0, facetpack_1.withFacetpack)(enhancedConfig, facetpackOptions);
140
+ if (verbose) {
141
+ console.log("[teardown/metro-config] Metro config enhanced successfully");
142
+ }
143
+ return finalConfig;
144
+ }
145
+ // Re-export Bun utilities
146
+ var bun_2 = require("./bun");
147
+ Object.defineProperty(exports, "BUN_BLOCK_PATTERN", { enumerable: true, get: function () { return bun_2.BUN_BLOCK_PATTERN; } });
148
+ Object.defineProperty(exports, "getBlockList", { enumerable: true, get: function () { return bun_2.getBlockList; } });
149
+ // Re-export dev-client utilities
150
+ var dev_client_1 = require("./dev-client");
151
+ Object.defineProperty(exports, "withTeardownDevClient", { enumerable: true, get: function () { return dev_client_1.withTeardownDevClient; } });
152
+ // Re-export tsconfig paths utilities
153
+ var tsconfig_paths_2 = require("./tsconfig-paths");
154
+ Object.defineProperty(exports, "createTsConfigPathsResolver", { enumerable: true, get: function () { return tsconfig_paths_2.createTsConfigPathsResolver; } });
155
+ Object.defineProperty(exports, "parseTsConfigPaths", { enumerable: true, get: function () { return tsconfig_paths_2.parseTsConfigPaths; } });
156
+ // Re-export workspace utilities for advanced use cases
157
+ var workspace_2 = require("./workspace");
158
+ Object.defineProperty(exports, "getMetroServerRoot", { enumerable: true, get: function () { return workspace_2.getMetroServerRoot; } });
159
+ Object.defineProperty(exports, "getModulesPaths", { enumerable: true, get: function () { return workspace_2.getModulesPaths; } });
160
+ Object.defineProperty(exports, "getRelativeProjectRoot", { enumerable: true, get: function () { return workspace_2.getRelativeProjectRoot; } });
161
+ Object.defineProperty(exports, "getWatchFolders", { enumerable: true, get: function () { return workspace_2.getWatchFolders; } });
162
+ Object.defineProperty(exports, "getWorkspaceRoot", { enumerable: true, get: function () { return workspace_2.getWorkspaceRoot; } });
163
+ Object.defineProperty(exports, "isInMonorepo", { enumerable: true, get: function () { return workspace_2.isInMonorepo; } });
@@ -0,0 +1,294 @@
1
+ "use strict";
2
+ /**
3
+ * TSConfig paths resolution for Metro.
4
+ *
5
+ * Enables `compilerOptions.paths` and `compilerOptions.baseUrl` support for import aliases.
6
+ */
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.parseTsConfigPaths = parseTsConfigPaths;
12
+ exports.buildPathMappings = buildPathMappings;
13
+ exports.resolveWithTsConfigPaths = resolveWithTsConfigPaths;
14
+ exports.createTsConfigPathsResolver = createTsConfigPathsResolver;
15
+ const node_fs_1 = require("node:fs");
16
+ const node_path_1 = __importDefault(require("node:path"));
17
+ /**
18
+ * Try to import TypeScript from the project.
19
+ */
20
+ function importTypeScriptFromProjectOptionally(projectRoot) {
21
+ try {
22
+ const tsPath = require.resolve("typescript", { paths: [projectRoot] });
23
+ return require(tsPath);
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ /**
30
+ * Evaluate tsconfig.json using TypeScript's parseJsonConfigFileContent.
31
+ * This properly handles `extends` and all inheritance.
32
+ */
33
+ function evaluateTsConfig(ts, configPath) {
34
+ const configDir = node_path_1.default.dirname(configPath);
35
+ const configFileText = ts.sys.readFile(configPath);
36
+ if (!configFileText) {
37
+ return {};
38
+ }
39
+ const result = ts.parseConfigFileTextToJson(configPath, configFileText);
40
+ if (result.error) {
41
+ return {};
42
+ }
43
+ const parsedConfig = ts.parseJsonConfigFileContent(result.config, ts.sys, configDir, undefined, configPath);
44
+ return {
45
+ compilerOptions: {
46
+ baseUrl: parsedConfig.options.baseUrl,
47
+ paths: parsedConfig.options.paths,
48
+ },
49
+ };
50
+ }
51
+ /**
52
+ * Clean JSON5 content (remove comments and trailing commas) for JSON.parse.
53
+ */
54
+ function cleanJsonContent(content) {
55
+ return content
56
+ .replace(/\/\*[\s\S]*?\*\//g, "") // Remove /* */ comments
57
+ .replace(/\/\/.*/g, "") // Remove // comments
58
+ .replace(/,(\s*[}\]])/g, "$1"); // Remove trailing commas
59
+ }
60
+ /**
61
+ * Parse a config file manually (fallback when TypeScript isn't available).
62
+ */
63
+ function parseConfigFileManually(configPath) {
64
+ try {
65
+ const content = (0, node_fs_1.readFileSync)(configPath, "utf8");
66
+ const config = JSON.parse(cleanJsonContent(content));
67
+ const compilerOptions = config.compilerOptions || {};
68
+ return {
69
+ baseUrl: compilerOptions.baseUrl,
70
+ paths: compilerOptions.paths,
71
+ };
72
+ }
73
+ catch (error) {
74
+ console.warn(`[teardown/metro-config] Failed to parse ${node_path_1.default.basename(configPath)}: ${error}`);
75
+ return null;
76
+ }
77
+ }
78
+ /**
79
+ * Normalize baseUrl from TypeScript's absolute path to relative.
80
+ */
81
+ function normalizeBaseUrl(baseUrl, projectRoot) {
82
+ if (!baseUrl)
83
+ return undefined;
84
+ return node_path_1.default.isAbsolute(baseUrl) ? node_path_1.default.relative(projectRoot, baseUrl) : baseUrl;
85
+ }
86
+ /**
87
+ * Try to parse tsconfig using TypeScript for full extends support.
88
+ */
89
+ function parseTsConfigWithTypeScript(projectRoot, configPath) {
90
+ const ts = importTypeScriptFromProjectOptionally(projectRoot);
91
+ if (!ts)
92
+ return null;
93
+ try {
94
+ const config = evaluateTsConfig(ts, configPath);
95
+ return {
96
+ baseUrl: normalizeBaseUrl(config.compilerOptions?.baseUrl, projectRoot),
97
+ paths: config.compilerOptions?.paths,
98
+ };
99
+ }
100
+ catch (error) {
101
+ console.warn(`[teardown/metro-config] Failed to evaluate tsconfig with TypeScript: ${error}`);
102
+ return null;
103
+ }
104
+ }
105
+ /**
106
+ * Parse tsconfig.json and extract paths configuration.
107
+ * Properly evaluates the full config including `extends` inheritance.
108
+ */
109
+ function parseTsConfigPaths(projectRoot) {
110
+ const tsconfigPath = node_path_1.default.join(projectRoot, "tsconfig.json");
111
+ const jsconfigPath = node_path_1.default.join(projectRoot, "jsconfig.json");
112
+ // Try tsconfig.json first
113
+ if ((0, node_fs_1.existsSync)(tsconfigPath)) {
114
+ // Try TypeScript evaluation first (handles extends)
115
+ const tsResult = parseTsConfigWithTypeScript(projectRoot, tsconfigPath);
116
+ if (tsResult)
117
+ return tsResult;
118
+ // Fallback to manual parsing
119
+ const manualResult = parseConfigFileManually(tsconfigPath);
120
+ if (manualResult)
121
+ return manualResult;
122
+ }
123
+ // Try jsconfig.json as fallback
124
+ if ((0, node_fs_1.existsSync)(jsconfigPath)) {
125
+ return parseConfigFileManually(jsconfigPath);
126
+ }
127
+ return null;
128
+ }
129
+ /**
130
+ * Convert tsconfig paths to regex patterns for efficient matching.
131
+ */
132
+ function buildPathMappings(projectRoot, config) {
133
+ if (!config.paths) {
134
+ return [];
135
+ }
136
+ const baseUrl = config.baseUrl ? node_path_1.default.resolve(projectRoot, config.baseUrl) : projectRoot;
137
+ const mappings = [];
138
+ for (const [alias, targets] of Object.entries(config.paths)) {
139
+ // Convert path pattern to regex
140
+ // @/* -> @/(.*) -> matches @/anything
141
+ const regexPattern = alias
142
+ .replace(/[.+?^${}()|[\]\\]/g, "\\$&") // Escape special regex chars except *
143
+ .replace(/\*/g, "(.*)"); // Convert * to capture group
144
+ mappings.push({
145
+ pattern: new RegExp(`^${regexPattern}$`),
146
+ replacements: targets.map((target) => node_path_1.default.join(baseUrl, target)),
147
+ });
148
+ }
149
+ return mappings;
150
+ }
151
+ /** File extensions to try when resolving modules */
152
+ const FILE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".json"];
153
+ /** Extensions to try for index files in directories */
154
+ const INDEX_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
155
+ /**
156
+ * Check if a path is an existing file.
157
+ */
158
+ function isExistingFile(filePath) {
159
+ return (0, node_fs_1.existsSync)(filePath) && (0, node_fs_1.statSync)(filePath).isFile();
160
+ }
161
+ /**
162
+ * Try to resolve a path by appending common file extensions.
163
+ * Returns the resolved path or null if not found.
164
+ */
165
+ function tryResolveWithExtensions(basePath) {
166
+ for (const ext of FILE_EXTENSIONS) {
167
+ const fullPath = basePath + ext;
168
+ if (isExistingFile(fullPath)) {
169
+ return fullPath;
170
+ }
171
+ }
172
+ return null;
173
+ }
174
+ /**
175
+ * Try to resolve a directory by looking for index files.
176
+ * Returns the resolved index path or null if not found.
177
+ */
178
+ function tryResolveDirectoryIndex(dirPath) {
179
+ for (const ext of INDEX_EXTENSIONS) {
180
+ const indexPath = node_path_1.default.join(dirPath, `index${ext}`);
181
+ if (isExistingFile(indexPath)) {
182
+ return indexPath;
183
+ }
184
+ }
185
+ return null;
186
+ }
187
+ /**
188
+ * Try to resolve an exact path (file or directory with index).
189
+ * Returns the resolved path or null if not found.
190
+ */
191
+ function tryResolveExactPath(resolvedPath) {
192
+ if (!(0, node_fs_1.existsSync)(resolvedPath)) {
193
+ return null;
194
+ }
195
+ const stat = (0, node_fs_1.statSync)(resolvedPath);
196
+ if (stat.isFile()) {
197
+ return resolvedPath;
198
+ }
199
+ if (stat.isDirectory()) {
200
+ return tryResolveDirectoryIndex(resolvedPath);
201
+ }
202
+ return null;
203
+ }
204
+ /**
205
+ * Try to resolve a single replacement path with all resolution strategies.
206
+ * Returns the resolved path or null if not found.
207
+ */
208
+ function tryResolveReplacement(replacement, captured) {
209
+ const resolvedPath = replacement.replace("*", captured);
210
+ // Try with file extensions first
211
+ const withExtension = tryResolveWithExtensions(resolvedPath);
212
+ if (withExtension) {
213
+ return withExtension;
214
+ }
215
+ // Try exact path (file or directory with index)
216
+ return tryResolveExactPath(resolvedPath);
217
+ }
218
+ /**
219
+ * Try to resolve a module against a single path mapping.
220
+ * Returns the resolved path or null if no match.
221
+ */
222
+ function tryResolveMapping(moduleName, mapping) {
223
+ const match = moduleName.match(mapping.pattern);
224
+ if (!match) {
225
+ return null;
226
+ }
227
+ const captured = match[1] || "";
228
+ for (const replacement of mapping.replacements) {
229
+ const resolved = tryResolveReplacement(replacement, captured);
230
+ if (resolved) {
231
+ return resolved;
232
+ }
233
+ }
234
+ return null;
235
+ }
236
+ /**
237
+ * Resolve a module using tsconfig paths.
238
+ * Returns the resolved file path or null if not matched.
239
+ */
240
+ function resolveWithTsConfigPaths(moduleName, mappings) {
241
+ for (const mapping of mappings) {
242
+ const resolved = tryResolveMapping(moduleName, mapping);
243
+ if (resolved) {
244
+ return resolved;
245
+ }
246
+ }
247
+ return null;
248
+ }
249
+ /**
250
+ * Create a resolver that handles tsconfig paths.
251
+ *
252
+ * IMPORTANT: This resolver returns null when it doesn't handle resolution, signaling
253
+ * Metro to use its default resolution. Do NOT call context.resolveRequest as that
254
+ * points to the outermost resolver (e.g., Uniwind) and creates infinite loops.
255
+ *
256
+ * @param projectRoot - The project root directory
257
+ * @param nextResolver - Optional next resolver in the chain.
258
+ * @param verbose - Whether to log debug information
259
+ */
260
+ function createTsConfigPathsResolver(projectRoot, nextResolver, verbose = false) {
261
+ const config = parseTsConfigPaths(projectRoot);
262
+ if (!config?.paths) {
263
+ if (verbose) {
264
+ console.log("[teardown/metro-config] No tsconfig paths found, skipping path resolution");
265
+ }
266
+ // Pass through to next resolver or return null for Metro's default
267
+ // Do NOT call context.resolveRequest - it points to the outermost resolver
268
+ return nextResolver ?? ((_context, _moduleName, _platform) => null);
269
+ }
270
+ const mappings = buildPathMappings(projectRoot, config);
271
+ if (verbose) {
272
+ console.log(`[teardown/metro-config] Loaded ${mappings.length} path mappings from tsconfig.json`);
273
+ for (const { pattern, replacements } of mappings) {
274
+ console.log(` ${pattern.source} -> ${replacements.join(", ")}`);
275
+ }
276
+ }
277
+ return (context, moduleName, platform) => {
278
+ // Try tsconfig paths first for alias patterns (typically start with @ or other configured prefixes)
279
+ const resolvedPath = resolveWithTsConfigPaths(moduleName, mappings);
280
+ if (resolvedPath) {
281
+ if (verbose) {
282
+ console.log(`[teardown/metro-config] Resolved ${moduleName} -> ${resolvedPath}`);
283
+ }
284
+ return { type: "sourceFile", filePath: resolvedPath };
285
+ }
286
+ // Fall back to next resolver in chain
287
+ if (nextResolver) {
288
+ return nextResolver(context, moduleName, platform);
289
+ }
290
+ // Return null to let Metro use its default resolution
291
+ // Do NOT call context.resolveRequest - it points to the outermost resolver
292
+ return null;
293
+ };
294
+ }
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ /**
3
+ * Type definitions for @teardown/metro-config
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,231 @@
1
+ "use strict";
2
+ /**
3
+ * Workspace and monorepo detection utilities for Metro configuration.
4
+ *
5
+ * Uses `resolve-workspace-root` to detect workspace roots across:
6
+ * - Yarn workspaces
7
+ * - npm workspaces
8
+ * - pnpm workspaces
9
+ * - Bun workspaces
10
+ */
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.globAllPackageJsonPaths = globAllPackageJsonPaths;
16
+ exports.resolveAllWorkspacePackageJsonPaths = resolveAllWorkspacePackageJsonPaths;
17
+ exports.getWorkspaceRoot = getWorkspaceRoot;
18
+ exports.getWorkspaceGlobs = getWorkspaceGlobs;
19
+ exports.isInMonorepo = isInMonorepo;
20
+ exports.getMetroServerRoot = getMetroServerRoot;
21
+ exports.getWatchFolders = getWatchFolders;
22
+ exports.getModulesPaths = getModulesPaths;
23
+ exports.getRelativeProjectRoot = getRelativeProjectRoot;
24
+ const node_fs_1 = require("node:fs");
25
+ const node_path_1 = __importDefault(require("node:path"));
26
+ const glob_1 = require("glob");
27
+ /**
28
+ * Read and parse a JSON file, returning null if invalid.
29
+ */
30
+ function readJsonFile(filePath) {
31
+ const file = (0, node_fs_1.readFileSync)(filePath, "utf8");
32
+ return JSON.parse(file);
33
+ }
34
+ /**
35
+ * Check if a file is a valid JSON file.
36
+ */
37
+ function isValidJsonFile(filePath) {
38
+ try {
39
+ readJsonFile(filePath);
40
+ return true;
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ }
46
+ /**
47
+ * Glob all package.json paths in a workspace.
48
+ * Matches Expo's implementation pattern.
49
+ *
50
+ * @param workspaceRoot Root file path for the workspace
51
+ * @param linkedPackages List of folders that contain linked node modules, ex: `['packages/*', 'apps/*']`
52
+ * @returns List of valid package.json file paths
53
+ */
54
+ function globAllPackageJsonPaths(workspaceRoot, linkedPackages) {
55
+ return linkedPackages
56
+ .flatMap((pattern) => {
57
+ // Globs should only contain `/` as separator, even on Windows.
58
+ return (0, glob_1.globSync)(node_path_1.default.posix.join(pattern, "package.json").replace(/\\/g, "/"), {
59
+ cwd: workspaceRoot,
60
+ absolute: true,
61
+ ignore: ["**/@(Carthage|Pods|node_modules)/**"],
62
+ }).filter((pkgPath) => isValidJsonFile(pkgPath));
63
+ })
64
+ .map((p) => node_path_1.default.join(p));
65
+ }
66
+ /**
67
+ * Resolve all workspace package.json paths.
68
+ *
69
+ * @param workspaceRoot root file path for a workspace.
70
+ * @returns list of package.json file paths that are linked to the workspace.
71
+ */
72
+ function resolveAllWorkspacePackageJsonPaths(workspaceRoot) {
73
+ try {
74
+ const workspaceGlobs = getWorkspaceGlobs(workspaceRoot);
75
+ if (!workspaceGlobs?.length)
76
+ return [];
77
+ return globAllPackageJsonPaths(workspaceRoot, workspaceGlobs);
78
+ }
79
+ catch {
80
+ return [];
81
+ }
82
+ }
83
+ /**
84
+ * Resolve the workspace root directory.
85
+ * Returns the project root if not in a workspace.
86
+ */
87
+ function getWorkspaceRoot(projectRoot) {
88
+ try {
89
+ // Dynamic import to handle the package
90
+ const { resolveWorkspaceRoot } = require("resolve-workspace-root");
91
+ const workspaceRoot = resolveWorkspaceRoot(projectRoot);
92
+ return workspaceRoot || projectRoot;
93
+ }
94
+ catch {
95
+ // Fallback: check for turbo.jsonc or package.json with workspaces
96
+ return findMonorepoRootFallback(projectRoot);
97
+ }
98
+ }
99
+ /**
100
+ * Fallback monorepo root detection for when resolve-workspace-root fails.
101
+ * Checks for turbo.jsonc or package.json with workspaces field.
102
+ */
103
+ function findMonorepoRootFallback(startDir) {
104
+ let current = startDir;
105
+ while (current !== node_path_1.default.dirname(current)) {
106
+ const turboConfig = node_path_1.default.join(current, "turbo.jsonc");
107
+ const turboJson = node_path_1.default.join(current, "turbo.json");
108
+ const packageJson = node_path_1.default.join(current, "package.json");
109
+ if ((0, node_fs_1.existsSync)(turboConfig) || (0, node_fs_1.existsSync)(turboJson)) {
110
+ return current;
111
+ }
112
+ if ((0, node_fs_1.existsSync)(packageJson)) {
113
+ try {
114
+ const pkg = JSON.parse((0, node_fs_1.readFileSync)(packageJson, "utf8"));
115
+ if (pkg.workspaces) {
116
+ return current;
117
+ }
118
+ }
119
+ catch {
120
+ // Ignore parse errors
121
+ }
122
+ }
123
+ current = node_path_1.default.dirname(current);
124
+ }
125
+ return startDir;
126
+ }
127
+ /**
128
+ * Get workspace glob patterns from the workspace root.
129
+ */
130
+ function getWorkspaceGlobs(workspaceRoot) {
131
+ try {
132
+ const { getWorkspaceGlobs: getGlobs } = require("resolve-workspace-root");
133
+ return getGlobs(workspaceRoot) ?? [];
134
+ }
135
+ catch {
136
+ // Fallback: try to read from package.json
137
+ const packageJsonPath = node_path_1.default.join(workspaceRoot, "package.json");
138
+ if ((0, node_fs_1.existsSync)(packageJsonPath)) {
139
+ try {
140
+ const pkg = JSON.parse((0, node_fs_1.readFileSync)(packageJsonPath, "utf8"));
141
+ if (Array.isArray(pkg.workspaces)) {
142
+ return pkg.workspaces;
143
+ }
144
+ if (pkg.workspaces?.packages) {
145
+ return pkg.workspaces.packages;
146
+ }
147
+ }
148
+ catch {
149
+ // Ignore parse errors
150
+ }
151
+ }
152
+ return [];
153
+ }
154
+ }
155
+ /**
156
+ * Check if the project is in a monorepo (workspace root differs from project root).
157
+ */
158
+ function isInMonorepo(projectRoot) {
159
+ const workspaceRoot = getWorkspaceRoot(projectRoot);
160
+ return workspaceRoot !== projectRoot;
161
+ }
162
+ /**
163
+ * Get the Metro server root for monorepo support.
164
+ * This should be set as `unstable_serverRoot` in Metro config.
165
+ */
166
+ function getMetroServerRoot(projectRoot) {
167
+ // Can be disabled with environment variable
168
+ if (process.env.TEARDOWN_NO_METRO_WORKSPACE_ROOT) {
169
+ return projectRoot;
170
+ }
171
+ return getWorkspaceRoot(projectRoot);
172
+ }
173
+ /**
174
+ * Helper to get unique items from an array.
175
+ */
176
+ function uniqueItems(items) {
177
+ return [...new Set(items)];
178
+ }
179
+ /**
180
+ * Get watch folders for Metro in a monorepo setup.
181
+ *
182
+ * Returns:
183
+ * - Empty array if not in a monorepo
184
+ * - Workspace root node_modules + all workspace package directories if in monorepo
185
+ */
186
+ function getWatchFolders(projectRoot) {
187
+ const resolvedProjectRoot = node_path_1.default.resolve(projectRoot);
188
+ const workspaceRoot = getMetroServerRoot(resolvedProjectRoot);
189
+ // Rely on default behavior in standard projects.
190
+ if (workspaceRoot === resolvedProjectRoot) {
191
+ return [];
192
+ }
193
+ const packages = resolveAllWorkspacePackageJsonPaths(workspaceRoot);
194
+ if (!packages?.length) {
195
+ return [];
196
+ }
197
+ return uniqueItems([node_path_1.default.join(workspaceRoot, "node_modules"), ...packages.map((pkg) => node_path_1.default.dirname(pkg))]);
198
+ }
199
+ /**
200
+ * Get node module paths for Metro resolver.
201
+ *
202
+ * Returns paths in priority order:
203
+ * 1. Project's local node_modules (always included)
204
+ * 2. Workspace root node_modules (if in monorepo)
205
+ *
206
+ * The project's node_modules must always be included to support packages
207
+ * that publish TypeScript source and need to resolve peer dependencies
208
+ * (e.g., react-native) from deeply nested paths.
209
+ */
210
+ function getModulesPaths(projectRoot) {
211
+ const resolvedProjectRoot = node_path_1.default.resolve(projectRoot);
212
+ const workspaceRoot = getMetroServerRoot(resolvedProjectRoot);
213
+ // Always include project's node_modules for proper peer dependency resolution
214
+ const paths = [node_path_1.default.resolve(projectRoot, "node_modules")];
215
+ // Add workspace root node_modules if in a monorepo
216
+ if (workspaceRoot !== resolvedProjectRoot) {
217
+ paths.push(node_path_1.default.resolve(workspaceRoot, "node_modules"));
218
+ }
219
+ return paths;
220
+ }
221
+ /**
222
+ * Get the relative project root from workspace root.
223
+ * Used for cache key generation to prevent collisions in monorepos.
224
+ */
225
+ function getRelativeProjectRoot(projectRoot) {
226
+ const workspaceRoot = getWorkspaceRoot(projectRoot);
227
+ if (workspaceRoot === projectRoot) {
228
+ return "";
229
+ }
230
+ return node_path_1.default.relative(workspaceRoot, projectRoot);
231
+ }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@teardown/metro-config",
3
- "version": "2.0.87",
3
+ "version": "2.0.89",
4
4
  "description": "Metro configuration for Teardown - Rust-powered transforms via Facetpack",
5
5
  "private": false,
6
6
  "publishConfig": {
7
7
  "access": "public"
8
8
  },
9
- "type": "commonjs",
10
- "main": "./dist/index.js",
9
+ "main": "dist/index.js",
10
+ "types": "dist/index.d.ts",
11
11
  "exports": {
12
12
  ".": {
13
13
  "types": "./dist/index.d.ts",
@@ -25,12 +25,13 @@
25
25
  "dist/**/*"
26
26
  ],
27
27
  "scripts": {
28
- "build": "tsc",
28
+ "build": "rm -rf dist && tsc -p tsconfig.json",
29
29
  "prepublishOnly": "bun run build",
30
30
  "typecheck": "bunx tsgo --noEmit",
31
31
  "lint": "bun x biome lint --write ./src",
32
32
  "fmt": "bun x biome format --write ./src",
33
- "check": "bun x biome check ./src"
33
+ "check": "bun x biome check ./src",
34
+ "test": "bun test"
34
35
  },
35
36
  "peerDependencies": {
36
37
  "@ecrindigital/facetpack": "^0.2.0",
@@ -52,7 +53,7 @@
52
53
  "devDependencies": {
53
54
  "@typescript/native-preview": "^7.0.0-dev.20260203.1",
54
55
  "@ecrindigital/facetpack": "^0.2.0",
55
- "@teardown/tsconfig": "2.0.87",
56
+ "@teardown/tsconfig": "2.0.89",
56
57
  "@types/bun": "1.3.8",
57
58
  "@types/node": "24.10.1",
58
59
  "typescript": "5.9.3"