use oxc_allocator::Allocator;
use oxc_ast::ast::*;
use oxc_parser::Parser;
use oxc_span::{GetSpan, SourceType};
#[derive(Debug, Clone)]
pub struct BlockInfo {
pub index: usize,
pub span: (u32, u32),
pub name: String,
pub kind: BlockKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlockKind {
Block,
Statement,
}
#[derive(Debug, Clone)]
pub struct TestInfo {
pub index: usize,
pub span: (u32, u32),
pub name: String,
}
#[derive(Debug, Clone)]
pub enum SubtestDiscovery {
None,
Block(Vec<BlockInfo>),
NodeTest(Vec<TestInfo>),
}
pub fn sanitize_name(s: &str) -> String {
let mut result = String::new();
let mut last_was_underscore = false;
for c in s.chars() {
if c.is_alphanumeric() {
result.push(c.to_ascii_lowercase());
last_was_underscore = false;
} else if !last_was_underscore {
result.push('_');
last_was_underscore = true;
}
}
let result = result
.trim_start_matches('_')
.trim_end_matches('_')
.to_string();
if result.len() > 60 {
let mut end = 60;
while end > 0 && !result.is_char_boundary(end) {
end -= 1;
}
result[..end].to_string()
} else {
result
}
}
fn extract_preceding_comment(source: &str, span_start: u32) -> Option<String> {
let bytes = source.as_bytes();
let start = span_start as usize;
if start == 0 {
return None;
}
let mut pos = start;
while pos > 0 && (bytes[pos - 1] == b' ' || bytes[pos - 1] == b'\t' || bytes[pos - 1] == b'\r')
{
pos -= 1;
}
if pos > 0 && bytes[pos - 1] == b'\n' {
pos -= 1;
if pos > 0 && bytes[pos - 1] == b'\r' {
pos -= 1;
}
} else {
return None;
}
let line_end = pos;
while pos > 0 && bytes[pos - 1] != b'\n' {
pos -= 1;
}
let line_start = pos;
let line = &source[line_start..line_end];
let trimmed = line.trim();
if let Some(comment) = trimmed.strip_prefix("//") {
let comment = comment.trim();
if !comment.is_empty() {
return Some(comment.to_string());
}
}
None
}
fn uses_node_test(program: &Program) -> bool {
for stmt in &program.body {
match stmt {
Statement::ImportDeclaration(import) if import.source.value == "node:test" => {
return true;
}
Statement::VariableDeclaration(var_decl) => {
for decl in &var_decl.declarations {
if decl
.init
.as_ref()
.is_some_and(|init| is_require_node_test(init))
{
return true;
}
}
}
Statement::ExpressionStatement(expr_stmt) => {
if is_require_node_test(&expr_stmt.expression) {
return true;
}
if let Expression::AssignmentExpression(assign) = &expr_stmt.expression
&& is_require_node_test(&assign.right)
{
return true;
}
}
_ => {}
}
}
false
}
fn is_require_node_test(expr: &Expression) -> bool {
if let Expression::CallExpression(call) = expr
&& let Expression::Identifier(id) = &call.callee
&& id.name == "require"
&& let Some(Argument::StringLiteral(s)) = call.arguments.first()
{
return s.value == "node:test";
}
false
}
fn call_name<'a>(call: &'a CallExpression<'a>) -> Option<&'a str> {
if let Expression::Identifier(id) = &call.callee {
Some(id.name.as_str())
} else {
None
}
}
fn is_test_call_name(name: &str) -> bool {
name == "test" || name == "it"
}
fn is_suite_call_name(name: &str) -> bool {
name == "suite" || name == "describe"
}
fn is_test_or_suite_call(expr: &Expression) -> bool {
if let Expression::CallExpression(call) = expr
&& let Some(name) = call_name(call)
{
return is_test_call_name(name) || is_suite_call_name(name);
}
false
}
fn extract_callback_body<'a>(call: &'a CallExpression<'a>) -> Option<&'a FunctionBody<'a>> {
for arg in call.arguments.iter().rev() {
match arg {
Argument::FunctionExpression(function) => {
if let Some(body) = function.body.as_ref() {
return Some(body);
}
}
Argument::ArrowFunctionExpression(arrow) if !arrow.expression => {
return Some(&arrow.body);
}
_ => {}
}
}
None
}
fn build_test_info_from_call(index: usize, call: &CallExpression, span: (u32, u32)) -> TestInfo {
let name = extract_test_name(call)
.map(|n| sanitize_name(&n))
.unwrap_or_else(|| format!("test_{index:02}"));
let full_name = format!("test_{index:02}_{name}");
TestInfo {
index,
span,
name: full_name,
}
}
fn discover_top_level_suite_nested_tests(
call: &CallExpression,
index: &mut usize,
) -> Vec<TestInfo> {
let Some(body) = extract_callback_body(call) else {
return Vec::new();
};
let mut tests = Vec::new();
for stmt in &body.statements {
if let Statement::ExpressionStatement(expr_stmt) = stmt
&& let Expression::CallExpression(nested_call) = &expr_stmt.expression
&& let Some(name) = call_name(nested_call)
&& is_test_call_name(name)
{
tests.push(build_test_info_from_call(
*index,
nested_call,
(expr_stmt.span.start, expr_stmt.span.end),
));
*index += 1;
}
}
tests
}
fn extract_test_name(call: &CallExpression) -> Option<String> {
if let Some(arg) = call.arguments.first() {
match arg {
Argument::StringLiteral(s) => return Some(s.value.to_string()),
Argument::TemplateLiteral(t) if t.expressions.is_empty() && !t.quasis.is_empty() => {
let value = t
.quasis
.iter()
.map(|q| q.value.raw.as_str())
.collect::<String>();
if !value.is_empty() {
return Some(value);
}
}
_ => {}
}
}
None
}
pub fn discover_subtests(path: &str, source: &str) -> SubtestDiscovery {
discover_subtests_with_options(path, source, false, false)
}
pub fn discover_subtests_with_options(
path: &str,
source: &str,
nested_node_test: bool,
isolate_top_level_expressions: bool,
) -> SubtestDiscovery {
let source_type = if path.ends_with(".mjs") {
SourceType::mjs()
} else {
SourceType::cjs()
};
let allocator = Allocator::default();
let ret = Parser::new(&allocator, source, source_type).parse();
let program = &ret.program;
if uses_node_test(program) {
let mut tests = Vec::new();
let mut index = 0;
for stmt in &program.body {
if let Statement::ExpressionStatement(expr_stmt) = stmt
&& let Expression::CallExpression(call) = &expr_stmt.expression
&& is_test_or_suite_call(&expr_stmt.expression)
{
if nested_node_test
&& let Some(name) = call_name(call)
&& is_suite_call_name(name)
{
let nested_tests = discover_top_level_suite_nested_tests(call, &mut index);
if nested_tests.is_empty() {
tests.push(build_test_info_from_call(
index,
call,
(expr_stmt.span.start, expr_stmt.span.end),
));
index += 1;
} else {
tests.extend(nested_tests);
}
} else {
tests.push(build_test_info_from_call(
index,
call,
(expr_stmt.span.start, expr_stmt.span.end),
));
index += 1;
}
}
}
if tests.len() < 2 {
SubtestDiscovery::None
} else {
SubtestDiscovery::NodeTest(tests)
}
} else {
let mut blocks = Vec::new();
let mut index = 0;
for stmt in &program.body {
let (span, kind, fallback_name) = if let Statement::BlockStatement(block) = stmt {
(block.span, BlockKind::Block, "block")
} else if isolate_top_level_expressions && !preserve_top_level_statement(stmt) {
(stmt.span(), BlockKind::Statement, "statement")
} else {
continue;
};
let comment = extract_preceding_comment(source, span.start);
let name = comment
.map(|c| sanitize_name(&c))
.filter(|s| !s.is_empty())
.unwrap_or_else(|| format!("{fallback_name}_{index:02}"));
let full_name = format!("block_{index:02}_{name}");
blocks.push(BlockInfo {
index,
span: (span.start, span.end),
name: full_name,
kind,
});
index += 1;
}
if blocks.len() < 2 {
SubtestDiscovery::None
} else {
SubtestDiscovery::Block(blocks)
}
}
}
pub fn rewrite_for_block(source: &str, blocks: &[BlockInfo], target_index: usize) -> String {
rewrite_for_block_with_options(source, blocks, target_index, false)
}
pub fn rewrite_for_block_with_options(
source: &str,
blocks: &[BlockInfo],
target_index: usize,
isolate_top_level_expressions: bool,
) -> String {
let bytes = source.as_bytes();
let mut edits: Vec<(usize, usize)> = Vec::new();
for block in blocks {
if block.index != target_index {
let start = block.span.0 as usize;
let end = block.span.1 as usize;
if start >= bytes.len() || end > bytes.len() {
eprintln!(
"WARNING: Block {} span ({},{}) is invalid, skipping rewrite",
block.index, start, end
);
continue;
}
match block.kind {
BlockKind::Block => {
if bytes[start] != b'{' || end == 0 || bytes[end - 1] != b'}' {
eprintln!(
"WARNING: Block {} span ({},{}) does not point at braces, skipping rewrite",
block.index, start, end
);
continue;
}
let inner_start = start + 1;
let inner_end = end - 1;
if inner_start < inner_end {
edits.push((inner_start, inner_end));
}
}
BlockKind::Statement if isolate_top_level_expressions => {
edits.push((start, end));
}
BlockKind::Statement => {}
}
}
}
edits.sort_by_key(|(start, _)| *start);
let mut result = bytes.to_vec();
for (start, end) in edits.into_iter().rev() {
if start < end && end <= result.len() {
result.splice(start..end, std::iter::once(b' '));
}
}
String::from_utf8(result).expect("UTF-8 source remained valid after block rewrite")
}
fn preserve_top_level_statement(stmt: &Statement) -> bool {
match stmt {
Statement::ImportDeclaration(_)
| Statement::VariableDeclaration(_)
| Statement::FunctionDeclaration(_)
| Statement::ClassDeclaration(_) => true,
Statement::ExpressionStatement(expr_stmt) => {
matches!(&expr_stmt.expression, Expression::StringLiteral(_))
}
_ => false,
}
}
pub fn rewrite_for_node_test(source: &str, tests: &[TestInfo], target_index: usize) -> String {
let bytes = source.as_bytes();
let mut result = bytes.to_vec();
for test in tests.iter().rev() {
if test.index != target_index {
let start = test.span.0 as usize;
let end = test.span.1 as usize;
if start >= bytes.len() || end > bytes.len() || start >= end {
eprintln!(
"WARNING: node:test span ({},{}) is invalid, skipping rewrite",
start, end
);
continue;
}
result.splice(start..end, std::iter::once(b' '));
}
}
String::from_utf8(result).expect("UTF-8 source remained valid after node:test rewrite")
}