diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index 870c827..081c473 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -11,10 +11,11 @@ jobs: outputs: release_created: ${{ steps.release.outputs.release_created }} steps: - - uses: googleapis/release-please-action@v4 + - uses: google-github-actions/release-please-action@v3 id: release with: release-type: node + package-name: test npm-publish: needs: release-please if: ${{ needs.release-please.outputs.release_created }} diff --git a/.npmignore b/.npmignore index 93121e1..9f9f4f6 100644 --- a/.npmignore +++ b/.npmignore @@ -1,2 +1,2 @@ test -.github \ No newline at end of file +.github diff --git a/.release-please-manifest.json b/.release-please-manifest.json deleted file mode 100644 index 5099974..0000000 --- a/.release-please-manifest.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - ".": "4.0.0" -} \ No newline at end of file diff --git a/MAINTAINING.md b/MAINTAINING.md index 96ac8fb..356aea8 100644 --- a/MAINTAINING.md +++ b/MAINTAINING.md @@ -1,44 +1,46 @@ -# Maintenance Guide for the Package +# Package Maintenance Guide -This guide outlines the procedures necessary for maintaining this package, ensuring its functionality and compatibility with newer versions of Node.js. The goal is to streamline the maintenance process until a majority of users can transition to the latest versions, paving the way for eventual deprecation of this library. +This guide provides a step-by-step approach to maintaining the package, ensuring its ongoing functionality and compatibility with newer Node.js versions. The aim is to simplify maintenance until the majority of users have transitioned to newer versions, ultimately leading to the package's deprecation. ## Overview -Maintaining this library involves updating specific internal files and ensuring that all references are correctly modified. The steps below provide a clear pathway for effective package maintenance. +Maintaining this package involves updating specific internal files and adjusting references as needed. The steps below outline a structured process to ensure effective and consistent maintenance. -## Maintenance Steps +## Steps for Maintenance -### 1. Identify Files for Update -Start by identifying the internal files that require updates. These files are typically located in the `lib/internal/` directory. For example, `lib/internal/test_runner/runner.js` is one file that may need attention. +### Identify Files to Update +Begin by locating the internal files that need updating. These files are generally found in the `lib/internal/test_runner` directory. For example, `lib/internal/test_runner/runner.js` is a file that might require changes. -### 2. Update File Contents -- Replace the entire contents of the identified file with the updated version from your reference source. Ensure you use the correct version that corresponds to the changes made in Node.js internals. +### Update the File Contents +- Replace the content of the identified file with the updated version from the appropriate reference source, ensuring you use the version that reflects recent changes in Node.js internals. -### 3. Modify Require Statements -- After replacing the file contents, locate all instances of the following pattern in the file: +- There may be cases where a slight modification of the file may be needed in order for it to work with this polyfill. Ideally, only the minimal amount should be modified, to make future updating as easy as possible. If contents *must* be altered, leave a comment `/* NOTE(Author): ... */` explaining the change. + +### Update `require` Statements +- Once the file content is updated, search for any occurrences of: ```javascript - require('internal/...'); + require('internal/...'); ``` -- Update these instances to the new syntax: +- Replace these instances with the updated syntax: ```javascript - require('#internal/...'); + require('#internal/...'); ``` -### 4. Add Necessary Imports -- If the updated file requires specific bindings, include the following line at the top of the file: +### Add Required Imports +- If the updated file needs specific bindings, add the following line at the top: ```javascript const { primordials, internalBinding } = require('#lib/bootstrap'); ``` -### 5. Follow Special Comments -- Pay close attention to any comments formatted as `/* NOTE(Author): ... */` within the files. These notes may contain essential guidelines or considerations regarding the code. Adhere to any instructions provided in these comments during the update process. +### Follow Special Comments +- Pay attention to any comments in the format `/* NOTE(Author): ... */` within the code. These may provide important instructions or considerations. Make sure to follow any guidelines specified in these comments. -### 6. Implement Polyfills as Needed -- When updating the library, you may encounter new features that require polyfilling if they are not present in the library. Add the minimal amount of code necessary for functionality. For instance, in `lib/internal/options`, only implement parsing for the options that are actually needed. +### Implement Polyfills if Necessary +- If new features require polyfills that are not already available, implement only the minimal code needed for functionality. For example, in `lib/internal/options`, add parsing for the required options only. ## Final Steps -- After completing the updates, conduct thorough testing of the package to ensure all functionality works as expected with the new changes. -- Document any significant modifications made during the update process to maintain a clear history for future reference. +- After making the updates, thoroughly test the package to ensure it functions correctly with the changes. +- Document any significant updates to maintain a clear record for future maintenance. -If you have any questions about this document, it was written by @RedYetiDev. \ No newline at end of file +For any questions about this guide, please refer to @RedYetiDev. \ No newline at end of file diff --git a/README.md b/README.md index 11e5868..10f5a0f 100644 --- a/README.md +++ b/README.md @@ -14,4 +14,6 @@ This package is a user-land implementation of [`node:test`](https://nodejs.org/a - Does not support module mocking. - No inherent file watching capabilities. - No built-in coverage support. -- Cannot import external scripts into `run()`-called test files. \ No newline at end of file +- Cannot import external scripts into `run()`-called test files. + +For the API reference, see [API.md](API.md). diff --git a/lib/bootstrap.js b/lib/bootstrap.js index 15957ad..e2a77b1 100644 --- a/lib/bootstrap.js +++ b/lib/bootstrap.js @@ -102,4 +102,4 @@ module.exports = { default: throw name } } -}; \ No newline at end of file +}; diff --git a/lib/cli.js b/lib/cli.js index 2695e60..5407e83 100755 --- a/lib/cli.js +++ b/lib/cli.js @@ -22,4 +22,4 @@ run(options).on('test:summary', (data) => { if (!data.success) { process.exitCode = 1; } -}); \ No newline at end of file +}); diff --git a/lib/internal/abort_controller.js b/lib/internal/abort_controller.js index f4da4aa..6c82bc7 100644 --- a/lib/internal/abort_controller.js +++ b/lib/internal/abort_controller.js @@ -1,3 +1,3 @@ module.exports = { AbortController -} \ No newline at end of file +} diff --git a/lib/internal/assert/utils.js b/lib/internal/assert/utils.js index 2ae9ed0..d4ca6f3 100644 --- a/lib/internal/assert/utils.js +++ b/lib/internal/assert/utils.js @@ -6,4 +6,4 @@ function innerOk(_caller, _length, ...args) { module.exports = { innerOk -} \ No newline at end of file +} diff --git a/lib/internal/console/global.js b/lib/internal/console/global.js index 9b3fe10..5cb1dfa 100644 --- a/lib/internal/console/global.js +++ b/lib/internal/console/global.js @@ -1 +1 @@ -module.exports = console; \ No newline at end of file +module.exports = console; diff --git a/lib/internal/deps/minimatch/index.js b/lib/internal/deps/minimatch/index.js index e7e64b6..265692b 100644 --- a/lib/internal/deps/minimatch/index.js +++ b/lib/internal/deps/minimatch/index.js @@ -1 +1 @@ -module.exports = require('minimatch'); \ No newline at end of file +module.exports = require('minimatch'); diff --git a/lib/internal/error_serdes.js b/lib/internal/error_serdes.js index ad7c084..744d50a 100644 --- a/lib/internal/error_serdes.js +++ b/lib/internal/error_serdes.js @@ -189,4 +189,4 @@ function deserializeError(error) { require('assert').fail('This should not happen'); } -module.exports = { serializeError, deserializeError }; \ No newline at end of file +module.exports = { serializeError, deserializeError }; diff --git a/lib/internal/errors.js b/lib/internal/errors.js index ae92076..e5aa271 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -363,4 +363,4 @@ registerError('ERR_OUT_OF_RANGE', return `${msg} It must be ${range}. Received ${received}`; }, RangeError); -registerError('UNSUPPORTED_FEATURE', '%s is not supported by this polyfill. Please upgrade to the latest version of Node.js to make use of this feature', Error); \ No newline at end of file +registerError('UNSUPPORTED_FEATURE', '%s is not supported by this polyfill. Please upgrade to the latest version of Node.js to make use of this feature', Error); diff --git a/lib/internal/event_target.js b/lib/internal/event_target.js index 0c1ba39..2e1d618 100644 --- a/lib/internal/event_target.js +++ b/lib/internal/event_target.js @@ -2,4 +2,4 @@ const kResistStopPropagation = Symbol('kResistStopPropagation'); module.exports = { kResistStopPropagation -} \ No newline at end of file +} diff --git a/lib/internal/events/abort_listener.js b/lib/internal/events/abort_listener.js index a93bf47..3af28ea 100644 --- a/lib/internal/events/abort_listener.js +++ b/lib/internal/events/abort_listener.js @@ -2,4 +2,4 @@ const { EventEmitter } = require('node:events'); module.exports = { addAbortListener: EventEmitter.addAbortListener -} \ No newline at end of file +} diff --git a/lib/internal/fs/glob.js b/lib/internal/fs/glob.js index 12e3367..8c68897 100644 --- a/lib/internal/fs/glob.js +++ b/lib/internal/fs/glob.js @@ -655,4 +655,4 @@ class Glob { module.exports = { __proto__: null, Glob, -}; \ No newline at end of file +}; diff --git a/lib/internal/fs/utils.js b/lib/internal/fs/utils.js index 88dc1d5..f548bd5 100644 --- a/lib/internal/fs/utils.js +++ b/lib/internal/fs/utils.js @@ -18,4 +18,4 @@ for (const name of Reflect.ownKeys(Dirent.prototype)) { }; } -module.exports = { DirentFromStats } \ No newline at end of file +module.exports = { DirentFromStats } diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index bdfc053..83801d0 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -1,3 +1,3 @@ module.exports = { Module: module.constructor -} \ No newline at end of file +} diff --git a/lib/internal/modules/esm/loader.js b/lib/internal/modules/esm/loader.js index 1026eed..8795224 100644 --- a/lib/internal/modules/esm/loader.js +++ b/lib/internal/modules/esm/loader.js @@ -16,4 +16,4 @@ module.exports = { getOrInitializeCascadedLoader() { return cascadedLoader } -} \ No newline at end of file +} diff --git a/lib/internal/options.js b/lib/internal/options.js index 9e5ae65..4893d2f 100644 --- a/lib/internal/options.js +++ b/lib/internal/options.js @@ -111,4 +111,4 @@ module.exports = { // Useful for determining file arguments notParsedAsOptions, parsedAsOptions -}; \ No newline at end of file +}; diff --git a/lib/internal/priority_queue.js b/lib/internal/priority_queue.js index 462d4b4..ce8dede 100644 --- a/lib/internal/priority_queue.js +++ b/lib/internal/priority_queue.js @@ -112,4 +112,4 @@ module.exports = class PriorityQueue { return value; } -}; \ No newline at end of file +}; diff --git a/lib/internal/process/task_queues.js b/lib/internal/process/task_queues.js index 530f976..16c187b 100644 --- a/lib/internal/process/task_queues.js +++ b/lib/internal/process/task_queues.js @@ -1,3 +1,3 @@ module.exports = { queueMicrotask, -} \ No newline at end of file +} diff --git a/lib/internal/readline/interface.js b/lib/internal/readline/interface.js index 85cc816..78a5f5c 100644 --- a/lib/internal/readline/interface.js +++ b/lib/internal/readline/interface.js @@ -1,4 +1,4 @@ const { Interface } = require('node:readline'); module.exports = { Interface -}; \ No newline at end of file +}; diff --git a/lib/internal/source_map/source_map_cache.js b/lib/internal/source_map/source_map_cache.js index 205c46a..40b7277 100644 --- a/lib/internal/source_map/source_map_cache.js +++ b/lib/internal/source_map/source_map_cache.js @@ -1,2 +1,2 @@ const { codes: { ERR_UNSUPPORTED_FEATURE } } = require('#internal/errors'); -throw new ERR_UNSUPPORTED_FEATURE('Sourcemap caching') \ No newline at end of file +throw new ERR_UNSUPPORTED_FEATURE('Sourcemap caching') diff --git a/lib/internal/streams/end-of-stream.js b/lib/internal/streams/end-of-stream.js index 7e31bac..25164cf 100644 --- a/lib/internal/streams/end-of-stream.js +++ b/lib/internal/streams/end-of-stream.js @@ -326,4 +326,4 @@ function finished(stream, opts) { } module.exports = eos; -module.exports.finished = finished; \ No newline at end of file +module.exports.finished = finished; diff --git a/lib/internal/streams/transform.js b/lib/internal/streams/transform.js index 0b33e15..0f870ca 100644 --- a/lib/internal/streams/transform.js +++ b/lib/internal/streams/transform.js @@ -1 +1 @@ -module.exports = require('node:stream').Transform; \ No newline at end of file +module.exports = require('node:stream').Transform; diff --git a/lib/internal/streams/utils.js b/lib/internal/streams/utils.js index 7d5eabf..cd95a15 100644 --- a/lib/internal/streams/utils.js +++ b/lib/internal/streams/utils.js @@ -362,4 +362,4 @@ module.exports = { kCloseEmitted, kErrored, kConstructed, -}; \ No newline at end of file +}; diff --git a/lib/internal/test_runner/coverage.js b/lib/internal/test_runner/coverage.js index 58d23f3..14b3067 100644 --- a/lib/internal/test_runner/coverage.js +++ b/lib/internal/test_runner/coverage.js @@ -1,687 +1,10 @@ -const { primordials, internalBinding = require('#lib/bootstrap'); - -'use strict'; -const { - ArrayFrom, - ArrayPrototypeMap, - ArrayPrototypePush, - JSONParse, - MathFloor, - MathMax, - MathMin, - NumberParseInt, - ObjectAssign, - RegExpPrototypeExec, - RegExpPrototypeSymbolSplit, - SafeMap, - SafeSet, - StringPrototypeIncludes, - StringPrototypeLocaleCompare, - StringPrototypeStartsWith, -} = primordials; const { - copyFileSync, - mkdirSync, - mkdtempSync, - opendirSync, - readFileSync, - rmSync, -} = require('fs'); -const { setupCoverageHooks } = require('#internal/util'); -const { tmpdir } = require('os'); -const { join, resolve, relative, matchesGlob } = require('path'); -const { fileURLToPath } = require('#internal/url'); -const { kMappings, SourceMap } = require('#internal/source_map/source_map'); -const { - codes: { - ERR_SOURCE_MAP_CORRUPT, - ERR_SOURCE_MAP_MISSING_SOURCE, - }, + codes: { ERR_UNSUPPORTED_FEATURE } } = require('#internal/errors'); -const kCoverageFileRegex = /^coverage-(\d+)-(\d{13})-(\d+)\.json$/; -const kIgnoreRegex = /\/\* node:coverage ignore next (?\d+ )?\*\//; -const kLineEndingRegex = /\r?\n$/u; -const kLineSplitRegex = /(?<=\r?\n)/u; -const kStatusRegex = /\/\* node:coverage (?enable|disable) \*\//; - -class CoverageLine { - constructor(line, startOffset, src, length = src?.length) { - const newlineLength = src == null ? 0 : - RegExpPrototypeExec(kLineEndingRegex, src)?.[0].length ?? 0; - - this.line = line; - this.src = src; - this.startOffset = startOffset; - this.endOffset = startOffset + length - newlineLength; - this.ignore = false; - this.count = this.startOffset === this.endOffset ? 1 : 0; - } -} - -class TestCoverage { - constructor(coverageDirectory, - originalCoverageDirectory, - workingDirectory, - excludeGlobs, - includeGlobs, - sourceMaps, - thresholds) { - this.coverageDirectory = coverageDirectory; - this.originalCoverageDirectory = originalCoverageDirectory; - this.workingDirectory = workingDirectory; - this.excludeGlobs = excludeGlobs; - this.includeGlobs = includeGlobs; - this.sourceMaps = sourceMaps; - this.thresholds = thresholds; - } - - #sourceLines = new SafeMap(); - - getLines(fileUrl, source) { - // Split the file source into lines. Make sure the lines maintain their - // original line endings because those characters are necessary for - // determining offsets in the file. - if (this.#sourceLines.has(fileUrl)) { - return this.#sourceLines.get(fileUrl); - } - - try { - source ??= readFileSync(fileURLToPath(fileUrl), 'utf8'); - } catch { - // The file can no longer be read. It may have been deleted among - // other possibilities. Leave it out of the coverage report. - this.#sourceLines.set(fileUrl, null); - return; - } - - const linesWithBreaks = - RegExpPrototypeSymbolSplit(kLineSplitRegex, source); - let ignoreCount = 0; - let enabled = true; - let offset = 0; - - const lines = ArrayPrototypeMap(linesWithBreaks, (line, i) => { - const startOffset = offset; - const coverageLine = new CoverageLine(i + 1, startOffset, line); - - offset += line.length; - - // Determine if this line is being ignored. - if (ignoreCount > 0) { - ignoreCount--; - coverageLine.ignore = true; - } else if (!enabled) { - coverageLine.ignore = true; - } - - if (!coverageLine.ignore) { - // If this line is not already being ignored, check for ignore - // comments. - const match = RegExpPrototypeExec(kIgnoreRegex, line); - - if (match !== null) { - ignoreCount = NumberParseInt(match.groups?.count ?? 1, 10); - } - } - - // Check for comments to enable/disable coverage no matter what. These - // take precedence over ignore comments. - const match = RegExpPrototypeExec(kStatusRegex, line); - const status = match?.groups?.status; - - if (status) { - ignoreCount = 0; - enabled = status === 'enable'; - } - - return coverageLine; - }); - this.#sourceLines.set(fileUrl, lines); - return lines; - } - - summary() { - internalBinding('profiler').takeCoverage(); - const coverage = this.getCoverageFromDirectory(); - const coverageSummary = { - __proto__: null, - workingDirectory: this.workingDirectory, - files: [], - totals: { - __proto__: null, - totalLineCount: 0, - totalBranchCount: 0, - totalFunctionCount: 0, - coveredLineCount: 0, - coveredBranchCount: 0, - coveredFunctionCount: 0, - coveredLinePercent: 0, - coveredBranchPercent: 0, - coveredFunctionPercent: 0, - }, - thresholds: this.thresholds, - }; - - if (!coverage) { - return coverageSummary; - } - - for (let i = 0; i < coverage.length; ++i) { - const { functions, url } = coverage[i]; - - let totalBranches = 0; - let totalFunctions = 0; - let branchesCovered = 0; - let functionsCovered = 0; - const functionReports = []; - const branchReports = []; - - const lines = this.getLines(url); - if (!lines) { - continue; - } - - - for (let j = 0; j < functions.length; ++j) { - const { isBlockCoverage, ranges } = functions[j]; - - let maxCountPerFunction = 0; - for (let k = 0; k < ranges.length; ++k) { - const range = ranges[k]; - maxCountPerFunction = MathMax(maxCountPerFunction, range.count); - - // Add some useful data to the range. The test runner has read these ranges - // from a file, so we own the data structures and can do what we want. - ObjectAssign(range, mapRangeToLines(range, lines)); - - if (isBlockCoverage) { - ArrayPrototypePush(branchReports, { - __proto__: null, - line: range.lines[0]?.line, - count: range.count, - }); - - if (range.count !== 0 || - range.ignoredLines === range.lines.length) { - branchesCovered++; - } - - totalBranches++; - } - } - - if (j > 0 && ranges.length > 0) { - const range = ranges[0]; - - ArrayPrototypePush(functionReports, { - __proto__: null, - name: functions[j].functionName, - count: maxCountPerFunction, - line: range.lines[0]?.line, - }); - - if (range.count !== 0 || range.ignoredLines === range.lines.length) { - functionsCovered++; - } - - totalFunctions++; - } - } - - let coveredCnt = 0; - const lineReports = []; - - for (let j = 0; j < lines.length; ++j) { - const line = lines[j]; - if (!line.ignore) { - ArrayPrototypePush(lineReports, { - __proto__: null, - line: line.line, - count: line.count, - }); - } - if (line.count > 0 || line.ignore) { - coveredCnt++; - } - } - - ArrayPrototypePush(coverageSummary.files, { - __proto__: null, - path: fileURLToPath(url), - totalLineCount: lines.length, - totalBranchCount: totalBranches, - totalFunctionCount: totalFunctions, - coveredLineCount: coveredCnt, - coveredBranchCount: branchesCovered, - coveredFunctionCount: functionsCovered, - coveredLinePercent: toPercentage(coveredCnt, lines.length), - coveredBranchPercent: toPercentage(branchesCovered, totalBranches), - coveredFunctionPercent: toPercentage(functionsCovered, totalFunctions), - functions: functionReports, - branches: branchReports, - lines: lineReports, - }); - - coverageSummary.totals.totalLineCount += lines.length; - coverageSummary.totals.totalBranchCount += totalBranches; - coverageSummary.totals.totalFunctionCount += totalFunctions; - coverageSummary.totals.coveredLineCount += coveredCnt; - coverageSummary.totals.coveredBranchCount += branchesCovered; - coverageSummary.totals.coveredFunctionCount += functionsCovered; - } - - coverageSummary.totals.coveredLinePercent = toPercentage( - coverageSummary.totals.coveredLineCount, - coverageSummary.totals.totalLineCount, - ); - coverageSummary.totals.coveredBranchPercent = toPercentage( - coverageSummary.totals.coveredBranchCount, - coverageSummary.totals.totalBranchCount, - ); - coverageSummary.totals.coveredFunctionPercent = toPercentage( - coverageSummary.totals.coveredFunctionCount, - coverageSummary.totals.totalFunctionCount, - ); - coverageSummary.files.sort(sortCoverageFiles); - - return coverageSummary; - } - - cleanup() { - // Restore the original value of process.env.NODE_V8_COVERAGE. Then, copy - // all of the created coverage files to the original coverage directory. - internalBinding('profiler').endCoverage(); - - if (this.originalCoverageDirectory === undefined) { - delete process.env.NODE_V8_COVERAGE; - } else { - process.env.NODE_V8_COVERAGE = this.originalCoverageDirectory; - let dir; - - try { - mkdirSync(this.originalCoverageDirectory, { __proto__: null, recursive: true }); - dir = opendirSync(this.coverageDirectory); - - for (let entry; (entry = dir.readSync()) !== null;) { - const src = join(this.coverageDirectory, entry.name); - const dst = join(this.originalCoverageDirectory, entry.name); - copyFileSync(src, dst); - } - } finally { - if (dir) { - dir.closeSync(); - } - } - } - - try { - rmSync(this.coverageDirectory, { __proto__: null, recursive: true }); - } catch { - // Ignore cleanup errors. - } - } - - getCoverageFromDirectory() { - const result = new SafeMap(); - let dir; - - try { - dir = opendirSync(this.coverageDirectory); - - for (let entry; (entry = dir.readSync()) !== null;) { - if (RegExpPrototypeExec(kCoverageFileRegex, entry.name) === null) { - continue; - } - - const coverageFile = join(this.coverageDirectory, entry.name); - const coverage = JSONParse(readFileSync(coverageFile, 'utf8')); - this.mergeCoverage(result, this.mapCoverageWithSourceMap(coverage)); - } - - return ArrayFrom(result.values()); - } finally { - if (dir) { - dir.closeSync(); - } - } - } - - - mapCoverageWithSourceMap(coverage) { - const { result } = coverage; - const sourceMapCache = coverage['source-map-cache']; - if (!this.sourceMaps || !sourceMapCache) { - return result; - } - const newResult = new SafeMap(); - for (let i = 0; i < result.length; ++i) { - const script = result[i]; - const { url, functions } = script; - if (this.shouldSkipFileCoverage(url) || sourceMapCache[url] == null) { - newResult.set(url, script); - continue; - } - const { data, lineLengths } = sourceMapCache[url]; - if (!data) throw new ERR_SOURCE_MAP_CORRUPT(url); - let offset = 0; - const executedLines = ArrayPrototypeMap(lineLengths, (length, i) => { - const coverageLine = new CoverageLine(i + 1, offset, null, length + 1); - offset += length + 1; - return coverageLine; - }); - if (data.sourcesContent != null) { - for (let j = 0; j < data.sources.length; ++j) { - this.getLines(data.sources[j], data.sourcesContent[j]); - } - } - const sourceMap = new SourceMap(data, { __proto__: null, lineLengths }); - - for (let j = 0; j < functions.length; ++j) { - const { ranges, functionName, isBlockCoverage } = functions[j]; - if (ranges == null) { - continue; - } - let newUrl; - const newRanges = []; - for (let k = 0; k < ranges.length; ++k) { - const { startOffset, endOffset, count } = ranges[k]; - const { lines } = mapRangeToLines(ranges[k], executedLines); - - let startEntry = sourceMap - .findEntry(lines[0].line - 1, MathMax(0, startOffset - lines[0].startOffset)); - const endEntry = sourceMap - .findEntry(lines[lines.length - 1].line - 1, (endOffset - lines[lines.length - 1].startOffset) - 1); - if (!startEntry.originalSource && endEntry.originalSource && - lines[0].line === 1 && startOffset === 0 && lines[0].startOffset === 0) { - // Edge case when the first line is not mappable - const { 2: originalSource, 3: originalLine, 4: originalColumn } = sourceMap[kMappings][0]; - startEntry = { __proto__: null, originalSource, originalLine, originalColumn }; - } - - if (!startEntry.originalSource || startEntry.originalSource !== endEntry.originalSource) { - // The range is not mappable. Skip it. - continue; - } - - newUrl ??= startEntry?.originalSource; - const mappedLines = this.getLines(newUrl); - if (!mappedLines) { - throw new ERR_SOURCE_MAP_MISSING_SOURCE(newUrl, url); - } - const mappedStartOffset = this.entryToOffset(startEntry, mappedLines); - const mappedEndOffset = this.entryToOffset(endEntry, mappedLines) + 1; - for (let l = startEntry.originalLine; l <= endEntry.originalLine; l++) { - mappedLines[l].count = count; - } - - ArrayPrototypePush(newRanges, { - __proto__: null, startOffset: mappedStartOffset, endOffset: mappedEndOffset, count, - }); - } - - if (!newUrl) { - // No mappable ranges. Skip the function. - continue; - } - const newScript = newResult.get(newUrl) ?? { __proto__: null, url: newUrl, functions: [] }; - ArrayPrototypePush(newScript.functions, { __proto__: null, functionName, ranges: newRanges, isBlockCoverage }); - newResult.set(newUrl, newScript); - } - } - - return ArrayFrom(newResult.values()); - } - - entryToOffset(entry, lines) { - const line = MathMax(entry.originalLine, 0); - return MathMin(lines[line].startOffset + entry.originalColumn, lines[line].endOffset); - } - - mergeCoverage(merged, coverage) { - for (let i = 0; i < coverage.length; ++i) { - const newScript = coverage[i]; - const { url } = newScript; - - if (this.shouldSkipFileCoverage(url)) { - continue; - } - - const oldScript = merged.get(url); - - if (oldScript === undefined) { - merged.set(url, newScript); - } else { - mergeCoverageScripts(oldScript, newScript); - } - } - } - - shouldSkipFileCoverage(url) { - // This check filters out core modules, which start with 'node:' in - // coverage reports, as well as any invalid coverages which have been - // observed on Windows. - if (!StringPrototypeStartsWith(url, 'file:')) return true; - - const absolutePath = fileURLToPath(url); - const relativePath = relative(this.workingDirectory, absolutePath); - - // This check filters out files that match the exclude globs. - if (this.excludeGlobs?.length > 0) { - for (let i = 0; i < this.excludeGlobs.length; ++i) { - if (matchesGlob(relativePath, this.excludeGlobs[i]) || - matchesGlob(absolutePath, this.excludeGlobs[i])) return true; - } - } - - // This check filters out files that do not match the include globs. - if (this.includeGlobs?.length > 0) { - for (let i = 0; i < this.includeGlobs.length; ++i) { - if (matchesGlob(relativePath, this.includeGlobs[i]) || - matchesGlob(absolutePath, this.includeGlobs[i])) return false; - } - return true; - } - - // This check filters out the node_modules/ directory, unless it is explicitly included. - return StringPrototypeIncludes(url, '/node_modules/'); - } -} - -function toPercentage(covered, total) { - return total === 0 ? 100 : (covered / total) * 100; -} - -function sortCoverageFiles(a, b) { - return StringPrototypeLocaleCompare(a.path, b.path); -} - -function setupCoverage(options) { - let originalCoverageDirectory = process.env.NODE_V8_COVERAGE; - - // If NODE_V8_COVERAGE was already specified, convert it to an absolute path - // and store it for later. The test runner will use a temporary directory - // so that no preexisting coverage files interfere with the results of the - // coverage report. Then, once the coverage is computed, move the coverage - // files back to the original NODE_V8_COVERAGE directory. - originalCoverageDirectory &&= resolve(options.cwd, originalCoverageDirectory); - - const coverageDirectory = mkdtempSync(join(tmpdir(), 'node-coverage-')); - const enabled = setupCoverageHooks(coverageDirectory); - - if (!enabled) { - return null; - } - - // Ensure that NODE_V8_COVERAGE is set so that coverage can propagate to - // child processes. - process.env.NODE_V8_COVERAGE = coverageDirectory; - - return new TestCoverage( - coverageDirectory, - originalCoverageDirectory, - options.cwd, - options.coverageExcludeGlobs, - options.coverageIncludeGlobs, - options.sourceMaps, - { - __proto__: null, - line: options.lineCoverage, - branch: options.branchCoverage, - function: options.functionCoverage, - }, - ); -} - -function mapRangeToLines(range, lines) { - const { startOffset, endOffset, count } = range; - const mappedLines = []; - let ignoredLines = 0; - let start = 0; - let end = lines.length; - let mid; - - while (start <= end) { - mid = MathFloor((start + end) / 2); - let line = lines[mid]; - - if (startOffset >= line?.startOffset && startOffset <= line?.endOffset) { - while (endOffset > line?.startOffset) { - // If the range is not covered, and the range covers the entire line, - // then mark that line as not covered. - if (startOffset <= line.startOffset && endOffset >= line.endOffset) { - line.count = count; - } - - ArrayPrototypePush(mappedLines, line); - - if (line.ignore) { - ignoredLines++; - } - - mid++; - line = lines[mid]; - } - - break; - } else if (startOffset >= line?.endOffset) { - start = mid + 1; - } else { - end = mid - 1; - } - } - - return { __proto__: null, lines: mappedLines, ignoredLines }; -} - -function mergeCoverageScripts(oldScript, newScript) { - // Merge the functions from the new coverage into the functions from the - // existing (merged) coverage. - for (let i = 0; i < newScript.functions.length; ++i) { - const newFn = newScript.functions[i]; - let found = false; - - for (let j = 0; j < oldScript.functions.length; ++j) { - const oldFn = oldScript.functions[j]; - - if (newFn.functionName === oldFn.functionName && - newFn.ranges?.[0].startOffset === oldFn.ranges?.[0].startOffset && - newFn.ranges?.[0].endOffset === oldFn.ranges?.[0].endOffset) { - // These are the same functions. - found = true; - - // If newFn is block level coverage, then it will: - // - Replace oldFn if oldFn is not block level coverage. - // - Merge with oldFn if it is also block level coverage. - // If newFn is not block level coverage, then it has no new data. - if (newFn.isBlockCoverage) { - if (oldFn.isBlockCoverage) { - // Merge the oldFn ranges with the newFn ranges. - mergeCoverageRanges(oldFn, newFn); - } else { - // Replace oldFn with newFn. - oldFn.isBlockCoverage = true; - oldFn.ranges = newFn.ranges; - } - } - - break; - } - } - - if (!found) { - // This is a new function to track. This is possible because V8 can - // generate a different list of functions depending on which code paths - // are executed. For example, if a code path dynamically creates a - // function, but that code path is not executed then the function does - // not show up in the coverage report. Unfortunately, this also means - // that the function counts in the coverage summary can never be - // guaranteed to be 100% accurate. - ArrayPrototypePush(oldScript.functions, newFn); - } - } -} - -function mergeCoverageRanges(oldFn, newFn) { - const mergedRanges = new SafeSet(); - - // Keep all of the existing covered ranges. - for (let i = 0; i < oldFn.ranges.length; ++i) { - const oldRange = oldFn.ranges[i]; - - if (oldRange.count > 0) { - mergedRanges.add(oldRange); - } - } - - // Merge in the new ranges where appropriate. - for (let i = 0; i < newFn.ranges.length; ++i) { - const newRange = newFn.ranges[i]; - let exactMatch = false; - - for (let j = 0; j < oldFn.ranges.length; ++j) { - const oldRange = oldFn.ranges[j]; - - if (doesRangeEqualOtherRange(newRange, oldRange)) { - // These are the same ranges, so keep the existing one. - oldRange.count += newRange.count; - mergedRanges.add(oldRange); - exactMatch = true; - break; - } - - // Look at ranges representing missing coverage and add ranges that - // represent the intersection. - if (oldRange.count === 0 && newRange.count === 0) { - if (doesRangeContainOtherRange(oldRange, newRange)) { - // The new range is completely within the old range. Discard the - // larger (old) range, and keep the smaller (new) range. - mergedRanges.add(newRange); - } else if (doesRangeContainOtherRange(newRange, oldRange)) { - // The old range is completely within the new range. Discard the - // larger (new) range, and keep the smaller (old) range. - mergedRanges.add(oldRange); - } - } - } - - // Add new ranges that do not represent missing coverage. - if (newRange.count > 0 && !exactMatch) { - mergedRanges.add(newRange); - } - } - - oldFn.ranges = ArrayFrom(mergedRanges); -} - -function doesRangeEqualOtherRange(range, otherRange) { - return range.startOffset === otherRange.startOffset && - range.endOffset === otherRange.endOffset; -} - -function doesRangeContainOtherRange(range, otherRange) { - return range.startOffset <= otherRange.startOffset && - range.endOffset >= otherRange.endOffset; -} - -module.exports = { setupCoverage, TestCoverage }; +module.exports = { + setupCoverage() { + throw new ERR_UNSUPPORTED_FEATURE('Code coverage'); + }, + TestCoverage: class {} +}; diff --git a/lib/internal/test_runner/mock/loader.js b/lib/internal/test_runner/mock/loader.js deleted file mode 100644 index c09eb6c..0000000 --- a/lib/internal/test_runner/mock/loader.js +++ /dev/null @@ -1,203 +0,0 @@ -const { primordials, internalBinding } = require('#lib/bootstrap'); - -'use strict'; -const { - JSONStringify, - SafeMap, - globalThis: { - Atomics: { - notify: AtomicsNotify, - store: AtomicsStore, - }, - }, -} = primordials; -const { - kBadExportsMessage, - kMockSearchParam, - kMockSuccess, - kMockExists, - kMockUnknownMessage, -} = require('#internal/test_runner/mock/mock'); -const { URL, URLParse } = require('#internal/url'); -let debug = require('#internal/util/debuglog').debuglog('test_runner', (fn) => { - debug = fn; -}); - -// TODO(cjihrig): The mocks need to be thread aware because the exports are -// evaluated on the thread that creates the mock. Before marking this API as -// stable, one of the following issues needs to be implemented: -// https://github.com/nodejs/node/issues/49472 -// or https://github.com/nodejs/node/issues/52219 - -const mocks = new SafeMap(); - -async function initialize(data) { - data?.port.on('message', ({ type, payload }) => { - debug('mock loader received message type "%s" with payload %o', type, payload); - - if (type === 'node:test:register') { - const { baseURL } = payload; - const mock = mocks.get(baseURL); - - if (mock?.active) { - debug('already mocking "%s"', baseURL); - sendAck(payload.ack, kMockExists); - return; - } - - const localVersion = mock?.localVersion ?? 0; - - debug('new mock version %d for "%s"', localVersion, baseURL); - mocks.set(baseURL, { - __proto__: null, - active: true, - cache: payload.cache, - exportNames: payload.exportNames, - format: payload.format, - hasDefaultExport: payload.hasDefaultExport, - localVersion, - url: baseURL, - }); - sendAck(payload.ack); - } else if (type === 'node:test:unregister') { - const mock = mocks.get(payload.baseURL); - - if (mock !== undefined) { - mock.active = false; - mock.localVersion++; - } - - sendAck(payload.ack); - } else { - sendAck(payload.ack, kMockUnknownMessage); - } - }); -} - -async function resolve(specifier, context, nextResolve) { - debug('resolve hook entry, specifier = "%s", context = %o', specifier, context); - - const nextResolveResult = await nextResolve(specifier, context); - const mockSpecifier = nextResolveResult.url; - - const mock = mocks.get(mockSpecifier); - debug('resolve hook, specifier = "%s", mock = %o', specifier, mock); - - if (mock?.active !== true) { - return nextResolveResult; - } - - const url = new URL(mockSpecifier); - url.searchParams.set(kMockSearchParam, mock.localVersion); - - if (!mock.cache) { - // With ESM, we can't remove modules from the cache. Bump the module's - // version instead so that the next import will be uncached. - mock.localVersion++; - } - - const { href } = url; - debug('resolve hook finished, url = "%s"', href); - return { __proto__: null, url: href, format: nextResolveResult.format }; -} - -async function load(url, context, nextLoad) { - debug('load hook entry, url = "%s", context = %o', url, context); - const parsedURL = URLParse(url); - if (parsedURL) { - parsedURL.searchParams.delete(kMockSearchParam); - } - - const baseURL = parsedURL ? parsedURL.href : url; - const mock = mocks.get(baseURL); - - const original = await nextLoad(url, context); - debug('load hook, mock = %o', mock); - if (mock?.active !== true) { - return original; - } - - // Treat builtins as commonjs because customization hooks do not allow a - // core module to be replaced. - // Also collapse 'commonjs-sync' and 'require-commonjs' to 'commonjs'. - const format = ( - original.format === 'builtin' || - original.format === 'commonjs-sync' || - original.format === 'require-commonjs') ? 'commonjs' : original.format; - - const result = { - __proto__: null, - format, - shortCircuit: true, - source: await createSourceFromMock(mock, format), - }; - - debug('load hook finished, result = %o', result); - return result; -} - -async function createSourceFromMock(mock, format) { - // Create mock implementation from provided exports. - const { exportNames, hasDefaultExport, url } = mock; - const useESM = format === 'module' || format === 'module-typescript'; - const source = `${testImportSource(useESM)} -if (!$__test.mock._mockExports.has(${JSONStringify(url)})) { - throw new Error(${JSONStringify(`mock exports not found for "${url}"`)}); -} - -const $__exports = $__test.mock._mockExports.get(${JSONStringify(url)}); -${defaultExportSource(useESM, hasDefaultExport)} -${namedExportsSource(useESM, exportNames)} -`; - - return source; -} - -function testImportSource(useESM) { - if (useESM) { - return "import $__test from 'node:test';"; - } - - return "const $__test = require('node:test');"; -} - -function defaultExportSource(useESM, hasDefaultExport) { - if (!hasDefaultExport) { - return ''; - } else if (useESM) { - return 'export default $__exports.defaultExport;'; - } - - return 'module.exports = $__exports.defaultExport;'; -} - -function namedExportsSource(useESM, exportNames) { - let source = ''; - - if (!useESM && exportNames.length > 0) { - source += ` -if (module.exports === null || typeof module.exports !== 'object') { - throw new Error('${JSONStringify(kBadExportsMessage)}'); -} -`; - } - - for (let i = 0; i < exportNames.length; ++i) { - const name = exportNames[i]; - - if (useESM) { - source += `export let ${name} = $__exports.namedExports[${JSONStringify(name)}];\n`; - } else { - source += `module.exports[${JSONStringify(name)}] = $__exports.namedExports[${JSONStringify(name)}];\n`; - } - } - - return source; -} - -function sendAck(buf, status = kMockSuccess) { - AtomicsStore(buf, 0, status); - AtomicsNotify(buf, 0); -} - -module.exports = { initialize, load, resolve }; diff --git a/lib/internal/timers.js b/lib/internal/timers.js index d269e51..3c73b50 100644 --- a/lib/internal/timers.js +++ b/lib/internal/timers.js @@ -1 +1 @@ -module.exports = { TIMEOUT_MAX: 2 ** 31 - 1 } \ No newline at end of file +module.exports = { TIMEOUT_MAX: 2 ** 31 - 1 } diff --git a/lib/internal/url.js b/lib/internal/url.js index 646d858..90db79c 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -13,4 +13,4 @@ module.exports = { return url.fileURLToPath(self); }, isURL: (self) => Boolean(self?.href && self.protocol && self.auth === undefined && self.path === undefined) -} \ No newline at end of file +} diff --git a/lib/internal/util.js b/lib/internal/util.js index 5173db3..63688ec 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -46,4 +46,4 @@ module.exports = { // TODO return ''; } -} \ No newline at end of file +} diff --git a/lib/internal/util/debuglog.js b/lib/internal/util/debuglog.js index 6b3ba95..2680f9e 100644 --- a/lib/internal/util/debuglog.js +++ b/lib/internal/util/debuglog.js @@ -1,3 +1,3 @@ module.exports = { debuglog: () => () => {} -}; \ No newline at end of file +}; diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index dfb6998..949bcef 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -1,2 +1,2 @@ const { inspect } = require('node:util'); -module.exports = { inspect }; \ No newline at end of file +module.exports = { inspect }; diff --git a/lib/internal/util/inspector.js b/lib/internal/util/inspector.js index 838f6e1..dd76e41 100644 --- a/lib/internal/util/inspector.js +++ b/lib/internal/util/inspector.js @@ -33,4 +33,4 @@ module.exports = { getInspectPort, isUsingInspector, isInspectorMessage, -} \ No newline at end of file +} diff --git a/lib/internal/util/types.js b/lib/internal/util/types.js index 6bd19f4..81fc140 100644 --- a/lib/internal/util/types.js +++ b/lib/internal/util/types.js @@ -1 +1 @@ -module.exports = require('node:util/types'); \ No newline at end of file +module.exports = require('node:util/types'); diff --git a/lib/internal/watch_mode/files_watcher.js b/lib/internal/watch_mode/files_watcher.js index bfac455..3e7311b 100644 --- a/lib/internal/watch_mode/files_watcher.js +++ b/lib/internal/watch_mode/files_watcher.js @@ -1,3 +1,3 @@ module.exports = { FilesWatcher: null // --watch is not supported -} \ No newline at end of file +} diff --git a/lib/test.js b/lib/test.js index b372c2e..15b885c 100644 --- a/lib/test.js +++ b/lib/test.js @@ -65,4 +65,4 @@ if (getOptionValue('--experimental-test-snapshots')) { return lazySnapshot; }, }); -} \ No newline at end of file +} diff --git a/test/common/index.js b/test/common/index.js index 75c3271..24fe226 100644 --- a/test/common/index.js +++ b/test/common/index.js @@ -268,4 +268,4 @@ module.exports = { isAIX, isIBMi, hasCrypto, -} \ No newline at end of file +} diff --git a/test/common/pseudo-tty.py b/test/common/pseudo-tty.py index 9bb3948..5ce9025 100644 --- a/test/common/pseudo-tty.py +++ b/test/common/pseudo-tty.py @@ -101,4 +101,4 @@ def pipe(sfd, dfd): if parent_fd in rfds: if pipe(parent_fd, STDOUT): - break \ No newline at end of file + break diff --git a/test/fixtures/empty.js b/test/fixtures/empty.js index e69de29..8b13789 100644 --- a/test/fixtures/empty.js +++ b/test/fixtures/empty.js @@ -0,0 +1 @@ + diff --git a/test/fixtures/module-mocking/basic-cjs.js b/test/fixtures/module-mocking/basic-cjs.js index 35483ad..df5d9b2 100644 --- a/test/fixtures/module-mocking/basic-cjs.js +++ b/test/fixtures/module-mocking/basic-cjs.js @@ -2,4 +2,4 @@ module.exports = { string: 'original cjs string', -}; \ No newline at end of file +}; diff --git a/test/fixtures/module-mocking/basic-esm-without-extension.js b/test/fixtures/module-mocking/basic-esm-without-extension.js index fc63ebd..f2b4722 100644 --- a/test/fixtures/module-mocking/basic-esm-without-extension.js +++ b/test/fixtures/module-mocking/basic-esm-without-extension.js @@ -1 +1 @@ -export let string = 'original esm string'; \ No newline at end of file +export let string = 'original esm string'; diff --git a/test/fixtures/module-mocking/basic-esm.mjs b/test/fixtures/module-mocking/basic-esm.mjs index fc63ebd..f2b4722 100644 --- a/test/fixtures/module-mocking/basic-esm.mjs +++ b/test/fixtures/module-mocking/basic-esm.mjs @@ -1 +1 @@ -export let string = 'original esm string'; \ No newline at end of file +export let string = 'original esm string'; diff --git a/test/fixtures/module-mocking/wrong-import-after-module-mocking.mjs b/test/fixtures/module-mocking/wrong-import-after-module-mocking.mjs index b82a72b..3fbe4ff 100644 --- a/test/fixtures/module-mocking/wrong-import-after-module-mocking.mjs +++ b/test/fixtures/module-mocking/wrong-import-after-module-mocking.mjs @@ -6,4 +6,4 @@ try { } catch {} const { string } = await import('./basic-esm-without-extension'); -console.log(`Found string: ${string}`); // prints 'original esm string' \ No newline at end of file +console.log(`Found string: ${string}`); // prints 'original esm string' diff --git a/test/fixtures/test-runner/default-behavior/subdir/subdir_test.js b/test/fixtures/test-runner/default-behavior/subdir/subdir_test.js index e69de29..8b13789 100644 --- a/test/fixtures/test-runner/default-behavior/subdir/subdir_test.js +++ b/test/fixtures/test-runner/default-behavior/subdir/subdir_test.js @@ -0,0 +1 @@ + diff --git a/test/fixtures/test-runner/issue-54726/latest.js b/test/fixtures/test-runner/issue-54726/latest.js index e69de29..8b13789 100644 --- a/test/fixtures/test-runner/issue-54726/latest.js +++ b/test/fixtures/test-runner/issue-54726/latest.js @@ -0,0 +1 @@ + diff --git a/test/fixtures/test-runner/issue-54726/non-matching.js b/test/fixtures/test-runner/issue-54726/non-matching.js index e69de29..8b13789 100644 --- a/test/fixtures/test-runner/issue-54726/non-matching.js +++ b/test/fixtures/test-runner/issue-54726/non-matching.js @@ -0,0 +1 @@ + diff --git a/test/fixtures/test-runner/nested.js b/test/fixtures/test-runner/nested.js index 424e278..07a1184 100644 --- a/test/fixtures/test-runner/nested.js +++ b/test/fixtures/test-runner/nested.js @@ -21,4 +21,4 @@ test('level 0a', { concurrency: 4 }, async (t) => { test('level 0b', async (t) => { throw new Error('level 0b error'); -}); \ No newline at end of file +}); diff --git a/test/parallel/test-runner-cli.js b/test/parallel/test-runner-cli.js index e78215f..1a20f49 100644 --- a/test/parallel/test-runner-cli.js +++ b/test/parallel/test-runner-cli.js @@ -388,4 +388,4 @@ for (const isolation of ['none', 'process']) { assert.strictEqual(child.status, 0); assert.strictEqual(child.signal, null); } -} \ No newline at end of file +} diff --git a/test/parallel/test-runner-inspect.mjs b/test/parallel/test-runner-inspect.mjs index c03778c..ec7a12f 100644 --- a/test/parallel/test-runner-inspect.mjs +++ b/test/parallel/test-runner-inspect.mjs @@ -56,4 +56,4 @@ tmpdir.refresh(); assert.doesNotMatch(stderr, /Warning: Using the inspector with --test forces running at a concurrency of 1\. Use the inspectPort option to run with concurrency/); assert.strictEqual(code, 1); assert.strictEqual(signal, null); -} \ No newline at end of file +} diff --git a/test/parallel/test-runner-run-files-undefined.mjs b/test/parallel/test-runner-run-files-undefined.mjs index aba2c4e..5a3bbbc 100644 --- a/test/parallel/test-runner-run-files-undefined.mjs +++ b/test/parallel/test-runner-run-files-undefined.mjs @@ -61,4 +61,4 @@ if (process.env.CHILD === 'true') { }).on('exit', common.mustCall((code) => { assert.strictEqual(code, 0); })); -} \ No newline at end of file +} diff --git a/test/parallel/test-runner-run.mjs b/test/parallel/test-runner-run.mjs index 2f6007c..8fc6175 100644 --- a/test/parallel/test-runner-run.mjs +++ b/test/parallel/test-runner-run.mjs @@ -570,4 +570,4 @@ process.on('exit', () => { assert.strictEqual(process.listeners('beforeExit').length, 0); assert.strictEqual(process.listeners('SIGINT').length, 0); assert.strictEqual(process.listeners('SIGTERM').length, 0); -}); \ No newline at end of file +});