-
-
Notifications
You must be signed in to change notification settings - Fork 306
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[New] add types #603
base: master
Are you sure you want to change the base?
[New] add types #603
Conversation
Are these hand written or generated from JSDoc ? It's unclear to me. Either way looks reasonable to me. |
Hand-written. |
📝 Walkthrough📝 WalkthroughWalkthroughThe update introduces comprehensive JSDoc type annotations across various JavaScript files to enhance type safety and documentation. This includes adjustments to function parameters and return types, new type definitions, and enhancements to existing logic, improving code clarity and robust type-checking during development. Changes
Sequence DiagramsNo sequence diagrams generated due to the nature of changes primarily adding type annotations and enhancing existing functionality. Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 3
Configuration used: CodeRabbit UI
Files ignored due to path filters (2)
package.json
is excluded by:!**/*.json
tsconfig.json
is excluded by:!**/*.json
Files selected for processing (12)
- .github/workflows/node-aught.yml (1 hunks)
- bin/import-or-require.js (1 hunks)
- bin/tape (2 hunks)
- index.d.ts (1 hunks)
- index.js (8 hunks)
- lib/default_stream.d.ts (1 hunks)
- lib/default_stream.js (2 hunks)
- lib/results.d.ts (1 hunks)
- lib/results.js (8 hunks)
- lib/test.d.ts (1 hunks)
- lib/test.js (42 hunks)
- test/common.js (4 hunks)
Additional comments: 43
lib/default_stream.d.ts (1)
- 1-5: The TypeScript declaration file for
defaultStream
correctly defines the function's return type asThroughStream
and uses the appropriate CommonJS export syntax. This enhances type safety and code clarity..github/workflows/node-aught.yml (1)
- 12-12: Adding
skip-ls-check: true
to the workflow configuration is a valid optimization that can potentially speed up the CI process by skipping unnecessary checks.bin/import-or-require.js (1)
- 7-7: The type annotation for the
importOrRequire
function accurately specifies its parameter and return types, enhancing code readability and type safety.lib/default_stream.js (2)
- 6-6: The type annotation for the exported module correctly references its own declaration file, which is a good practice for maintaining consistency between the implementation and its TypeScript definitions.
- 18-28: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [12-25]
The refactoring of the
write
function to handle different types of input buffers more explicitly improves the function's readability and robustness. The type annotation forbuf
asunknown
and the subsequent type assertion are appropriate given the function's need to handle various input types.lib/results.d.ts (1)
- 1-54: The TypeScript declaration file for
Results
accurately defines the class's structure, methods, and related types. This addition significantly enhances type safety and code clarity, making it easier to work withResults
instances and their associated data.index.d.ts (1)
- 1-72: The TypeScript declaration file for the
tape
testing library accurately defines the library's API, including test options, assert options, test cases, stream options, and the harness. This addition significantly enhances type safety and code clarity, making it easier to work with tests and their configurations.bin/tape (2)
- 98-98: The type annotation for the
importFiles
function accurately specifies its parameter and return types, enhancing code readability and maintainability.- 108-108: The type annotation for the
filesPromise
variable clarifies its type as aPromise
, which is appropriate given its role in handling asynchronous file imports. This enhances code readability and maintainability.test/common.js (4)
- 8-8: The type annotation for the
getDiag
function accurately specifies its parameters and return type, enhancing code readability and maintainability.- 42-42: The type annotation for the
stripChangingData
function accurately specifies its parameter and return type, enhancing code readability and maintainability.- 67-67: The type annotation for the
stripFullStack
function accurately specifies its parameter and return type, enhancing code readability and maintainability.- 103-103: The type annotation for the
runProgram
function accurately specifies its parameters and return type, enhancing code readability and maintainability.index.js (7)
- 4-4: The addition of the
through
import is appropriate for stream operations within this file, aligning with the changes made to introduce stream functionality.- 16-18: The type definitions (
Tape
,Harness
,HarnessConfig
) provide clear and concise information about the types used within this file, enhancing code readability and maintainability.- 25-25: The
getHarness
function is correctly typed and provides a mechanism to lazily initialize the harness, which is a good practice for resource management.- 55-55: The
createStream
function is correctly typed and provides a clear interface for creating a stream, enhancing the library's functionality and usability.- 80-80: The
createHarness
function is well-documented and correctly typed, providing a foundational piece for creating test harnesses. This enhances the library's extensibility and usability.- 142-142: The
createExitHarness
function introduces a mechanism to handle process exit behavior, which is crucial for a testing library. The function is correctly typed and well-documented.- 204-207: The modifications to exports, including the workaround for circular exports, are necessary and correctly implemented to ensure the library's API is correctly exposed and usable.
lib/results.js (11)
- 21-22: The type aliases
Stream
andResult
provide clear and concise information about the types used within this file, enhancing code readability and maintainability.- 24-24: The
coalesceWhiteSpaces
function is correctly typed and provides a utility for string manipulation, which is useful for formatting output.- 29-29: The
getNextTest
function is correctly typed and provides a mechanism for iterating over tests, which is crucial for running tests in sequence.- 45-45: The
invalidYaml
function is correctly typed and provides a utility for YAML validation, which is useful for ensuring test result output is correctly formatted.- 50-50: The
encodeResult
function is correctly typed and provides a mechanism for encoding test results into a TAP-compliant format, enhancing the library's compatibility with TAP consumers.- 102-105: The constructor documentation for
Results
provides clear information about the function's purpose and its parameters, enhancing code readability and maintainability.- 122-122: The
createStream
method is correctly typed and provides a clear interface for creating a stream of test results, enhancing the library's functionality and usability.- 185-185: The
push
method is correctly typed and provides a mechanism for adding tests to the results, which is crucial for managing test execution.- 192-192: The
only
method is correctly typed and provides a mechanism for specifying a single test to run, which is useful for focused testing.- 197-197: The
_watch
method is correctly typed and provides a mechanism for monitoring test execution, which is crucial for managing test results.- 233-233: The
close
method is correctly typed and provides a mechanism for finalizing test results, which is crucial for ensuring test completion and outputting final results.lib/test.d.ts (4)
- 1-3: The imports at the beginning of the file are clear and concise, correctly importing only the types needed for this declaration file.
- 11-172: The
Test
class declaration and its method signatures are well-defined, providing clear type annotations for parameters and return types. This significantly improves the usability and type safety of theTest
class in TypeScript projects. However, there are a couple of minor issues to address:
- Line 9: There's an extra semicolon at the end of the import statement. While this is not a syntax error, it's unnecessary and should be removed for consistency and cleanliness.
- General: Ensure that all callback types (
Test.Callback
) and option types (Options
) are defined and correctly imported or declared within this file or its dependencies. This is crucial for maintaining the integrity and usability of the type declarations.- } from './results';; + } from './results';Please verify that all referenced types (
Test.Callback
,Options
, etc.) are correctly defined and accessible within this context.
- 174-220: The
Test
namespace provides additional type definitions that are essential for the detailed and specific typing of callback functions, call results, and other utility types used within theTest
class. This is a good practice as it encapsulates related types within the namespace of the class they support, enhancing modularity and readability.- 222-222: Exporting the
Test
class usingexport = Test;
is appropriate for this module pattern and ensures compatibility with CommonJS imports. This is a good practice for TypeScript declaration files that correspond to JavaScript modules intended to be used in Node.js environments.lib/test.js (8)
- 15-15: The modification of the
is
module import to useobject-is/polyfill
instead ofobject-is
is a significant change that enhances compatibility across different environments by ensuring a consistent implementation of theObject.is
method. This change is particularly important for environments that may not supportObject.is
natively.- 38-44: The
isErrorConstructor
function and its type definition (IsErrorConstructor
) are well-implemented, providing a robust way to check if a given constructor is one of the standard JavaScript error constructors. This is crucial for error handling and validation within theTest
class methods. However, there's a minor improvement that can be made for readability:
- Consider adding a brief comment explaining the purpose of the
isErrorConstructor
function and why there are two different implementations based on the environment. This will help future maintainers understand the rationale behind this design choice.Consider adding explanatory comments for the
isErrorConstructor
function.
- 54-54: The
getTestArgs
function is correctly annotated with a JSDoc comment, providing type information for its parameters and return type. This enhances code readability and helps TypeScript users understand the expected types, even though this is a JavaScript file. Good practice in maintaining type annotations in comments for JavaScript projects that may be used alongside TypeScript.- 108-128: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [125-141]
The
run
method implementation correctly handles asynchronous test callbacks by supporting both synchronous and Promise-based asynchronous tests. This is a crucial feature for a testing framework, allowing users to write tests that perform asynchronous operations. However, there's a minor improvement that can be made for error handling:
- When handling Promise rejection, consider checking if
err
is an instance of a specific error class (e.g.,AssertionError
) to provide more detailed error messages or handling specific to assertion errors. This can improve the debugging experience for users.Consider enhancing error handling in the Promise rejection case by checking for specific error types.
- 166-170: The
test
method correctly creates and manages child test instances, allowing for nested tests. This is a key feature for a testing framework, enabling complex test structures and hierarchies. The implementation is clear and follows best practices for event-driven programming with Node.js'EventEmitter
. However, ensure that theTest
class and its methods are thoroughly tested, especially with nested tests, to prevent any potential issues with event handling or state management.Consider adding more comprehensive tests for the
test
method, particularly focusing on nested tests and event handling.
- 191-194: The
comment
method implementation is straightforward and correctly emits test result comments as events. This allows for flexible reporting and integration with test runners or other tools. It's a good practice to support comments in testing frameworks, as they can provide valuable context or explanations alongside test results.- 218-218: The
end
method's implementation correctly handles error reporting and ensures that.end()
is called only once per test instance. This is crucial for maintaining the integrity of test results and preventing duplicate or misleading output. However, consider adding more explicit error handling or logging for cases where.end()
is called multiple times, to aid in debugging such issues.Consider enhancing error handling for multiple calls to
.end()
to improve debuggability.
- 231-231: The
teardown
method provides a mechanism for registering teardown functions to be executed after a test completes. This is an essential feature for cleaning up resources or state between tests. The implementation is clear and follows best practices. However, ensure that teardown functions are always called, even if a test fails or times out, to prevent resource leaks or interference between tests.Verify that teardown functions are correctly executed in all scenarios, including test failures and timeouts.
54b4f2d
to
decd5d2
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 1
Configuration used: CodeRabbit UI
Files ignored due to path filters (2)
package.json
is excluded by:!**/*.json
tsconfig.json
is excluded by:!**/*.json
Files selected for processing (12)
- .github/workflows/node-aught.yml (1 hunks)
- bin/import-or-require.js (1 hunks)
- bin/tape (2 hunks)
- index.d.ts (1 hunks)
- index.js (8 hunks)
- lib/default_stream.d.ts (1 hunks)
- lib/default_stream.js (2 hunks)
- lib/results.d.ts (1 hunks)
- lib/results.js (8 hunks)
- lib/test.d.ts (1 hunks)
- lib/test.js (41 hunks)
- test/common.js (4 hunks)
Files skipped from review as they are similar to previous changes (8)
- .github/workflows/node-aught.yml
- bin/import-or-require.js
- bin/tape
- index.d.ts
- lib/default_stream.d.ts
- lib/results.d.ts
- lib/test.d.ts
- lib/test.js
Additional comments: 26
lib/default_stream.js (4)
- 6-6: Adding a type annotation for the module export is a good practice for clarity and type safety. This change enhances the maintainability of the code by making the expected type of the exported function explicit.
- 12-12: The type annotation for the
write
function parameterbuf
asunknown
is appropriate here since the function is designed to handle various types of input. This use ofunknown
encourages type checking within the function, improving code safety.- 21-21: The casting of
buf
tostring | ArrayLike<number>
is necessary given the subsequent operations onb
. However, ensure that this casting aligns with the expected types ofbuf
throughout the application to prevent runtime errors.- 22-25: The loop iterates over
b
, handling both string andArrayLike<number>
types. This approach is flexible but relies on the correct type casting ofbuf
. Consider adding more explicit type checks or documentation to clarify the expected types ofbuf
for future maintainability.test/common.js (5)
- 8-8: Adding type annotations for the
getDiag
function improves code clarity by specifying the expected parameter types and return type. This change enhances maintainability by making the function's contract explicit.- 42-42: The type annotation for the
stripChangingData
function is clear and accurately describes the function's purpose and expected input/output. This addition aids in understanding the function's role in processing test output.- 67-67: The type annotation for the
stripFullStack
function is a good practice, making the function's behavior and return type explicit. This change contributes to the overall maintainability and readability of the test utilities.- 103-103: The type annotation for the
runProgram
function clearly defines the expected parameters and their types, as well as the callback's signature. This explicit typing is beneficial for maintainability and understanding the function's usage.- 5-11: > 📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [111-111]
The concern regarding potential security issues with user input going into
path.join
orpath.resolve
functions is noted. However, as this is a test file and the inputs are controlled within the test environment, the risk is minimal. It's important to remain vigilant about such patterns in production code.index.js (7)
- 16-18: The addition of type declarations for
Tape
,Harness
, andHarnessConfig
is a significant improvement for type safety and code clarity. These declarations help developers understand the expected types and interfaces within the library.- 25-25: The
getHarness
function's type annotation enhances the function's readability by making the optional parameter and return type explicit. This change is beneficial for maintainability and type safety.- 35-35: The type annotation for the
lazyLoad
function and its usage ofParameters<Tape>
andReturnType<Tape>
is a clever way to ensure type consistency with theTape
interface. This approach maintains type safety across the library.- 55-55: The type annotation for the
createStream
function withinlazyLoad
is clear and accurately describes the expected parameter and return type. This explicit typing aids in understanding the function's purpose and usage.- 80-80: The
createHarness
function's documentation and type annotations provide a clear understanding of its purpose and usage. This explicit typing and documentation are beneficial for maintainability and clarity.- 142-142: The
createExitHarness
function's type annotation and detailed implementation comments enhance the understanding of its purpose and behavior. This explicit typing and documentation contribute to the code's maintainability and clarity.- 204-207: The workaround for resolving circular exports by assigning
module.exports
to a variable and then modifying that variable is a practical solution to a common issue in JavaScript modules. However, ensure that this pattern is consistently understood and documented across the codebase to avoid confusion.lib/results.js (10)
- 21-22: The introduction of type aliases
Stream
andResult
is a significant improvement, enhancing code readability and maintainability by providing clear, reusable type definitions.- 24-24: The
coalesceWhiteSpaces
function's type annotation is straightforward and accurately describes the function's behavior. This explicit typing is beneficial for understanding the function's purpose.- 29-29: The type annotation for the
getNextTest
function clearly defines the expected parameter and return type, improving the function's readability and maintainability.- 45-45: The
invalidYaml
function's type annotation is clear and accurately describes the function's expected input and output. This explicit typing aids in understanding the function's role in YAML validation.- 50-50: The
encodeResult
function's type annotation and detailed implementation enhance the understanding of its purpose and behavior. This explicit typing and documentation contribute to the code's maintainability and clarity.- 102-105: The constructor documentation for
Results
and the addition of type annotations for its parameters improve the class's readability and maintainability. This explicit typing and documentation are beneficial for understanding the class's purpose and usage.- 122-122: The type annotation for the
createStream
method in theResults
class clearly defines the expected parameter and return type, enhancing the method's readability and maintainability.- 185-185: The
push
method's type annotation in theResults
class is straightforward and accurately describes the method's behavior. This explicit typing is beneficial for understanding the method's purpose.- 192-192: The
only
method's type annotation in theResults
class is clear and accurately describes the method's expected input. This explicit typing aids in understanding the method's role in test execution.- 233-233: The
close
method's type annotation in theResults
class enhances the method's readability by making the expected behavior explicit. This change contributes to the overall maintainability and clarity of the class.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Cool to see this addition - thanks for mentioning it!
I can take a deeper look if the tsc
having a lot of errors already thing isn't a blocker.
Thanks, I've updated the PR and gotten it down to 4 errors (i swear it was at zero when I put up the PR :-p) I'd love to get suggestions for those. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 0
Configuration used: CodeRabbit UI
Files ignored due to path filters (2)
package.json
is excluded by:!**/*.json
tsconfig.json
is excluded by:!**/*.json
Files selected for processing (12)
- .github/workflows/node-aught.yml (1 hunks)
- bin/import-or-require.js (1 hunks)
- bin/tape (2 hunks)
- index.d.ts (1 hunks)
- index.js (8 hunks)
- lib/default_stream.d.ts (1 hunks)
- lib/default_stream.js (2 hunks)
- lib/results.d.ts (1 hunks)
- lib/results.js (8 hunks)
- lib/test.d.ts (1 hunks)
- lib/test.js (41 hunks)
- test/common.js (4 hunks)
Files skipped from review as they are similar to previous changes (9)
- .github/workflows/node-aught.yml
- bin/import-or-require.js
- bin/tape
- index.d.ts
- lib/default_stream.d.ts
- lib/results.d.ts
- lib/results.js
- lib/test.d.ts
- lib/test.js
Additional comments: 21
lib/default_stream.js (4)
- 6-6: The type annotation for the module export is correctly specified, enhancing type safety and clarity for consumers of this module.
- 18-28: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [12-25]
The
write
function's type annotation forbuf
asunknown
is appropriate, given the function's intent to handle various types of input. The explicit handling of different buffer types, including nullish values and strings, is well-implemented. However, consider adding a comment explaining the rationale behind treatingObject(buf) !== buf
as a condition to flush the buffer, as it might not be immediately clear to future maintainers.
- 21-21: Using a type assertion for
b
as eitherstring
orArrayLike<number>
is a pragmatic approach to handle the two expected types of buffers. This assertion allows for type-safe operations within the loop that follows. Good use of type annotations to ensure type safety.- 3-15: > 📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [47-47]
The use of
innerHTML
for appending content, especially in a library context, can lead to XSS vulnerabilities. This concern was previously raised, and the justification was that it's for IE < 9 compatibility. While the explanation is valid, it's crucial to document this exception clearly in the code to inform future maintainers of the security implications and the specific use case. It appears that a comment regarding the use ofinnerHTML
for IE < 9 compatibility is indeed present, albeit in a concise form. It's good practice to ensure such exceptions are well-documented.test/common.js (5)
- 8-8: The type annotation for
getDiag
function is correctly specified, clearly indicating the function's parameters and return type. This enhances the readability and maintainability of the code.- 42-42: The type annotation for
stripChangingData
function is correctly specified. This function's purpose is well-documented through its type annotation, improving code clarity.- 67-67: The type annotation for
stripFullStack
function is correctly specified, clearly indicating the function's parameter and return type. This addition aids in understanding the function's usage and expected behavior.- 103-103: The type annotation for
runProgram
function is correctly specified, providing clear information about the function's parameters and return type. This enhances the function's readability and maintainability.- 5-11: > 📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [111-111]
The concern regarding potential security issues with user input going into a
path.join
orpath.resolve
function, which could lead to a path traversal vulnerability, has been addressed. It's noted that this is a test file, and there is no security concern here. It's good practice to be vigilant about potential security vulnerabilities, even in test environments, but in this case, the concern is not applicable.index.js (12)
- 4-4: The addition of the
through
module import is correctly implemented. This import is necessary for the functionality introduced in this file.- 16-22: The type definitions added for
Tape
,Harness
,HarnessConfig
,TestOptions
,HarnessEventHandler
,CreateStream
, andResult
are correctly specified. These definitions enhance the code's readability and maintainability by providing clear type information.- 29-29: The
getHarness
function is correctly annotated with its return type. The comment about the override due to test failures via nyc is helpful for future maintainers to understand the rationale behind the current implementation.- 39-39: The
lazyLoad
function's type annotation is correctly specified, enhancing the function's clarity by indicating the expected parameters and return type.- 59-59: The
createStream
function's type annotation is correctly specified, providing clear information about the function's parameters and return type. This addition aids in understanding the function's usage and expected behavior.- 84-84: The
createHarness
function's type annotation is correctly specified, enhancing the function's clarity by indicating the expected parameters and return type.- 91-91: The
test
function's type annotation is correctly specified, providing clear information about the function's parameters and return type. This enhances the function's readability and maintainability.- 112-112: The
createStream
method within thetest
function is correctly annotated, enhancing clarity and maintainability by providing type information for the parameters and return type.- 117-117: The
onFinish
method within thetest
function is correctly annotated, providing clear type information that enhances the code's readability and maintainability.- 122-122: The
onFailure
method within thetest
function is correctly annotated, enhancing the code's clarity by providing type information for the parameters and return type.- 146-146: The
createExitHarness
function's type annotation is correctly specified, providing clear information about the function's parameters and return type. This enhances the function's readability and maintainability.- 208-211: The modifications to the module exports to resolve a circular export issue are correctly implemented. This hack is necessary due to TypeScript's limitations with circular exports, and it's good practice to document such workarounds for future maintainers.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 6
Configuration used: CodeRabbit UI
Files ignored due to path filters (2)
package.json
is excluded by:!**/*.json
tsconfig.json
is excluded by:!**/*.json
Files selected for processing (12)
- .github/workflows/node-aught.yml (1 hunks)
- bin/import-or-require.js (1 hunks)
- bin/tape (2 hunks)
- index.d.ts (1 hunks)
- index.js (8 hunks)
- lib/default_stream.d.ts (1 hunks)
- lib/default_stream.js (2 hunks)
- lib/results.d.ts (1 hunks)
- lib/results.js (9 hunks)
- lib/test.d.ts (1 hunks)
- lib/test.js (41 hunks)
- test/common.js (4 hunks)
Files skipped from review as they are similar to previous changes (9)
- .github/workflows/node-aught.yml
- bin/import-or-require.js
- bin/tape
- index.d.ts
- lib/default_stream.d.ts
- lib/results.d.ts
- lib/results.js
- lib/test.d.ts
- lib/test.js
Additional comments: 3
lib/default_stream.js (2)
- 6-6: The addition of a type annotation for the module export is a good practice for clarity and type safety.
- 12-12: The type annotation for the
write
function parameterbuf
asunknown
is appropriate, considering the function's logic to handle various types of input. This ensures type safety while allowing flexibility in the input types.test/common.js (1)
- 8-10: The addition of type definitions via
@typedef
for external modules enhances the clarity and maintainability of the code by providing explicit type information. This is a good practice for projects that aim to improve type safety and documentation.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 4
Configuration used: CodeRabbit UI
Files ignored due to path filters (2)
package.json
is excluded by:!**/*.json
tsconfig.json
is excluded by:!**/*.json
Files selected for processing (12)
- .github/workflows/node-aught.yml (1 hunks)
- bin/import-or-require.js (1 hunks)
- bin/tape (2 hunks)
- index.d.ts (1 hunks)
- index.js (8 hunks)
- lib/default_stream.d.ts (1 hunks)
- lib/default_stream.js (2 hunks)
- lib/results.d.ts (1 hunks)
- lib/results.js (9 hunks)
- lib/test.d.ts (1 hunks)
- lib/test.js (41 hunks)
- test/common.js (4 hunks)
Files skipped from review as they are similar to previous changes (9)
- .github/workflows/node-aught.yml
- bin/import-or-require.js
- bin/tape
- index.d.ts
- lib/default_stream.d.ts
- lib/results.d.ts
- lib/results.js
- lib/test.d.ts
- lib/test.js
Additional comments: 3
lib/default_stream.js (1)
- 6-6: The addition of type annotations enhances code clarity and TypeScript compatibility.
test/common.js (1)
- 11-11: The addition of type annotations for
getDiag
enhances code clarity and TypeScript compatibility.index.js (1)
- 16-26: The addition of type definitions for various entities enhances code clarity and TypeScript compatibility.
flush(); | ||
return; | ||
} | ||
for (var i = 0; i < buf.length; i++) { | ||
var c = typeof buf === 'string' | ||
? buf.charAt(i) | ||
: String.fromCharCode(buf[i]); | ||
var b = /** @type {string | ArrayLike<number>} */ (buf); // eslint-disable-line no-extra-parens | ||
for (var i = 0; i < b.length; i++) { | ||
var c = typeof b === 'string' | ||
? b.charAt(i) | ||
: String.fromCharCode(b[i]); | ||
if (c === '\n') { | ||
flush(); | ||
} else { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [12-25]
The casting of buf
to string | ArrayLike<number>
is sensible given the function's need to support both string and buffer inputs. However, ensure that this casting is safe by validating the input type before casting, as incorrect assumptions about the type can lead to runtime errors.
Consider adding explicit type checks before casting to ensure safety.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 2
Configuration used: CodeRabbit UI
Files ignored due to path filters (2)
package.json
is excluded by:!**/*.json
tsconfig.json
is excluded by:!**/*.json
Files selected for processing (12)
- .github/workflows/node-aught.yml (1 hunks)
- bin/import-or-require.js (1 hunks)
- bin/tape (2 hunks)
- index.d.ts (1 hunks)
- index.js (8 hunks)
- lib/default_stream.d.ts (1 hunks)
- lib/default_stream.js (2 hunks)
- lib/results.d.ts (1 hunks)
- lib/results.js (9 hunks)
- lib/test.d.ts (1 hunks)
- lib/test.js (41 hunks)
- test/common.js (4 hunks)
Additional comments: 47
lib/default_stream.d.ts (1)
- 1-5: The TypeScript definition for
defaultStream
is correctly implemented with appropriate use of type imports, declaration, and export syntax..github/workflows/node-aught.yml (1)
- 12-12: The addition of
skip-ls-check: true
to the workflow configuration is syntactically correct. Please ensure that skipping the ls check aligns with the project's CI/CD goals.bin/import-or-require.js (1)
- 7-7: The concise JSDoc type annotation for
importOrRequire
is appropriate and correctly specifies the parameter and return types. The decision to use a less verbose annotation style aligns with previous discussions and preferences.lib/default_stream.js (2)
- 6-6: The type declaration for the module is correctly implemented, enhancing the code's readability and maintainability.
- 18-28: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [12-25]
The type annotations and logic within the
write
function are correctly implemented. The handling of different types forbuf
and the subsequent processing are sound.lib/results.d.ts (1)
- 1-52: The TypeScript definitions in
lib/results.d.ts
are correctly implemented, with well-defined class properties, methods, and additional type definitions within the namespace. The use of imports,declare
, andexport
syntax aligns with TypeScript best practices.index.d.ts (1)
- 1-82: The comprehensive type definitions in
index.d.ts
enhance the library's usability and clarity. The structure and organization of types, interfaces, and function overloads align well with TypeScript best practices. The approach respects the project's preferences regarding documentation and code separation.bin/tape (2)
- 98-98: The type annotation for the
importFiles
function is correctly implemented, enhancing the clarity of the function's purpose and expected parameter type.- 108-108: The type annotation for the
filesPromise
variable is correctly implemented, clarifying the expected type and enhancing code maintainability.test/common.js (5)
- 8-9: The addition of typedefs for
Result
andSyncCallback
enhances the clarity and maintainability of the test utilities by providing clear type definitions.- 11-11: The type annotation for the
getDiag
function is correctly implemented, providing clear documentation on the expected parameter types and return type.- 45-45: The type annotation for the
stripChangingData
function is correctly implemented, enhancing the readability and maintainability of the function.- 70-70: The type annotation for the
stripFullStack
function is correctly implemented, providing clear documentation on the expected parameter type and return type.- 106-106: The type annotation for the
runProgram
function is correctly implemented, enhancing the clarity of the function's purpose and expected parameter types.index.js (6)
- 11-12: The use of
/** @type {{ browser?: boolean }} */
for type casting in the condition to check ifprocess
is not running in a browser environment is a clever way to provide type information for TypeScript without changing the runtime behavior. However, ensure that this casting accurately reflects the expected properties of theprocess
object in all execution environments where this code might run.- 16-26: The addition of JSDoc type definitions (
@typedef
) enhances the readability and maintainability of the code by providing clear type information for various entities used throughout the file. This is a good practice, especially in a dynamically typed language like JavaScript, as it aids in understanding the expected types of variables and function parameters/returns.- 1-36: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [33-43]
The
getHarness
function correctly checks if a harness has already been created and, if not, creates one usingcreateExitHarness
. This lazy initialization pattern is efficient. However, consider adding error handling or logging within this function to catch and report potential issues during the harness creation process, especially sincecreateExitHarness
involves complex logic.
- 63-63: The
createStream
method inlazyLoad
is well-annotated with types, which improves code clarity. However, ensure that the fallback logic for whenharness
is not yet initialized (creating a new stream and getting the harness with specific options) is thoroughly tested, especially in concurrent scenarios where multiple streams might be created before the harness is initialized.- 87-87: The
createHarness
function is well-structured and makes good use of theResults
class to manage test results. The handling of thetodoIsOK
environment variable and the autoclose behavior based on configuration are clear examples of thoughtful design. However, consider documenting the rationale behind the decision to automatically close results in most cases but allow for disabling this behavior through configuration.- 211-214: The workaround for TypeScript's bug with circular exports is cleverly documented with a comment. This kind of documentation is crucial for maintainability and understanding the rationale behind certain code patterns that might otherwise seem unusual. Good job on ensuring this hack is well-explained.
lib/results.js (7)
- 28-28: The
coalesceWhiteSpaces
function is a simple utility that replaces multiple whitespace characters with a single space. This is useful for normalizing strings before output. Consider adding a brief comment explaining the purpose of this function, as utility functions can sometimes be unclear to new contributors or when revisiting the code after some time.- 33-33: The
getNextTest
function provides a mechanism to retrieve the next test to run, considering the_only
property for focused testing. This logic is crucial for test runners that support.only
syntax. Ensure that the handling of the_only
property is thoroughly tested, especially in scenarios with nested tests or multiple.only
calls across different test suites.- 49-49: The
invalidYaml
function checks if a string contains characters that could be interpreted as YAML indicators. This is an important check for generating accurate TAP output. However, the nameinvalidYaml
might be slightly misleading as it checks for the presence of YAML indicators rather than validating YAML syntax. Consider renaming it to more accurately reflect its purpose, such ascontainsYamlIndicators
.- 54-54: The
encodeResult
function has been modified to handleactualStack
differently. This change is crucial for providing more detailed error information in test results. Ensure that this modification is compatible with all expected input types forres.actual
andres.error
, and consider adding tests specifically for this logic to verify its behavior across different error scenarios.- 106-106: The
Results
constructor now accepts anoptions
parameter, which is used to configure thetodoIsOK
property. This enhancement allows for more flexible configuration of test result handling. Ensure that the handling of theoptions
parameter is thoroughly tested, especially with regards to default values and edge cases whereoptions
might be malformed or contain unexpected properties.- 126-126: The
createStream
method inResults.prototype
has been enhanced to support both object mode and TAP output. This dual-mode functionality is a significant improvement for test result reporting. However, ensure that the transition between these modes is seamless and well-documented, especially for consumers of theResults
class who may need to understand how to configure and interpret the output correctly.- 190-190: The
push
method inResults.prototype
is straightforward in adding a test to the internal tests array and emitting an_push
event. This method is crucial for managing the queue of tests to run. Ensure that the interaction betweenpush
and other parts of theResults
class, such asgetNextTest
, is well-understood and tested, particularly in scenarios with dynamic test addition or removal.lib/test.d.ts (5)
- 1-1: The inclusion of
EventEmitter
andmockProperty
types at the beginning of the file sets a clear foundation for theTest
class and related functionalities. This is a good practice as it ensures that all necessary types are available and correctly referenced throughout the file.- 13-13: The
Test
class declaration is comprehensive, covering various constructor signatures and properties. This thorough approach ensures that TypeScript can accurately type-check usage of theTest
class in different contexts. However, ensure that all properties and methods of theTest
class are covered, especially those that might be dynamically added or are part of the class's public API but not explicitly declared here.- 41-41: The method
captureFn
and other utility methods likecapture
,end
, etc., are well-typed, providing clear signatures for their usage. This level of detail is crucial for developers to understand how to interact with theTest
class and its utilities. Ensure that the documentation or external resources are available to explain the purpose and usage of these utility methods, as their names alone may not be self-explanatory.- 58-58: The assertion methods (
ok
,notOK
,error
, etc.) are correctly typed, reflecting their usage in theTest
class. This ensures that developers can rely on TypeScript for type checking when writing tests. Consider adding brief comments to these methods to explain their expected usage and any nuances in their behavior, especially for less commonly used assertions.- 185-185: The
Test
namespace declaration provides additional types and interfaces that are essential for advanced usage of theTest
class, such asSyncCallback
,Callback
, and various types related to method wrapping and interception. This is a good practice as it organizes related types and makes them easily accessible. Ensure that these types are used consistently throughout the project's TypeScript codebase to maintain type safety and clarity.lib/test.js (15)
- 38-44: The JSDoc type annotations added for various typedefs are a good practice for improving code clarity and maintainability. However, ensure that these typedefs accurately reflect the types used throughout the codebase and that they are consistent with the project's existing documentation and type definitions.
- 81-98: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [84-124]
The constructor for the
Test
class is well-documented with JSDoc comments, enhancing readability and maintainability. However, the dynamic binding of methods within the constructor usingcallBind
is noted. Given the project's constraints (ES3 syntax and no TypeScript), this approach is suitable. To further improve clarity, consider adding a comment explaining why this dynamic binding approach is used, adhering to the guideline that comments should describe "why" or the history/motivation behind code decisions.
- 145-152: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [132-149]
The
run
method's implementation to handle promises returned by the callback is a modern approach to asynchronous testing. However, ensure that this pattern is compatible with the environments where thetape
library is expected to run, considering the project's adherence to ES3 syntax.
- 173-177: Creating a new
Test
instance within thetest
method and casting it toTestType
is a clear way to manage test hierarchy. This approach allows for nested tests, contributing to the modularity and flexibility of the testing framework. Ensure that theTestType
accurately represents theTest
class's interface and capabilities.- 198-201: The
comment
method's implementation to emit each line of a multi-line comment as a separate result is a thoughtful detail that enhances the readability of test output. This approach ensures that comments are clearly visible in the test results, aiding in test result interpretation.- 195-215: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [212-225]
The
timeoutAfter
method correctly implements a timeout mechanism for tests, which is crucial for identifying tests that may hang or take too long to complete. The use ofsafeSetTimeout
andsafeClearTimeout
is a good practice to ensure that the timeout functionality is reliable and does not interfere with other timers.
- 235-241: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [238-247]
The
teardown
method provides a mechanism for cleaning up after tests, which is essential for maintaining a clean test environment and avoiding side effects between tests. This method enhances the framework's flexibility and usability by allowing test-specific teardown logic.
- 289-297: The
capture
method's implementation to intercept and replace a method on an object with a wrapped function is a powerful feature for testing. It allows for detailed inspection of method calls, including arguments and return values. Ensure that this functionality is well-documented and that examples are provided to help users understand how to use it effectively.- 323-331: The
intercept
method introduces a way to intercept property access and modification, which can be invaluable for testing code that interacts with objects in complex ways. This method's flexibility, including support for both data properties and accessor properties, enhances the testing framework's capabilities. Ensure that the documentation clearly explains the method's usage and the scenarios where it can be particularly useful.- 458-476: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [428-469]
The
_end
method's implementation to handle the end of a test, including running teardown functions and emitting theend
event, is crucial for the correct functioning of the testing framework. The handling of asynchronous teardown functions with promises is a modern approach that increases the method's utility. However, ensure that this approach is consistent with the project's overall adherence to ES3 syntax and environments.Verification successful
The project consistently uses ES6+ features, including
Promise
andasync/await
, across various parts of its codebase, including both test files and some core library files. Therefore, the implementation of asynchronous teardown functions using promises in the_end
method aligns with the project's use of modern JavaScript features.* 482-488: > 📝 **NOTE** > This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [485-501]Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for usage of ES6+ features like Promise in other parts of the project to ensure consistency. rg --type js "Promise"Length of output: 3134
The
_exit
method's implementation to check for discrepancies between the planned number of assertions and the actual number of assertions at the end of a test is an important feature for ensuring test integrity. This method helps identify cases where tests may not be executing as expected, contributing to the robustness of the testing framework.
- 519-525: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [509-644]
The
_assert
method is central to the testing framework, providing the mechanism for making assertions within tests. The detailed handling of assertion results, including capturing stack traces and handling errors, enhances the utility and usability of the framework. Ensure that the stack trace processing logic is robust and tested across different environments to provide consistent and helpful error reporting.
- 876-896: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [886-908]
The
throws
method's implementation to test if a function throws an error as expected is a key feature of the testing framework. The detailed handling of different types of expected errors, including support for validation objects, increases the method's flexibility. Ensure that the documentation clearly explains how to use this method effectively, including examples for different types of expected errors.
- 956-962: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [959-981]
The
doesNotThrow
method complements thethrows
method by testing that a function does not throw an error. This method is important for testing the normal operation of code that should not produce errors under certain conditions. Ensure that the implementation is consistent with the framework's error handling and reporting practices.
- 1012-1018: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1015-1049]
The
match
anddoesNotMatch
methods provide a way to test if a string matches or does not match a regular expression. These methods enhance the framework's capabilities for testing string processing and pattern matching in code. Ensure that the error messages produced by these methods are clear and helpful for diagnosing test failures.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 2
Configuration used: CodeRabbit UI
Files ignored due to path filters (2)
package.json
is excluded by:!**/*.json
tsconfig.json
is excluded by:!**/*.json
Files selected for processing (12)
- .github/workflows/node-aught.yml (1 hunks)
- bin/import-or-require.js (1 hunks)
- bin/tape (2 hunks)
- index.d.ts (1 hunks)
- index.js (8 hunks)
- lib/default_stream.d.ts (1 hunks)
- lib/default_stream.js (2 hunks)
- lib/results.d.ts (1 hunks)
- lib/results.js (9 hunks)
- lib/test.d.ts (1 hunks)
- lib/test.js (41 hunks)
- test/common.js (4 hunks)
Files skipped from review as they are similar to previous changes (11)
- .github/workflows/node-aught.yml
- bin/import-or-require.js
- bin/tape
- index.d.ts
- index.js
- lib/default_stream.d.ts
- lib/default_stream.js
- lib/results.d.ts
- lib/test.d.ts
- lib/test.js
- test/common.js
Additional comments: 9
lib/results.js (9)
- 21-27: The addition of type definitions (
Stream
,Result
,Test
,ResultsType
,StreamOptions
,WritableStream
) is a positive step towards improving code clarity and maintainability. These definitions will help developers understand the expected types of variables and function parameters/returns more clearly.- 18-36: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [33-48]
The
getNextTest
function is well-implemented and serves a clear purpose within the context of managing test execution. The use ofvoid undefined
is appropriate here to explicitly returnundefined
. Good job on typing and implementing this function.
- 49-53: The
invalidYaml
function is a concise utility for detecting YAML-indicative characters. It's correctly implemented and typed. This function enhances the robustness of YAML-related operations by pre-validating strings.- 46-57: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [54-89]
The
encodeResult
function has been modified to handleactualStack
differently. This change improves error reporting by distinguishing between the stack of anactual
value and an error's stack. Ensure that this differentiation is clearly documented in the function's comments to aid future maintainability.+ // Encodes a test result into a TAP-formatted string, handling actualStack and errorStack separately. function encodeResult(res, count, todoIsOK) {
- 103-112: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [106-125]
The
Results
constructor is well-defined, with clear options handling and initialization of properties. It's a good practice to document the expected properties of theoptions
parameter for better code readability and maintainability./** * @constructor * @param {{ todoIsOK?: boolean }} [options] - Options for Results instance. */ function Results(options) {
- 123-156: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [126-187]
The
createStream
method added toResults.prototype
is comprehensive and well-implemented, covering both object mode and non-object mode streams. Ensure thorough testing, especially around the dynamic handling of tests and results in both modes, to prevent any potential issues with stream management.
- 190-196: The
push
method is a straightforward addition toResults.prototype
, correctly managing test addition. It's well-implemented and typed.- 187-208: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [202-237]
The
_watch
method is a key addition for monitoring test execution and formatting results. It's well-implemented, with clear handling of different test states. Consider adding more detailed comments explaining the logic, especially for the handling ofskip
andtodo
states, to improve readability.+ // Watches a test's lifecycle events to format and output results. Results.prototype._watch = function (t) {
- 232-247: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [238-259]
The
close
method correctly finalizes the test results and ensures the stream is properly closed. It's important to handle theALREADY CLOSED
error state as it does, preventing multiple close attempts. This method is well-implemented and typed.
Oop, sorry for taking so long - I'd added this tab on my phone and forgot about it 😅. Looking now!
On the latest commit I get no errors. So, nicely done! 😄 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks great!
Left some suggestions, but nothing showing anything wrong. Nicely done! 👏
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You might consider also porting in the types tests from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e1386bb7838c35504edfdb12876bf0d156d84a2a/types/tap/tap-tests.ts. Since the .d.ts
is being hand-written rather than auto-generated from source files, it wouldn't be unheard of for it to fall out of sync.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if it were out of sync, wouldn't tsc
fail?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not in all cases. If you, say, added an extra optional parameter somewhere but never used it, tsc
wouldn't think to fail on it.
Test.prototype['throws'] = function (fn, expected, msg, extra) { | ||
if (typeof expected === 'string') { | ||
msg = expected; | ||
expected = undefined; | ||
} | ||
|
||
/** @type {undefined | { error: unknown | Error }} */ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
error: unknown | Error
is equivalent to error: unknown
. unknown
is a top type indicating it could be anything in the world, including Error
. plugin:@typescript-eslint/no-redundant-type-constituents
The code later on just checks if (caught.error && typeof caught.error === 'object')
, not instanceof Error
or an equivalent. So if a caught.error
is a non-Error
object, the assumption it could be an Error
would be wrong.
Can caught.error
be something other than Error
? If so, what?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
technically line 897 doesn't ensure it's an Error, but if that branch is entered, then it's so Error-like as to not make a difference. there doesn't seem to be any way i can do a type assertion without runtime code :-/
// TS TODO: `caught.error` and `expected` should both be `object` here | ||
passed = every(keys, /** @type {(key: PropertyKey) => boolean} */ function (key) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unfortunately, TypeScript doesn't have a way of being informed that every
's callbacks should keep narrowing. A type assertion would be the appropriate thing to do here instead of // @ts-expect-error
to avoid changing runtime code.
A small runtime change could be to store error
and expected
as variables after narrowing them.
Alternately, the next version of TypeScript might be nicer about preserving narrowings - I haven't tried.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i'm using next
, so it doesn't help me here. this isn't TS-expect-error tho; it's just a TODO comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I meant the // @ts-expect-error
s later.
c16dde3
to
2ad86d4
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
Outside diff range and nitpick comments (1)
lib/test.js (1)
Line range hint
83-128
:
Well-annotatedTest
class constructor.The type annotations improve readability and maintainability. The dynamic method binding approach is appropriate given the project's constraints.
Consider adding a comment explaining the rationale behind the dynamic method binding to help future maintainers.
Do you want me to add a comment explaining the rationale behind this choice?
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files ignored due to path filters (2)
package.json
is excluded by!**/*.json
tsconfig.json
is excluded by!**/*.json
Files selected for processing (12)
- .github/workflows/node-aught.yml (1 hunks)
- bin/import-or-require.js (1 hunks)
- bin/tape (2 hunks)
- index.d.ts (1 hunks)
- index.js (8 hunks)
- lib/default_stream.d.ts (1 hunks)
- lib/default_stream.js (2 hunks)
- lib/results.d.ts (1 hunks)
- lib/results.js (9 hunks)
- lib/test.d.ts (1 hunks)
- lib/test.js (41 hunks)
- test/common.js (4 hunks)
Files skipped from review due to trivial changes (3)
- .github/workflows/node-aught.yml
- bin/import-or-require.js
- lib/default_stream.d.ts
Additional context used
Learnings (3)
test/common.js (1)
Learnt from: ljharb PR: tape-testing/tape#603 File: test/common.js:106-106 Timestamp: 2024-03-12T04:16:16.696Z Learning: Code within the `test/` directory is considered test code and is not subject to the same security concerns as production code, as it does not handle user input.
index.js (1)
Learnt from: ljharb PR: tape-testing/tape#603 File: index.js:147-147 Timestamp: 2024-03-12T04:35:01.528Z Learning: Comments in the codebase should focus on explaining "why" or providing history/motivation, rather than detailing "what" the code does, as per ljharb's guidance.
lib/results.js (2)
Learnt from: ljharb PR: tape-testing/tape#603 File: lib/results.js:197-201 Timestamp: 2024-03-22T05:25:05.727Z Learning: For the `tape` project, code comments should explain "why" or history/motivation, but never "what". Documentation belongs outside of source files.
Learnt from: ljharb PR: tape-testing/tape#603 File: index.js:147-147 Timestamp: 2024-03-12T04:35:01.528Z Learning: Comments in the codebase should focus on explaining "why" or providing history/motivation, rather than detailing "what" the code does, as per ljharb's guidance.
Biome
lib/default_stream.js
[error] 22-22: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 23-25: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
index.js
[error] 1-1: Redundant use strict directive.
The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.(lint/suspicious/noRedundantUseStrict)
[error] 134-134: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
lib/results.js
[error] 92-92: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
lib/test.d.ts
[error] 116-116: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 130-130: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 196-196: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
[error] 202-202: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
lib/test.js
[error] 150-150: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 264-267: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 363-363: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 365-369: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 388-388: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 391-391: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 900-900: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
Additional comments not posted (42)
lib/default_stream.js (2)
6-6
: Type annotation for module export looks good.The type annotation correctly specifies the import type.
12-12
: Type annotation forwrite
function parameter looks good.The type annotation correctly specifies the parameter type.
lib/results.d.ts (4)
1-2
: Type imports look good.The type imports correctly specify the required types.
4-6
: Type imports look good.The type imports correctly specify the required types.
7-28
: Type declarations forResults
class look good.The type declarations correctly specify the class properties and methods.
30-50
: Type declarations forResults
namespace look good.The type declarations correctly specify the namespace types.
index.d.ts (4)
1-2
: Type import forThroughStream
looks good.The type import correctly specifies the required type.
3-4
: Type imports forTest
andResults
look good.The type imports correctly specify the required types.
6-13
: Type declarations forharnessFunction
look good.The type declarations correctly specify the function overloads.
14-82
: Type declarations for interfaces, functions, and namespaces look good.The type declarations correctly specify the required types and interfaces.
bin/tape (2)
98-98
: Type annotation forimportFiles
function looks good.The type annotation correctly specifies the function's return type.
108-108
: Type annotation forfilesPromise
variable looks good.The type annotation correctly specifies the variable's type.
test/common.js (6)
8-9
: Type annotations are correct.The type annotations for
Result
andSyncCallback
are correctly added and provide clarity.
Line range hint
11-24
: FunctiongetDiag
implementation is correct.The function correctly extracts and processes YAML diagnostic information from a string.
Line range hint
45-68
: FunctionstripChangingData
implementation is correct.The function correctly normalizes stack trace data for consistency.
Line range hint
70-85
: FunctionstripFullStack
implementation is correct.The function correctly processes stack traces to remove unnecessary information.
Line range hint
115-132
: FunctionrunProgram
implementation is correct.The function correctly runs a specified program and captures its output.
Line range hint
134-141
: FunctionstripDeprecations
implementation is correct.The function correctly removes deprecation warnings from a message string.
index.js (5)
16-26
: Type annotations are correct.The type annotations for various types such as
Tape
,Harness
,HarnessConfig
, etc., are correctly added and provide clarity.
Line range hint
33-41
: FunctiongetHarness
implementation is correct.The function correctly retrieves or creates a test harness.
Tools
Biome
[error] 1-1: Redundant use strict directive.
The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.(lint/suspicious/noRedundantUseStrict)
Line range hint
43-86
: FunctionlazyLoad
implementation is correct.The function correctly lazily loads the test harness and provides various utility methods.
Line range hint
87-147
: FunctioncreateHarness
implementation is correct.The function correctly creates a test harness and sets up result handling.
Tools
Biome
[error] 134-134: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
Line range hint
148-209
: FunctioncreateExitHarness
implementation is correct.The function correctly creates a test harness that handles exit conditions.
lib/results.js (6)
21-26
: Type annotations are correct.The type annotations for
Stream
,Result
,Test
,ResultsType
,StreamOptions
, andWritableStream
are correctly added and provide clarity.
28-32
: FunctioncoalesceWhiteSpaces
implementation is correct.The function correctly normalizes whitespace in strings.
Line range hint
33-48
: FunctiongetNextTest
implementation is correct.The function correctly retrieves the next test to be run.
49-53
: FunctioninvalidYaml
implementation is correct.The function correctly checks if a string contains YAML indicators.
Line range hint
54-105
: FunctionencodeResult
implementation is correct.The function correctly encodes a test result into a string.
Tools
Biome
[error] 92-92: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
Line range hint
106-253
: ClassResults
and its methods implementation is correct.The class and its methods are correctly typed and implemented, providing the necessary functionalities.
lib/test.d.ts (4)
1-12
: Type annotations for imports are correct.The type annotations for various imports such as
EventEmitter
,mockProperty
, etc., are correctly added and provide clarity.
22-39
: Type annotations forTest
class properties are correct.The type annotations for the properties of the
Test
class are correctly added and provide clarity.
41-187
: Type annotations forTest
class methods are correct.The type annotations for the methods of the
Test
class are correctly added and provide clarity.Tools
Biome
[error] 116-116: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 130-130: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
190-236
: Type annotations forTest
namespace are correct.The type annotations for the
Test
namespace are correctly added and provide clarity.Tools
Biome
[error] 196-196: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
[error] 202-202: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
lib/test.js (9)
38-45
: Good use of JSDoc typedefs.These typedefs enhance type safety and documentation.
47-50
: Appropriate type annotation forisErrorConstructor
.The type annotation improves clarity and the function handles different environments correctly.
60-61
: Clear type annotation forgetTestArgs
.The type annotation enhances documentation and ensures the return type is clear.
131-134
: Clear type annotation forrun
method.The type annotations improve documentation and ensure the types of parameters and return values are clear.
147-148
: Appropriate type annotation forcallbackReturn
.The type annotation ensures clarity in understanding the flow of the method.
172-176
: Clear type annotation fortest
method.The type annotations improve documentation and ensure the types of parameters and return values are clear.
197-200
: Clear type annotation forcomment
method.The type annotations improve documentation and ensure the types of parameters and return values are clear.
246-260
: Clear type annotation forwrapFunction
.The type annotation enhances documentation and ensures the types of parameters and return values are clear.
298-298
: Appropriate type annotation forimplementation
variable.The type annotation ensures clarity in understanding the flow of the method.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files ignored due to path filters (2)
package.json
is excluded by!**/*.json
tsconfig.json
is excluded by!**/*.json
Files selected for processing (12)
- .github/workflows/node-aught.yml (1 hunks)
- bin/import-or-require.js (1 hunks)
- bin/tape (2 hunks)
- index.d.ts (1 hunks)
- index.js (8 hunks)
- lib/default_stream.d.ts (1 hunks)
- lib/default_stream.js (2 hunks)
- lib/results.d.ts (1 hunks)
- lib/results.js (9 hunks)
- lib/test.d.ts (1 hunks)
- lib/test.js (41 hunks)
- test/common.js (4 hunks)
Files skipped from review as they are similar to previous changes (7)
- .github/workflows/node-aught.yml
- bin/import-or-require.js
- bin/tape
- index.d.ts
- lib/default_stream.d.ts
- lib/results.d.ts
- test/common.js
Additional context used
Learnings (3)
lib/default_stream.js (3)
Learnt from: ljharb PR: tape-testing/tape#603 File: lib/default_stream.js:23-25 Timestamp: 2024-07-05T21:18:22.587Z Learning: The modern JavaScript practice favors defining variables where they are first needed, rather than declaring all `var`s at the top of the function. This approach improves readability and maintainability.
Learnt from: ljharb PR: tape-testing/tape#603 File: lib/default_stream.js:21-21 Timestamp: 2024-07-05T21:17:37.138Z Learning: Avoid suggesting moving variable declarations to the root of the containing function if it affects the type definition and the scope of the variable.
Learnt from: ljharb PR: tape-testing/tape#603 File: lib/default_stream.js:23-25 Timestamp: 2024-07-05T21:12:23.639Z Learning: The linting rule regarding inner declarations in Biome is subjective and not agreed upon by ljharb. Future suggestions should consider this perspective.
index.js (1)
Learnt from: ljharb PR: tape-testing/tape#603 File: index.js:147-147 Timestamp: 2024-03-12T04:35:01.528Z Learning: Comments in the codebase should focus on explaining "why" or providing history/motivation, rather than detailing "what" the code does, as per ljharb's guidance.
lib/results.js (2)
Learnt from: ljharb PR: tape-testing/tape#603 File: lib/results.js:197-201 Timestamp: 2024-03-22T05:25:05.727Z Learning: For the `tape` project, code comments should explain "why" or history/motivation, but never "what". Documentation belongs outside of source files.
Learnt from: ljharb PR: tape-testing/tape#603 File: index.js:147-147 Timestamp: 2024-03-12T04:35:01.528Z Learning: Comments in the codebase should focus on explaining "why" or providing history/motivation, rather than detailing "what" the code does, as per ljharb's guidance.
Biome
lib/default_stream.js
[error] 22-22: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 23-25: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
index.js
[error] 1-1: Redundant use strict directive.
The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.(lint/suspicious/noRedundantUseStrict)
[error] 133-133: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
lib/results.js
[error] 92-92: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
lib/test.d.ts
[error] 112-112: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 126-126: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 192-192: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
[error] 198-198: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
lib/test.js
[error] 150-150: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 264-267: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 363-363: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 365-369: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 388-388: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 391-391: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 900-900: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
Additional comments not posted (39)
lib/default_stream.js (4)
6-6
: LGTM!The type annotation for the module export improves clarity.
12-12
: LGTM!The type annotation for the
write
function improves clarity.
21-21
: LGTM!The type annotation for the variable
b
ensures type safety.
23-25
: LGTM!The type annotation for the variable
c
ensures type safety.Tools
Biome
[error] 23-25: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
index.js (5)
4-5
: LGTM!The import statement for the
through
module is necessary for the functionality of the file.
11-12
: LGTM!The type annotation for the
canEmitExit
variable improves clarity.
16-26
: LGTM!The type annotations for the typedefs improve clarity and type safety.
29-29
: LGTM!The type annotation for the
harness
variable ensures type safety.
32-35
: LGTM!The type annotation for the
getHarness
function improves clarity and type safety.lib/results.js (5)
21-27
: LGTM!The type annotations for the typedefs improve clarity and type safety.
28-32
: LGTM!The type annotation for the
coalesceWhiteSpaces
function improves clarity and type safety.
Line range hint
33-48
:
LGTM!The type annotation for the
getNextTest
function improves clarity and type safety.
49-53
: LGTM!The type annotation for the
invalidYaml
function improves clarity and type safety.
Line range hint
54-105
:
LGTM!The type annotation for the
encodeResult
function improves clarity and type safety.Tools
Biome
[error] 92-92: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
lib/test.d.ts (5)
1-3
: LGTM!The import type statements for various modules improve type safety and clarity.
4-11
: LGTM!The import type statements for various typedefs improve type safety and clarity.
12-17
: LGTM!The constructor overloads for the
Test
class provide flexibility in creatingTest
instances.
37-51
: LGTM!The type annotations for the methods in the
Test
class improve clarity and type safety.
153-157
: LGTM!The type annotation for the
assertion
method improves clarity and type safety.lib/test.js (20)
38-45
: Type definitions and helper functions look good!The added type definitions and helper functions are well-structured and align with the project's use of the TypeScript compiler for type checking.
Line range hint
60-74
: Type annotations forgetTestArgs
look good!The type annotations improve the clarity of the function's parameters and return type.
Line range hint
83-130
: Constructor forTest
class looks good!The constructor is well-implemented, correctly initializing class properties and handling default values. Consider adding a comment explaining the rationale behind the dynamic method binding approach to help future maintainers understand the choice.
for (var prop in this) { if (typeof this[prop] === 'function') { // Dynamically bind methods to the instance to avoid listing each method explicitly // @ts-expect-error TODO: FIXME this[prop] = callBind(this[prop], this); } }
Line range hint
131-170
: Type annotations forrun
method look good!The type annotations improve the clarity of the method's parameters and return type.
Tools
Biome
[error] 150-150: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
Line range hint
172-195
: Type annotations fortest
method look good!The type annotations improve the clarity of the method's parameters and return type.
197-203
: Type annotations forcomment
method look good!The type annotations improve the clarity of the method's parameters and return type.
205-209
: Type annotations forplan
method look good!The type annotations improve the clarity of the method's parameters and return type.
Line range hint
211-222
: Type annotations fortimeoutAfter
method look good!The type annotations improve the clarity of the method's parameters and return type.
Line range hint
224-235
: Type annotations forend
method look good!The type annotations improve the clarity of the method's parameters and return type.
Line range hint
237-244
: Type annotations forteardown
method look good!The type annotations improve the clarity of the method's parameters and return type.
Line range hint
246-288
: Type annotations forwrapFunction
look good!The type annotations improve the clarity of the function's parameters and return type. However, consider refactoring variable declarations to the root of the function to avoid confusion.
function wrapFunction(original) { if (typeof original !== 'undefined' && typeof original !== 'function') { throw new TypeError('`original` must be a function or `undefined`'); } var bound = original && callBind.apply(original); /** @type {WrappedCall[]} */ var calls = []; /** @type {import('./test').WrapObject<NonNullable<typeof original>>} */ var wrapObject = { __proto__: null, wrapped: /** @type {() => ReturnType<original>} */ function wrapped() { var args = $slice(arguments); var completed = false; try { var returned = bound ? bound(this, /** @type {readonly[]} */ (/** @type {unknown} */ (arguments))) : void undefined; $push(calls, { args: args, receiver: this, returned: returned }); completed = true; return returned; } finally { if (!completed) { $push(calls, { args: args, receiver: this, threw: true }); } } }, calls: calls, results: function results() { try { return calls; } finally { calls = []; wrapObject.calls = calls; } } }; return wrapObject; }Tools
Biome
[error] 264-267: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
Line range hint
290-311
: Type annotations forcapture
method look good!The type annotations improve the clarity of the method's parameters and return type.
Line range hint
313-321
: Type annotations forcaptureFn
method look good!The type annotations improve the clarity of the method's parameters and return type.
Line range hint
324-430
: Type annotations forintercept
method look good!The type annotations improve the clarity of the method's parameters and return type. However, consider refactoring variable declarations to the root of the function to avoid confusion.
function intercept(obj, property) { if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { throw new TypeError('`obj` must be an object'); } if (typeof property !== 'string' && typeof property !== 'symbol') { throw new TypeError('`property` must be a string or a symbol'); } /** @type {PropertyDescriptor} */ var desc = arguments.length > 2 ? arguments[2] : { __proto__: null }; if (typeof desc !== 'undefined' && (!desc || typeof desc !== 'object')) { throw new TypeError('`desc`, if provided, must be an object'); } if ('configurable' in desc && !desc.configurable) { throw new TypeError('`desc.configurable`, if provided, must be `true`, so that the interception can be restored later'); } var isData = 'writable' in desc || 'value' in desc; var isAccessor = 'get' in desc || 'set' in desc; if (isData && isAccessor) { throw new TypeError('`value` and `writable` can not be mixed with `get` and `set`'); } var strictMode = arguments.length > 3 ? arguments[3] : true; if (typeof strictMode !== 'boolean') { throw new TypeError('`strictMode`, if provided, must be a boolean'); } /** @type {Call[]} */ var calls = []; var getter = desc.get && callBind.apply(desc.get); var setter = desc.set && callBind.apply(desc.set); var value = !isAccessor ? desc.value : void undefined; var writable = !!desc.writable; /** @type {<T = unknown>(this: T, ...args: unknown[]) => unknown} */ function getInterceptor() { /** @type {unknown[]} */ var args = $slice(arguments); if (isAccessor) { if (getter) { var completed = false; try { var returned = getter( this, /** @type {readonly []} */ (/** @type {unknown} */ (arguments)) ); completed = true; $push(calls, { type: 'get', success: true, value: returned, args: args, receiver: this }); return returned; } finally { if (!completed) { $push(calls, { type: 'get', success: false, threw: true, args: args, receiver: this }); } } } } $push(calls, { type: 'get', success: true, value: value, args: args, receiver: this }); return value; } /** @type {<T = unknown>(this: T, v: unknown) => unknown} */ function setInterceptor(v) { var args = $slice(arguments); if (isAccessor && setter) { var completed = false; try { var returned = setter(this, /** @type {readonly [v: unknown]} */ (/** @type {unknown} */ (arguments))); completed = true; $push(calls, { type: 'set', success: true, value: v, args: args, receiver: this }); return returned; } finally { if (!completed) { $push(calls, { type: 'set', success: false, threw: true, args: args, receiver: this }); } } } var canSet = isAccessor || writable; if (canSet) { value = v; } $push(calls, { type: 'set', success: !!canSet, value: value, args: args, receiver: this }); if (!canSet && strictMode) { throw new TypeError('Cannot assign to read only property `' + inspect(property) + '` of object `' + inspect(obj) + '`'); } return value; } var restore = mockProperty(obj, property, { nonEnumerable: !!desc.enumerable, get: getInterceptor, set: setInterceptor }); this.teardown(restore); function results() { try { return calls; } finally { calls = []; } } results.restore = restore; return results; }Tools
Biome
[error] 363-363: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
[error] 365-369: This var should be declared at the root of the enclosing function.
The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.(lint/correctness/noInnerDeclarations)
Line range hint
432-487
: Type annotations for_end
method look good!The type annotations improve the clarity of the method's parameters and return type.
Line range hint
489-502
: Type annotations for_exit
method look good!The type annotations improve the clarity of the method's parameters and return type.
505-511
: Type annotations for_pendingAsserts
method look good!The type annotations improve the clarity of the method's parameters and return type.
Line range hint
513-651
: Type annotations for_assert
method look good!The type annotations improve the clarity of the method's parameters and return type.
Line range hint
653-660
: Type annotations forfail
method look good!The type annotations improve the clarity of the method's parameters and return type.
Line range hint
662-669
: Type annotations forpass
method look good!The type annotations improve the clarity of the method's parameters and return type.
92aa51c
to
e80d128
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
Outside diff range, codebase verification and nitpick comments (4)
lib/test.d.ts (1)
13-16
: Potential mismatch in constructor usageThe constructor call
new Test(name, conf, cb);
does not match any of the defined overloads in theTest
class. Please review this instance to ensure it aligns with the intended overloads.
- File:
index.js
- Line:
var t = new Test(name, conf, cb);
Analysis chain
Constructor overloads are appropriate.
The current constructor overloads provide necessary flexibility and should be maintained as is.
However, ensure that all constructor calls in the codebase match these overloads.
Run the following script to verify the constructor usage:
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify all constructor calls to `Test` match the defined overloads. # Test: Search for the constructor usage. Expect: Only occurrences of the defined overloads. rg --type js -A 5 $'new Test'Length of output: 988
lib/test.js (3)
60-60
: Clarify the return type annotation forgetTestArgs
.The return type annotation could be more explicit about the optional nature of
cb
.Apply this diff for clarity:
- /** @type {(name_: string, opts_: TestOptions, cb_: Callback) => { name: string, opts: TestOptions, cb: Callback }} */ + /** @type {(name_: string, opts_: TestOptions, cb_: Callback) => { name: string, opts: TestOptions, cb?: Callback }} */
246-246
: Improve type annotations forwrapFunction
.The type annotations could be more explicit for clarity.
Apply this diff for clarity:
- /** @type {<T extends Callback>(original: undefined | T) => import('./test').WrapObject<T>} */ + /** @type {<T extends Callback | undefined>(original: T) => import('./test').WrapObject<NonNullable<T>>} */
985-985
: Improve type annotations formatch
.The type annotations could be more explicit for clarity.
Apply this diff for clarity:
- /** @type {import('./test').prototype.match} */ + /** @type {(string: string, regexp: RegExp, msg?: string, extra?: unknown) => void} */
Codecov ReportAttention: Patch coverage is
❗ Your organization needs to install the Codecov GitHub app to enable full functionality. Additional details and impacted files@@ Coverage Diff @@
## master #603 +/- ##
==========================================
+ Coverage 96.59% 96.61% +0.01%
==========================================
Files 4 4
Lines 764 768 +4
Branches 194 195 +1
==========================================
+ Hits 738 742 +4
Misses 26 26 ☔ View full report in Codecov by Sentry. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 9
🧹 Outside diff range and nitpick comments (9)
bin/tape (2)
103-103
: LGTM! Consider adding more detailed JSDoc documentation.The type annotation
(hasSupport: boolean) => Promise<void> | void
accurately reflects the function's behavior.Consider expanding the JSDoc to document the parameter and return type meanings:
-/** @type {(hasSupport: boolean) => Promise<void> | void} */ +/** + * Imports test files using either dynamic import or require based on runtime support + * @param {boolean} hasSupport - Whether dynamic import is supported in the runtime + * @returns {Promise<void> | void} Promise when using dynamic import, void when using require + */
107-107
: Consider refining the type annotation.The type
null | undefined | Promise<unknown>
could be simplified asnull | Promise<unknown>
since the variable is always initialized andundefined
is not a possible value in the implementation.-/** @type {null | undefined | Promise<unknown>} */ +/** @type {null | Promise<unknown>} */test/common.js (1)
70-70
: LGTM: Type annotation for stripFullStack is correct.The type annotation accurately reflects the string input and output. Consider adding JSDoc description for better documentation of this complex function's purpose.
+/** + * Strips and normalizes stack traces for consistent test assertions + * @param {string} output - The stack trace output to process + * @returns {string} The normalized stack trace + */ /** @type {(output: string) => string} */index.js (1)
170-170
: Consider enhancing error handling.The error handler ignores the error parameter. Consider logging or handling the error appropriately, especially since it affects the exit code.
-es.on('error', function (_) { harness._exitCode = 1; }); +es.on('error', function (err) { + console.error('Stream error:', err); + harness._exitCode = 1; +});lib/results.js (1)
168-169
: Simplify complex type casting.The double type casting (
unknown
toWritableStream
) could be simplified.Consider refactoring to:
- self._stream.pipe(/** @type {WritableStream} */ (/** @type {unknown} */ (output))); + self._stream.pipe(/** @type {WritableStream} */ (output));lib/test.js (3)
Line range hint
60-81
: Consider strengthening type safety in getTestArgs.The function's type annotation suggests it accepts specific types (
string
,TestOptions
,Callback
), but the implementation accepts any arguments and performs runtime type checking. This could lead to runtime errors if TypeScript's type checking is bypassed.Consider using rest parameters with type guards:
-/** @type {(name_: string, opts_: TestOptions, cb_: Callback) => { name: string, opts: TestOptions, cb: Callback }} */ -function getTestArgs() { +/** @type {(...args: unknown[]) => { name: string, opts: TestOptions, cb: Callback }} */ +function getTestArgs(...args) {
897-897
: Consider alternative type narrowing approach.The current type narrowing using
Object(err) === err
is a clever workaround, but it might be clearer to use a type predicate function.Consider creating a type guard:
/** @type {(err: unknown): err is object & { message?: unknown }} */ function isObjectWithOptionalMessage(err) { return Object(err) === err; }
123-125
: Consider alternatives to @ts-expect-error.The
@ts-expect-error
directive is used to handle dynamic method binding. While this works, it might be clearer to use a type assertion.Consider using a type assertion:
-// @ts-expect-error TODO: FIXME -this[prop] = callBind(this[prop], this); +this[prop] = callBind(/** @type {Function} */(this[prop]), this);lib/results.d.ts (1)
36-37
: Specify more precise types forskip
andtodo
properties inResult
Currently,
skip
andtodo
are typed asunknown
. If possible, specify more precise types (e.g.,boolean
or specific allowed values) to enhance type safety and clarity.Consider this change:
export type Result = { // ... - skip: unknown; - todo: unknown; + skip: boolean | number | string; + todo: boolean | number | string; // ... };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (3)
.github/workflows/node-aught.yml
is excluded by!**/*.yml
package.json
is excluded by!**/*.json
tsconfig.json
is excluded by!**/*.json
📒 Files selected for processing (11)
bin/import-or-require.js
(1 hunks)bin/tape
(1 hunks)index.d.ts
(1 hunks)index.js
(8 hunks)lib/default_stream.d.ts
(1 hunks)lib/default_stream.js
(2 hunks)lib/results.d.ts
(1 hunks)lib/results.js
(9 hunks)lib/test.d.ts
(1 hunks)lib/test.js
(41 hunks)test/common.js
(4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- bin/import-or-require.js
- lib/default_stream.d.ts
- lib/default_stream.js
🧰 Additional context used
📓 Learnings (2)
index.js (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: index.js:147-147
Timestamp: 2024-11-12T06:00:40.803Z
Learning: Comments in the codebase should focus on explaining "why" or providing history/motivation, rather than detailing "what" the code does, as per ljharb's guidance.
lib/results.js (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/results.js:197-201
Timestamp: 2024-11-12T06:00:40.803Z
Learning: For the `tape` project, code comments should explain "why" or history/motivation, but never "what". Documentation belongs outside of source files.
🪛 Biome (1.9.4)
lib/test.d.ts
[error] 112-112: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 126-126: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 192-192: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
[error] 198-198: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
🔇 Additional comments (16)
bin/tape (1)
Line range hint 110-121
: Verify type safety of dynamic imports across module boundaries.
The code handles both CommonJS and ES Module imports. Let's ensure type safety is maintained across module boundaries.
✅ Verification successful
Type safety is properly maintained across module boundaries
The implementation of import-or-require.js
is well-typed with proper JSDoc annotations:
- The module exports a properly typed function:
@type {(file: string) => undefined | Promise<unknown>}
- It correctly handles both ESM (
.mjs
or type "module") and CommonJS files - The dynamic import is properly wrapped with
pathToFileURL().href
for URL-safe imports
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify type consistency in import handling
# Check if import-or-require.js has corresponding type definitions
ast-grep --pattern $'/** @type' ./bin/import-or-require.js
# Look for potential type mismatches in dynamic imports
rg -l "import\(" . | while read -r file; do
ast-grep --pattern $'/** @type' "$file"
done
Length of output: 556
Script:
#!/bin/bash
# Let's examine the import-or-require implementation and its usage
# Check the implementation of import-or-require
cat ./bin/import-or-require.js
# Look for type annotations or JSDoc comments in the file
rg "@(param|returns?|type)" ./bin/import-or-require.js
# Check how dynamic imports are handled
rg -A 5 "import\(" .
Length of output: 18032
test/common.js (4)
8-9
: LGTM: Type imports are correctly defined.
The type imports are properly structured and reference the correct paths.
11-11
: LGTM: Type annotation for getDiag is accurate.
The type annotation correctly specifies the string and boolean parameters and Result return type, matching the function's implementation.
45-45
: LGTM: Type annotation for stripChangingData is precise.
The union type null | string
correctly captures both possible return values based on the implementation.
115-115
: LGTM: Type annotation for runProgram is well-defined.
The type annotation correctly specifies the string parameters and SyncCallback type, matching the asynchronous nature of the function.
index.js (4)
29-32
: LGTM! Type annotations enhance code clarity.
The added type annotations for harness
, getHarness
, lazyLoad
, and createStream
provide excellent type safety and documentation.
Also applies to: 42-42, 62-62
209-212
: Consider investigating alternatives to the circular exports hack.
While the current workaround for TypeScript's circular exports limitation works, it would be beneficial to investigate if there's a cleaner solution, such as restructuring the exports to avoid circularity.
4-4
: Verify the package change impact.
The package import has been changed from 'through' to '@ljharb/through'. This change might have implications on the package's dependencies and functionality.
✅ Verification successful
Let me gather more information about the package usage and its potential impact.
Let me check the actual usage of the through package in the identified files to understand the impact better.
Package change is safe to use
The change from 'through' to '@ljharb/through' is verified to be safe because:
- The package is properly declared in the project's dependencies (
@ljharb/through: ^2.3.13
) - It's a maintained fork of the original 'through' package by a trusted maintainer
- The package usage across the codebase (index.js, lib/default_stream.js, lib/results.js, and test files) follows the same API pattern as the original 'through' package
- The repository description confirms it maintains the same functionality: "simple way to create a ReadableWritable stream that works"
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if the package is available and compare its API with the original 'through' package
curl -s https://registry.npmjs.org/@ljharb/through/latest | jq -r '.version'
# Check for any breaking changes or differences in the API
gh api graphql -f query='
{
repository(owner: "ljharb", name: "through") {
description
url
releases(first: 1) {
nodes {
description
tagName
}
}
}
}'
Length of output: 448
Script:
#!/bin/bash
# Check package.json for dependencies
cat package.json | jq '.dependencies, .devDependencies'
# Search for any other usage of 'through' package in the codebase
rg -l "require\(['\"](through|@ljharb/through)" --type js
# Check git history for the specific change
git log -p -S "require('through')" --pickaxe-regex -- index.js
Length of output: 1861
Script:
#!/bin/bash
# Check the content of files using through
echo "=== index.js ==="
cat index.js | grep -A 5 -B 5 "through"
echo -e "\n=== lib/default_stream.js ==="
cat lib/default_stream.js | grep -A 5 -B 5 "through"
echo -e "\n=== lib/results.js ==="
cat lib/results.js | grep -A 5 -B 5 "through"
echo -e "\n=== test/objectModeWithComment.js ==="
cat test/objectModeWithComment.js | grep -A 5 -B 5 "through"
echo -e "\n=== test/objectMode.js ==="
cat test/objectMode.js | grep -A 5 -B 5 "through"
Length of output: 3710
143-143
: Investigate type compatibility issue.
The @ts-expect-error
comment indicates a type compatibility issue between test
and Harness
. This should be investigated and properly fixed rather than suppressed.
lib/results.js (4)
21-27
: LGTM! Consider documenting the Result type properties.
The type definitions are well-structured and comprehensive. The Result
type accurately captures the shape of test results with appropriate optional fields.
Consider adding brief descriptions for the Result
type properties to improve maintainability:
/**
* Represents a test result
* @typedef {object} Result
* @property {boolean} ok - Whether the test passed
* @property {string} name - Name of the test
* @property {unknown} - Skip reason if test was skipped
* @property {unknown} [todo] - TODO reason if test is marked as TODO
* ...remaining properties...
*/
Line range hint 106-125
: LGTM! Constructor implementation is robust.
The constructor properly handles both direct calls and new
instantiation with appropriate type annotations.
Line range hint 219-234
: LGTM! Event handler types are well-defined.
The result event handler properly handles both string and Result types with appropriate type guards.
90-91
: Verify type assertion safety.
The type assertion for res.actual
to Error
might be unsafe if res.actual
doesn't match the Error
interface.
✅ Verification successful
Let me gather more information about how res.actual
is used and populated.
Let me check one more thing to understand how the test results are created and what types of values are actually passed.
Based on the gathered information, I can now provide the final response:
Type assertion is safe in this context.
The type assertion for res.actual
to Error
is guarded by a type check typeof res.actual === 'object' || typeof res.actual === 'function'
before accessing the stack property. The code is used to extract stack traces from error objects, and the type assertion is only performed after verifying that res.actual
could potentially be an Error object. The test framework's implementation shows that error objects are properly passed through the assertion system, particularly in error-related assertions like throws()
.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for all usages of encodeResult to verify res.actual types
rg -A 3 "encodeResult\("
Length of output: 456
Script:
#!/bin/bash
# Search for assignments or references to res.actual
rg "res\.actual" -B 2 -A 2
# Also search for test result object creation
ast-grep --pattern 'res = { $$$, actual: $_, $$$}'
Length of output: 1046
Script:
#!/bin/bash
# Search for test assertions or result creation patterns
ast-grep --pattern 'test($$$, function ($$$) { $$$assert($$$) })'
# Also look for direct test result creation
rg "assert\(" -B 2 -A 2
Length of output: 6361
lib/test.js (3)
38-44
: LGTM: Type definitions are well-structured.
The type definitions are clear and properly imported from their respective modules.
Line range hint 46-58
: LGTM: Error constructor check is well-typed.
The dual implementation for IE8 compatibility is properly typed and maintains backward compatibility.
Line range hint 935-945
: TODO comment about array method type narrowing.
The comment indicates a TypeScript limitation with preserving type narrowing in array method callbacks. This is a known limitation in TypeScript.
Let's check if this is still an issue in the latest TypeScript version:
✅ Verification successful
TypeScript type narrowing TODO comment is still relevant
The TODO comment is valid as the project uses TypeScript's latest version ("typescript": "next" in package.json) and the type narrowing limitation in array method callbacks is still a known issue. The comment serves as a helpful documentation of why the @ts-expect-error
directive is needed in this context.
- The code correctly works around the limitation by using
@ts-expect-error
annotations - The project actively maintains TypeScript support with strict type checking enabled
- The TODO comment should be kept as it documents a TypeScript limitation rather than a code issue
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check TypeScript version and relevant issues
gh api graphql -f query='
{
repository(owner: "microsoft", name: "TypeScript") {
issues(first: 5, states: OPEN, query: "is:issue array method type narrowing") {
nodes {
title
url
createdAt
}
}
}
}'
Length of output: 557
Script:
#!/bin/bash
# Let's check the TypeScript configuration and version in the project
fd -e json "tsconfig.json|package.json" --exec cat {}
# Let's also look for similar type narrowing patterns in the codebase
ast-grep --pattern 'every($_, function ($$$) { $$$ })'
# And check for any other TODO comments related to TypeScript type narrowing
rg -i "ts.*todo.*narrow" -A 2 -B 2
Length of output: 4549
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (17)
lib/results.d.ts (3)
1-6
: Consider standardizing import styleThe file mixes ES module imports (
import through
,import type
) with CommonJS imports (require
). Consider standardizing to one style for better consistency.-import through from '@ljharb/through'; -import type { EventEmitter } from 'events'; -import type { StreamOptions } from '../'; -import Test = require('./test'); +import type { EventEmitter } from 'events'; +import type { StreamOptions } from '../'; +import type { default as through } from '@ljharb/through'; +import type Test from './test';
10-16
: Add JSDoc comments for public propertiesConsider adding JSDoc comments to document the purpose of each property. This would improve the developer experience when using the library.
+ /** Total number of tests */ count: number; + /** Number of failed tests */ fail: number; + /** Number of passed tests */ pass: number; + /** Array of all test instances */ tests: Test[]; + /** Number of todo tests */ todo: number; + /** Whether todo tests are considered OK */ todoIsOK: boolean; + /** Whether the test run has completed */ closed?: boolean;
33-49
: Consider stricter types for Result propertiesThe
skip
andtodo
properties are typed asunknown
, which might be too permissive. Consider using more specific types if possible. Also,objectPrintDepth
should probably be a positive number.export type Result = { id: number; ok: boolean; - skip: unknown; - todo: unknown; + skip: boolean | string | undefined; + todo: boolean | string | undefined; name?: string; operator: undefined | Operator; - objectPrintDepth?: number; + objectPrintDepth?: number & { __brand: 'PositiveNumber' }; actual?: unknown; expected?: unknown; error?: unknown; functionName?: string; file?: string; line?: number; column?: number; at?: string; };index.d.ts (2)
6-12
: Consider adding JSDoc comments for better documentationThe function overloads are well-structured and cover all valid parameter combinations. However, adding JSDoc comments would improve documentation for users.
Example documentation:
/** * Creates a new test harness * @param name - The name of the test * @param opts - Test options * @param cb - Test callback function * @returns A new Test instance */ declare function harnessFunction(this: Test, name: string, opts: tape.TestOptions, cb: Test.Callback): Test;
58-63
: Consider documenting config options impactThe HarnessConfig type is well-structured, but consider adding JSDoc comments to explain the impact of each option on the harness behavior.
Example:
export type HarnessConfig = { /** Automatically close the harness after all tests complete */ autoclose?: boolean; /** Disable .only() functionality */ noOnly?: boolean; /** Custom output stream for test results */ stream?: NodeJS.WritableStream | ThroughStream; /** Exit after tests complete */ exit?: boolean; } & StreamOptions;index.js (3)
11-12
: Consider adding a comment explaining the type casting and parentheses.The type casting and extra parentheses are necessary for TypeScript compatibility, but their purpose might not be immediately clear to future maintainers.
// eslint-disable-next-line no-extra-parens -&& typeof process.on === 'function' && /** @type {{ browser?: boolean }} */ (process).browser !== true; +// Type casting is needed here because TypeScript doesn't recognize `process.browser` by default +&& typeof process.on === 'function' && /** @type {{ browser?: boolean }} */ (process).browser !== true;
16-24
: Consider standardizing the import paths.Most types are imported from '.', but Result is imported from './lib/results'. For consistency, consider importing all types from the main entry point.
164-165
: Consider using type assertion alternatives.The type casting with extra parentheses could be simplified using alternative TypeScript type assertion syntax.
-var es = stream.pipe(/** @type {WritableStream} */ (cStream || createDefaultStream())); +var es = stream.pipe(cStream || createDefaultStream()) as WritableStream;lib/results.js (3)
21-26
: Consider breaking down the Result type definition for better maintainabilityThe
Result
type definition is quite complex with multiple optional and required fields. Consider breaking it down into smaller, more focused interfaces.-/** @typedef {{ ok: boolean, name: string, skip?: unknown, todo?: unknown, operator: unknown, objectPrintDepth?: number, expected: unknown, actual: unknown, at?: string, error?: Error, test: unknown, type: unknown}} Result */ +/** @typedef {{ ok: boolean, name: string }} BaseResult */ +/** @typedef {{ skip?: unknown, todo?: unknown }} TestModifiers */ +/** @typedef {{ operator: unknown, objectPrintDepth?: number, expected: unknown, actual: unknown }} AssertionDetails */ +/** @typedef {{ at?: string, error?: Error, test: unknown, type: unknown }} MetaInfo */ +/** @typedef {BaseResult & TestModifiers & AssertionDetails & MetaInfo} Result */
90-91
: Consider using type predicates for cleaner type narrowingThe type assertion for
res.actual
could be made clearer using a type predicate function.+/** @type {(value: unknown): value is object | Function} */ +function isObjectOrFunction(value) { + return typeof value === 'object' || typeof value === 'function'; +} -var actualStack = res.actual && (typeof res.actual === 'object' || typeof res.actual === 'function') ? /** @type {Error} */ (res.actual).stack : undefined; +var actualStack = res.actual && isObjectOrFunction(res.actual) ? /** @type {Error} */ (res.actual).stack : undefined;
168-169
: Simplify the double type assertionThe double type casting could be simplified using a more direct approach.
-self._stream.pipe(/** @type {WritableStream} */ (/** @type {unknown} */ (output))); +self._stream.pipe(output as WritableStream);lib/test.d.ts (3)
18-36
: Consider adding JSDoc comments for properties.While the properties are well-organized and properly typed, adding JSDoc comments would improve documentation and provide better IDE support.
Example for a few properties:
+ /** Indicates if the test is readable */ readable: boolean; + /** The name of the test */ name: string; + /** The count of assertions made in this test */ assertCount: number;
37-51
: Consider adding explicit return type annotations.While TypeScript can infer return types, explicit annotations improve readability and maintainability.
Example for a few methods:
- captureFn<X extends Test.Callback>(this: Test, original: X): Test.WrappedFn<X>; + captureFn<X extends Test.Callback>(this: Test, original: X): Test.WrappedFn<X>; - run(this: Test): void; + run(this: Test): void; - test(this: Test, name: string, cb: Test.Callback): void; + test(this: Test, name: string, cb: Test.Callback): void;
166-184
: Consider adding documentation for private methods.While these are private methods, adding documentation would help maintainers understand their purpose and usage.
Example:
+ /** + * Internal assertion handler + * @param maybeOK - The assertion result + * @param opts - Options for the assertion + */ _assert( this: Test, maybeOK: boolean | unknown, opts: TestOptions & { message?: string; operator?: Operator; // ... }, ): void;lib/test.js (3)
122-125
: Consider using a type-safe method binding approach.The
@ts-expect-error
comment for method binding could be replaced with a type-safe approach.Consider using a type-safe helper function:
-// @ts-expect-error TODO: FIXME -this[prop] = callBind(this[prop], this); +/** @type {<T>(obj: T, prop: keyof T) => void} */ +function bindMethod(obj, prop) { + if (typeof obj[prop] === 'function') { + obj[prop] = callBind(obj[prop], obj); + } +} +bindMethod(this, prop);
Line range hint
897-903
: Improve type narrowing for error objects.The
@ts-expect-error
comment for Object type narrowing could be replaced with a more explicit type check.Consider using a type predicate:
-// @ts-expect-error TS doesn't understand that `Object(err) === err` narrows `err` to `object` -if (Object(err) === err && 'message' in err && (!isEnumerable(err, 'message') || !hasOwn(err, 'message'))) { +/** @type {(value: unknown): value is object} */ +function isObject(value) { + return Object(value) === value; +} +if (isObject(err) && 'message' in err && (!isEnumerable(err, 'message') || !hasOwn(err, 'message'))) {
Line range hint
935-945
: Improve type safety in array iteration.The TODO comment about type narrowing in the array iteration could be addressed.
Consider using a type guard:
-// TS TODO: `caught.error` and `expected` should both be `object` here -passed = every(keys, /** @type {(key: PropertyKey) => boolean} */ function (key) { +/** @type {(value: unknown): value is Record<PropertyKey, unknown>} */ +function isRecord(value) { + return typeof value === 'object' && value !== null; +} +if (isRecord(caught.error) && isRecord(expected)) { + passed = every(keys, function (key) {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (3)
.github/workflows/node-aught.yml
is excluded by!**/*.yml
package.json
is excluded by!**/*.json
tsconfig.json
is excluded by!**/*.json
📒 Files selected for processing (11)
bin/import-or-require.js
(1 hunks)bin/tape
(1 hunks)index.d.ts
(1 hunks)index.js
(8 hunks)lib/default_stream.d.ts
(1 hunks)lib/default_stream.js
(2 hunks)lib/results.d.ts
(1 hunks)lib/results.js
(9 hunks)lib/test.d.ts
(1 hunks)lib/test.js
(41 hunks)test/common.js
(4 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
- bin/import-or-require.js
- bin/tape
- lib/default_stream.d.ts
- lib/default_stream.js
🧰 Additional context used
📓 Learnings (6)
index.d.ts (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: index.d.ts:68-70
Timestamp: 2024-11-27T00:58:49.749Z
Learning: In a `.d.ts` file, it's acceptable to declare constants of types imported with `import type`, because type and value spaces are separate.
index.js (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: index.js:147-147
Timestamp: 2024-11-12T06:00:40.803Z
Learning: Comments in the codebase should focus on explaining "why" or providing history/motivation, rather than detailing "what" the code does, as per ljharb's guidance.
lib/results.d.ts (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/results.d.ts:18-20
Timestamp: 2024-11-27T00:54:06.607Z
Learning: Do not suggest adding the `private` modifier to properties and methods in TypeScript code, as `private` is not part of standard JavaScript. Avoid recommending the use of the `private` keyword in code reviews for TypeScript projects.
lib/results.js (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/results.js:197-201
Timestamp: 2024-11-12T06:00:40.803Z
Learning: For the `tape` project, code comments should explain "why" or history/motivation, but never "what". Documentation belongs outside of source files.
lib/test.d.ts (5)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:112-112
Timestamp: 2024-11-27T00:57:05.043Z
Learning: In `lib/test.d.ts`, for the `throws` method's `exceptionExpected` parameter, using `Function` as a type is correct and should not be replaced with `ErrorConstructor`, as it avoids introducing bugs.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:126-126
Timestamp: 2024-11-27T00:56:43.820Z
Learning: In the TypeScript declarations in `lib/test.d.ts`, for the `throws` method in the `Test` class, the `exceptionExpected` parameter intentionally uses the `Function` type to accept any function-like value. Replacing it with `ErrorConstructor` is not appropriate in this context.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:192-192
Timestamp: 2024-11-27T00:56:52.796Z
Learning: In `lib/test.d.ts`, it's acceptable to use `{}` as the type for the `receiver` property.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:198-198
Timestamp: 2024-11-27T00:56:04.598Z
Learning: In this codebase, using `{}` as a type for the `receiver` property is intentional to allow primitives as receivers because `unknown` is invalid in this context.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:14-20
Timestamp: 2024-11-12T06:00:40.803Z
Learning: When suggesting changes to constructor overloads in TypeScript, ensure that all possible argument combinations are covered, including the option for a single callback argument.
lib/test.js (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.js:0-0
Timestamp: 2024-11-12T06:00:40.803Z
Learning: The project `tape-testing/tape` uses ES3 syntax only and does not use TypeScript as a language. However, it employs the TypeScript Compiler (tsc) for type checking JavaScript files. This distinction is crucial for understanding the project's approach to handling types and syntax.
🪛 Biome (1.9.4)
lib/test.d.ts
[error] 112-112: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 126-126: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 192-192: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
[error] 198-198: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
🔇 Additional comments (22)
lib/results.d.ts (1)
52-52
: LGTM!
The export statement is correct and consistent with the CommonJS module system.
index.d.ts (5)
1-5
: LGTM! Clean type-only imports
The imports are properly structured using type-only imports, which is the correct approach for a declaration file.
15-34
: LGTM! Well-structured option interfaces
The option interfaces are well-defined with appropriate optional properties and type unions where needed.
71-76
: LGTM! Well-defined main function declarations
The tape function declarations are consistent with the harness function patterns and properly typed for 'this' context. The CommonJS export is correctly declared.
1-76
: Verify test coverage for type definitions
The type definitions look complete and well-structured. Consider adding tests using dtslint
or similar tools to verify the type definitions work as expected with different usage patterns.
Would you like help setting up type definition tests to verify these declarations?
46-56
: Verify the completeness of Harness properties
The Harness type correctly uses intersection type to combine function type with additional properties. Consider verifying if all properties from the runtime implementation are covered.
✅ Verification successful
Let me gather more information about the harness implementation to ensure we have a complete picture.
The Harness type definition is complete and accurate
The type definition in index.d.ts
correctly includes all properties that are assigned and used in the implementation:
- Function properties:
run
,only
,close
,createStream
,onFailure
,onFinish
- Internal properties:
_exitCode
,_results
,_tests
The implementation in createHarness
function matches exactly with the type definition, with no additional properties being assigned or accessed.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for properties accessed on harness instances
rg -g '!*.d.ts' -g '!*.map' '\bharness\.[_a-zA-Z][_a-zA-Z0-9]*\b'
Length of output: 696
Script:
#!/bin/bash
# Search for harness property assignments and declarations
ast-grep --pattern 'harness.$_ = $_'
# Also check the harness function implementation
ast-grep --pattern 'function createHarness($_) {
$$$
}'
Length of output: 2525
test/common.js (5)
8-9
: LGTM: Type definitions are correctly imported
The type imports for Result
and SyncCallback
are properly defined using TypeScript's type import syntax.
11-11
: LGTM: Function signature is accurately typed
The type annotation correctly specifies the parameter types (string
, boolean
) and return type (Result
), matching the function's implementation.
45-45
: LGTM: Return type accurately captures both outcomes
The type annotation (line: string) => null | string
correctly reflects that the function can return either null
or a processed string
.
70-70
: LGTM: Type signature matches implementation
The type annotation (output: string) => string
correctly reflects that the function always returns a processed string.
115-115
: Verify the SyncCallback type definition
The type annotation looks correct, but let's verify that the SyncCallback
type definition matches the callback usage in this function.
✅ Verification successful
Let me verify how the callback is used in the runProgram function to ensure it matches the SyncCallback type definition.
Let me get the actual implementation of runProgram to see exactly how the callback is used.
SyncCallback type definition is correct and matches usage
The SyncCallback type definition (...args: unknown[]) => unknown
perfectly matches its usage in the runProgram function. The callback is called with a single result object containing stdout
, stderr
, and exitCode
, which fits within the flexible unknown[]
parameters. The return type being unknown
is also appropriate as the callback's return value isn't used in the implementation.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify the SyncCallback type definition matches the callback usage
# Search for the SyncCallback type definition
echo "Searching for SyncCallback type definition:"
ast-grep --pattern 'type SyncCallback = $_'
# Search for other usages of SyncCallback for consistency
echo -e "\nSearching for other SyncCallback usages:"
rg 'SyncCallback'
Length of output: 695
Script:
#!/bin/bash
# Get the implementation of runProgram to see how the callback is used
ast-grep --pattern 'function runProgram($_) {
$$$
}'
# Also get any direct calls to runProgram to see callback usage
rg "runProgram\(" -A 3
Length of output: 2050
Script:
#!/bin/bash
# Search for runProgram implementation in common.js
cat test/common.js
Length of output: 5868
index.js (2)
208-211
: LGTM! Well-documented workaround for TypeScript's circular exports.
The comment clearly explains why the hack is needed, which is perfect for maintainability.
142-142
: Investigate type compatibility issue with test
function.
The TODO comment indicates a type compatibility issue between test
and Harness
. This should be investigated and fixed rather than suppressed with @ts-expect-error
.
Would you like help investigating and fixing this type compatibility issue?
✅ Verification successful
Let me gather more information about the test
function to understand the type compatibility issue better.
Let me search for the test function definition and usage to understand the type compatibility issue better.
Let me search for the test function implementation to understand why it's not assignable to Harness.
Let me search for the test function type definition and its relationship with Harness.
I now have enough information to explain the type compatibility issue.
Type compatibility issue resolved: test
function is missing required Harness properties
The test
function is not assignable to Harness
because the Harness
type requires additional properties beyond just being a function. The Harness
type is defined as:
type Harness = typeof harnessFunction & {
run?: () => void;
only: typeof only;
_exitCode: number;
_results: Results;
_tests: Test[];
// ... other properties
}
The test
function needs to be augmented with these additional properties before it can be assigned to Harness
. The @ts-expect-error
is necessary here since the function is dynamically enhanced with these properties after its creation.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for the Harness type definition and its usage
ast-grep --pattern 'type Harness = $_'
Length of output: 526
Script:
#!/bin/bash
# Search for test function definition and its type
ast-grep --pattern 'function test($_) {
$$$
}'
# Search for test function type annotations
ast-grep --pattern 'test: $_'
# Search for test function usage context
rg "test\(" -A 5 -B 5
Length of output: 131179
Script:
#!/bin/bash
# Search for test function definition and type annotations
ast-grep --pattern 'function test($_) {
$$$
}'
# Search for Harness type usage
rg "Harness" -A 2 -B 2
Length of output: 21794
Script:
#!/bin/bash
# Search for test function implementation and its return type
ast-grep --pattern 'function test($args) {
$$$
}'
# Search for test function type annotations
rg "test:" -A 2 -B 2 index.d.ts
Length of output: 228
Script:
#!/bin/bash
# Search for test function type definition
rg "type test" -A 5 -B 5
# Search for tape function declaration
rg "declare function tape" -A 5 -B 5 index.d.ts
# Search for harnessFunction type usage
rg "harnessFunction" -A 5 -B 5
Length of output: 2176
lib/results.js (2)
Line range hint 28-54
: LGTM! Type annotations are clear and accurate
The type annotations for utility functions are well-defined and accurately represent their parameters and return types.
Line range hint 219-235
: LGTM! Well-typed event handlers
The event handler type annotations are precise and help ensure type safety when handling different result types.
lib/test.d.ts (4)
1-12
: LGTM! Well-structured imports and class declaration.
The imports are properly typed and organized, and the class correctly extends EventEmitter.
13-16
: LGTM! Constructor overloads are well-defined.
The constructor overloads cover all possible argument combinations, including the single callback argument case, as discussed in previous reviews.
109-135
: LGTM! Assertion methods are well-typed.
The use of Function
type in throws
and doesNotThrow
methods is intentional and correct, as it allows for accepting any function-like value without introducing bugs, as confirmed in previous discussions.
🧰 Tools
🪛 Biome (1.9.4)
[error] 112-112: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 126-126: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
186-232
: LGTM! Well-structured type definitions.
The namespace declarations provide comprehensive type definitions. The use of {}
type for receiver
properties is intentional and correct, as it allows for primitives as receivers, as confirmed in previous discussions.
🧰 Tools
🪛 Biome (1.9.4)
[error] 192-192: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
[error] 198-198: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
lib/test.js (3)
38-44
: LGTM! Type definitions are well-structured.
The type definitions are comprehensive and properly imported from their respective modules. The IsErrorConstructor
type correctly handles all error constructor types.
Line range hint 46-58
: LGTM! Error constructor handling is robust.
The code properly handles browser compatibility (specifically IE8) while maintaining type safety. Both implementations are correctly type-annotated.
Line range hint 60-1064
: LGTM! Type annotations are comprehensive and accurate.
The added type annotations improve type safety while maintaining the existing functionality. The annotations are well-documented and follow TypeScript best practices.
@andrewbranch attw is failing with "named exports" as of 0.17, and I can't figure out what i could change to make it pass. any tips? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (3)
index.js (2)
11-12
: Consider using type assertion instead of type casting.The type casting with JSDoc comment could be replaced with a type assertion for better type safety.
- // eslint-disable-next-line no-extra-parens - && typeof process.on === 'function' && /** @type {{ browser?: boolean }} */ (process).browser !== true; + && typeof process.on === 'function' && (process as { browser?: boolean }).browser !== true;
164-165
: Consider using type assertion for stream pipe.The type casting with JSDoc comment could be replaced with a type assertion for better type safety.
- // eslint-disable-next-line no-extra-parens - var es = stream.pipe(/** @type {WritableStream} */ (cStream || createDefaultStream())); + var es = stream.pipe((cStream || createDefaultStream()) as WritableStream);Also applies to: 169-169
lib/test.js (1)
Line range hint
883-962
: Consider improving type narrowing in the throws method.While the implementation is functionally correct, the type narrowing could be made clearer by storing the narrowed types in intermediate variables:
- // @ts-expect-error TS doesn't understand that `Object(err) === err` narrows `err` to `object` - if (Object(err) === err && 'message' in err && (!isEnumerable(err, 'message') || !hasOwn(err, 'message'))) { + const isObject = Object(err) === err; + const hasMessage = 'message' in err; + const needsMessageFix = !isEnumerable(err, 'message') || !hasOwn(err, 'message'); + if (isObject && hasMessage && needsMessageFix) {This would help TypeScript understand the type narrowing without needing
@ts-expect-error
.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (3)
.github/workflows/node-aught.yml
is excluded by!**/*.yml
package.json
is excluded by!**/*.json
tsconfig.json
is excluded by!**/*.json
📒 Files selected for processing (11)
bin/import-or-require.js
(1 hunks)bin/tape
(1 hunks)index.d.ts
(1 hunks)index.js
(8 hunks)lib/default_stream.d.ts
(1 hunks)lib/default_stream.js
(2 hunks)lib/results.d.ts
(1 hunks)lib/results.js
(9 hunks)lib/test.d.ts
(1 hunks)lib/test.js
(41 hunks)test/common.js
(4 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
- bin/import-or-require.js
- lib/default_stream.d.ts
- bin/tape
- lib/default_stream.js
- test/common.js
🧰 Additional context used
📓 Learnings (6)
index.js (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: index.js:147-147
Timestamp: 2024-11-12T06:00:40.803Z
Learning: Comments in the codebase should focus on explaining "why" or providing history/motivation, rather than detailing "what" the code does, as per ljharb's guidance.
lib/results.js (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/results.js:197-201
Timestamp: 2024-11-12T06:00:40.803Z
Learning: For the `tape` project, code comments should explain "why" or history/motivation, but never "what". Documentation belongs outside of source files.
lib/results.d.ts (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/results.d.ts:18-20
Timestamp: 2024-11-27T00:54:06.607Z
Learning: Do not suggest adding the `private` modifier to properties and methods in TypeScript code, as `private` is not part of standard JavaScript. Avoid recommending the use of the `private` keyword in code reviews for TypeScript projects.
index.d.ts (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: index.d.ts:68-70
Timestamp: 2024-11-27T00:58:49.749Z
Learning: In a `.d.ts` file, it's acceptable to declare constants of types imported with `import type`, because type and value spaces are separate.
lib/test.js (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.js:0-0
Timestamp: 2024-11-12T06:00:40.803Z
Learning: The project `tape-testing/tape` uses ES3 syntax only and does not use TypeScript as a language. However, it employs the TypeScript Compiler (tsc) for type checking JavaScript files. This distinction is crucial for understanding the project's approach to handling types and syntax.
lib/test.d.ts (5)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:112-112
Timestamp: 2024-11-27T00:57:05.043Z
Learning: In `lib/test.d.ts`, for the `throws` method's `exceptionExpected` parameter, using `Function` as a type is correct and should not be replaced with `ErrorConstructor`, as it avoids introducing bugs.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:126-126
Timestamp: 2024-11-27T00:56:43.820Z
Learning: In the TypeScript declarations in `lib/test.d.ts`, for the `throws` method in the `Test` class, the `exceptionExpected` parameter intentionally uses the `Function` type to accept any function-like value. Replacing it with `ErrorConstructor` is not appropriate in this context.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:192-192
Timestamp: 2024-11-27T00:56:52.796Z
Learning: In `lib/test.d.ts`, it's acceptable to use `{}` as the type for the `receiver` property.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:198-198
Timestamp: 2024-11-27T00:56:04.598Z
Learning: In this codebase, using `{}` as a type for the `receiver` property is intentional to allow primitives as receivers because `unknown` is invalid in this context.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:14-20
Timestamp: 2024-11-12T06:00:40.803Z
Learning: When suggesting changes to constructor overloads in TypeScript, ensure that all possible argument combinations are covered, including the option for a single callback argument.
🪛 Biome (1.9.4)
lib/test.d.ts
[error] 112-112: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 126-126: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 192-192: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
[error] 198-198: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
🔇 Additional comments (18)
lib/results.d.ts (3)
1-5
: LGTM! Clean import declarations.
The imports are well-organized and properly typed, using the type
modifier appropriately for type-only imports.
7-13
: LGTM! Well-structured class declaration with clear property types.
The Results class declaration is clear and properly extends EventEmitter. The constructor and properties are well-typed.
33-49
: LGTM! Comprehensive Result type definition.
The Result type captures all necessary properties with appropriate optionality and type definitions.
index.d.ts (3)
6-12
: LGTM! Comprehensive function overloads.
The harnessFunction overloads cover all possible parameter combinations with proper this-type annotations.
14-34
: LGTM! Well-structured type definitions.
The TestOptions, AssertOptions, and StreamOptions interfaces are clearly defined with appropriate optionality.
46-56
: LGTM! Clean Harness type definition using intersection type.
The Harness type correctly uses intersection type with harnessFunction, following the established pattern.
index.js (3)
16-24
: LGTM! Well-organized type imports.
The type imports are clearly organized and properly reference the corresponding declaration files.
210-213
: LGTM! Clean exports with proper type compatibility.
The exports are well-organized and maintain compatibility with the TypeScript declarations.
142-142
: Consider investigating the type incompatibility.
The TODO comment indicates a type incompatibility between test
and Harness
. This might need further investigation to understand and fix the root cause.
lib/results.js (4)
21-26
: Type definitions look good!
The JSDoc type definitions are well-structured and correctly reference the appropriate types from the codebase.
28-31
: LGTM! Type annotation matches implementation.
The function's type annotation correctly specifies string input and output, and the implementation properly coerces the input using String().
Line range hint 33-48
: Type annotation correctly handles undefined return case.
The function's type annotation properly specifies the possible return types (Test | undefined), and the implementation uses the ES3-compatible void undefined
pattern for explicit undefined returns.
49-52
: LGTM! Type annotation and implementation are well-aligned.
The function's type annotation correctly specifies the string to boolean conversion, and the implementation uses ES3-compatible patterns.
lib/test.d.ts (3)
12-17
: Constructor overloads look good!
The Test class declaration and constructor overloads properly handle all use cases, including the single callback argument scenario.
109-135
: Method signatures are well-defined.
The throws
and doesNotThrow
methods correctly use the Function
type to accept any function-like value, which is intentional and appropriate for this testing framework.
🧰 Tools
🪛 Biome (1.9.4)
[error] 112-112: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 126-126: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
186-232
: Type definitions in Test namespace are well-structured.
The interfaces correctly use {}
as the type for receiver
properties to allow primitives as receivers, which is intentional and appropriate for this testing framework.
🧰 Tools
🪛 Biome (1.9.4)
[error] 192-192: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
[error] 198-198: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
lib/test.js (2)
38-44
: Type definitions are comprehensive and well-structured.
The type definitions, especially the IsErrorConstructor
type, properly handle all error constructor cases while maintaining ES3 compatibility.
Line range hint 83-126
: Constructor implementation maintains ES3 compatibility.
The constructor properly initializes all properties and uses ES3-compatible patterns for method binding. The @ts-expect-error
directive is necessary for the dynamic method binding approach.
@ljharb can you point me to the failure message in CI? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Outside diff range and nitpick comments (9)
lib/results.d.ts (5)
10-16
: Consider adding JSDoc comments for public properties.Adding documentation for these properties would improve code maintainability and help users understand their purpose.
+ /** Total number of tests */ count: number; + /** Number of failed tests */ fail: number; + /** Number of passed tests */ pass: number; + /** Array of all tests */ tests: Test[]; + /** Number of todo tests */ todo: number; + /** Whether todo tests are considered OK */ todoIsOK: boolean; + /** Whether the test suite is closed */ closed?: boolean;
18-20
: Consider adding JSDoc comments for internal properties.Adding documentation for these internal properties would help maintainers understand their purpose.
+ /** Whether tests are currently running */ _isRunning: boolean; + /** Currently focused test, if any */ _only: Test | null; + /** Output stream for test results */ _stream: through.ThroughStream;
22-25
: Consider adding JSDoc comments for public methods.Adding documentation for these methods would improve code maintainability and help users understand their purpose.
+ /** Closes the test suite and prevents further tests from being added */ close(this: Results): void; + /** Creates a stream for test output with optional configuration */ createStream(this: Results, opts?: StreamOptions): through.ThroughStream; + /** Marks a test as the only one to be run */ only(this: Results, t: Test): void; + /** Adds a test to the suite */ push(this: Results, t: Test): void;
27-27
: Consider adding JSDoc comment for internal method.Adding documentation for this internal method would help maintainers understand its purpose.
+ /** Watches a test for completion and updates test counts */ _watch(this: Results, t: Test): void;
30-50
: Consider adding JSDoc comments for type definitions.Adding documentation for these types would improve code maintainability and help users understand their purpose.
declare namespace Results { + /** Type representing test operator names */ export type Operator = string; + /** Type representing a test result with detailed information */ export type Result = { + /** Unique identifier for the test */ id: number; + /** Whether the test passed */ ok: boolean; + /** Skip condition, if any */ skip: unknown; + /** Todo condition, if any */ todo: unknown; + /** Test name or description */ name?: string; + /** Test operator used */ operator: undefined | Operator; + /** Maximum depth for object printing */ objectPrintDepth?: number; + /** Actual value in assertion */ actual?: unknown; + /** Expected value in assertion */ expected?: unknown; + /** Error object if test failed */ error?: unknown; + /** Name of the function being tested */ functionName?: string; + /** File where the test is located */ file?: string; + /** Line number in the file */ line?: number; + /** Column number in the file */ column?: number; + /** Stack trace or location information */ at?: string; }; }index.js (3)
11-12
: Consider simplifying the type casting syntax.The parentheses around the type cast might be unnecessary. Consider simplifying the syntax while maintaining the same type safety.
- // eslint-disable-next-line no-extra-parens - && typeof process.on === 'function' && /** @type {{ browser?: boolean }} */ (process).browser !== true; + && typeof process.on === 'function' && /** @type {{ browser?: boolean }} */ process.browser !== true;
164-165
: Consider using a type predicate for stream type narrowing.Instead of using type assertion, consider using a type predicate function to narrow the stream type safely.
- // eslint-disable-next-line no-extra-parens - var es = stream.pipe(/** @type {WritableStream} */ (cStream || createDefaultStream())); + function isWritableStream(s: unknown): s is WritableStream { + return s !== null && typeof s === 'object' && 'write' in s; + } + var es = stream.pipe(cStream || createDefaultStream()); + if (!isWritableStream(es)) { + throw new TypeError('Expected a WritableStream'); + }
210-210
: Consider alternative approaches for handling circular exports.The commented-out workaround suggests issues with circular dependencies. Consider restructuring the exports to avoid circular dependencies, possibly by:
- Moving shared types to a separate file
- Using interface merging
- Implementing a proper dependency injection pattern
Would you like suggestions for implementing any of these alternatives?
lib/test.js (1)
935-936
: Consider using type guards for better type narrowing.Instead of using
@ts-expect-error
, consider implementing a type guard function to properly narrow the types:function isValidationObject(obj: unknown): obj is Record<PropertyKey, unknown> { return obj !== null && typeof obj === 'object'; }This would provide better type safety while maintaining runtime behavior.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (3)
.github/workflows/node-aught.yml
is excluded by!**/*.yml
package.json
is excluded by!**/*.json
tsconfig.json
is excluded by!**/*.json
📒 Files selected for processing (11)
bin/import-or-require.js
(1 hunks)bin/tape
(1 hunks)index.d.ts
(1 hunks)index.js
(8 hunks)lib/default_stream.d.ts
(1 hunks)lib/default_stream.js
(2 hunks)lib/results.d.ts
(1 hunks)lib/results.js
(9 hunks)lib/test.d.ts
(1 hunks)lib/test.js
(41 hunks)test/common.js
(4 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
- bin/import-or-require.js
- lib/default_stream.d.ts
- bin/tape
- lib/default_stream.js
- lib/results.js
🧰 Additional context used
📓 Learnings (5)
index.js (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: index.js:147-147
Timestamp: 2024-11-12T06:00:40.803Z
Learning: Comments in the codebase should focus on explaining "why" or providing history/motivation, rather than detailing "what" the code does, as per ljharb's guidance.
index.d.ts (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: index.d.ts:68-70
Timestamp: 2024-11-27T00:58:49.749Z
Learning: In a `.d.ts` file, it's acceptable to declare constants of types imported with `import type`, because type and value spaces are separate.
lib/results.d.ts (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/results.d.ts:18-20
Timestamp: 2024-11-27T00:54:06.607Z
Learning: Do not suggest adding the `private` modifier to properties and methods in TypeScript code, as `private` is not part of standard JavaScript. Avoid recommending the use of the `private` keyword in code reviews for TypeScript projects.
lib/test.js (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.js:0-0
Timestamp: 2024-11-12T06:00:40.803Z
Learning: The project `tape-testing/tape` uses ES3 syntax only and does not use TypeScript as a language. However, it employs the TypeScript Compiler (tsc) for type checking JavaScript files. This distinction is crucial for understanding the project's approach to handling types and syntax.
lib/test.d.ts (5)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:112-112
Timestamp: 2024-11-27T00:57:05.043Z
Learning: In `lib/test.d.ts`, for the `throws` method's `exceptionExpected` parameter, using `Function` as a type is correct and should not be replaced with `ErrorConstructor`, as it avoids introducing bugs.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:126-126
Timestamp: 2024-11-27T00:56:43.820Z
Learning: In the TypeScript declarations in `lib/test.d.ts`, for the `throws` method in the `Test` class, the `exceptionExpected` parameter intentionally uses the `Function` type to accept any function-like value. Replacing it with `ErrorConstructor` is not appropriate in this context.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:192-192
Timestamp: 2024-11-27T00:56:52.796Z
Learning: In `lib/test.d.ts`, it's acceptable to use `{}` as the type for the `receiver` property.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:198-198
Timestamp: 2024-11-27T00:56:04.598Z
Learning: In this codebase, using `{}` as a type for the `receiver` property is intentional to allow primitives as receivers because `unknown` is invalid in this context.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/test.d.ts:14-20
Timestamp: 2024-11-12T06:00:40.803Z
Learning: When suggesting changes to constructor overloads in TypeScript, ensure that all possible argument combinations are covered, including the option for a single callback argument.
🪛 Biome (1.9.4)
lib/test.d.ts
[error] 112-112: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 126-126: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 192-192: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
[error] 198-198: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
🔇 Additional comments (10)
index.d.ts (4)
13-16
: LGTM: Constructor overloads are well-defined.
The constructor overloads cover all possible argument combinations, including the single callback argument case, as previously discussed.
18-36
: LGTM: Properties and private members are well-typed.
Clear separation between public and private members with appropriate type annotations.
Line range hint 37-184
: LGTM: Methods and assertions are well-defined.
Methods have appropriate this type annotations and parameters are well-typed. The use of Function type in throws() method is intentional and correct as per previous discussions.
Line range hint 186-232
: LGTM: Namespace declarations are well-structured.
Type definitions are clear and well-organized. The use of {} type for receiver properties is intentional to allow primitives as receivers.
test/common.js (5)
8-9
: LGTM: Type imports are properly defined.
JSDoc type imports are correctly defined for Result and SyncCallback types.
11-11
: LGTM: getDiag function type annotation is correct.
The function signature accurately represents the parameter and return types.
45-45
: LGTM: stripChangingData function type annotation is accurate.
The function signature correctly indicates it takes a string and returns either null or string.
70-70
: LGTM: stripFullStack function type annotation is well-defined.
The function signature properly represents the string input and output types.
115-115
: LGTM: runProgram function type annotation is correct.
The function signature accurately represents the parameter types and void return type.
lib/test.d.ts (1)
1-234
: LGTM: Test class definition is comprehensive and well-typed.
The type definitions are thorough and align with the project's requirements. Previous discussions have confirmed the intentional use of specific type choices.
🧰 Tools
🪛 Biome (1.9.4)
[error] 112-112: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 126-126: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
[error] 192-192: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
[error] 198-198: Don't use '{}' as a type.
Prefer explicitly define the object shape. '{}' means "any non-nullable value".
(lint/complexity/noBannedTypes)
@@ -117,9 +139,11 @@ function createHarness(conf_) { | |||
|
|||
test.close = function () { results.close(); }; | |||
|
|||
// @ts-expect-error TODO FIXME: why is `test` not assignable to `Harness`??? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
The type error occurs because the test
function is missing required properties from Harness
type
Looking at the type definitions, Harness
is defined as typeof harnessFunction & {...}
, which means it must have both the function signature and additional properties. The error occurs because while the test
function has some properties added (_exitCode
, close
), it's missing other required properties from the Harness
type like run
, only
, _results
, and _tests
.
To fix this:
- Add all required properties from the
Harness
type to thetest
function - Or modify the type assertion to handle partial implementation
🔗 Analysis chain
Address the TODO comment regarding type compatibility.
The comment indicates that test
is not assignable to Harness
. This might indicate a structural incompatibility between the types that should be investigated.
Would you like help investigating and resolving the type compatibility issue?
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for the definition of Harness type and its usage
ast-grep --pattern $'interface Harness {
$$$
}'
Length of output: 50
Script:
#!/bin/bash
# Let's try different approaches to find Harness and test related code
# Search for Harness type/interface/class definition
rg -A 5 "(?:type|interface|class)\s+Harness"
# Search for the specific TODO comment and its context
rg -B 5 -A 5 "TODO FIXME: why is .test. not assignable to .Harness"
# Search for test variable declaration and usage
ast-grep --pattern "test = $_"
Length of output: 1518
Script:
#!/bin/bash
# Let's examine the test function definition and its properties
rg -B 10 -A 5 "function createHarness"
# Look for the harnessFunction type definition
rg -A 5 "harnessFunction"
# Check the test variable's type annotations
ast-grep --pattern "/** @type {$_} */"
Length of output: 2347
Normally I'd just push this commit up and publish it, but since
@types/tape
already exists, I thought this was worth a PR so others can double check me.