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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
test_r::enable!();

#[allow(dead_code)]
#[path = "common/mod.rs"]
mod common;

use crate::common::js_subtest_parser::{
    SubtestDiscovery, discover_subtests, discover_subtests_with_options,
};
use crate::common::strip_jsonc_comments;
use serde_json::Value;
use std::collections::BTreeSet;
use std::fs;
use test_r::test;

/// Find the byte span (start, end) of a JSON object value for a given key in JSONC text.
/// Returns the byte range of the value object `{...}` (inclusive of braces).
/// Handles JSONC line/block comments and nested objects.
fn find_value_span(content: &str, key: &str) -> Option<(usize, usize)> {
    let search = format!("\"{}\"", key);
    let key_pos = content.find(&search)?;
    let bytes = content.as_bytes();
    let mut pos = key_pos + search.len();

    // Skip whitespace
    while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
        pos += 1;
    }
    // Expect ':'
    if pos >= bytes.len() || bytes[pos] != b':' {
        return None;
    }
    pos += 1;
    // Skip whitespace
    while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
        pos += 1;
    }
    if pos >= bytes.len() || bytes[pos] != b'{' {
        return None;
    }

    let value_start = pos;
    let mut depth = 0;
    let mut in_string = false;

    while pos < bytes.len() {
        if in_string {
            if bytes[pos] == b'\\' && pos + 1 < bytes.len() {
                pos += 2;
                continue;
            }
            if bytes[pos] == b'"' {
                in_string = false;
            }
        } else {
            match bytes[pos] {
                b'"' => in_string = true,
                b'{' => depth += 1,
                b'}' => {
                    depth -= 1;
                    if depth == 0 {
                        return Some((value_start, pos + 1));
                    }
                }
                b'/' if pos + 1 < bytes.len() && bytes[pos + 1] == b'/' => {
                    pos += 2;
                    while pos < bytes.len() && bytes[pos] != b'\n' {
                        pos += 1;
                    }
                    continue;
                }
                b'/' if pos + 1 < bytes.len() && bytes[pos + 1] == b'*' => {
                    pos += 2;
                    while pos + 1 < bytes.len() && !(bytes[pos] == b'*' && bytes[pos + 1] == b'/') {
                        pos += 1;
                    }
                    if pos + 1 < bytes.len() {
                        pos += 2;
                    }
                    continue;
                }
                _ => {}
            }
        }
        pos += 1;
    }

    None
}

/// Find the byte position of the closing '}' of the "tests" object in JSONC content.
fn find_tests_object_close(content: &str) -> Option<usize> {
    let tests_key = "\"tests\"";
    let key_pos = content.find(tests_key)?;
    let bytes = content.as_bytes();
    let mut pos = key_pos + tests_key.len();

    // Skip to ':'
    while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
        pos += 1;
    }
    if pos >= bytes.len() || bytes[pos] != b':' {
        return None;
    }
    pos += 1;
    // Skip to '{'
    while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
        pos += 1;
    }
    if pos >= bytes.len() || bytes[pos] != b'{' {
        return None;
    }

    let mut depth = 0;
    let mut in_string = false;

    while pos < bytes.len() {
        if in_string {
            if bytes[pos] == b'\\' && pos + 1 < bytes.len() {
                pos += 2;
                continue;
            }
            if bytes[pos] == b'"' {
                in_string = false;
            }
        } else {
            match bytes[pos] {
                b'"' => in_string = true,
                b'{' => depth += 1,
                b'}' => {
                    depth -= 1;
                    if depth == 0 {
                        return Some(pos);
                    }
                }
                b'/' if pos + 1 < bytes.len() && bytes[pos + 1] == b'/' => {
                    pos += 2;
                    while pos < bytes.len() && bytes[pos] != b'\n' {
                        pos += 1;
                    }
                    continue;
                }
                b'/' if pos + 1 < bytes.len() && bytes[pos + 1] == b'*' => {
                    pos += 2;
                    while pos + 1 < bytes.len() && !(bytes[pos] == b'*' && bytes[pos + 1] == b'/') {
                        pos += 1;
                    }
                    if pos + 1 < bytes.len() {
                        pos += 2;
                    }
                    continue;
                }
                _ => {}
            }
        }
        pos += 1;
    }

    None
}

/// Escape a string for embedding in a JSON string literal.
fn escape_json(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
        .replace('\t', "\\t")
}

/// Format a split entry value (the part after `"key": `).
fn format_split_value(
    skip: bool,
    reason: &str,
    subtests: &[(String, bool, String)], // (name, skip, reason)
) -> String {
    let mut lines = Vec::new();
    lines.push("{".to_string());

    if skip {
        lines.push("      \"skip\": true,".to_string());
        if !reason.is_empty() {
            lines.push(format!("      \"reason\": \"{}\",", escape_json(reason)));
        }
    }

    lines.push("      \"split\": true,".to_string());
    lines.push("      \"subtests\": {".to_string());

    for (i, (name, sub_skip, sub_reason)) in subtests.iter().enumerate() {
        let comma = if i + 1 < subtests.len() { "," } else { "" };
        if *sub_skip {
            lines.push(format!(
                "        \"{}\": {{ \"skip\": true, \"reason\": \"{}\" }}{}",
                escape_json(name),
                escape_json(sub_reason),
                comma
            ));
        } else {
            lines.push(format!("        \"{}\": {{}}{}", escape_json(name), comma));
        }
    }

    lines.push("      }".to_string());
    lines.push("    }".to_string());
    lines.join("\n")
}

/// Build subtests list from discovery, inheriting skip/reason from file level.
fn build_subtests(
    discovery: &SubtestDiscovery,
    file_skip: bool,
    file_reason: &str,
) -> Vec<(String, bool, String)> {
    let names: Vec<String> = match discovery {
        SubtestDiscovery::None => return Vec::new(),
        SubtestDiscovery::Block(blocks) => blocks.iter().map(|b| b.name.clone()).collect(),
        SubtestDiscovery::NodeTest(tests) => tests.iter().map(|t| t.name.clone()).collect(),
    };

    names
        .into_iter()
        .map(|name| {
            if file_skip {
                let reason = if file_reason.is_empty() {
                    "inherited".to_string()
                } else {
                    format!("inherited: {}", file_reason)
                };
                (name, true, reason)
            } else {
                (name, false, String::new())
            }
        })
        .collect()
}

/// Build merged subtests from discovery, preserving existing skip/reason for subtests
/// that still exist in the new discovery.
fn build_merged_subtests(
    discovery: &SubtestDiscovery,
    existing_subtests: &serde_json::Map<String, Value>,
    file_skip: bool,
    file_reason: &str,
) -> Vec<(String, bool, String)> {
    let names: Vec<String> = match discovery {
        SubtestDiscovery::None => return Vec::new(),
        SubtestDiscovery::Block(blocks) => blocks.iter().map(|b| b.name.clone()).collect(),
        SubtestDiscovery::NodeTest(tests) => tests.iter().map(|t| t.name.clone()).collect(),
    };

    names
        .into_iter()
        .map(|name| {
            if let Some(existing) = existing_subtests.get(&name) {
                // Preserve existing skip/reason
                let skip = existing
                    .get("skip")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                let reason = existing
                    .get("reason")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                (name, skip, reason)
            } else if file_skip {
                let reason = if file_reason.is_empty() {
                    "inherited".to_string()
                } else {
                    format!("inherited: {}", file_reason)
                };
                (name, true, reason)
            } else {
                (name, false, String::new())
            }
        })
        .collect()
}

/// Format a non-split entry value.
fn format_unsplit_value(skip: bool, reason: &str) -> String {
    if skip {
        if reason.is_empty() {
            "{ \"skip\": true }".to_string()
        } else {
            format!(
                "{{ \"skip\": true, \"reason\": \"{}\" }}",
                escape_json(reason)
            )
        }
    } else {
        "{}".to_string()
    }
}

/// Extract discovered subtest names as a BTreeSet.
fn discovered_names(discovery: &SubtestDiscovery) -> BTreeSet<String> {
    match discovery {
        SubtestDiscovery::None => BTreeSet::new(),
        SubtestDiscovery::Block(blocks) => blocks.iter().map(|b| b.name.clone()).collect(),
        SubtestDiscovery::NodeTest(tests) => tests.iter().map(|t| t.name.clone()).collect(),
    }
}

/// Discover all `.js` test files from vendored suite directories.
/// Matches the approach used by the config report generator.
fn discover_suite_files() -> BTreeSet<String> {
    let suites = ["parallel", "sequential", "es-module"];
    let mut files = BTreeSet::new();

    for suite in &suites {
        let suite_dir = format!("tests/node_compat/suite/{suite}");
        let suite_path = std::path::Path::new(&suite_dir);
        if !suite_path.exists() {
            eprintln!("Suite directory {suite_dir} not found, skipping");
            continue;
        }
        if let Ok(entries) = fs::read_dir(&suite_dir) {
            for entry in entries.flatten() {
                let name = entry.file_name().to_string_lossy().to_string();
                if name.ends_with(".js") {
                    files.insert(format!("{suite}/{name}"));
                }
            }
        }
    }

    files
}

#[test]
fn migrate_config_split() {
    let config_path = "tests/node_compat/config.jsonc";
    let content = fs::read_to_string(config_path).expect("Failed to read config.jsonc");
    let json_str = strip_jsonc_comments(&content);
    let config: Value = serde_json::from_str(&json_str).expect("Failed to parse config");

    let tests_obj = config
        .get("tests")
        .and_then(|v| v.as_object())
        .expect("config.jsonc missing 'tests' object");

    let existing_keys: BTreeSet<String> = tests_obj.keys().cloned().collect();

    // Discover all .js files from suite directories
    let all_suite_files = discover_suite_files();
    let new_files: Vec<String> = all_suite_files
        .difference(&existing_keys)
        .cloned()
        .collect();

    let mut modified_content = content.clone();
    let mut split_count = 0;
    let mut update_count = 0;
    let mut unsplit_count = 0;
    let mut total_subtests = 0;
    let mut new_count = 0;
    let mut new_split_count = 0;
    let empty_map = serde_json::Map::new();

    // Phase 1: Split new entries and update stale split entries
    let mut split_updates: Vec<(String, String)> = Vec::new();

    for (test_path, opts) in tests_obj.iter() {
        let is_split = opts.get("split").and_then(|v| v.as_bool()).unwrap_or(false);

        let suite_file = format!("tests/node_compat/suite/{}", test_path);
        let source = match fs::read_to_string(&suite_file) {
            Ok(s) => s,
            Err(_) => {
                eprintln!("Skipping {}: file not found", test_path);
                continue;
            }
        };

        let nested_node_test = opts
            .get("nestedNodeTest")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let isolate_block_subtests = opts
            .get("isolateBlockSubtests")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let discovery = discover_subtests_with_options(
            test_path,
            &source,
            nested_node_test,
            isolate_block_subtests,
        );
        let file_skip = opts.get("skip").and_then(|v| v.as_bool()).unwrap_or(false);
        let file_reason = opts.get("reason").and_then(|v| v.as_str()).unwrap_or("");

        if is_split {
            // Check if subtests need updating
            let existing_subtests = opts
                .get("subtests")
                .and_then(|v| v.as_object())
                .unwrap_or(&empty_map);
            let existing_names: BTreeSet<String> = existing_subtests.keys().cloned().collect();
            let disc_names = discovered_names(&discovery);

            if existing_names == disc_names {
                continue; // No change needed
            }

            if disc_names.len() < 2 {
                // Discovery no longer warrants split, convert back to unsplit
                let new_value = format_unsplit_value(file_skip, file_reason);
                split_updates.push((test_path.clone(), new_value));
                unsplit_count += 1;
            } else {
                // Update split with merged subtests, preserving existing skip/reason
                let subtests =
                    build_merged_subtests(&discovery, existing_subtests, file_skip, file_reason);
                let new_value = format_split_value(file_skip, file_reason, &subtests);
                split_updates.push((test_path.clone(), new_value));
                update_count += 1;
                total_subtests += subtests.len();
            }
        } else {
            let subtests = build_subtests(&discovery, file_skip, file_reason);
            if subtests.len() < 2 {
                continue;
            }

            let new_value = format_split_value(file_skip, file_reason, &subtests);
            split_updates.push((test_path.clone(), new_value));
            split_count += 1;
            total_subtests += subtests.len();
        }
    }

    // Apply split updates in reverse order of position to preserve byte offsets
    let mut positioned_updates: Vec<(usize, usize, String)> = Vec::new();
    for (key, new_value) in &split_updates {
        if let Some((start, end)) = find_value_span(&modified_content, key) {
            positioned_updates.push((start, end, new_value.clone()));
        } else {
            eprintln!("WARNING: Could not find value span for key: {}", key);
        }
    }
    positioned_updates.sort_by_key(|b| std::cmp::Reverse(b.0)); // reverse order preserves offsets

    for (start, end, new_value) in positioned_updates {
        modified_content.replace_range(start..end, &new_value);
    }

    // Phase 2: Insert new entries before the closing '}' of the tests object
    if !new_files.is_empty() {
        let close_pos = find_tests_object_close(&modified_content)
            .expect("Could not find closing brace of tests object");

        // Split content at the tests object closing brace
        let prefix = &modified_content[..close_pos];
        let suffix = &modified_content[close_pos..]; // starts with '}'

        // Check if the last existing entry needs a trailing comma
        let trimmed_prefix = prefix.trim_end();
        let needs_comma = !trimmed_prefix.ends_with(',') && !trimmed_prefix.ends_with('{');

        let mut new_section = String::new();

        if needs_comma {
            // Insert comma right after the last entry value
            // We append it to trimmed_prefix and then re-add the whitespace
            new_section.push(',');
        }

        new_section.push_str("\n\n    // === newly discovered tests (not yet evaluated) ===");

        for test_path in &new_files {
            let suite_file = format!("tests/node_compat/suite/{}", test_path);
            let source = match fs::read_to_string(&suite_file) {
                Ok(s) => s,
                Err(_) => {
                    eprintln!("Skipping new file {}: could not read", test_path);
                    continue;
                }
            };

            let discovery = discover_subtests(test_path, &source);
            let subtests = build_subtests(&discovery, true, "newly discovered, not yet evaluated");

            if subtests.len() >= 2 {
                let value =
                    format_split_value(true, "newly discovered, not yet evaluated", &subtests);
                new_section.push_str(&format!("\n    \"{}\": {},", test_path, value));
                total_subtests += subtests.len();
                new_split_count += 1;
            } else {
                new_section.push_str(&format!(
                    "\n    \"{}\": {{ \"skip\": true, \"reason\": \"newly discovered, not yet evaluated\" }},",
                    test_path
                ));
            }
            new_count += 1;
        }

        // Remove trailing comma from the very last new entry
        if new_section.ends_with(',') {
            new_section.pop();
        }

        new_section.push_str("\n  "); // indentation before closing '}'

        // Reconstruct: trimmed prefix + new section + suffix
        modified_content = format!("{}{}{}", trimmed_prefix, new_section, suffix);
    }

    // Write back
    fs::write(config_path, &modified_content).expect("Failed to write config.jsonc");

    println!("Migration complete:");
    println!("  Existing files split: {}", split_count);
    println!("  Existing splits updated: {}", update_count);
    println!("  Existing splits unsplit: {}", unsplit_count);
    println!(
        "  New files added: {} ({} with splits)",
        new_count, new_split_count
    );
    println!("  Total subtests discovered: {}", total_subtests);
    println!("  Config written to: {}", config_path);
}