Skip to main content

rust_anything/ts/
exports.rs

1//! Exported functions of a TS/JS file, with their parameter and return types as written.
2
3use oxc_allocator::Allocator;
4use oxc_ast::ast::{
5    BindingPattern, Declaration, Expression, FormalParameters, Statement, TSTypeAnnotation,
6};
7use oxc_parser::Parser;
8use oxc_span::{GetSpan, SourceType};
9use serde::{Deserialize, Serialize};
10
11use super::jsdoc::{self, JsDoc, ParamTag};
12
13#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
14pub struct Param {
15    pub name: String,
16    /// The type in the TS-like dialect; `unknown` when there is no annotation.
17    pub ts_type: String,
18    pub optional: bool,
19    pub rest: bool,
20    /// The default value as written in the source, when the language has defaults.
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub default: Option<String>,
23    /// Python keyword-only parameter (after `*`).
24    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
25    pub keyword_only: bool,
26    /// The exact source type, for languages whose bridge must match it (C: `size_t`).
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub native_type: Option<String>,
29}
30
31#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
32pub struct ExportedFn {
33    pub name: String,
34    /// Source file, relative to the repository root.
35    pub file: String,
36    pub line: u32,
37    pub params: Vec<Param>,
38    /// The TS return type as written; `unknown` when there is no annotation.
39    pub returns: String,
40    pub is_async: bool,
41    #[serde(default)]
42    pub is_generator: bool,
43    /// Names of the function's own type parameters (`T` in `f<T>(x: T)`).
44    #[serde(default)]
45    pub type_params: Vec<String>,
46    /// The body checks `instanceof`: class identity, which does not survive a bridge.
47    #[serde(default)]
48    pub uses_instanceof: bool,
49    /// Why the function must stay in its language, found by the language plugin.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub blocker: Option<String>,
52    /// The exact source return type (C: `unsigned long`).
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub native_return: Option<String>,
55    /// The declaration as written (C: `int word_count(const char *text)`).
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub prototype: Option<String>,
58}
59
60/// An exported class: its constructor and public instance methods, or why it must stay in TS.
61#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
62pub struct ExportedClass {
63    pub name: String,
64    pub file: String,
65    pub line: u32,
66    pub constructor: Vec<Param>,
67    pub methods: Vec<ExportedFn>,
68    /// Set when the class cannot cross a bridge as it is (inheritance, public fields, ...).
69    pub blocker: Option<String>,
70}
71
72/// Top-level `export class` declarations.
73pub fn exported_classes(path: &str, source: &str) -> Vec<ExportedClass> {
74    use oxc_ast::ast::{ClassElement, MethodDefinitionKind, TSAccessibility};
75    let source_type = SourceType::from_path(path).unwrap_or_else(|_| SourceType::ts());
76    let allocator = Allocator::default();
77    let ret = Parser::new(&allocator, source, source_type).parse();
78    let text = |span: oxc_span::Span| source[span.start as usize..span.end as usize].to_string();
79    let line = |offset: u32| {
80        u32::try_from(source[..offset as usize].matches('\n').count() + 1).unwrap_or(u32::MAX)
81    };
82    let annotation = |ann: Option<&TSTypeAnnotation>| {
83        ann.map_or_else(|| "unknown".to_string(), |a| text(a.type_annotation.span()))
84    };
85    let params_of = |params: &FormalParameters| -> Vec<Param> {
86        params
87            .items
88            .iter()
89            .enumerate()
90            .map(|(i, p)| Param {
91                name: binding_name(&p.pattern).unwrap_or_else(|| format!("arg{i}")),
92                ts_type: annotation(p.type_annotation.as_deref()),
93                optional: p.optional || p.initializer.is_some(),
94                rest: false,
95                ..Default::default()
96            })
97            .collect()
98    };
99    let mut out = Vec::new();
100    for statement in &ret.program.body {
101        let Statement::ExportDeclaration(export) = statement else {
102            continue;
103        };
104        let Declaration::ClassDeclaration(class) = &export.declaration else {
105            continue;
106        };
107        let Some(id) = &class.id else { continue };
108        let mut blockers: Vec<String> = Vec::new();
109        if class.heritage.is_some() {
110            blockers.push("extends another class".into());
111        }
112        let mut constructor = Vec::new();
113        let mut methods = Vec::new();
114        for element in &class.body.body {
115            match element {
116                ClassElement::MethodDefinition(m) => {
117                    let hidden = m.key.is_private_identifier()
118                        || matches!(
119                            m.accessibility,
120                            Some(TSAccessibility::Private | TSAccessibility::Protected)
121                        );
122                    let name = m
123                        .key
124                        .static_name()
125                        .and_then(|n| n.as_str().map(str::to_string));
126                    match m.kind {
127                        MethodDefinitionKind::Constructor => {
128                            constructor = params_of(&m.value.params);
129                            // `constructor(public data)`: a parameter property is a public field.
130                            if m.value.params.items.iter().any(|p| {
131                                matches!(p.accessibility, Some(TSAccessibility::Public))
132                                    || (p.readonly && p.accessibility.is_none())
133                            }) {
134                                blockers.push("public parameter properties".into());
135                            }
136                        }
137                        _ if hidden => {}
138                        MethodDefinitionKind::Get | MethodDefinitionKind::Set => {
139                            blockers.push(format!("accessor `{}`", name.unwrap_or_default()));
140                        }
141                        MethodDefinitionKind::Method if m.r#static => {
142                            blockers.push(format!("static method `{}`", name.unwrap_or_default()));
143                        }
144                        MethodDefinitionKind::Method => {
145                            let Some(name) = name else {
146                                blockers.push("computed method name".into());
147                                continue;
148                            };
149                            let f = &m.value;
150                            methods.push(ExportedFn {
151                                name,
152                                file: path.to_string(),
153                                line: line(m.span.start),
154                                params: params_of(&f.params),
155                                returns: annotation(f.return_type.as_deref()),
156                                is_async: f.r#async,
157                                is_generator: f.generator,
158                                type_params: Vec::new(),
159                                uses_instanceof: uses_instanceof(&text(m.span)),
160                                ..Default::default()
161                            });
162                        }
163                    }
164                }
165                ClassElement::PropertyDefinition(p) => {
166                    let hidden = p.key.is_private_identifier()
167                        || matches!(
168                            p.accessibility,
169                            Some(TSAccessibility::Private | TSAccessibility::Protected)
170                        );
171                    if !hidden {
172                        let name = p
173                            .key
174                            .static_name()
175                            .and_then(|n| n.as_str().map(str::to_string))
176                            .unwrap_or_default();
177                        blockers.push(format!("public field `{name}`"));
178                    }
179                }
180                ClassElement::AccessorProperty(_) => blockers.push("accessor property".into()),
181                ClassElement::StaticBlock(_) => blockers.push("static block".into()),
182                ClassElement::TSIndexSignature(_) => {}
183            }
184        }
185        let name = id.name.as_str().to_string();
186        for m in &methods {
187            if m.is_async || m.is_generator {
188                blockers.push(format!("async or generator method `{}`", m.name));
189            }
190            let returns_self = m
191                .returns
192                .split(|c: char| !(c.is_alphanumeric() || c == '_'))
193                .any(|w| w == name || w == "this");
194            if returns_self {
195                blockers.push(format!("method `{}` returns an instance", m.name));
196            }
197        }
198        out.push(ExportedClass {
199            name,
200            file: path.to_string(),
201            line: line(class.span.start),
202            constructor,
203            methods,
204            blocker: (!blockers.is_empty()).then(|| blockers.join(", ")),
205        });
206    }
207    out
208}
209
210/// Top-level `export function f()` and `export const f = () => ...` declarations.
211pub fn exported_functions(path: &str, source: &str) -> Vec<ExportedFn> {
212    functions(path, source, false)
213}
214
215pub fn declared_functions(path: &str, source: &str) -> Vec<ExportedFn> {
216    functions(path, source, true)
217}
218
219fn functions(path: &str, source: &str, declarations: bool) -> Vec<ExportedFn> {
220    let source_type = SourceType::from_path(path).unwrap_or_else(|_| SourceType::ts());
221    let allocator = Allocator::default();
222    let ret = Parser::new(&allocator, source, source_type).parse();
223    let text = |span: oxc_span::Span| source[span.start as usize..span.end as usize].to_string();
224    let annotation = |ann: Option<&TSTypeAnnotation>| {
225        ann.map_or_else(|| "unknown".to_string(), |a| text(a.type_annotation.span()))
226    };
227    let line = |offset: u32| {
228        u32::try_from(source[..offset as usize].matches('\n').count() + 1).unwrap_or(u32::MAX)
229    };
230    let params = |params: &FormalParameters, doc: &JsDoc| -> Vec<Param> {
231        let mut out: Vec<Param> = params
232            .items
233            .iter()
234            .enumerate()
235            .map(|(i, p)| {
236                let name = binding_name(&p.pattern).unwrap_or_else(|| format!("arg{i}"));
237                let tag = doc.param(&name);
238                let documented = tag.and_then(|t| t.ts_type.clone());
239                Param {
240                    ts_type: match (&p.type_annotation, documented, p.initializer.as_deref()) {
241                        (Some(a), _, _) => annotation(Some(a)),
242                        (None, Some(t), _) => t,
243                        // `namespaced = true`: the type comes from the default value.
244                        (None, None, Some(Expression::BooleanLiteral(_))) => "boolean".into(),
245                        (None, None, Some(Expression::NumericLiteral(_))) => "number".into(),
246                        (
247                            None,
248                            None,
249                            Some(Expression::StringLiteral(_) | Expression::TemplateLiteral(_)),
250                        ) => "string".into(),
251                        (None, None, _) => "unknown".into(),
252                    },
253                    optional: p.optional
254                        || p.initializer.is_some()
255                        || (p.type_annotation.is_none() && tag.is_some_and(|t| t.optional)),
256                    rest: false,
257                    name,
258                    ..Default::default()
259                }
260            })
261            .collect();
262        if let Some(rest) = &params.rest {
263            let name = binding_name(&rest.rest.argument).unwrap_or_else(|| "rest".into());
264            let ts_type = match (&rest.type_annotation, doc.param(&name)) {
265                (
266                    None,
267                    Some(ParamTag {
268                        ts_type: Some(t), ..
269                    }),
270                ) => t.clone(),
271                (ann, _) => annotation(ann.as_deref()),
272            };
273            out.push(Param {
274                name,
275                ts_type,
276                optional: true,
277                rest: true,
278                ..Default::default()
279            });
280        }
281        out
282    };
283    let returns_of = |ann: Option<&TSTypeAnnotation>, doc: &JsDoc| match (ann, &doc.returns) {
284        (None, Some(t)) => t.clone(),
285        (ann, _) => annotation(ann),
286    };
287
288    let function_entry = |f: &oxc_ast::ast::Function, doc: &JsDoc, exported: Option<String>| {
289        let id = f.id.as_ref()?;
290        Some(ExportedFn {
291            name: exported.unwrap_or_else(|| id.name.as_str().to_string()),
292            file: path.to_string(),
293            line: line(f.span.start),
294            params: params(&f.params, doc),
295            returns: returns_of(f.return_type.as_deref(), doc),
296            is_async: f.r#async,
297            is_generator: f.generator,
298            type_params: type_params_of(f.type_parameters.as_deref(), &text),
299            uses_instanceof: uses_instanceof(&text(f.span)),
300            ..Default::default()
301        })
302    };
303    let declarator_entry =
304        |declarator: &oxc_ast::ast::VariableDeclarator, doc: &JsDoc, exported: Option<String>| {
305            let name = binding_name(&declarator.id)?;
306            let type_names =
307                |tp: Option<&oxc_ast::ast::TSTypeParameterDeclaration>| type_params_of(tp, &text);
308            let (fn_params, returns, is_async, is_generator, span, type_params) =
309                match &declarator.init {
310                    Some(Expression::ArrowFunctionExpression(f)) => (
311                        &f.params,
312                        f.return_type.as_deref(),
313                        f.r#async,
314                        false,
315                        f.span,
316                        type_names(f.type_parameters.as_deref()),
317                    ),
318                    Some(Expression::FunctionExpression(f)) => (
319                        &f.params,
320                        f.return_type.as_deref(),
321                        f.r#async,
322                        f.generator,
323                        f.span,
324                        type_names(f.type_parameters.as_deref()),
325                    ),
326                    _ => return None,
327                };
328            Some(ExportedFn {
329                name: exported.unwrap_or(name),
330                file: path.to_string(),
331                line: line(span.start),
332                params: params(fn_params, doc),
333                returns: returns_of(returns, doc),
334                is_async,
335                is_generator,
336                type_params,
337                uses_instanceof: uses_instanceof(&text(span)),
338                ..Default::default()
339            })
340        };
341
342    let mut out = Vec::new();
343    let mut local = std::collections::HashMap::new();
344    let mut listed = Vec::new();
345    for statement in &ret.program.body {
346        let doc = jsdoc::leading(source, statement.span().start as usize).unwrap_or_default();
347        match statement {
348            Statement::ExportDeclaration(export) => match &export.declaration {
349                // Overload signatures have no body: the implementation signature follows them.
350                Declaration::FunctionDeclaration(f) if f.body.is_some() != declarations => {
351                    out.extend(function_entry(f, &doc, None));
352                }
353                Declaration::VariableDeclaration(vars) if !declarations => {
354                    for declarator in &vars.declarations {
355                        out.extend(declarator_entry(declarator, &doc, None));
356                    }
357                }
358                _ => {}
359            },
360            Statement::ExportNamedDeclaration(export)
361                if !declarations && !export.export_kind.is_type() =>
362            {
363                for spec in &export.specifiers {
364                    if !spec.export_kind.is_type() {
365                        listed.push((
366                            spec.local.name().to_string(),
367                            spec.exported.name().to_string(),
368                        ));
369                    }
370                }
371            }
372            Statement::ExpressionStatement(e) if !declarations => {
373                listed.extend(commonjs_exports(&e.expression));
374            }
375            Statement::FunctionDeclaration(f) if f.body.is_some() => {
376                if let Some(id) = &f.id {
377                    local.insert(id.name.as_str().to_string(), (Local::Function(f), doc));
378                }
379            }
380            Statement::VariableDeclaration(vars) => {
381                for declarator in &vars.declarations {
382                    if let Some(name) = binding_name(&declarator.id) {
383                        local.insert(name, (Local::Declarator(declarator), doc.clone()));
384                    }
385                }
386            }
387            _ => {}
388        }
389    }
390    for (name, exported) in listed {
391        match local.get(&name) {
392            Some((Local::Function(f), doc)) => out.extend(function_entry(f, doc, Some(exported))),
393            Some((Local::Declarator(d), doc)) => {
394                out.extend(declarator_entry(d, doc, Some(exported)));
395            }
396            None => {}
397        }
398    }
399    out
400}
401
402fn commonjs_exports(expression: &Expression) -> Vec<(String, String)> {
403    let Expression::AssignmentExpression(assign) = expression else {
404        return Vec::new();
405    };
406    let is_module_exports = |e: &Expression| {
407        matches!(e, Expression::StaticMemberExpression(m)
408            if m.property.name == "exports"
409                && matches!(&m.object, Expression::Identifier(o) if o.name == "module"))
410    };
411    let target = match &assign.left {
412        oxc_ast::ast::AssignmentTarget::StaticMemberExpression(m) => {
413            if m.property.name == "exports"
414                && matches!(&m.object, Expression::Identifier(o) if o.name == "module")
415            {
416                None
417            } else if is_module_exports(&m.object)
418                || matches!(&m.object, Expression::Identifier(o) if o.name == "exports")
419            {
420                Some(m.property.name.to_string())
421            } else {
422                return Vec::new();
423            }
424        }
425        _ => return Vec::new(),
426    };
427    match (target, &assign.right) {
428        (Some(exported), Expression::Identifier(local)) => {
429            vec![(local.name.to_string(), exported)]
430        }
431        (None, Expression::ObjectExpression(object)) => object
432            .properties
433            .iter()
434            .filter_map(|p| match p {
435                oxc_ast::ast::ObjectPropertyKind::ObjectProperty(prop) if !prop.computed => {
436                    let exported = match &prop.key {
437                        oxc_ast::ast::PropertyKey::StaticIdentifier(id) => id.name.to_string(),
438                        oxc_ast::ast::PropertyKey::StringLiteral(s) => {
439                            s.value.as_str()?.to_string()
440                        }
441                        _ => return None,
442                    };
443                    match &prop.value {
444                        Expression::Identifier(local) => Some((local.name.to_string(), exported)),
445                        _ => None,
446                    }
447                }
448                _ => None,
449            })
450            .collect(),
451        _ => Vec::new(),
452    }
453}
454
455enum Local<'b, 'a> {
456    Function(&'b oxc_ast::ast::Function<'a>),
457    Declarator(&'b oxc_ast::ast::VariableDeclarator<'a>),
458}
459
460/// Type parameters as `T`, or `T extends <constraint>` when constrained.
461fn type_params_of(
462    tp: Option<&oxc_ast::ast::TSTypeParameterDeclaration>,
463    text: &dyn Fn(oxc_span::Span) -> String,
464) -> Vec<String> {
465    tp.map(|tp| {
466        tp.params
467            .iter()
468            .map(|p| match &p.constraint {
469                Some(c) => format!("{} extends {}", p.name.name.as_str(), text(c.span())),
470                None => p.name.name.as_str().to_string(),
471            })
472            .collect()
473    })
474    .unwrap_or_default()
475}
476
477fn uses_instanceof(code: &str) -> bool {
478    code.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
479        .any(|word| word == "instanceof")
480}
481
482/// A top-level interface or type alias.
483#[derive(Clone, Debug, PartialEq, Eq)]
484pub struct LocalType {
485    pub name: String,
486    /// The whole interface, or the right-hand side of a type alias.
487    pub text: String,
488    /// A type alias without type parameters: its uses can be replaced by `text`.
489    pub alias: bool,
490}
491
492/// Interfaces and type aliases declared at the top level of a file.
493pub fn local_types(path: &str, source: &str) -> Vec<LocalType> {
494    let source_type = SourceType::from_path(path).unwrap_or_else(|_| SourceType::ts());
495    let allocator = Allocator::default();
496    let ret = Parser::new(&allocator, source, source_type).parse();
497    let text = |span: oxc_span::Span| source[span.start as usize..span.end as usize].to_string();
498    let mut out = Vec::new();
499    for statement in &ret.program.body {
500        let declaration = match statement {
501            Statement::ExportDeclaration(export) => &export.declaration,
502            Statement::TSInterfaceDeclaration(_) | Statement::TSTypeAliasDeclaration(_) => {
503                match statement.as_declaration() {
504                    Some(d) => d,
505                    None => continue,
506                }
507            }
508            _ => continue,
509        };
510        match declaration {
511            Declaration::TSInterfaceDeclaration(d) => out.push(LocalType {
512                name: d.id.name.as_str().to_string(),
513                text: text(d.span),
514                alias: false,
515            }),
516            Declaration::TSTypeAliasDeclaration(d) => out.push(LocalType {
517                name: d.id.name.as_str().to_string(),
518                text: text(d.type_annotation.span()),
519                alias: d.type_parameters.is_none(),
520            }),
521            _ => {}
522        }
523    }
524    out
525}
526
527fn binding_name(pattern: &BindingPattern) -> Option<String> {
528    match pattern {
529        BindingPattern::BindingIdentifier(id) => Some(id.name.as_str().to_string()),
530        _ => None,
531    }
532}
533
534#[cfg(test)]
535mod tests {
536    use super::*;
537
538    #[test]
539    fn reads_function_and_arrow_exports() {
540        let found = exported_functions(
541            "a.ts",
542            "export function score(query: string, text: string): number { return 1 }\n\
543             export const words = (text: string, ...extra: string[]): string[] => []\n\
544             export async function load(path?: string, strict = false) {}\n\
545             function hidden() {}\n\
546             export const value = 1\n",
547        );
548        let names: Vec<&str> = found.iter().map(|f| f.name.as_str()).collect();
549        assert_eq!(names, ["score", "words", "load"]);
550        assert_eq!(found[0].params[1].ts_type, "string");
551        assert_eq!(found[0].returns, "number");
552        assert_eq!(found[1].line, 2);
553        assert!(found[1].params[1].rest);
554        assert!(found[2].is_async && found[2].params[0].optional);
555        assert_eq!(
556            (
557                found[2].params[1].ts_type.as_str(),
558                found[2].params[1].optional
559            ),
560            ("boolean", true)
561        );
562        assert_eq!(found[2].returns, "unknown");
563    }
564
565    #[test]
566    fn reads_jsdoc_types_of_untyped_parameters() {
567        let found = exported_functions(
568            "m.js",
569            "/**\n * @param {string} source\n * @param {?number} [limit]\n * @returns {string[]}\n */\n\
570             export function parse(source, limit = 0) { return [] }\n\
571             /** @param {...string} parts */\n\
572             export const join = (...parts) => parts.join('')\n\
573             /** @param {function(string): number} f */\n\
574             export function apply(f, n = 1) {}\n",
575        );
576        let types = |i: usize| -> Vec<(&str, bool)> {
577            found[i]
578                .params
579                .iter()
580                .map(|p| (p.ts_type.as_str(), p.optional))
581                .collect()
582        };
583        assert_eq!(types(0), [("string", false), ("(number) | null", true)]);
584        assert_eq!(found[0].returns, "string[]");
585        assert_eq!(types(1), [("(string)[]", true)]);
586        assert_eq!(found[1].returns, "unknown");
587        assert_eq!(types(2), [("unknown", false), ("number", true)]);
588    }
589
590    #[test]
591    fn reads_classes() {
592        let classes = exported_classes(
593            "a.ts",
594            "export class Counter {\n  private lines: string[] = []\n  #seen = 0\n  constructor(initial: string, private readonly sep = '\\n') {}\n\
595             add(text: string): number { return 1 }\n  private hidden(): void {}\n  values(): string[] { return [] }\n}\n\
596             export class Box extends Counter { get size(): number { return 1 } static of(): Box { return new Box('') } }\n\
597             export class Point { x = 1\n  constructor(public y: number) {}\n  clone(): Point { return this } }\n",
598        );
599        assert_eq!(classes.len(), 3);
600        let counter = &classes[0];
601        assert_eq!(counter.blocker, None);
602        assert_eq!(counter.constructor.len(), 2);
603        assert_eq!(
604            counter
605                .methods
606                .iter()
607                .map(|m| m.name.as_str())
608                .collect::<Vec<_>>(),
609            ["add", "values"]
610        );
611        let blocked = classes[1].blocker.as_deref().unwrap();
612        assert!(
613            blocked.contains("extends")
614                && blocked.contains("accessor")
615                && blocked.contains("static")
616        );
617        let point = classes[2].blocker.as_deref().unwrap();
618        assert!(
619            point.contains("public field `x`")
620                && point.contains("parameter properties")
621                && point.contains("returns an instance")
622        );
623    }
624
625    #[test]
626    fn notices_instanceof() {
627        let found = exported_functions(
628            "a.ts",
629            "export function isErr(e: unknown): boolean { return e instanceof Error }\n\
630             export const plain = (instanceofCount: number): number => instanceofCount\n",
631        );
632        assert!(found[0].uses_instanceof);
633        assert!(!found[1].uses_instanceof);
634    }
635
636    #[test]
637    fn reads_local_types() {
638        let types = local_types(
639            "a.ts",
640            "export interface LineIndex { readonly line: (n: number) => string }\ntype Id = string\n",
641        );
642        let names: Vec<&str> = types.iter().map(|t| t.name.as_str()).collect();
643        assert_eq!(names, ["LineIndex", "Id"]);
644        assert!(types[0].text.contains("=>") && !types[0].alias);
645        assert_eq!((types[1].text.as_str(), types[1].alias), ("string", true));
646    }
647
648    #[test]
649    fn reads_export_lists() {
650        let found = exported_functions(
651            "a.js",
652            "function printDoc(doc, options) { return doc }\n\
653             const width = (text) => text.length\n\
654             function hidden() {}\n\
655             const value = 1\n\
656             export { printDoc, width as getWidth, value };\n",
657        );
658        let names: Vec<&str> = found.iter().map(|f| f.name.as_str()).collect();
659        assert_eq!(names, ["printDoc", "getWidth"]);
660        assert_eq!(found[0].params.len(), 2);
661        assert_eq!(found[1].line, 2);
662    }
663
664    #[test]
665    fn reads_commonjs_exports() {
666        let found = exported_functions(
667            "a.js",
668            "\"use strict\";\n\
669             async function lintText(args, text) { return text }\n\
670             const width = (text) => text.length\n\
671             function helper() {}\n\
672             const value = 1\n\
673             module.exports = { lintText, getWidth: width, value, other: () => 1 };\n\
674             module.exports.helper = helper;\n",
675        );
676        let names: Vec<&str> = found.iter().map(|f| f.name.as_str()).collect();
677        assert_eq!(names, ["lintText", "getWidth", "helper"]);
678        assert!(found[0].is_async);
679        assert_eq!(found[0].params.len(), 2);
680        let exported = exported_functions("b.js", "function f(a) {}\nexports.f = f;\n");
681        assert_eq!(exported.len(), 1);
682        assert!(exported_functions("c.js", "function f() {}\nfoo.exports = { f };\n").is_empty());
683    }
684}