Skip to main content

fallow_extract/
graphql.rs

1//! GraphQL document parsing.
2//!
3//! Supports the widely-used `#import "./fragment.graphql"` convention by
4//! turning relative document imports into side-effect module edges.
5
6use std::path::Path;
7use std::sync::LazyLock;
8
9use oxc_span::Span;
10
11use crate::{ImportInfo, ImportedName, ModuleInfo};
12use fallow_types::discover::FileId;
13
14static GRAPHQL_IMPORT_RE: LazyLock<regex::Regex> =
15    LazyLock::new(|| crate::static_regex(r#"(?m)^[ \t]*#\s*import\s+["']([^"'\r\n]+)["']"#));
16
17pub(crate) fn is_graphql_file(path: &Path) -> bool {
18    path.extension()
19        .and_then(|e| e.to_str())
20        .is_some_and(|ext| ext == "graphql" || ext == "gql")
21}
22
23fn is_relative_graphql_import(source: &str) -> bool {
24    source.starts_with("./") || source.starts_with("../")
25}
26
27#[expect(
28    clippy::cast_possible_truncation,
29    reason = "source spans are bounded by source file size, which is practically below u32::MAX"
30)]
31fn span_from_usize(start: usize, end: usize) -> Span {
32    Span::new(start as u32, end as u32)
33}
34
35#[must_use]
36pub(crate) fn extract_graphql_imports(source: &str) -> Vec<ImportInfo> {
37    let mut imports = Vec::new();
38
39    for cap in GRAPHQL_IMPORT_RE.captures_iter(source) {
40        let Some(source_match) = cap.get(1) else {
41            continue;
42        };
43        let import_source = source_match.as_str().trim();
44        if import_source.is_empty() || !is_relative_graphql_import(import_source) {
45            continue;
46        }
47
48        imports.push(ImportInfo {
49            source: import_source.to_string(),
50            imported_name: ImportedName::SideEffect,
51            local_name: String::new(),
52            is_type_only: false,
53            from_style: false,
54            span: cap
55                .get(0)
56                .map_or_else(Span::default, |m| span_from_usize(m.start(), m.end())),
57            source_span: span_from_usize(source_match.start(), source_match.end()),
58        });
59    }
60
61    imports.sort_unstable_by(|a, b| {
62        a.source
63            .cmp(&b.source)
64            .then(a.source_span.start.cmp(&b.source_span.start))
65    });
66    imports.dedup_by(|a, b| a.source == b.source);
67    imports
68}
69
70pub(crate) fn parse_graphql_to_module(
71    file_id: FileId,
72    source: &str,
73    content_hash: u64,
74) -> ModuleInfo {
75    let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
76    ModuleInfo {
77        file_id,
78        exports: Vec::new(),
79        imports: extract_graphql_imports(source),
80        re_exports: Vec::new(),
81        dynamic_imports: Vec::new(),
82        dynamic_import_patterns: Vec::new(),
83        require_calls: Vec::new(),
84        member_accesses: Vec::new(),
85        whole_object_uses: Vec::new(),
86        has_cjs_exports: false,
87        has_angular_component_template_url: false,
88        content_hash,
89        suppressions: parsed_suppressions.suppressions,
90        unknown_suppression_kinds: parsed_suppressions.unknown_kinds,
91        unused_import_bindings: Vec::new(),
92        type_referenced_import_bindings: Vec::new(),
93        value_referenced_import_bindings: Vec::new(),
94        line_offsets: fallow_types::extract::compute_line_offsets(source),
95        complexity: Vec::new(),
96        flag_uses: Vec::new(),
97        class_heritage: Vec::new(),
98        local_type_declarations: Vec::new(),
99        public_signature_type_references: Vec::new(),
100        namespace_object_aliases: Vec::new(),
101        iconify_prefixes: Vec::new(),
102        auto_import_candidates: Vec::new(),
103        directives: Vec::new(),
104        security_sinks: Vec::new(),
105        security_sinks_skipped: 0,
106        tainted_bindings: Vec::new(),
107        sanitized_sink_args: Vec::new(),
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    #[test]
116    fn graphql_file_extensions_are_supported() {
117        assert!(is_graphql_file(Path::new("schema.graphql")));
118        assert!(is_graphql_file(Path::new("fragment.gql")));
119        assert!(!is_graphql_file(Path::new("query.ts")));
120    }
121
122    #[test]
123    fn extracts_relative_hash_imports() {
124        let imports = extract_graphql_imports(
125            r#"
126            #import "./content.graphql"
127            # import '../shared/leaf.gql'
128            #import "package/schema.graphql"
129            fragment Story on Story { id }
130            "#,
131        );
132
133        let sources: Vec<&str> = imports
134            .iter()
135            .map(|import| import.source.as_str())
136            .collect();
137        assert_eq!(sources, vec!["../shared/leaf.gql", "./content.graphql"]);
138        assert!(
139            imports
140                .iter()
141                .all(|import| matches!(import.imported_name, ImportedName::SideEffect))
142        );
143    }
144
145    #[test]
146    fn parse_graphql_to_module_sets_imports_and_offsets() {
147        let info = parse_graphql_to_module(
148            FileId(7),
149            "#import \"./content.graphql\"\nfragment Story on Story { id }\n",
150            42,
151        );
152
153        assert_eq!(info.file_id, FileId(7));
154        assert_eq!(info.content_hash, 42);
155        assert_eq!(info.imports.len(), 1);
156        assert_eq!(info.imports[0].source, "./content.graphql");
157        assert_eq!(info.line_offsets, vec![0, 28, 59]);
158    }
159}