id
int64
0
3.78k
code
stringlengths
13
37.9k
declarations
stringlengths
16
64.6k
1,600
create(options: Options): Promise<IHasteMap>
interface Options extends ShouldInstrumentOptions, CallerTransformOptions { isInternalModule?: boolean; }
1,601
create(options: Options): Promise<IHasteMap>
type Options = { clearTimeout: (typeof globalThis)['clearTimeout']; fail: (error: Error) => void; onException: (error: Error) => void; queueableFns: Array<QueueableFn>; setTimeout: (typeof globalThis)['setTimeout']; userContext: unknown; };
1,602
create(options: Options): Promise<IHasteMap>
type Options = { matcherName: string; passed: boolean; actual?: any; error?: any; expected?: any; message?: string | null; };
1,603
create(options: Options): Promise<IHasteMap>
type Options = { nodeComplete: (suite: TreeNode) => void; nodeStart: (suite: TreeNode) => void; queueRunnerFactory: any; runnableIds: Array<string>; tree: TreeNode; };
1,604
create(options: Options): Promise<IHasteMap>
type Options = { lastCommit?: boolean; withAncestor?: boolean; changedSince?: string; includePaths?: Array<string>; };
1,605
create(options: Options): Promise<IHasteMap>
type Options = { cacheDirectory?: string; computeDependencies?: boolean; computeSha1?: boolean; console?: Console; dependencyExtractor?: string | null; enableSymlinks?: boolean; extensions: Array<string>; forceNodeFilesystemAPI?: boolean; hasteImplModulePath?: string; hasteMapModulePath?: string; id: string; ignorePattern?: HasteRegExp; maxWorkers: number; mocksPattern?: string; platforms: Array<string>; resetCache?: boolean; retainAllFiles: boolean; rootDir: string; roots: Array<string>; skipPackageJson?: boolean; throwOnModuleCollision?: boolean; useWatchman?: boolean; watch?: boolean; };
1,606
create(options: Options): Promise<IHasteMap>
interface Options extends Omit<RequiredOptions, 'compareKeys' | 'theme'> { compareKeys: CompareKeys; theme: Required<RequiredOptions['theme']>; }
1,607
async function worker(data: WorkerMessage): Promise<WorkerMetadata> { if ( data.hasteImplModulePath && data.hasteImplModulePath !== hasteImplModulePath ) { if (hasteImpl) { throw new Error('jest-haste-map: hasteImplModulePath changed'); } hasteImplModulePath = data.hasteImplModulePath; hasteImpl = require(hasteImplModulePath); } let content: string | undefined; let dependencies: WorkerMetadata['dependencies']; let id: WorkerMetadata['id']; let module: WorkerMetadata['module']; let sha1: WorkerMetadata['sha1']; const {computeDependencies, computeSha1, rootDir, filePath} = data; const getContent = (): string => { if (content === undefined) { content = fs.readFileSync(filePath, 'utf8'); } return content; }; if (filePath.endsWith(PACKAGE_JSON)) { // Process a package.json that is returned as a PACKAGE type with its name. try { const fileData = JSON.parse(getContent()); if (fileData.name) { const relativeFilePath = path.relative(rootDir, filePath); id = fileData.name; module = [relativeFilePath, H.PACKAGE]; } } catch (err: any) { throw new Error(`Cannot parse ${filePath} as JSON: ${err.message}`); } } else if (!blacklist.has(filePath.substring(filePath.lastIndexOf('.')))) { // Process a random file that is returned as a MODULE. if (hasteImpl) { id = hasteImpl.getHasteName(filePath); } if (computeDependencies) { const content = getContent(); const extractor = data.dependencyExtractor ? await requireOrImportModule<DependencyExtractor>( data.dependencyExtractor, false, ) : defaultDependencyExtractor; dependencies = Array.from( extractor.extract( content, filePath, defaultDependencyExtractor.extract, ), ); } if (id) { const relativeFilePath = path.relative(rootDir, filePath); module = [relativeFilePath, H.MODULE]; } } // If a SHA-1 is requested on update, compute it. if (computeSha1) { sha1 = sha1hex(content || fs.readFileSync(filePath)); } return {dependencies, id, module, sha1}; }
type WorkerMessage = { computeDependencies: boolean; computeSha1: boolean; dependencyExtractor?: string | null; rootDir: string; filePath: string; hasteImplModulePath?: string; retainAllFiles?: boolean; };
1,608
async function getSha1(data: WorkerMessage): Promise<WorkerMetadata> { const sha1 = data.computeSha1 ? sha1hex(fs.readFileSync(data.filePath)) : null; return { dependencies: undefined, id: undefined, module: undefined, sha1, }; }
type WorkerMessage = { computeDependencies: boolean; computeSha1: boolean; dependencyExtractor?: string | null; rootDir: string; filePath: string; hasteImplModulePath?: string; retainAllFiles?: boolean; };
1,609
constructor(raw: RawModuleMap) { this._raw = raw; }
type RawModuleMap = { rootDir: string; duplicates: DuplicatesIndex; map: ModuleMapData; mocks: MockData; };
1,610
static fromJSON(serializableModuleMap: SerializableModuleMap): ModuleMap { return new ModuleMap({ duplicates: ModuleMap.mapFromArrayRecursive( serializableModuleMap.duplicates, ) as RawModuleMap['duplicates'], map: new Map(serializableModuleMap.map), mocks: new Map(serializableModuleMap.mocks), rootDir: serializableModuleMap.rootDir, }); }
type SerializableModuleMap = { duplicates: ReadonlyArray<[string, [string, [string, [string, number]]]]>; map: ReadonlyArray<[string, ValueType<ModuleMapData>]>; mocks: ReadonlyArray<[string, ValueType<MockData>]>; rootDir: string; };
1,611
async function watchmanCrawl(options: CrawlerOptions): Promise<{ changedFiles?: FileData; removedFiles: FileData; hasteMap: InternalHasteMap; }> { const fields = ['name', 'exists', 'mtime_ms', 'size']; const {data, extensions, ignore, rootDir, roots} = options; const defaultWatchExpression: Array<any> = ['allof', ['type', 'f']]; const clocks = data.clocks; const client = new watchman.Client(); // https://facebook.github.io/watchman/docs/capabilities.html // Check adds about ~28ms const capabilities = await capabilityCheck(client, { // If a required capability is missing then an error will be thrown, // we don't need this assertion, so using optional instead. optional: ['suffix-set'], }); if (capabilities?.capabilities['suffix-set']) { // If available, use the optimized `suffix-set` operation: // https://facebook.github.io/watchman/docs/expr/suffix.html#suffix-set defaultWatchExpression.push(['suffix', extensions]); } else { // Otherwise use the older and less optimal suffix tuple array defaultWatchExpression.push([ 'anyof', ...extensions.map(extension => ['suffix', extension]), ]); } let clientError; client.on('error', error => (clientError = WatchmanError(error))); const cmd = <T>(...args: Array<any>): Promise<T> => new Promise((resolve, reject) => client.command(args, (error, result) => error ? reject(WatchmanError(error)) : resolve(result), ), ); if (options.computeSha1) { const {capabilities} = await cmd<WatchmanListCapabilitiesResponse>( 'list-capabilities', ); if (capabilities.indexOf('field-content.sha1hex') !== -1) { fields.push('content.sha1hex'); } } async function getWatchmanRoots( roots: Array<string>, ): Promise<WatchmanRoots> { const watchmanRoots = new Map(); await Promise.all( roots.map(async root => { const response = await cmd<WatchmanWatchProjectResponse>( 'watch-project', root, ); const existing = watchmanRoots.get(response.watch); // A root can only be filtered if it was never seen with a // relative_path before. const canBeFiltered = !existing || existing.length > 0; if (canBeFiltered) { if (response.relative_path) { watchmanRoots.set( response.watch, (existing || []).concat(response.relative_path), ); } else { // Make the filter directories an empty array to signal that this // root was already seen and needs to be watched for all files or // directories. watchmanRoots.set(response.watch, []); } } }), ); return watchmanRoots; } async function queryWatchmanForDirs(rootProjectDirMappings: WatchmanRoots) { const results = new Map<string, WatchmanQueryResponse>(); let isFresh = false; await Promise.all( Array.from(rootProjectDirMappings).map( async ([root, directoryFilters]) => { const expression = Array.from(defaultWatchExpression); const glob = []; if (directoryFilters.length > 0) { expression.push([ 'anyof', ...directoryFilters.map(dir => ['dirname', dir]), ]); for (const directory of directoryFilters) { for (const extension of extensions) { glob.push(`${directory}/**/*.${extension}`); } } } else { for (const extension of extensions) { glob.push(`**/*.${extension}`); } } // Jest is only going to store one type of clock; a string that // represents a local clock. However, the Watchman crawler supports // a second type of clock that can be written by automation outside of // Jest, called an "scm query", which fetches changed files based on // source control mergebases. The reason this is necessary is because // local clocks are not portable across systems, but scm queries are. // By using scm queries, we can create the haste map on a different // system and import it, transforming the clock into a local clock. const since = clocks.get(fastPath.relative(rootDir, root)); const query = since !== undefined ? // Use the `since` generator if we have a clock available {expression, fields, since} : // Otherwise use the `glob` filter {expression, fields, glob, glob_includedotfiles: true}; const response = await cmd<WatchmanQueryResponse>( 'query', root, query, ); if ('warning' in response) { console.warn('watchman warning: ', response.warning); } // When a source-control query is used, we ignore the "is fresh" // response from Watchman because it will be true despite the query // being incremental. const isSourceControlQuery = typeof since !== 'string' && since?.scm?.['mergebase-with'] !== undefined; if (!isSourceControlQuery) { isFresh = isFresh || response.is_fresh_instance; } results.set(root, response); }, ), ); return { isFresh, results, }; } let files = data.files; let removedFiles = new Map(); const changedFiles = new Map(); let results: Map<string, WatchmanQueryResponse>; let isFresh = false; try { const watchmanRoots = await getWatchmanRoots(roots); const watchmanFileResults = await queryWatchmanForDirs(watchmanRoots); // Reset the file map if watchman was restarted and sends us a list of // files. if (watchmanFileResults.isFresh) { files = new Map(); removedFiles = new Map(data.files); isFresh = true; } results = watchmanFileResults.results; } finally { client.end(); } if (clientError) { throw clientError; } for (const [watchRoot, response] of results) { const fsRoot = normalizePathSep(watchRoot); const relativeFsRoot = fastPath.relative(rootDir, fsRoot); clocks.set( relativeFsRoot, // Ensure we persist only the local clock. typeof response.clock === 'string' ? response.clock : response.clock.clock, ); for (const fileData of response.files) { const filePath = fsRoot + path.sep + normalizePathSep(fileData.name); const relativeFilePath = fastPath.relative(rootDir, filePath); const existingFileData = data.files.get(relativeFilePath); // If watchman is fresh, the removed files map starts with all files // and we remove them as we verify they still exist. if (isFresh && existingFileData && fileData.exists) { removedFiles.delete(relativeFilePath); } if (!fileData.exists) { // No need to act on files that do not exist and were not tracked. if (existingFileData) { files.delete(relativeFilePath); // If watchman is not fresh, we will know what specific files were // deleted since we last ran and can track only those files. if (!isFresh) { removedFiles.set(relativeFilePath, existingFileData); } } } else if (!ignore(filePath)) { const mtime = typeof fileData.mtime_ms === 'number' ? fileData.mtime_ms : fileData.mtime_ms.toNumber(); const size = fileData.size; let sha1hex = fileData['content.sha1hex']; if (typeof sha1hex !== 'string' || sha1hex.length !== 40) { sha1hex = undefined; } let nextData: FileMetaData; if (existingFileData && existingFileData[H.MTIME] === mtime) { nextData = existingFileData; } else if ( existingFileData && sha1hex && existingFileData[H.SHA1] === sha1hex ) { nextData = [ existingFileData[0], mtime, existingFileData[2], existingFileData[3], existingFileData[4], existingFileData[5], ]; } else { // See ../constants.ts nextData = ['', mtime, size, 0, '', sha1hex ?? null]; } files.set(relativeFilePath, nextData); changedFiles.set(relativeFilePath, nextData); } } } data.files = files; return { changedFiles: isFresh ? undefined : changedFiles, hasteMap: data, removedFiles, }; }
type CrawlerOptions = { computeSha1: boolean; enableSymlinks: boolean; data: InternalHasteMap; extensions: Array<string>; forceNodeFilesystemAPI: boolean; ignore: IgnoreMatcher; rootDir: string; roots: Array<string>; };
1,612
async function queryWatchmanForDirs(rootProjectDirMappings: WatchmanRoots) { const results = new Map<string, WatchmanQueryResponse>(); let isFresh = false; await Promise.all( Array.from(rootProjectDirMappings).map( async ([root, directoryFilters]) => { const expression = Array.from(defaultWatchExpression); const glob = []; if (directoryFilters.length > 0) { expression.push([ 'anyof', ...directoryFilters.map(dir => ['dirname', dir]), ]); for (const directory of directoryFilters) { for (const extension of extensions) { glob.push(`${directory}/**/*.${extension}`); } } } else { for (const extension of extensions) { glob.push(`**/*.${extension}`); } } // Jest is only going to store one type of clock; a string that // represents a local clock. However, the Watchman crawler supports // a second type of clock that can be written by automation outside of // Jest, called an "scm query", which fetches changed files based on // source control mergebases. The reason this is necessary is because // local clocks are not portable across systems, but scm queries are. // By using scm queries, we can create the haste map on a different // system and import it, transforming the clock into a local clock. const since = clocks.get(fastPath.relative(rootDir, root)); const query = since !== undefined ? // Use the `since` generator if we have a clock available {expression, fields, since} : // Otherwise use the `glob` filter {expression, fields, glob, glob_includedotfiles: true}; const response = await cmd<WatchmanQueryResponse>( 'query', root, query, ); if ('warning' in response) { console.warn('watchman warning: ', response.warning); } // When a source-control query is used, we ignore the "is fresh" // response from Watchman because it will be true despite the query // being incremental. const isSourceControlQuery = typeof since !== 'string' && since?.scm?.['mergebase-with'] !== undefined; if (!isSourceControlQuery) { isFresh = isFresh || response.is_fresh_instance; } results.set(root, response); }, ), ); return { isFresh, results, }; }
type WatchmanRoots = Map<string, Array<string>>;
1,613
(result: Result) => void
interface Result extends ExecaSyncReturnValue { status: number; error: string; }
1,614
(result: Result) => void
type Result = Array<[/* id */ string, /* mtime */ number, /* size */ number]>;
1,615
async function nodeCrawl(options: CrawlerOptions): Promise<{ removedFiles: FileData; hasteMap: InternalHasteMap; }> { const { data, extensions, forceNodeFilesystemAPI, ignore, rootDir, enableSymlinks, roots, } = options; const useNativeFind = await hasNativeFindSupport(forceNodeFilesystemAPI); return new Promise(resolve => { const callback = (list: Result) => { const files = new Map(); const removedFiles = new Map(data.files); list.forEach(fileData => { const [filePath, mtime, size] = fileData; const relativeFilePath = fastPath.relative(rootDir, filePath); const existingFile = data.files.get(relativeFilePath); if (existingFile && existingFile[H.MTIME] === mtime) { files.set(relativeFilePath, existingFile); } else { // See ../constants.js; SHA-1 will always be null and fulfilled later. files.set(relativeFilePath, ['', mtime, size, 0, '', null]); } removedFiles.delete(relativeFilePath); }); data.files = files; resolve({ hasteMap: data, removedFiles, }); }; if (useNativeFind) { findNative(roots, extensions, ignore, enableSymlinks, callback); } else { find(roots, extensions, ignore, enableSymlinks, callback); } }); }
type CrawlerOptions = { computeSha1: boolean; enableSymlinks: boolean; data: InternalHasteMap; extensions: Array<string>; forceNodeFilesystemAPI: boolean; ignore: IgnoreMatcher; rootDir: string; roots: Array<string>; };
1,616
(list: Result) => { const files = new Map(); const removedFiles = new Map(data.files); list.forEach(fileData => { const [filePath, mtime, size] = fileData; const relativeFilePath = fastPath.relative(rootDir, filePath); const existingFile = data.files.get(relativeFilePath); if (existingFile && existingFile[H.MTIME] === mtime) { files.set(relativeFilePath, existingFile); } else { // See ../constants.js; SHA-1 will always be null and fulfilled later. files.set(relativeFilePath, ['', mtime, size, 0, '', null]); } removedFiles.delete(relativeFilePath); }); data.files = files; resolve({ hasteMap: data, removedFiles, }); }
interface Result extends ExecaSyncReturnValue { status: number; error: string; }
1,617
(list: Result) => { const files = new Map(); const removedFiles = new Map(data.files); list.forEach(fileData => { const [filePath, mtime, size] = fileData; const relativeFilePath = fastPath.relative(rootDir, filePath); const existingFile = data.files.get(relativeFilePath); if (existingFile && existingFile[H.MTIME] === mtime) { files.set(relativeFilePath, existingFile); } else { // See ../constants.js; SHA-1 will always be null and fulfilled later. files.set(relativeFilePath, ['', mtime, size, 0, '', null]); } removedFiles.delete(relativeFilePath); }); data.files = files; resolve({ hasteMap: data, removedFiles, }); }
type Result = Array<[/* id */ string, /* mtime */ number, /* size */ number]>;
1,618
private _emit(type: FsEventsWatcherEvent, file: string, stat?: fs.Stats) { this.emit(type, file, this.root, stat); this.emit(ALL_EVENT, type, file, this.root, stat); }
type FsEventsWatcherEvent = | typeof CHANGE_EVENT | typeof DELETE_EVENT | typeof ADD_EVENT | typeof ALL_EVENT;
1,619
function isNewPlugin(plugin: Plugin): plugin is NewPlugin { return (plugin as NewPlugin).serialize != null; }
type Plugin = NewPlugin | OldPlugin;
1,620
function printPlugin( plugin: Plugin, val: any, config: Config, indentation: string, depth: number, refs: Refs, ): string { let printed; try { printed = isNewPlugin(plugin) ? plugin.serialize(val, config, indentation, depth, refs, printer) : plugin.print( val, valChild => printer(valChild, config, indentation, depth, refs), str => { const indentationNext = indentation + config.indent; return ( indentationNext + str.replace(NEWLINE_REGEXP, `\n${indentationNext}`) ); }, { edgeSpacing: config.spacingOuter, min: config.min, spacing: config.spacingInner, }, config.colors, ); } catch (error: any) { throw new PrettyFormatPluginError(error.message, error.stack); } if (typeof printed !== 'string') { throw new Error( `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".`, ); } return printed; }
type Plugin = NewPlugin | OldPlugin;
1,621
function printPlugin( plugin: Plugin, val: any, config: Config, indentation: string, depth: number, refs: Refs, ): string { let printed; try { printed = isNewPlugin(plugin) ? plugin.serialize(val, config, indentation, depth, refs, printer) : plugin.print( val, valChild => printer(valChild, config, indentation, depth, refs), str => { const indentationNext = indentation + config.indent; return ( indentationNext + str.replace(NEWLINE_REGEXP, `\n${indentationNext}`) ); }, { edgeSpacing: config.spacingOuter, min: config.min, spacing: config.spacingInner, }, config.colors, ); } catch (error: any) { throw new PrettyFormatPluginError(error.message, error.stack); } if (typeof printed !== 'string') { throw new Error( `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".`, ); } return printed; }
type Config = ConfigTypes.InitialOptions;
1,622
function printPlugin( plugin: Plugin, val: any, config: Config, indentation: string, depth: number, refs: Refs, ): string { let printed; try { printed = isNewPlugin(plugin) ? plugin.serialize(val, config, indentation, depth, refs, printer) : plugin.print( val, valChild => printer(valChild, config, indentation, depth, refs), str => { const indentationNext = indentation + config.indent; return ( indentationNext + str.replace(NEWLINE_REGEXP, `\n${indentationNext}`) ); }, { edgeSpacing: config.spacingOuter, min: config.min, spacing: config.spacingInner, }, config.colors, ); } catch (error: any) { throw new PrettyFormatPluginError(error.message, error.stack); } if (typeof printed !== 'string') { throw new Error( `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".`, ); } return printed; }
type Config = { callToJSON: boolean; compareKeys: CompareKeys; colors: Colors; escapeRegex: boolean; escapeString: boolean; indent: string; maxDepth: number; maxWidth: number; min: boolean; plugins: Plugins; printBasicPrototype: boolean; printFunctionName: boolean; spacingInner: string; spacingOuter: string; };
1,623
function printPlugin( plugin: Plugin, val: any, config: Config, indentation: string, depth: number, refs: Refs, ): string { let printed; try { printed = isNewPlugin(plugin) ? plugin.serialize(val, config, indentation, depth, refs, printer) : plugin.print( val, valChild => printer(valChild, config, indentation, depth, refs), str => { const indentationNext = indentation + config.indent; return ( indentationNext + str.replace(NEWLINE_REGEXP, `\n${indentationNext}`) ); }, { edgeSpacing: config.spacingOuter, min: config.min, spacing: config.spacingInner, }, config.colors, ); } catch (error: any) { throw new PrettyFormatPluginError(error.message, error.stack); } if (typeof printed !== 'string') { throw new Error( `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".`, ); } return printed; }
type Refs = Array<unknown>;
1,624
function findPlugin(plugins: Plugins, val: unknown) { for (let p = 0; p < plugins.length; p++) { try { if (plugins[p].test(val)) { return plugins[p]; } } catch (error: any) { throw new PrettyFormatPluginError(error.message, error.stack); } } return null; }
type Plugins = Array<Plugin>;
1,625
function validateOptions(options: OptionsReceived) { Object.keys(options).forEach(key => { if (!Object.prototype.hasOwnProperty.call(DEFAULT_OPTIONS, key)) { throw new Error(`pretty-format: Unknown option "${key}".`); } }); if (options.min && options.indent !== undefined && options.indent !== 0) { throw new Error( 'pretty-format: Options "min" and "indent" cannot be used together.', ); } if (options.theme !== undefined) { if (options.theme === null) { throw new Error('pretty-format: Option "theme" must not be null.'); } if (typeof options.theme !== 'object') { throw new Error( `pretty-format: Option "theme" must be of type "object" but instead received "${typeof options.theme}".`, ); } } }
type OptionsReceived = PrettyFormatOptions;
1,626
(options: OptionsReceived): Colors => DEFAULT_THEME_KEYS.reduce((colors, key) => { const value = options.theme && options.theme[key] !== undefined ? options.theme[key] : DEFAULT_THEME[key]; const color = value && (style as any)[value]; if ( color && typeof color.close === 'string' && typeof color.open === 'string' ) { colors[key] = color; } else { throw new Error( `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.`, ); } return colors; }, Object.create(null))
type OptionsReceived = PrettyFormatOptions;
1,627
(options?: OptionsReceived) => options?.printFunctionName ?? DEFAULT_OPTIONS.printFunctionName
type OptionsReceived = PrettyFormatOptions;
1,628
(options?: OptionsReceived) => options?.escapeRegex ?? DEFAULT_OPTIONS.escapeRegex
type OptionsReceived = PrettyFormatOptions;
1,629
(options?: OptionsReceived) => options?.escapeString ?? DEFAULT_OPTIONS.escapeString
type OptionsReceived = PrettyFormatOptions;
1,630
(options?: OptionsReceived): Config => ({ callToJSON: options?.callToJSON ?? DEFAULT_OPTIONS.callToJSON, colors: options?.highlight ? getColorsHighlight(options) : getColorsEmpty(), compareKeys: typeof options?.compareKeys === 'function' || options?.compareKeys === null ? options.compareKeys : DEFAULT_OPTIONS.compareKeys, escapeRegex: getEscapeRegex(options), escapeString: getEscapeString(options), indent: options?.min ? '' : createIndent(options?.indent ?? DEFAULT_OPTIONS.indent), maxDepth: options?.maxDepth ?? DEFAULT_OPTIONS.maxDepth, maxWidth: options?.maxWidth ?? DEFAULT_OPTIONS.maxWidth, min: options?.min ?? DEFAULT_OPTIONS.min, plugins: options?.plugins ?? DEFAULT_OPTIONS.plugins, printBasicPrototype: options?.printBasicPrototype ?? true, printFunctionName: getPrintFunctionName(options), spacingInner: options?.min ? ' ' : '\n', spacingOuter: options?.min ? '' : '\n', })
type OptionsReceived = PrettyFormatOptions;
1,631
function nodeIsText(node: HandledType): node is Text { return node.nodeType === TEXT_NODE; }
type HandledType = Element | Text | Comment | DocumentFragment;
1,632
function nodeIsComment(node: HandledType): node is Comment { return node.nodeType === COMMENT_NODE; }
type HandledType = Element | Text | Comment | DocumentFragment;
1,633
function nodeIsFragment(node: HandledType): node is DocumentFragment { return node.nodeType === FRAGMENT_NODE; }
type HandledType = Element | Text | Comment | DocumentFragment;
1,634
( node: HandledType, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, ) => { if (nodeIsText(node)) { return printText(node.data, config); } if (nodeIsComment(node)) { return printComment(node.data, config); } const type = nodeIsFragment(node) ? 'DocumentFragment' : node.tagName.toLowerCase(); if (++depth > config.maxDepth) { return printElementAsLeaf(type, config); } return printElement( type, printProps( nodeIsFragment(node) ? [] : Array.from(node.attributes) .map(attr => attr.name) .sort(), nodeIsFragment(node) ? {} : Array.from(node.attributes).reduce<Record<string, string>>( (props, attribute) => { props[attribute.name] = attribute.value; return props; }, {}, ), config, indentation + config.indent, depth, refs, printer, ), printChildren( Array.prototype.slice.call(node.childNodes || node.children), config, indentation + config.indent, depth, refs, printer, ), config, indentation, ); }
type Config = ConfigTypes.InitialOptions;
1,635
( node: HandledType, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, ) => { if (nodeIsText(node)) { return printText(node.data, config); } if (nodeIsComment(node)) { return printComment(node.data, config); } const type = nodeIsFragment(node) ? 'DocumentFragment' : node.tagName.toLowerCase(); if (++depth > config.maxDepth) { return printElementAsLeaf(type, config); } return printElement( type, printProps( nodeIsFragment(node) ? [] : Array.from(node.attributes) .map(attr => attr.name) .sort(), nodeIsFragment(node) ? {} : Array.from(node.attributes).reduce<Record<string, string>>( (props, attribute) => { props[attribute.name] = attribute.value; return props; }, {}, ), config, indentation + config.indent, depth, refs, printer, ), printChildren( Array.prototype.slice.call(node.childNodes || node.children), config, indentation + config.indent, depth, refs, printer, ), config, indentation, ); }
type Config = { callToJSON: boolean; compareKeys: CompareKeys; colors: Colors; escapeRegex: boolean; escapeString: boolean; indent: string; maxDepth: number; maxWidth: number; min: boolean; plugins: Plugins; printBasicPrototype: boolean; printFunctionName: boolean; spacingInner: string; spacingOuter: string; };
1,636
( node: HandledType, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, ) => { if (nodeIsText(node)) { return printText(node.data, config); } if (nodeIsComment(node)) { return printComment(node.data, config); } const type = nodeIsFragment(node) ? 'DocumentFragment' : node.tagName.toLowerCase(); if (++depth > config.maxDepth) { return printElementAsLeaf(type, config); } return printElement( type, printProps( nodeIsFragment(node) ? [] : Array.from(node.attributes) .map(attr => attr.name) .sort(), nodeIsFragment(node) ? {} : Array.from(node.attributes).reduce<Record<string, string>>( (props, attribute) => { props[attribute.name] = attribute.value; return props; }, {}, ), config, indentation + config.indent, depth, refs, printer, ), printChildren( Array.prototype.slice.call(node.childNodes || node.children), config, indentation + config.indent, depth, refs, printer, ), config, indentation, ); }
type HandledType = Element | Text | Comment | DocumentFragment;
1,637
( node: HandledType, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, ) => { if (nodeIsText(node)) { return printText(node.data, config); } if (nodeIsComment(node)) { return printComment(node.data, config); } const type = nodeIsFragment(node) ? 'DocumentFragment' : node.tagName.toLowerCase(); if (++depth > config.maxDepth) { return printElementAsLeaf(type, config); } return printElement( type, printProps( nodeIsFragment(node) ? [] : Array.from(node.attributes) .map(attr => attr.name) .sort(), nodeIsFragment(node) ? {} : Array.from(node.attributes).reduce<Record<string, string>>( (props, attribute) => { props[attribute.name] = attribute.value; return props; }, {}, ), config, indentation + config.indent, depth, refs, printer, ), printChildren( Array.prototype.slice.call(node.childNodes || node.children), config, indentation + config.indent, depth, refs, printer, ), config, indentation, ); }
type Refs = Array<unknown>;
1,638
( node: HandledType, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, ) => { if (nodeIsText(node)) { return printText(node.data, config); } if (nodeIsComment(node)) { return printComment(node.data, config); } const type = nodeIsFragment(node) ? 'DocumentFragment' : node.tagName.toLowerCase(); if (++depth > config.maxDepth) { return printElementAsLeaf(type, config); } return printElement( type, printProps( nodeIsFragment(node) ? [] : Array.from(node.attributes) .map(attr => attr.name) .sort(), nodeIsFragment(node) ? {} : Array.from(node.attributes).reduce<Record<string, string>>( (props, attribute) => { props[attribute.name] = attribute.value; return props; }, {}, ), config, indentation + config.indent, depth, refs, printer, ), printChildren( Array.prototype.slice.call(node.childNodes || node.children), config, indentation + config.indent, depth, refs, printer, ), config, indentation, ); }
type Printer = ( val: unknown, config: Config, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean, ) => string;
1,639
(object: ReactTestObject) => { const {props} = object; return props ? Object.keys(props) .filter(key => props[key] !== undefined) .sort() : []; }
type ReactTestObject = { $$typeof: symbol; type: string; props?: Record<string, unknown>; children?: null | Array<ReactTestChild>; };
1,640
( object: ReactTestObject, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, ) => ++depth > config.maxDepth ? printElementAsLeaf(object.type, config) : printElement( object.type, object.props ? printProps( getPropKeys(object), object.props, config, indentation + config.indent, depth, refs, printer, ) : '', object.children ? printChildren( object.children, config, indentation + config.indent, depth, refs, printer, ) : '', config, indentation, )
type ReactTestObject = { $$typeof: symbol; type: string; props?: Record<string, unknown>; children?: null | Array<ReactTestChild>; };
1,641
( object: ReactTestObject, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, ) => ++depth > config.maxDepth ? printElementAsLeaf(object.type, config) : printElement( object.type, object.props ? printProps( getPropKeys(object), object.props, config, indentation + config.indent, depth, refs, printer, ) : '', object.children ? printChildren( object.children, config, indentation + config.indent, depth, refs, printer, ) : '', config, indentation, )
type Config = ConfigTypes.InitialOptions;
1,642
( object: ReactTestObject, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, ) => ++depth > config.maxDepth ? printElementAsLeaf(object.type, config) : printElement( object.type, object.props ? printProps( getPropKeys(object), object.props, config, indentation + config.indent, depth, refs, printer, ) : '', object.children ? printChildren( object.children, config, indentation + config.indent, depth, refs, printer, ) : '', config, indentation, )
type Config = { callToJSON: boolean; compareKeys: CompareKeys; colors: Colors; escapeRegex: boolean; escapeString: boolean; indent: string; maxDepth: number; maxWidth: number; min: boolean; plugins: Plugins; printBasicPrototype: boolean; printFunctionName: boolean; spacingInner: string; spacingOuter: string; };
1,643
( object: ReactTestObject, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, ) => ++depth > config.maxDepth ? printElementAsLeaf(object.type, config) : printElement( object.type, object.props ? printProps( getPropKeys(object), object.props, config, indentation + config.indent, depth, refs, printer, ) : '', object.children ? printChildren( object.children, config, indentation + config.indent, depth, refs, printer, ) : '', config, indentation, )
type Refs = Array<unknown>;
1,644
( object: ReactTestObject, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, ) => ++depth > config.maxDepth ? printElementAsLeaf(object.type, config) : printElement( object.type, object.props ? printProps( getPropKeys(object), object.props, config, indentation + config.indent, depth, refs, printer, ) : '', object.children ? printChildren( object.children, config, indentation + config.indent, depth, refs, printer, ) : '', config, indentation, )
type Printer = ( val: unknown, config: Config, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean, ) => string;
1,645
(plugins: Plugins) => { expect.extend({ toPrettyPrintTo( received: unknown, expected: unknown, options?: OptionsReceived, ) { const prettyFormatted = prettyFormat(received, {plugins, ...options}); const pass = prettyFormatted === expected; return { actual: prettyFormatted, message: pass ? () => `${this.utils.matcherHint('.not.toBe')}\n\n` + 'Expected value to not be:\n' + ` ${this.utils.printExpected(expected)}\n` + 'Received:\n' + ` ${this.utils.printReceived(prettyFormatted)}` : () => { const diffString = this.utils.diff(expected, prettyFormatted, { expand: this.expand, }); return ( `${this.utils.matcherHint('.toBe')}\n\n` + 'Expected value to be:\n' + ` ${this.utils.printExpected(expected)}\n` + 'Received:\n' + ` ${this.utils.printReceived(prettyFormatted)}${ diffString != null ? `\n\nDifference:\n\n${diffString}` : '' }` ); }, pass, }; }, }); }
type Plugins = Array<Plugin>;
1,646
constructor(config: JestEnvironmentConfig, _context: EnvironmentContext) { const {projectConfig} = config; this.context = createContext(); const global = runInContext( 'this', Object.assign(this.context, projectConfig.testEnvironmentOptions), ) as Global.Global; this.global = global; const contextGlobals = new Set(Object.getOwnPropertyNames(global)); for (const [nodeGlobalsKey, descriptor] of nodeGlobals) { if (!contextGlobals.has(nodeGlobalsKey)) { if (descriptor.configurable) { Object.defineProperty(global, nodeGlobalsKey, { configurable: true, enumerable: descriptor.enumerable, get() { // @ts-expect-error: no index signature const val = globalThis[nodeGlobalsKey] as unknown; // override lazy getter Object.defineProperty(global, nodeGlobalsKey, { configurable: true, enumerable: descriptor.enumerable, value: val, writable: descriptor.writable === true || // Node 19 makes performance non-readable. This is probably not the correct solution. nodeGlobalsKey === 'performance', }); return val; }, set(val: unknown) { // override lazy getter Object.defineProperty(global, nodeGlobalsKey, { configurable: true, enumerable: descriptor.enumerable, value: val, writable: true, }); }, }); } else if ('value' in descriptor) { Object.defineProperty(global, nodeGlobalsKey, { configurable: false, enumerable: descriptor.enumerable, value: descriptor.value, writable: descriptor.writable, }); } else { Object.defineProperty(global, nodeGlobalsKey, { configurable: false, enumerable: descriptor.enumerable, get: descriptor.get, set: descriptor.set, }); } } } // @ts-expect-error - Buffer and gc is "missing" global.global = global; global.Buffer = Buffer; global.ArrayBuffer = ArrayBuffer; // TextEncoder (global or via 'util') references a Uint8Array constructor // different than the global one used by users in tests. This makes sure the // same constructor is referenced by both. global.Uint8Array = Uint8Array; installCommonGlobals(global, projectConfig.globals); // Node's error-message stack size is limited at 10, but it's pretty useful // to see more than that when a test fails. global.Error.stackTraceLimit = 100; if ('customExportConditions' in projectConfig.testEnvironmentOptions) { const {customExportConditions} = projectConfig.testEnvironmentOptions; if ( Array.isArray(customExportConditions) && customExportConditions.every(isString) ) { this.customExportConditions = customExportConditions; } else { throw new Error( 'Custom export conditions specified but they are not an array of strings', ); } } this.moduleMocker = new ModuleMocker(global); const timerIdToRef = (id: number) => ({ id, ref() { return this; }, unref() { return this; }, }); const timerRefToId = (timer: Timer): number | undefined => timer?.id; this.fakeTimers = new LegacyFakeTimers({ config: projectConfig, global, moduleMocker: this.moduleMocker, timerConfig: { idToRef: timerIdToRef, refToId: timerRefToId, }, }); this.fakeTimersModern = new ModernFakeTimers({ config: projectConfig, global, }); }
type EnvironmentContext = { console: Console; docblockPragmas: Record<string, string | Array<string>>; testPath: string; };
1,647
constructor(config: JestEnvironmentConfig, _context: EnvironmentContext) { const {projectConfig} = config; this.context = createContext(); const global = runInContext( 'this', Object.assign(this.context, projectConfig.testEnvironmentOptions), ) as Global.Global; this.global = global; const contextGlobals = new Set(Object.getOwnPropertyNames(global)); for (const [nodeGlobalsKey, descriptor] of nodeGlobals) { if (!contextGlobals.has(nodeGlobalsKey)) { if (descriptor.configurable) { Object.defineProperty(global, nodeGlobalsKey, { configurable: true, enumerable: descriptor.enumerable, get() { // @ts-expect-error: no index signature const val = globalThis[nodeGlobalsKey] as unknown; // override lazy getter Object.defineProperty(global, nodeGlobalsKey, { configurable: true, enumerable: descriptor.enumerable, value: val, writable: descriptor.writable === true || // Node 19 makes performance non-readable. This is probably not the correct solution. nodeGlobalsKey === 'performance', }); return val; }, set(val: unknown) { // override lazy getter Object.defineProperty(global, nodeGlobalsKey, { configurable: true, enumerable: descriptor.enumerable, value: val, writable: true, }); }, }); } else if ('value' in descriptor) { Object.defineProperty(global, nodeGlobalsKey, { configurable: false, enumerable: descriptor.enumerable, value: descriptor.value, writable: descriptor.writable, }); } else { Object.defineProperty(global, nodeGlobalsKey, { configurable: false, enumerable: descriptor.enumerable, get: descriptor.get, set: descriptor.set, }); } } } // @ts-expect-error - Buffer and gc is "missing" global.global = global; global.Buffer = Buffer; global.ArrayBuffer = ArrayBuffer; // TextEncoder (global or via 'util') references a Uint8Array constructor // different than the global one used by users in tests. This makes sure the // same constructor is referenced by both. global.Uint8Array = Uint8Array; installCommonGlobals(global, projectConfig.globals); // Node's error-message stack size is limited at 10, but it's pretty useful // to see more than that when a test fails. global.Error.stackTraceLimit = 100; if ('customExportConditions' in projectConfig.testEnvironmentOptions) { const {customExportConditions} = projectConfig.testEnvironmentOptions; if ( Array.isArray(customExportConditions) && customExportConditions.every(isString) ) { this.customExportConditions = customExportConditions; } else { throw new Error( 'Custom export conditions specified but they are not an array of strings', ); } } this.moduleMocker = new ModuleMocker(global); const timerIdToRef = (id: number) => ({ id, ref() { return this; }, unref() { return this; }, }); const timerRefToId = (timer: Timer): number | undefined => timer?.id; this.fakeTimers = new LegacyFakeTimers({ config: projectConfig, global, moduleMocker: this.moduleMocker, timerConfig: { idToRef: timerIdToRef, refToId: timerRefToId, }, }); this.fakeTimersModern = new ModernFakeTimers({ config: projectConfig, global, }); }
interface JestEnvironmentConfig { projectConfig: Config.ProjectConfig; globalConfig: Config.GlobalConfig; }
1,648
(timer: Timer): number | undefined => timer?.id
type Timer = { type: string; callback: Callback; expiry: number; interval?: number; };
1,649
(timer: Timer): number | undefined => timer?.id
class Timer { start: () => void; elapsed: () => number; constructor(options?: {now?: () => number}) { options = options || {}; const now = options.now || defaultNow; let startTime: number; this.start = function () { startTime = now(); }; this.elapsed = function () { return now() - startTime; }; } }
1,650
(timer: Timer): number | undefined => timer?.id
type Timer = { id: number; ref: () => Timer; unref: () => Timer; };
1,651
(test: Test) => Promise<void>
type Test = { context: TestContext; duration?: number; path: string; };
1,652
(test: Test) => Promise<void>
type Test = (arg0: any) => boolean;
1,653
( test: Test, serializableError: SerializableError, ) => Promise<void>
type Test = { context: TestContext; duration?: number; path: string; };
1,654
( test: Test, serializableError: SerializableError, ) => Promise<void>
type Test = (arg0: any) => boolean;
1,655
( test: Test, serializableError: SerializableError, ) => Promise<void>
type SerializableError = TestResult.SerializableError;
1,656
( test: Test, serializableError: SerializableError, ) => Promise<void>
type SerializableError = { code?: unknown; message: string; stack: string | null | undefined; type?: string; };
1,657
( test: Test, testResult: TestResult, ) => Promise<void>
type Test = { context: TestContext; duration?: number; path: string; };
1,658
( test: Test, testResult: TestResult, ) => Promise<void>
type Test = (arg0: any) => boolean;
1,659
( test: Test, testResult: TestResult, ) => Promise<void>
type TestResult = { console?: ConsoleBuffer; coverage?: CoverageMapData; displayName?: Config.DisplayName; failureMessage?: string | null; leaks: boolean; memoryUsage?: number; numFailingTests: number; numPassingTests: number; numPendingTests: number; numTodoTests: number; openHandles: Array<Error>; perfStats: { end: number; runtime: number; slow: boolean; start: number; }; skipped: boolean; snapshot: { added: number; fileDeleted: boolean; matched: number; unchecked: number; uncheckedKeys: Array<string>; unmatched: number; updated: number; }; testExecError?: SerializableError; testFilePath: string; testResults: Array<AssertionResult>; v8Coverage?: V8CoverageResult; };
1,660
( test: Test, testResult: TestResult, ) => Promise<void>
type TestResult = { duration?: number | null; errors: Array<FormattedError>; errorsDetailed: Array<MatcherResults | unknown>; invocations: number; status: TestStatus; location?: {column: number; line: number} | null; numPassingAsserts: number; retryReasons: Array<FormattedError>; testPath: Array<TestName | BlockName>; };
1,661
(test: Test) => mutex(async () => { if (watcher.isInterrupted()) { return Promise.reject(); } await this.#eventEmitter.emit('test-file-start', [test]); const promise = worker.worker({ config: test.context.config, context: { ...this._context, changedFiles: this._context.changedFiles && Array.from(this._context.changedFiles), sourcesRelatedToTestsInChangedFiles: this._context.sourcesRelatedToTestsInChangedFiles && Array.from(this._context.sourcesRelatedToTestsInChangedFiles), }, globalConfig: this._globalConfig, path: test.path, }) as PromiseWithCustomMessage<TestResult>; if (promise.UNSTABLE_onCustomMessage) { // TODO: Get appropriate type for `onCustomMessage` promise.UNSTABLE_onCustomMessage(([event, payload]: any) => this.#eventEmitter.emit(event, payload), ); } return promise; })
type Test = { context: TestContext; duration?: number; path: string; };
1,662
(test: Test) => mutex(async () => { if (watcher.isInterrupted()) { return Promise.reject(); } await this.#eventEmitter.emit('test-file-start', [test]); const promise = worker.worker({ config: test.context.config, context: { ...this._context, changedFiles: this._context.changedFiles && Array.from(this._context.changedFiles), sourcesRelatedToTestsInChangedFiles: this._context.sourcesRelatedToTestsInChangedFiles && Array.from(this._context.sourcesRelatedToTestsInChangedFiles), }, globalConfig: this._globalConfig, path: test.path, }) as PromiseWithCustomMessage<TestResult>; if (promise.UNSTABLE_onCustomMessage) { // TODO: Get appropriate type for `onCustomMessage` promise.UNSTABLE_onCustomMessage(([event, payload]: any) => this.#eventEmitter.emit(event, payload), ); } return promise; })
type Test = (arg0: any) => boolean;
1,663
async function worker({ config, globalConfig, path, context, }: WorkerData): Promise<TestResult> { try { return await runTest( path, globalConfig, config, getResolver(config), { ...context, changedFiles: context.changedFiles && new Set(context.changedFiles), sourcesRelatedToTestsInChangedFiles: context.sourcesRelatedToTestsInChangedFiles && new Set(context.sourcesRelatedToTestsInChangedFiles), }, sendMessageToJest, ); } catch (error: any) { throw formatError(error); } }
type WorkerData = { config: Config.ProjectConfig; globalConfig: Config.GlobalConfig; path: string; context: TestRunnerSerializedContext; };
1,664
function fakeConsolePush( _type: LogType, message: LogMessage, ) { const error = new ErrorWithStack( `${chalk.red( `${chalk.bold( 'Cannot log after tests are done.', )} Did you forget to wait for something async in your test?`, )}\nAttempted to log "${message}".`, fakeConsolePush, ); const formattedError = formatExecError( error, config, {noStackTrace: false}, undefined, true, ); process.stderr.write(`\n${formattedError}\n`); process.exitCode = 1; }
type LogType = | 'assert' | 'count' | 'debug' | 'dir' | 'dirxml' | 'error' | 'group' | 'groupCollapsed' | 'info' | 'log' | 'time' | 'warn';
1,665
function fakeConsolePush( _type: LogType, message: LogMessage, ) { const error = new ErrorWithStack( `${chalk.red( `${chalk.bold( 'Cannot log after tests are done.', )} Did you forget to wait for something async in your test?`, )}\nAttempted to log "${message}".`, fakeConsolePush, ); const formattedError = formatExecError( error, config, {noStackTrace: false}, undefined, true, ); process.stderr.write(`\n${formattedError}\n`); process.exitCode = 1; }
type LogMessage = string;
1,666
(type: LogType, message: LogMessage) => getConsoleOutput( // 4 = the console call is buried 4 stack frames deep BufferedConsole.write([], type, message, 4), projectConfig, globalConfig, )
type LogType = | 'assert' | 'count' | 'debug' | 'dir' | 'dirxml' | 'error' | 'group' | 'groupCollapsed' | 'info' | 'log' | 'time' | 'warn';
1,667
(type: LogType, message: LogMessage) => getConsoleOutput( // 4 = the console call is buried 4 stack frames deep BufferedConsole.write([], type, message, 4), projectConfig, globalConfig, )
type LogMessage = string;
1,668
constructor( resolver: Resolver, hasteFS: IHasteFS, snapshotResolver: SnapshotResolver, ) { this._resolver = resolver; this._hasteFS = hasteFS; this._snapshotResolver = snapshotResolver; }
type SnapshotResolver = { /** Resolves from `testPath` to snapshot path. */ resolveSnapshotPath(testPath: string, snapshotExtension?: string): string; /** Resolves from `snapshotPath` to test path. */ resolveTestPath(snapshotPath: string, snapshotExtension?: string): string; /** Example test path, used for preflight consistency check of the implementation above. */ testPathForConsistencyCheck: string; };
1,669
constructor( resolver: Resolver, hasteFS: IHasteFS, snapshotResolver: SnapshotResolver, ) { this._resolver = resolver; this._hasteFS = hasteFS; this._snapshotResolver = snapshotResolver; }
class Resolver { private readonly _options: ResolverConfig; private readonly _moduleMap: IModuleMap; private readonly _moduleIDCache: Map<string, string>; private readonly _moduleNameCache: Map<string, string>; private readonly _modulePathCache: Map<string, Array<string>>; private readonly _supportsNativePlatform: boolean; constructor(moduleMap: IModuleMap, options: ResolverConfig) { this._options = { defaultPlatform: options.defaultPlatform, extensions: options.extensions, hasCoreModules: options.hasCoreModules === undefined ? true : options.hasCoreModules, moduleDirectories: options.moduleDirectories || ['node_modules'], moduleNameMapper: options.moduleNameMapper, modulePaths: options.modulePaths, platforms: options.platforms, resolver: options.resolver, rootDir: options.rootDir, }; this._supportsNativePlatform = options.platforms ? options.platforms.includes(NATIVE_PLATFORM) : false; this._moduleMap = moduleMap; this._moduleIDCache = new Map(); this._moduleNameCache = new Map(); this._modulePathCache = new Map(); } static ModuleNotFoundError = ModuleNotFoundError; static tryCastModuleNotFoundError( error: unknown, ): ModuleNotFoundError | null { if (error instanceof ModuleNotFoundError) { return error; } const casted = error as ModuleNotFoundError; if (casted.code === 'MODULE_NOT_FOUND') { return ModuleNotFoundError.duckType(casted); } return null; } static clearDefaultResolverCache(): void { clearFsCache(); clearCachedLookups(); } static findNodeModule( path: string, options: FindNodeModuleConfig, ): string | null { const resolverModule = loadResolver(options.resolver); let resolver: SyncResolver = defaultResolver; if (typeof resolverModule === 'function') { resolver = resolverModule; } else if (typeof resolverModule.sync === 'function') { resolver = resolverModule.sync; } const paths = options.paths; try { return resolver(path, { basedir: options.basedir, conditions: options.conditions, defaultResolver, extensions: options.extensions, moduleDirectory: options.moduleDirectory, paths: paths ? (nodePaths || []).concat(paths) : nodePaths, rootDir: options.rootDir, }); } catch (e) { // we always wanna throw if it's an internal import if (options.throwIfNotFound || path.startsWith('#')) { throw e; } } return null; } static async findNodeModuleAsync( path: string, options: FindNodeModuleConfig, ): Promise<string | null> { const resolverModule = loadResolver(options.resolver); let resolver: ResolverInterface = defaultResolver; if (typeof resolverModule === 'function') { resolver = resolverModule; } else if ( typeof resolverModule.async === 'function' || typeof resolverModule.sync === 'function' ) { const asyncOrSync = resolverModule.async || resolverModule.sync; if (asyncOrSync == null) { throw new Error(`Unable to load resolver at ${options.resolver}`); } resolver = asyncOrSync; } const paths = options.paths; try { const result = await resolver(path, { basedir: options.basedir, conditions: options.conditions, defaultResolver, extensions: options.extensions, moduleDirectory: options.moduleDirectory, paths: paths ? (nodePaths || []).concat(paths) : nodePaths, rootDir: options.rootDir, }); return result; } catch (e: unknown) { // we always wanna throw if it's an internal import if (options.throwIfNotFound || path.startsWith('#')) { throw e; } } return null; } // unstable as it should be replaced by https://github.com/nodejs/modules/issues/393, and we don't want people to use it static unstable_shouldLoadAsEsm = shouldLoadAsEsm; resolveModuleFromDirIfExists( dirname: string, moduleName: string, options?: ResolveModuleConfig, ): string | null { const {extensions, key, moduleDirectory, paths, skipResolution} = this._prepareForResolution(dirname, moduleName, options); let module; // 1. If we have already resolved this module for this directory name, // return a value from the cache. const cacheResult = this._moduleNameCache.get(key); if (cacheResult) { return cacheResult; } // 2. Check if the module is a haste module. module = this.getModule(moduleName); if (module) { this._moduleNameCache.set(key, module); return module; } // 3. Check if the module is a node module and resolve it based on // the node module resolution algorithm. If skipNodeResolution is given we // ignore all modules that look like node modules (ie. are not relative // requires). This enables us to speed up resolution when we build a // dependency graph because we don't have to look at modules that may not // exist and aren't mocked. const resolveNodeModule = (name: string, throwIfNotFound = false) => { // Only skip default resolver if (this.isCoreModule(name) && !this._options.resolver) { return name; } return Resolver.findNodeModule(name, { basedir: dirname, conditions: options?.conditions, extensions, moduleDirectory, paths, resolver: this._options.resolver, rootDir: this._options.rootDir, throwIfNotFound, }); }; if (!skipResolution) { module = resolveNodeModule(moduleName, Boolean(process.versions.pnp)); if (module) { this._moduleNameCache.set(key, module); return module; } } // 4. Resolve "haste packages" which are `package.json` files outside of // `node_modules` folders anywhere in the file system. try { const hasteModulePath = this._getHasteModulePath(moduleName); if (hasteModulePath) { // try resolving with custom resolver first to support extensions, // then fallback to require.resolve const resolvedModule = resolveNodeModule(hasteModulePath) || require.resolve(hasteModulePath); this._moduleNameCache.set(key, resolvedModule); return resolvedModule; } } catch {} return null; } async resolveModuleFromDirIfExistsAsync( dirname: string, moduleName: string, options?: ResolveModuleConfig, ): Promise<string | null> { const {extensions, key, moduleDirectory, paths, skipResolution} = this._prepareForResolution(dirname, moduleName, options); let module; // 1. If we have already resolved this module for this directory name, // return a value from the cache. const cacheResult = this._moduleNameCache.get(key); if (cacheResult) { return cacheResult; } // 2. Check if the module is a haste module. module = this.getModule(moduleName); if (module) { this._moduleNameCache.set(key, module); return module; } // 3. Check if the module is a node module and resolve it based on // the node module resolution algorithm. If skipNodeResolution is given we // ignore all modules that look like node modules (ie. are not relative // requires). This enables us to speed up resolution when we build a // dependency graph because we don't have to look at modules that may not // exist and aren't mocked. const resolveNodeModule = async (name: string, throwIfNotFound = false) => { // Only skip default resolver if (this.isCoreModule(name) && !this._options.resolver) { return name; } return Resolver.findNodeModuleAsync(name, { basedir: dirname, conditions: options?.conditions, extensions, moduleDirectory, paths, resolver: this._options.resolver, rootDir: this._options.rootDir, throwIfNotFound, }); }; if (!skipResolution) { module = await resolveNodeModule( moduleName, Boolean(process.versions.pnp), ); if (module) { this._moduleNameCache.set(key, module); return module; } } // 4. Resolve "haste packages" which are `package.json` files outside of // `node_modules` folders anywhere in the file system. try { const hasteModulePath = this._getHasteModulePath(moduleName); if (hasteModulePath) { // try resolving with custom resolver first to support extensions, // then fallback to require.resolve const resolvedModule = (await resolveNodeModule(hasteModulePath)) || // QUESTION: should this be async? require.resolve(hasteModulePath); this._moduleNameCache.set(key, resolvedModule); return resolvedModule; } } catch {} return null; } resolveModule( from: string, moduleName: string, options?: ResolveModuleConfig, ): string { const dirname = path.dirname(from); const module = this.resolveStubModuleName(from, moduleName) || this.resolveModuleFromDirIfExists(dirname, moduleName, options); if (module) return module; // 5. Throw an error if the module could not be found. `resolve.sync` only // produces an error based on the dirname but we have the actual current // module name available. this._throwModNotFoundError(from, moduleName); } async resolveModuleAsync( from: string, moduleName: string, options?: ResolveModuleConfig, ): Promise<string> { const dirname = path.dirname(from); const module = (await this.resolveStubModuleNameAsync(from, moduleName)) || (await this.resolveModuleFromDirIfExistsAsync( dirname, moduleName, options, )); if (module) return module; // 5. Throw an error if the module could not be found. `resolve` only // produces an error based on the dirname but we have the actual current // module name available. this._throwModNotFoundError(from, moduleName); } /** * _prepareForResolution is shared between the sync and async module resolution * methods, to try to keep them as DRY as possible. */ private _prepareForResolution( dirname: string, moduleName: string, options?: ResolveModuleConfig, ) { const paths = options?.paths || this._options.modulePaths; const moduleDirectory = this._options.moduleDirectories; const stringifiedOptions = options ? JSON.stringify(options) : ''; const key = dirname + path.delimiter + moduleName + stringifiedOptions; const defaultPlatform = this._options.defaultPlatform; const extensions = this._options.extensions.slice(); if (this._supportsNativePlatform) { extensions.unshift( ...this._options.extensions.map(ext => `.${NATIVE_PLATFORM}${ext}`), ); } if (defaultPlatform) { extensions.unshift( ...this._options.extensions.map(ext => `.${defaultPlatform}${ext}`), ); } const skipResolution = options && options.skipNodeResolution && !moduleName.includes(path.sep); return {extensions, key, moduleDirectory, paths, skipResolution}; } /** * _getHasteModulePath attempts to return the path to a haste module. */ private _getHasteModulePath(moduleName: string) { const parts = moduleName.split('/'); const hastePackage = this.getPackage(parts.shift()!); if (hastePackage) { return path.join.apply(path, [path.dirname(hastePackage)].concat(parts)); } return null; } private _throwModNotFoundError(from: string, moduleName: string): never { const relativePath = slash(path.relative(this._options.rootDir, from)) || '.'; throw new ModuleNotFoundError( `Cannot find module '${moduleName}' from '${relativePath}'`, moduleName, ); } private _getMapModuleName(matches: RegExpMatchArray | null) { return matches ? (moduleName: string) => moduleName.replace( /\$([0-9]+)/g, (_, index) => matches[parseInt(index, 10)], ) : (moduleName: string) => moduleName; } private _isAliasModule(moduleName: string): boolean { const moduleNameMapper = this._options.moduleNameMapper; if (!moduleNameMapper) { return false; } return moduleNameMapper.some(({regex}) => regex.test(moduleName)); } isCoreModule(moduleName: string): boolean { return ( this._options.hasCoreModules && (isBuiltinModule(moduleName) || moduleName.startsWith('node:')) && !this._isAliasModule(moduleName) ); } getModule(name: string): string | null { return this._moduleMap.getModule( name, this._options.defaultPlatform, this._supportsNativePlatform, ); } getModulePath(from: string, moduleName: string): string { if (moduleName[0] !== '.' || path.isAbsolute(moduleName)) { return moduleName; } return path.normalize(`${path.dirname(from)}/${moduleName}`); } getPackage(name: string): string | null { return this._moduleMap.getPackage( name, this._options.defaultPlatform, this._supportsNativePlatform, ); } getMockModule(from: string, name: string): string | null { const mock = this._moduleMap.getMockModule(name); if (mock) { return mock; } else { const moduleName = this.resolveStubModuleName(from, name); if (moduleName) { return this.getModule(moduleName) || moduleName; } } return null; } async getMockModuleAsync(from: string, name: string): Promise<string | null> { const mock = this._moduleMap.getMockModule(name); if (mock) { return mock; } else { const moduleName = await this.resolveStubModuleNameAsync(from, name); if (moduleName) { return this.getModule(moduleName) || moduleName; } } return null; } getModulePaths(from: string): Array<string> { const cachedModule = this._modulePathCache.get(from); if (cachedModule) { return cachedModule; } const moduleDirectory = this._options.moduleDirectories; const paths = nodeModulesPaths(from, {moduleDirectory}); if (paths[paths.length - 1] === undefined) { // circumvent node-resolve bug that adds `undefined` as last item. paths.pop(); } this._modulePathCache.set(from, paths); return paths; } getGlobalPaths(moduleName?: string): Array<string> { if (!moduleName || moduleName[0] === '.' || this.isCoreModule(moduleName)) { return []; } return GlobalPaths; } getModuleID( virtualMocks: Map<string, boolean>, from: string, moduleName = '', options?: ResolveModuleConfig, ): string { const stringifiedOptions = options ? JSON.stringify(options) : ''; const key = from + path.delimiter + moduleName + stringifiedOptions; const cachedModuleID = this._moduleIDCache.get(key); if (cachedModuleID) { return cachedModuleID; } const moduleType = this._getModuleType(moduleName); const absolutePath = this._getAbsolutePath( virtualMocks, from, moduleName, options, ); const mockPath = this._getMockPath(from, moduleName); const sep = path.delimiter; const id = moduleType + sep + (absolutePath ? absolutePath + sep : '') + (mockPath ? mockPath + sep : '') + (stringifiedOptions ? stringifiedOptions + sep : ''); this._moduleIDCache.set(key, id); return id; } async getModuleIDAsync( virtualMocks: Map<string, boolean>, from: string, moduleName = '', options?: ResolveModuleConfig, ): Promise<string> { const stringifiedOptions = options ? JSON.stringify(options) : ''; const key = from + path.delimiter + moduleName + stringifiedOptions; const cachedModuleID = this._moduleIDCache.get(key); if (cachedModuleID) { return cachedModuleID; } if (moduleName.startsWith('data:')) { return moduleName; } const moduleType = this._getModuleType(moduleName); const absolutePath = await this._getAbsolutePathAsync( virtualMocks, from, moduleName, options, ); const mockPath = await this._getMockPathAsync(from, moduleName); const sep = path.delimiter; const id = moduleType + sep + (absolutePath ? absolutePath + sep : '') + (mockPath ? mockPath + sep : '') + (stringifiedOptions ? stringifiedOptions + sep : ''); this._moduleIDCache.set(key, id); return id; } private _getModuleType(moduleName: string): 'node' | 'user' { return this.isCoreModule(moduleName) ? 'node' : 'user'; } private _getAbsolutePath( virtualMocks: Map<string, boolean>, from: string, moduleName: string, options?: ResolveModuleConfig, ): string | null { if (this.isCoreModule(moduleName)) { return moduleName; } if (moduleName.startsWith('data:')) { return moduleName; } return this._isModuleResolved(from, moduleName) ? this.getModule(moduleName) : this._getVirtualMockPath(virtualMocks, from, moduleName, options); } private async _getAbsolutePathAsync( virtualMocks: Map<string, boolean>, from: string, moduleName: string, options?: ResolveModuleConfig, ): Promise<string | null> { if (this.isCoreModule(moduleName)) { return moduleName; } if (moduleName.startsWith('data:')) { return moduleName; } const isModuleResolved = await this._isModuleResolvedAsync( from, moduleName, ); return isModuleResolved ? this.getModule(moduleName) : this._getVirtualMockPathAsync(virtualMocks, from, moduleName, options); } private _getMockPath(from: string, moduleName: string): string | null { return !this.isCoreModule(moduleName) ? this.getMockModule(from, moduleName) : null; } private async _getMockPathAsync( from: string, moduleName: string, ): Promise<string | null> { return !this.isCoreModule(moduleName) ? this.getMockModuleAsync(from, moduleName) : null; } private _getVirtualMockPath( virtualMocks: Map<string, boolean>, from: string, moduleName: string, options?: ResolveModuleConfig, ): string { const virtualMockPath = this.getModulePath(from, moduleName); return virtualMocks.get(virtualMockPath) ? virtualMockPath : moduleName ? this.resolveModule(from, moduleName, options) : from; } private async _getVirtualMockPathAsync( virtualMocks: Map<string, boolean>, from: string, moduleName: string, options?: ResolveModuleConfig, ): Promise<string> { const virtualMockPath = this.getModulePath(from, moduleName); return virtualMocks.get(virtualMockPath) ? virtualMockPath : moduleName ? this.resolveModuleAsync(from, moduleName, options) : from; } private _isModuleResolved(from: string, moduleName: string): boolean { return !!( this.getModule(moduleName) || this.getMockModule(from, moduleName) ); } private async _isModuleResolvedAsync( from: string, moduleName: string, ): Promise<boolean> { return !!( this.getModule(moduleName) || (await this.getMockModuleAsync(from, moduleName)) ); } resolveStubModuleName(from: string, moduleName: string): string | null { const dirname = path.dirname(from); const {extensions, moduleDirectory, paths} = this._prepareForResolution( dirname, moduleName, ); const moduleNameMapper = this._options.moduleNameMapper; const resolver = this._options.resolver; if (moduleNameMapper) { for (const {moduleName: mappedModuleName, regex} of moduleNameMapper) { if (regex.test(moduleName)) { // Note: once a moduleNameMapper matches the name, it must result // in a module, or else an error is thrown. const matches = moduleName.match(regex); const mapModuleName = this._getMapModuleName(matches); const possibleModuleNames = Array.isArray(mappedModuleName) ? mappedModuleName : [mappedModuleName]; let module: string | null = null; for (const possibleModuleName of possibleModuleNames) { const updatedName = mapModuleName(possibleModuleName); module = this.getModule(updatedName) || Resolver.findNodeModule(updatedName, { basedir: dirname, extensions, moduleDirectory, paths, resolver, rootDir: this._options.rootDir, }); if (module) { break; } } if (!module) { throw createNoMappedModuleFoundError( moduleName, mapModuleName, mappedModuleName, regex, resolver, ); } return module; } } } return null; } async resolveStubModuleNameAsync( from: string, moduleName: string, ): Promise<string | null> { const dirname = path.dirname(from); const {extensions, moduleDirectory, paths} = this._prepareForResolution( dirname, moduleName, ); const moduleNameMapper = this._options.moduleNameMapper; const resolver = this._options.resolver; if (moduleNameMapper) { for (const {moduleName: mappedModuleName, regex} of moduleNameMapper) { if (regex.test(moduleName)) { // Note: once a moduleNameMapper matches the name, it must result // in a module, or else an error is thrown. const matches = moduleName.match(regex); const mapModuleName = this._getMapModuleName(matches); const possibleModuleNames = Array.isArray(mappedModuleName) ? mappedModuleName : [mappedModuleName]; let module: string | null = null; for (const possibleModuleName of possibleModuleNames) { const updatedName = mapModuleName(possibleModuleName); module = this.getModule(updatedName) || (await Resolver.findNodeModuleAsync(updatedName, { basedir: dirname, extensions, moduleDirectory, paths, resolver, rootDir: this._options.rootDir, })); if (module) { break; } } if (!module) { throw createNoMappedModuleFoundError( moduleName, mapModuleName, mappedModuleName, regex, resolver, ); } return module; } } } return null; } }
1,670
constructor( resolver: Resolver, hasteFS: IHasteFS, snapshotResolver: SnapshotResolver, ) { this._resolver = resolver; this._hasteFS = hasteFS; this._snapshotResolver = snapshotResolver; }
type Resolver = SyncResolver | AsyncResolver;
1,671
constructor( resolver: Resolver, hasteFS: IHasteFS, snapshotResolver: SnapshotResolver, ) { this._resolver = resolver; this._hasteFS = hasteFS; this._snapshotResolver = snapshotResolver; }
interface IHasteFS { exists(path: string): boolean; getAbsoluteFileIterator(): Iterable<string>; getAllFiles(): Array<string>; getDependencies(file: string): Array<string> | null; getSize(path: string): number | null; matchFiles(pattern: RegExp | string): Array<string>; matchFilesWithGlob( globs: ReadonlyArray<string>, root: string | null, ): Set<string>; }
1,672
register(reporter: Reporter): void { this._reporters.push(reporter); }
type Reporter = { jasmineDone: (runDetails: RunDetails) => void; jasmineStarted: (runDetails: RunDetails) => void; specDone: (result: SpecResult) => void; specStarted: (spec: SpecResult) => void; suiteDone: (result: SuiteResult) => void; suiteStarted: (result: SuiteResult) => void; };
1,673
register(reporter: Reporter): void { this._reporters.push(reporter); }
interface Reporter { readonly onTestResult?: ( test: Test, testResult: TestResult, aggregatedResult: AggregatedResult, ) => Promise<void> | void; readonly onTestFileResult?: ( test: Test, testResult: TestResult, aggregatedResult: AggregatedResult, ) => Promise<void> | void; readonly onTestCaseResult?: ( test: Test, testCaseResult: TestCaseResult, ) => Promise<void> | void; readonly onRunStart: ( results: AggregatedResult, options: ReporterOnStartOptions, ) => Promise<void> | void; readonly onTestStart?: (test: Test) => Promise<void> | void; readonly onTestFileStart?: (test: Test) => Promise<void> | void; readonly onRunComplete: ( testContexts: Set<TestContext>, results: AggregatedResult, ) => Promise<void> | void; readonly getLastError: () => Error | void; }
1,674
unregister(reporterConstructor: ReporterConstructor): void { this._reporters = this._reporters.filter( reporter => !(reporter instanceof reporterConstructor), ); }
type ReporterConstructor = new ( globalConfig: Config.GlobalConfig, reporterConfig: Record<string, unknown>, reporterContext: ReporterContext, ) => JestReporter;
1,675
async onTestFileResult( test: Test, testResult: TestResult, results: AggregatedResult, ): Promise<void> { for (const reporter of this._reporters) { if (reporter.onTestFileResult) { await reporter.onTestFileResult(test, testResult, results); } else if (reporter.onTestResult) { await reporter.onTestResult(test, testResult, results); } } // Release memory if unused later. testResult.coverage = undefined; testResult.console = undefined; }
type Test = { context: TestContext; duration?: number; path: string; };
1,676
async onTestFileResult( test: Test, testResult: TestResult, results: AggregatedResult, ): Promise<void> { for (const reporter of this._reporters) { if (reporter.onTestFileResult) { await reporter.onTestFileResult(test, testResult, results); } else if (reporter.onTestResult) { await reporter.onTestResult(test, testResult, results); } } // Release memory if unused later. testResult.coverage = undefined; testResult.console = undefined; }
type Test = (arg0: any) => boolean;
1,677
async onTestFileResult( test: Test, testResult: TestResult, results: AggregatedResult, ): Promise<void> { for (const reporter of this._reporters) { if (reporter.onTestFileResult) { await reporter.onTestFileResult(test, testResult, results); } else if (reporter.onTestResult) { await reporter.onTestResult(test, testResult, results); } } // Release memory if unused later. testResult.coverage = undefined; testResult.console = undefined; }
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,678
async onTestFileResult( test: Test, testResult: TestResult, results: AggregatedResult, ): Promise<void> { for (const reporter of this._reporters) { if (reporter.onTestFileResult) { await reporter.onTestFileResult(test, testResult, results); } else if (reporter.onTestResult) { await reporter.onTestResult(test, testResult, results); } } // Release memory if unused later. testResult.coverage = undefined; testResult.console = undefined; }
type TestResult = { console?: ConsoleBuffer; coverage?: CoverageMapData; displayName?: Config.DisplayName; failureMessage?: string | null; leaks: boolean; memoryUsage?: number; numFailingTests: number; numPassingTests: number; numPendingTests: number; numTodoTests: number; openHandles: Array<Error>; perfStats: { end: number; runtime: number; slow: boolean; start: number; }; skipped: boolean; snapshot: { added: number; fileDeleted: boolean; matched: number; unchecked: number; uncheckedKeys: Array<string>; unmatched: number; updated: number; }; testExecError?: SerializableError; testFilePath: string; testResults: Array<AssertionResult>; v8Coverage?: V8CoverageResult; };
1,679
async onTestFileResult( test: Test, testResult: TestResult, results: AggregatedResult, ): Promise<void> { for (const reporter of this._reporters) { if (reporter.onTestFileResult) { await reporter.onTestFileResult(test, testResult, results); } else if (reporter.onTestResult) { await reporter.onTestResult(test, testResult, results); } } // Release memory if unused later. testResult.coverage = undefined; testResult.console = undefined; }
type TestResult = { duration?: number | null; errors: Array<FormattedError>; errorsDetailed: Array<MatcherResults | unknown>; invocations: number; status: TestStatus; location?: {column: number; line: number} | null; numPassingAsserts: number; retryReasons: Array<FormattedError>; testPath: Array<TestName | BlockName>; };
1,680
async onTestFileStart(test: Test): Promise<void> { for (const reporter of this._reporters) { if (reporter.onTestFileStart) { await reporter.onTestFileStart(test); } else if (reporter.onTestStart) { await reporter.onTestStart(test); } } }
type Test = { context: TestContext; duration?: number; path: string; };
1,681
async onTestFileStart(test: Test): Promise<void> { for (const reporter of this._reporters) { if (reporter.onTestFileStart) { await reporter.onTestFileStart(test); } else if (reporter.onTestStart) { await reporter.onTestStart(test); } } }
type Test = (arg0: any) => boolean;
1,682
async onRunStart( results: AggregatedResult, options: ReporterOnStartOptions, ): Promise<void> { for (const reporter of this._reporters) { reporter.onRunStart && (await reporter.onRunStart(results, options)); } }
type ReporterOnStartOptions = { estimatedTime: number; showStatus: boolean; };
1,683
async onRunStart( results: AggregatedResult, options: ReporterOnStartOptions, ): Promise<void> { for (const reporter of this._reporters) { reporter.onRunStart && (await reporter.onRunStart(results, options)); } }
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,684
async onTestCaseResult( test: Test, testCaseResult: TestCaseResult, ): Promise<void> { for (const reporter of this._reporters) { if (reporter.onTestCaseResult) { await reporter.onTestCaseResult(test, testCaseResult); } } }
type Test = { context: TestContext; duration?: number; path: string; };
1,685
async onTestCaseResult( test: Test, testCaseResult: TestCaseResult, ): Promise<void> { for (const reporter of this._reporters) { if (reporter.onTestCaseResult) { await reporter.onTestCaseResult(test, testCaseResult); } } }
type Test = (arg0: any) => boolean;
1,686
async onTestCaseResult( test: Test, testCaseResult: TestCaseResult, ): Promise<void> { for (const reporter of this._reporters) { if (reporter.onTestCaseResult) { await reporter.onTestCaseResult(test, testCaseResult); } } }
type TestCaseResult = AssertionResult;
1,687
({ bail, changedSince, collectCoverage, collectCoverageFrom, coverageDirectory, coverageReporters, findRelatedTests, mode, nonFlagArgs, notify, notifyMode, onlyFailures, reporters, testNamePattern, testPathPattern, updateSnapshot, verbose, }: AllowedConfigOptions = {}) => { const previousUpdateSnapshot = globalConfig.updateSnapshot; globalConfig = updateGlobalConfig(globalConfig, { bail, changedSince, collectCoverage, collectCoverageFrom, coverageDirectory, coverageReporters, findRelatedTests, mode, nonFlagArgs, notify, notifyMode, onlyFailures, reporters, testNamePattern, testPathPattern, updateSnapshot, verbose, }); startRun(globalConfig); globalConfig = updateGlobalConfig(globalConfig, { // updateSnapshot is not sticky after a run. updateSnapshot: previousUpdateSnapshot === 'all' ? 'none' : previousUpdateSnapshot, }); }
type AllowedConfigOptions = Partial< Pick< Config.GlobalConfig, | 'bail' | 'changedSince' | 'collectCoverage' | 'collectCoverageFrom' | 'coverageDirectory' | 'coverageReporters' | 'findRelatedTests' | 'nonFlagArgs' | 'notify' | 'notifyMode' | 'onlyFailures' | 'reporters' | 'testNamePattern' | 'testPathPattern' | 'updateSnapshot' | 'verbose' > & {mode: 'watch' | 'watchAll'} >;
1,688
(plugin: WatchPlugin) => { const hookSubscriber = hooks.getSubscriber(); if (plugin.apply) { plugin.apply(hookSubscriber); } }
interface WatchPlugin { isInternal?: boolean; apply?: (hooks: JestHookSubscriber) => void; getUsageInfo?: (globalConfig: Config.GlobalConfig) => UsageData | null; onKey?: (value: string) => void; run?: ( globalConfig: Config.GlobalConfig, updateConfigAndRun: UpdateConfigCallback, ) => Promise<void | boolean>; }
1,689
( watchPluginKeys: WatchPluginKeysMap, plugin: WatchPlugin, globalConfig: Config.GlobalConfig, ) => { const key = getPluginKey(plugin, globalConfig); if (!key) { return; } const conflictor = watchPluginKeys.get(key); if (!conflictor || conflictor.overwritable) { watchPluginKeys.set(key, { overwritable: false, plugin, }); return; } let error; if (conflictor.forbiddenOverwriteMessage) { error = ` Watch plugin ${chalk.bold.red( getPluginIdentifier(plugin), )} attempted to register key ${chalk.bold.red(`<${key}>`)}, that is reserved internally for ${chalk.bold.red( conflictor.forbiddenOverwriteMessage, )}. Please change the configuration key for this plugin.`.trim(); } else { const plugins = [conflictor.plugin, plugin] .map(p => chalk.bold.red(getPluginIdentifier(p))) .join(' and '); error = ` Watch plugins ${plugins} both attempted to register key ${chalk.bold.red( `<${key}>`, )}. Please change the key configuration for one of the conflicting plugins to avoid overlap.`.trim(); } throw new ValidationError('Watch plugin configuration error', error); }
interface WatchPlugin { isInternal?: boolean; apply?: (hooks: JestHookSubscriber) => void; getUsageInfo?: (globalConfig: Config.GlobalConfig) => UsageData | null; onKey?: (value: string) => void; run?: ( globalConfig: Config.GlobalConfig, updateConfigAndRun: UpdateConfigCallback, ) => Promise<void | boolean>; }
1,690
( watchPluginKeys: WatchPluginKeysMap, plugin: WatchPlugin, globalConfig: Config.GlobalConfig, ) => { const key = getPluginKey(plugin, globalConfig); if (!key) { return; } const conflictor = watchPluginKeys.get(key); if (!conflictor || conflictor.overwritable) { watchPluginKeys.set(key, { overwritable: false, plugin, }); return; } let error; if (conflictor.forbiddenOverwriteMessage) { error = ` Watch plugin ${chalk.bold.red( getPluginIdentifier(plugin), )} attempted to register key ${chalk.bold.red(`<${key}>`)}, that is reserved internally for ${chalk.bold.red( conflictor.forbiddenOverwriteMessage, )}. Please change the configuration key for this plugin.`.trim(); } else { const plugins = [conflictor.plugin, plugin] .map(p => chalk.bold.red(getPluginIdentifier(p))) .join(' and '); error = ` Watch plugins ${plugins} both attempted to register key ${chalk.bold.red( `<${key}>`, )}. Please change the key configuration for one of the conflicting plugins to avoid overlap.`.trim(); } throw new ValidationError('Watch plugin configuration error', error); }
type WatchPluginKeysMap = Map<string, ReservedInfo>;
1,691
(plugin: WatchPlugin) => // This breaks as `displayName` is not defined as a static, but since // WatchPlugin is an interface, and it is my understanding interface // static fields are not definable anymore, no idea how to circumvent // this :-( // @ts-expect-error: leave `displayName` be. plugin.constructor.displayName || plugin.constructor.name
interface WatchPlugin { isInternal?: boolean; apply?: (hooks: JestHookSubscriber) => void; getUsageInfo?: (globalConfig: Config.GlobalConfig) => UsageData | null; onKey?: (value: string) => void; run?: ( globalConfig: Config.GlobalConfig, updateConfigAndRun: UpdateConfigCallback, ) => Promise<void | boolean>; }
1,692
( plugin: WatchPlugin, globalConfig: Config.GlobalConfig, ) => { if (typeof plugin.getUsageInfo === 'function') { return (plugin.getUsageInfo(globalConfig) || {key: null}).key; } return null; }
interface WatchPlugin { isInternal?: boolean; apply?: (hooks: JestHookSubscriber) => void; getUsageInfo?: (globalConfig: Config.GlobalConfig) => UsageData | null; onKey?: (value: string) => void; run?: ( globalConfig: Config.GlobalConfig, updateConfigAndRun: UpdateConfigCallback, ) => Promise<void | boolean>; }
1,693
(result: AggregatedResult) => void
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,694
async ( runResults: AggregatedResult, options: ProcessResultOptions, ) => { const { outputFile, json: isJSON, onComplete, outputStream, testResultsProcessor, collectHandles, } = options; if (collectHandles) { runResults.openHandles = await collectHandles(); } else { runResults.openHandles = []; } if (testResultsProcessor) { const processor = await requireOrImportModule<TestResultsProcessor>( testResultsProcessor, ); runResults = await processor(runResults); } if (isJSON) { if (outputFile) { const cwd = tryRealpath(process.cwd()); const filePath = path.resolve(cwd, outputFile); fs.writeFileSync( filePath, `${JSON.stringify(formatTestResults(runResults))}\n`, ); outputStream.write( `Test results written to: ${path.relative(cwd, filePath)}\n`, ); } else { process.stdout.write( `${JSON.stringify(formatTestResults(runResults))}\n`, ); } } onComplete?.(runResults); }
type ProcessResultOptions = Pick< Config.GlobalConfig, 'json' | 'outputFile' | 'testResultsProcessor' > & { collectHandles?: HandleCollectionResult; onComplete?: (result: AggregatedResult) => void; outputStream: NodeJS.WriteStream; };
1,695
async ( runResults: AggregatedResult, options: ProcessResultOptions, ) => { const { outputFile, json: isJSON, onComplete, outputStream, testResultsProcessor, collectHandles, } = options; if (collectHandles) { runResults.openHandles = await collectHandles(); } else { runResults.openHandles = []; } if (testResultsProcessor) { const processor = await requireOrImportModule<TestResultsProcessor>( testResultsProcessor, ); runResults = await processor(runResults); } if (isJSON) { if (outputFile) { const cwd = tryRealpath(process.cwd()); const filePath = path.resolve(cwd, outputFile); fs.writeFileSync( filePath, `${JSON.stringify(formatTestResults(runResults))}\n`, ); outputStream.write( `Test results written to: ${path.relative(cwd, filePath)}\n`, ); } else { process.stdout.write( `${JSON.stringify(formatTestResults(runResults))}\n`, ); } } onComplete?.(runResults); }
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,696
(testResults: AggregatedResult) => void
type AggregatedResult = AggregatedResultWithoutCoverage & { coverageMap?: CoverageMap | null; };
1,697
addReporter(reporter: Reporter): void { this._dispatcher.register(reporter); }
type Reporter = { jasmineDone: (runDetails: RunDetails) => void; jasmineStarted: (runDetails: RunDetails) => void; specDone: (result: SpecResult) => void; specStarted: (spec: SpecResult) => void; suiteDone: (result: SuiteResult) => void; suiteStarted: (result: SuiteResult) => void; };
1,698
addReporter(reporter: Reporter): void { this._dispatcher.register(reporter); }
interface Reporter { readonly onTestResult?: ( test: Test, testResult: TestResult, aggregatedResult: AggregatedResult, ) => Promise<void> | void; readonly onTestFileResult?: ( test: Test, testResult: TestResult, aggregatedResult: AggregatedResult, ) => Promise<void> | void; readonly onTestCaseResult?: ( test: Test, testCaseResult: TestCaseResult, ) => Promise<void> | void; readonly onRunStart: ( results: AggregatedResult, options: ReporterOnStartOptions, ) => Promise<void> | void; readonly onTestStart?: (test: Test) => Promise<void> | void; readonly onTestFileStart?: (test: Test) => Promise<void> | void; readonly onRunComplete: ( testContexts: Set<TestContext>, results: AggregatedResult, ) => Promise<void> | void; readonly getLastError: () => Error | void; }
1,699
removeReporter(reporterConstructor: ReporterConstructor): void { this._dispatcher.unregister(reporterConstructor); }
type ReporterConstructor = new ( globalConfig: Config.GlobalConfig, reporterConfig: Record<string, unknown>, reporterContext: ReporterContext, ) => JestReporter;