wasm-rquickjs-cli 0.5.3

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use oxc_allocator::Allocator;
use oxc_ast::ast::*;
use oxc_parser::Parser;
use oxc_span::{GetSpan, SourceType};

/// Info about a top-level block or executable statement.
#[derive(Debug, Clone)]
pub struct BlockInfo {
    pub index: usize,
    /// End-exclusive byte span: (start, end).
    pub span: (u32, u32),
    pub name: String,
    pub kind: BlockKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlockKind {
    Block,
    Statement,
}

/// Info about a top-level `test('name', fn)` call.
#[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>),
}

/// Sanitize a string to a valid Rust identifier fragment.
/// Non-alphanumeric → `_`, lowercase, collapse consecutive `_`, truncate at 60 chars.
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
    }
}

/// Extract a comment from the line immediately preceding a block statement.
/// Looks backward from span_start in the source bytes for a `//` comment on the preceding line.
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;
    }

    // Skip backwards past any whitespace to find end of preceding line
    let mut pos = start;
    while pos > 0 && (bytes[pos - 1] == b' ' || bytes[pos - 1] == b'\t' || bytes[pos - 1] == b'\r')
    {
        pos -= 1;
    }
    // We should now be at a newline or at content
    if pos > 0 && bytes[pos - 1] == b'\n' {
        pos -= 1;
        if pos > 0 && bytes[pos - 1] == b'\r' {
            pos -= 1;
        }
    } else {
        return None;
    }

    // Now find the start of this preceding line
    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
}

/// Check if the AST imports or requires 'node:test'.
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"
}

/// Check if an expression is a discoverable node:test call.
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
}

/// Extract test name from a test() call's first argument.
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
}

/// Discover subtests in a JS source file.
///
/// - `path`: file path (used to determine SourceType: .js → CJS, .mjs → ESM)
/// - `source`: the JS source code
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)
        }
    }
}

/// Rewrite source to run only `target_index`, emptying all other top-level
/// blocks.  Top-level non-block code is always preserved.
/// Processes in reverse order to preserve byte offsets.
pub fn rewrite_for_block(source: &str, blocks: &[BlockInfo], target_index: usize) -> String {
    rewrite_for_block_with_options(source, blocks, target_index, false)
}

/// Rewrite source to run only `target_index`.
///
/// With `isolate_top_level_expressions`, non-declaration top-level executable
/// statements are also removed. This is useful for legacy block-split fixtures
/// that contain top-level IIFEs before the discoverable blocks.
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,
    }
}

/// Rewrite source to keep only the targeted discovered node:test call.
///
/// Non-target discovered calls are blanked by span in reverse order to
/// preserve offsets while keeping unrelated top-level code intact.
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")
}