Skip to main content

rust_anything/ts/
mod.rs

1//! The TypeScript/JavaScript language plugin: discovery, parsing and the npm crate table.
2
3pub mod deps;
4pub mod discover;
5pub mod exports;
6pub mod jsdoc;
7pub mod scan;
8pub mod shape;
9pub mod tsconfig;
10
11/// The code of a file as TS: the file itself, or only the `<script>` blocks of a
12/// `.vue`/`.svelte`/`.astro` component. Text outside scripts becomes blank lines so
13/// reported line numbers stay right.
14pub fn script_of(path: &str, text: &str) -> String {
15    let is_sfc = [".vue", ".svelte", ".astro"]
16        .iter()
17        .any(|ext| path.ends_with(ext));
18    if !is_sfc {
19        return text.to_string();
20    }
21    let mut out = String::with_capacity(text.len());
22    let mut rest = text;
23    while let Some(open) = rest.find("<script") {
24        out.extend(rest[..open].chars().filter(|&c| c == '\n'));
25        let after_open = &rest[open..];
26        let Some(tag_end) = after_open.find('>') else {
27            break;
28        };
29        out.extend(after_open[..=tag_end].chars().filter(|&c| c == '\n'));
30        let body = &after_open[tag_end + 1..];
31        let close = body.find("</script>").unwrap_or(body.len());
32        out.push_str(&body[..close]);
33        // Two blocks on one line (`<script>a</script><script>b</script>`) must not glue their
34        // bodies together, and a newline here would push every later block down a line: a space
35        // keeps them apart on the line they are already on.
36        if !body[..close].ends_with('\n') {
37            out.push(' ');
38        }
39        rest = &body[close..];
40        rest = rest.strip_prefix("</script>").unwrap_or(rest);
41    }
42    out
43}
44
45#[cfg(test)]
46mod tests {
47    use super::script_of;
48
49    #[test]
50    fn keeps_only_scripts_with_line_numbers() {
51        let sfc = "<template>\n<div/>\n</template>\n<script setup lang=\"ts\">\nimport x from './x'\n</script>\n";
52        let script = script_of("App.vue", sfc);
53        assert_eq!(script.lines().nth(4), Some("import x from './x'"));
54    }
55
56    #[test]
57    fn a_second_block_stays_on_its_own_lines() {
58        let sfc = "<script context=\"module\">\nexport const a = 1\n</script>\n<script>\nlet b = 2\n</script>\n";
59        let script = script_of("App.svelte", sfc);
60        assert_eq!(script.lines().nth(1), Some("export const a = 1"));
61        assert_eq!(script.lines().nth(4), Some("let b = 2"), "{script:?}");
62    }
63
64    #[test]
65    fn two_blocks_on_one_line_do_not_glue_their_bodies() {
66        let script = script_of("App.svelte", "<script>a</script><script>b</script>");
67        assert!(!script.contains("ab"), "{script:?}");
68        assert_eq!(script.lines().count(), 1, "{script:?}");
69    }
70}