0
# File System Mapping
1
2
Core file system crawling and mapping functionality for creating fast lookups of project files. Supports parallel processing, intelligent caching, and multiple crawler implementations for optimal performance across different environments.
3
4
## Capabilities
5
6
### HasteMap Class
7
8
The main class for orchestrating file system mapping, providing factory methods and lifecycle management.
9
10
```typescript { .api }
11
/**
12
* Main class for creating and managing haste maps
13
* Extends EventEmitter to provide change notifications in watch mode
14
*/
15
class HasteMap extends EventEmitter implements IHasteMap {
16
/**
17
* Factory method to create a HasteMap instance with proper cache setup
18
* @param options - Configuration options for the haste map
19
* @returns Promise resolving to configured IHasteMap instance
20
*/
21
static create(options: Options): Promise<IHasteMap>;
22
23
/**
24
* Get static HasteMap implementation, supports custom implementations
25
* @param config - Jest project configuration
26
* @returns HasteMapStatic implementation
27
*/
28
static getStatic(config: Config.ProjectConfig): HasteMapStatic;
29
30
/**
31
* Build the complete haste map by crawling files and extracting metadata
32
* @returns Promise with hasteFS for file operations and moduleMap for resolution
33
*/
34
build(): Promise<{hasteFS: IHasteFS; moduleMap: IModuleMap}>;
35
36
/**
37
* Get the cache file path for this haste map instance
38
* @returns Absolute path to cache file
39
*/
40
getCacheFilePath(): string;
41
42
/**
43
* Read existing haste map data from cache
44
* @returns Internal haste map data structure
45
*/
46
read(): InternalHasteMap;
47
48
/**
49
* Read just the module map from cache, faster than full read
50
* @returns ModuleMap instance from cached data
51
*/
52
readModuleMap(): HasteModuleMap;
53
54
/**
55
* Stop file watching and cleanup resources
56
* @returns Promise that resolves when cleanup is complete
57
*/
58
end(): Promise<void>;
59
}
60
```
61
62
### Configuration Options
63
64
Comprehensive configuration interface for customizing haste map behavior.
65
66
```typescript { .api }
67
/**
68
* Configuration options for HasteMap creation
69
*/
70
interface Options {
71
/** Unique identifier for caching, typically project name */
72
id: string;
73
/** File extensions to include in the map */
74
extensions: Array<string>;
75
/** Maximum number of worker processes for parallel processing */
76
maxWorkers: number;
77
/** Platform extensions to recognize (e.g., ['ios', 'android']) */
78
platforms: Array<string>;
79
/** Whether to retain all files in memory, including node_modules */
80
retainAllFiles: boolean;
81
/** Root directory of the project */
82
rootDir: string;
83
/** Directories to crawl, subset of rootDir */
84
roots: Array<string>;
85
86
/** Directory for cache storage, defaults to os.tmpdir() */
87
cacheDirectory?: string;
88
/** Whether to compute file dependencies, defaults to true */
89
computeDependencies?: boolean;
90
/** Whether to compute SHA-1 hashes for files, defaults to false */
91
computeSha1?: boolean;
92
/** Console instance for logging, defaults to global console */
93
console?: Console;
94
/** Path to custom dependency extractor module */
95
dependencyExtractor?: string | null;
96
/** Whether to follow symbolic links, defaults to false */
97
enableSymlinks?: boolean;
98
/** Force Node.js filesystem API instead of native implementations */
99
forceNodeFilesystemAPI?: boolean;
100
/** Path to custom haste implementation module */
101
hasteImplModulePath?: string;
102
/** Path to custom haste map implementation module */
103
hasteMapModulePath?: string;
104
/** Pattern to ignore files and directories */
105
ignorePattern?: HasteRegExp;
106
/** Pattern to identify mock files */
107
mocksPattern?: string;
108
/** Whether to clear existing cache before building */
109
resetCache?: boolean;
110
/** Whether to skip processing package.json files */
111
skipPackageJson?: boolean;
112
/** Whether to throw errors on module name collisions */
113
throwOnModuleCollision?: boolean;
114
/** Whether to use Watchman for file system operations, defaults to true */
115
useWatchman?: boolean;
116
/** Whether to enable file system watching, defaults to false */
117
watch?: boolean;
118
/** Whether to use worker threads instead of child processes */
119
workerThreads?: boolean;
120
}
121
```
122
123
### Static Utility Methods
124
125
Static methods for cache management and module map creation.
126
127
```typescript { .api }
128
/**
129
* Generate cache file path with deterministic hashing
130
* @param tmpdir - Temporary directory for cache storage
131
* @param id - Base identifier for the cache file
132
* @param extra - Additional parameters for cache key generation
133
* @returns Absolute path to cache file
134
*/
135
static getCacheFilePath(
136
tmpdir: string,
137
id: string,
138
...extra: Array<string>
139
): string;
140
141
/**
142
* Create ModuleMap instance from serialized JSON data
143
* @param json - Serialized module map data
144
* @returns ModuleMap instance
145
*/
146
static getModuleMapFromJSON(json: SerializableModuleMap): HasteModuleMap;
147
```
148
149
**Usage Examples:**
150
151
```typescript
152
import HasteMap from "jest-haste-map";
153
import os from "os";
154
155
// Basic project mapping
156
const hasteMap = await HasteMap.create({
157
id: "my-app",
158
extensions: ["js", "ts", "jsx", "tsx"],
159
maxWorkers: os.availableParallelism(),
160
platforms: [],
161
roots: ["/src", "/tests"],
162
retainAllFiles: false,
163
rootDir: "/project/root",
164
});
165
166
// Build the map
167
const {hasteFS, moduleMap} = await hasteMap.build();
168
169
// Advanced configuration with caching and watching
170
const advancedMap = await HasteMap.create({
171
id: "advanced-project",
172
extensions: ["js", "ts", "json"],
173
maxWorkers: 4,
174
platforms: ["ios", "android", "web"],
175
roots: ["/src"],
176
retainAllFiles: true,
177
rootDir: "/project/root",
178
cacheDirectory: "/tmp/haste-cache",
179
computeDependencies: true,
180
computeSha1: true,
181
watch: true,
182
useWatchman: true,
183
ignorePattern: /node_modules|\.git/,
184
mocksPattern: "__mocks__",
185
});
186
187
// Handle file changes in watch mode
188
advancedMap.on('change', (event) => {
189
console.log('Files changed:', event.eventsQueue.length);
190
// Access updated file system and module map
191
const updatedFiles = event.hasteFS.getAllFiles();
192
});
193
194
// Clean up when done
195
await advancedMap.end();
196
```
197
198
### Internal Data Structures
199
200
Core data structures used internally by the haste map system.
201
202
```typescript { .api }
203
/**
204
* Internal representation of the complete haste map
205
*/
206
interface InternalHasteMap {
207
/** Watchman clock specifications for change detection */
208
clocks: WatchmanClocks;
209
/** Map of duplicate module names to their file paths */
210
duplicates: DuplicatesIndex;
211
/** Map of file paths to metadata arrays */
212
files: FileData;
213
/** Map of module names to platform-specific metadata */
214
map: ModuleMapData;
215
/** Map of mock names to file paths */
216
mocks: MockData;
217
}
218
219
/**
220
* File metadata stored as array for memory efficiency
221
* [id, mtime, size, visited, dependencies, sha1]
222
*/
223
type FileMetaData = [
224
id: string,
225
mtime: number,
226
size: number,
227
visited: 0 | 1,
228
dependencies: string,
229
sha1: string | null | undefined,
230
];
231
232
type FileData = Map<string, FileMetaData>;
233
type ModuleMapData = Map<string, ModuleMapItem>;
234
type MockData = Map<string, string>;
235
type WatchmanClocks = Map<string, WatchmanClockSpec>;
236
type WatchmanClockSpec = string | {scm: {'mergebase-with': string}};
237
```