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 scan;
7pub mod shape;
8pub mod tsconfig;
9
10/// The code of a file as TS: the file itself, or only the `<script>` blocks of a
11/// `.vue`/`.svelte`/`.astro` component. Text outside scripts becomes blank lines so
12/// reported line numbers stay right.
13pub fn script_of(path: &str, text: &str) -> String {
14    let is_sfc = [".vue", ".svelte", ".astro"]
15        .iter()
16        .any(|ext| path.ends_with(ext));
17    if !is_sfc {
18        return text.to_string();
19    }
20    let mut out = String::with_capacity(text.len());
21    let mut rest = text;
22    while let Some(open) = rest.find("<script") {
23        out.extend(rest[..open].chars().filter(|&c| c == '\n'));
24        let after_open = &rest[open..];
25        let Some(tag_end) = after_open.find('>') else {
26            break;
27        };
28        out.extend(after_open[..=tag_end].chars().filter(|&c| c == '\n'));
29        let body = &after_open[tag_end + 1..];
30        let close = body.find("</script>").unwrap_or(body.len());
31        out.push_str(&body[..close]);
32        out.push('\n');
33        rest = &body[close..];
34        rest = rest.strip_prefix("</script>").unwrap_or(rest);
35    }
36    out
37}
38
39#[cfg(test)]
40mod tests {
41    use super::script_of;
42
43    #[test]
44    fn keeps_only_scripts_with_line_numbers() {
45        let sfc = "<template>\n<div/>\n</template>\n<script setup lang=\"ts\">\nimport x from './x'\n</script>\n";
46        let script = script_of("App.vue", sfc);
47        assert_eq!(script.lines().nth(4), Some("import x from './x'"));
48    }
49}