fallow-core 3.43.0

Internal detector backend for fallow-engine and fallow-api
Documentation
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
//! Put the value of a local binding of a config callback in the values that
//! the callback returns.
//!
//! A config file can export a function that builds its value in local
//! bindings: `const common = {...}; const web = { ...common, entry }; return
//! [web];`. The config walkers read literal objects only. This pass replaces
//! each returned identifier, each array element and property value that names
//! a local, and each object spread of a local with a copy of the literal value
//! of that local. It never runs the code of the config.
//!
//! The pass ignores the order of the statements. A returned value that names a
//! local declared after the `return` fails at run time, but this pass reads the
//! value of the local.

use oxc_allocator::{Allocator, CloneIn};
use oxc_ast::ast::*;
use rustc_hash::{FxHashMap, FxHashSet};

use super::const_inline::{Inliner, constant_values, literal_value, stable_values};
use super::{
    MAX_CONFIG_BRANCH_DEPTH, MAX_CONFIG_WRAPPER_DEPTH, extract_object_from_expression,
    is_module_exports_target,
};

/// The budget of the local pass, as a multiple of the source size. A config
/// that spreads one shared local into two configs copies that local twice.
const LOCAL_BUDGET_FACTOR: usize = 2;

/// Inline the stable locals of each exported config callback into the values
/// that the callback returns.
///
/// A local qualifies when a `const` or `let` statement at the callback body's
/// own level declares it with an object, array or string literal, and it is
/// the only binding of its name in the program, with no writes, no mutating
/// calls and no call that can change it. The stable top-level constants are
/// available too. The copied AST
/// nodes stay at or below `LOCAL_BUDGET_FACTOR` times `source_len`.
pub(super) fn inline_callback_locals<'a>(
    allocator: &'a Allocator,
    program: &mut Program<'a>,
    source_len: usize,
) {
    let Some(mut values) = callback_locals(allocator, program) else {
        return;
    };
    for (name, value) in constant_values(allocator, program) {
        values.entry(name).or_insert(value);
    }
    if values.is_empty() {
        return;
    }
    let mut inliner = Inliner::new(
        allocator,
        &values,
        source_len.saturating_mul(LOCAL_BUDGET_FACTOR),
    );
    for callback in config_callbacks(program) {
        callback.inline_returns(&mut inliner, &values);
    }
}

/// A copy of the literal value of each stable local of the config callbacks.
/// Returns `None` when the program exports no config callback.
fn callback_locals<'a>(
    allocator: &'a Allocator,
    program: &mut Program<'a>,
) -> Option<FxHashMap<String, Expression<'a>>> {
    let callbacks = config_callbacks(program);
    if callbacks.is_empty() {
        return None;
    }
    let mut candidates: Vec<(String, Expression<'a>)> = Vec::new();
    for callback in callbacks {
        let Callback::Body(body) = callback else {
            continue;
        };
        for statement in &body.statements {
            let Statement::VariableDeclaration(decl) = statement else {
                continue;
            };
            if !matches!(
                decl.kind,
                VariableDeclarationKind::Const | VariableDeclarationKind::Let
            ) {
                continue;
            }
            for declarator in &decl.declarations {
                let BindingPattern::BindingIdentifier(id) = &declarator.id else {
                    continue;
                };
                if let Some(value) = declarator.init.as_ref().and_then(literal_value) {
                    candidates.push((id.name.to_string(), value.clone_in(allocator)));
                }
            }
        }
    }
    if candidates.is_empty() {
        return Some(FxHashMap::default());
    }
    let stable: FxHashSet<String> = stable_values(
        program,
        candidates
            .iter()
            .map(|(name, value)| (name.as_str(), value)),
        false,
    )
    .into_iter()
    .map(str::to_string)
    .collect();
    Some(keep_stable(candidates, &stable))
}

/// The candidates whose name is in `stable`. A config callback can declare
/// many thousands of locals, so the lookup must be a hash lookup: a search
/// of a list compares each local with each stable name.
fn keep_stable<N: Eq + std::hash::Hash, V>(
    candidates: Vec<(N, V)>,
    stable: &FxHashSet<N>,
) -> FxHashMap<N, V> {
    candidates
        .into_iter()
        .filter(|(name, _)| stable.contains(name))
        .collect()
}

/// The body of a config callback: a function body, or the expression body of
/// an arrow.
enum Callback<'p, 'a> {
    Body(&'p mut FunctionBody<'a>),
    Expression(&'p mut Expression<'a>),
}

impl<'a> Callback<'_, 'a> {
    /// Inline the values that `find_config_object` and the multi-config reader
    /// can read as the returned config: the expression body of an arrow, or the
    /// argument of each `return` at the body's own level or in the bounded
    /// branch search. Returns of nested functions belong to those functions and
    /// stay out.
    ///
    /// `find_config_object` prefers an object that a top-level `return` gives
    /// over a branch return. A top-level `return base;` gave no object before
    /// this pass, so the search used the first branch return that gives an
    /// object. To keep that result, a returned identifier at the top level
    /// stays when a branch return gives an object after inlining. A returned
    /// array stays out of this rule: `find_config_object` never reads it, and
    /// the multi-config reader reads only top-level returns.
    fn inline_returns(
        self,
        inliner: &mut Inliner<'a, '_>,
        values: &FxHashMap<String, Expression<'a>>,
    ) {
        let body = match self {
            Callback::Body(body) => body,
            Callback::Expression(expr) => {
                inliner.inline_value(expr);
                return;
            }
        };
        let mut returns = Vec::new();
        collect_returns(
            &mut body.statements,
            MAX_CONFIG_BRANCH_DEPTH,
            true,
            &mut returns,
        );
        let (top_level, branches): (Vec<_>, Vec<_>) =
            returns.into_iter().partition(|ret| ret.top_level);
        let mut branch_gives_object = false;
        for ret in branches {
            inliner.inline_value(ret.value);
            branch_gives_object |= extract_object_from_expression(ret.value).is_some();
        }
        for ret in top_level {
            if branch_gives_object && names_a_non_array(ret.value, values) {
                continue;
            }
            inliner.inline_value(ret.value);
        }
    }
}

/// Whether `expr` is an identifier whose known value is not an array literal.
fn names_a_non_array(expr: &Expression<'_>, values: &FxHashMap<String, Expression<'_>>) -> bool {
    let Expression::Identifier(id) = expr.get_inner_expression() else {
        return false;
    };
    !values
        .get(id.name.as_str())
        .is_some_and(|value| matches!(value.get_inner_expression(), Expression::ArrayExpression(_)))
}

/// The config callbacks that the program exports, in the shapes that
/// `find_config_object` reads: an exported function or arrow, also as an
/// argument of an exported call such as `defineConfig(fn)`.
fn config_callbacks<'p, 'a>(program: &'p mut Program<'a>) -> Vec<Callback<'p, 'a>> {
    let mut callbacks = Vec::new();
    let mut exported_names = Vec::new();
    let mut declarations = Vec::new();
    for statement in &mut program.body {
        match statement {
            Statement::ExportDefaultDeclaration(decl) => match &mut decl.declaration {
                ExportDefaultDeclarationKind::FunctionDeclaration(func) => {
                    push_function(func, &mut callbacks);
                }
                kind => {
                    if let Some(expr) = kind.as_expression_mut() {
                        collect_exported(expr, &mut callbacks, &mut exported_names);
                    }
                }
            },
            Statement::ExpressionStatement(stmt) => {
                if let Expression::AssignmentExpression(assign) = &mut stmt.expression
                    && is_module_exports_target(&assign.left)
                {
                    collect_exported(&mut assign.right, &mut callbacks, &mut exported_names);
                }
            }
            Statement::VariableDeclaration(decl) => declarations.push(&mut **decl),
            Statement::ExportDeclaration(export) => {
                if let Declaration::VariableDeclaration(decl) = &mut export.declaration {
                    declarations.push(&mut **decl);
                }
            }
            _ => {}
        }
    }
    // `module.exports = config` reads the callback of one top-level binding,
    // as `find_config_object` does.
    for decl in declarations {
        for declarator in &mut decl.declarations {
            let BindingPattern::BindingIdentifier(id) = &declarator.id else {
                continue;
            };
            if !exported_names.iter().any(|name| name == id.name.as_str()) {
                continue;
            }
            if let Some(init) = &mut declarator.init {
                collect_callbacks(init, MAX_CONFIG_WRAPPER_DEPTH, &mut callbacks);
            }
        }
    }
    callbacks
}

/// Collect the callbacks of an exported expression, and the name of an
/// exported identifier such as `config` in `module.exports = config`.
fn collect_exported<'p, 'a>(
    expr: &'p mut Expression<'a>,
    callbacks: &mut Vec<Callback<'p, 'a>>,
    exported_names: &mut Vec<String>,
) {
    if let Expression::Identifier(id) = expr.get_inner_expression() {
        exported_names.push(id.name.to_string());
        return;
    }
    collect_callbacks(expr, MAX_CONFIG_WRAPPER_DEPTH, callbacks);
}

fn collect_callbacks<'p, 'a>(
    expr: &'p mut Expression<'a>,
    depth: u8,
    callbacks: &mut Vec<Callback<'p, 'a>>,
) {
    match expr {
        Expression::ParenthesizedExpression(paren) => {
            collect_callbacks(&mut paren.expression, depth, callbacks);
        }
        Expression::TSAsExpression(ts_as) => {
            collect_callbacks(&mut ts_as.expression, depth, callbacks);
        }
        Expression::TSSatisfiesExpression(ts_sat) => {
            collect_callbacks(&mut ts_sat.expression, depth, callbacks);
        }
        Expression::ArrowFunctionExpression(arrow) => match &mut arrow.body {
            ArrowFunctionBody::FunctionBody(body) => callbacks.push(Callback::Body(body)),
            body => {
                if let Some(expr) = body.as_expression_mut() {
                    callbacks.push(Callback::Expression(expr));
                }
            }
        },
        Expression::FunctionExpression(func) => push_function(func, callbacks),
        Expression::CallExpression(call) if depth > 0 => {
            for argument in &mut call.arguments {
                if let Some(expr) = argument.as_expression_mut() {
                    collect_callbacks(expr, depth - 1, callbacks);
                }
            }
        }
        _ => {}
    }
}

fn push_function<'p, 'a>(func: &'p mut Function<'a>, callbacks: &mut Vec<Callback<'p, 'a>>) {
    if func.generator {
        return;
    }
    if let Some(body) = &mut func.body {
        callbacks.push(Callback::Body(body));
    }
}

/// The argument of one `return`, and whether the `return` is at the body's own
/// level.
struct Returned<'p, 'a> {
    value: &'p mut Expression<'a>,
    top_level: bool,
}

/// The argument of each `return` in `statements`, through the same control
/// flow and depth as the returned-object search of `find_config_object`.
fn collect_returns<'p, 'a>(
    statements: &'p mut [Statement<'a>],
    depth: u8,
    top_level: bool,
    values: &mut Vec<Returned<'p, 'a>>,
) {
    if depth == 0 {
        return;
    }
    for statement in statements {
        match statement {
            Statement::ReturnStatement(ret) => {
                if let Some(value) = &mut ret.argument {
                    values.push(Returned { value, top_level });
                }
            }
            Statement::BlockStatement(block) => {
                collect_returns(&mut block.body, depth - 1, false, values);
            }
            Statement::IfStatement(if_stmt) => {
                let IfStatement {
                    consequent,
                    alternate,
                    ..
                } = &mut **if_stmt;
                collect_branch_returns(consequent, depth - 1, values);
                if let Some(alternate) = alternate {
                    collect_branch_returns(alternate, depth - 1, values);
                }
            }
            Statement::TryStatement(try_stmt) => {
                let TryStatement {
                    block,
                    handler,
                    finalizer,
                    ..
                } = &mut **try_stmt;
                collect_returns(&mut block.body, depth - 1, false, values);
                if let Some(handler) = handler {
                    collect_returns(&mut handler.body.body, depth - 1, false, values);
                }
                if let Some(finalizer) = finalizer {
                    collect_returns(&mut finalizer.body, depth - 1, false, values);
                }
            }
            Statement::SwitchStatement(switch) => {
                for case in &mut switch.cases {
                    collect_returns(&mut case.consequent, depth - 1, false, values);
                }
            }
            _ => {}
        }
    }
}

fn collect_branch_returns<'p, 'a>(
    statement: &'p mut Statement<'a>,
    depth: u8,
    values: &mut Vec<Returned<'p, 'a>>,
) {
    match statement {
        Statement::BlockStatement(block) => collect_returns(&mut block.body, depth, false, values),
        other => collect_returns(std::slice::from_mut(other), depth, false, values),
    }
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    use oxc_ast::ast::Program;

    use super::super::const_inline::{MAX_ALIAS_STEPS, take_alias_steps, take_name_visits};
    use super::super::{
        PathScope, extract_config_path_aliases, extract_config_string,
        extract_config_string_or_array, get_nested_string_from_object, get_nested_string_or_array,
        read_each_config, read_last_config,
    };

    fn js() -> &'static Path {
        Path::new("webpack.config.js")
    }

    fn aliases(source: &str) -> Vec<(String, PathBuf)> {
        extract_config_path_aliases(source, js(), &["resolve", "alias"])
    }

    #[derive(Default)]
    struct NodeCount(usize);

    impl<'a> oxc_ast_visit::Visit<'a> for NodeCount {
        fn enter_node(&mut self, _kind: oxc_ast::AstKind<'a>) {
            self.0 += 1;
        }
    }

    /// The number of AST nodes after both inline passes.
    fn inlined_node_count(source: &str) -> usize {
        super::super::extract_from_source(source, js(), |program| {
            let mut count = NodeCount::default();
            oxc_ast_visit::Visit::visit_program(&mut count, program);
            Some(count.0)
        })
        .expect("source parses")
    }

    #[test]
    fn copies_of_expanded_constants_stay_within_the_budget() {
        // The top-level pass expands `C` to 64 copies of `A`, but the source
        // of `C` stays short. Each pass charges a copy by its node count, so
        // the AST stays within the node budget of both passes.
        let props: Vec<String> = (0..50).map(|i| format!("p{i}: {i}")).collect();
        let eight = |name: &str| {
            (0..8)
                .map(|i| format!("k{i}: {name}"))
                .collect::<Vec<_>>()
                .join(", ")
        };
        let many_c = vec!["C"; 64].join(", ");
        let source = format!(
            "const A = {{ {props} }};\nconst B = {{ {b} }};\nconst C = {{ {c} }};\n\
             module.exports = () => ({{ entry: [{many_c}] }});\n/* {pad} */\n",
            props = props.join(", "),
            b = eight("A"),
            c = eight("B"),
            pad = "x".repeat(30_000),
        );
        let nodes = inlined_node_count(&source);
        assert!(
            nodes <= 4 * source.len(),
            "{nodes} nodes for a source of {} bytes",
            source.len()
        );
    }

    /// The work counts of one parse of `source`, with the value that `read`
    /// gets from the inlined program.
    struct Work<T> {
        value: T,
        name_visits: usize,
        alias_steps: usize,
    }

    /// Parse `source`, run both inline passes and `read` the program, and
    /// count the work. The counters are thread-local. A large source can
    /// parse on a new thread with a larger stack, so `read` takes the counts
    /// on the thread that ran the passes.
    fn count_work<T: Send>(source: &str, read: impl FnOnce(&Program<'_>) -> T + Send) -> Work<T> {
        take_name_visits();
        take_alias_steps();
        super::super::extract_from_source(source, js(), |program| {
            let value = read(program);
            Some(Work {
                value,
                name_visits: take_name_visits(),
                alias_steps: take_alias_steps(),
            })
        })
        .expect("source parses")
    }

    /// The number of identifiers that the stable filter reads for a config
    /// callback with `count` string locals.
    fn name_visits_for_callback_locals(count: usize) -> usize {
        let locals = (0..count)
            .map(|i| format!("const l{i} = \"x\";"))
            .collect::<Vec<_>>()
            .join("\n");
        let source = format!("module.exports = () => {{\n{locals}return {{ entry: l0 }};\n}};\n");
        let work = count_work(&source, |program| {
            read_last_config(program, &["entry"], get_nested_string_from_object)
        });
        assert_eq!(work.value, Some("x".to_string()));
        work.name_visits
    }

    #[test]
    fn many_callback_locals_stay_linear() {
        // The stable filter must not compare each local with each other one.
        // Linear work reads about twice the identifiers for twice the
        // locals. Work that compares each pair of locals reads four times.
        let small = name_visits_for_callback_locals(2_000);
        let large = name_visits_for_callback_locals(4_000);
        assert!(
            large <= small * 5 / 2,
            "2000 locals read {small} identifiers, 4000 locals read {large}"
        );
    }

    thread_local! {
        static COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    }

    /// A name that counts each equality comparison in [`COMPARISONS`].
    struct CountedName(String);

    impl std::hash::Hash for CountedName {
        fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
            self.0.hash(state);
        }
    }

    impl PartialEq for CountedName {
        fn eq(&self, other: &Self) -> bool {
            COMPARISONS.set(COMPARISONS.get() + 1);
            self.0 == other.0
        }
    }

    impl Eq for CountedName {}

    /// The number of name comparisons that the stable filter makes for
    /// `count` candidates, of which every second one is stable.
    fn stable_filter_comparisons(count: usize) -> usize {
        let name = |i: usize| CountedName(format!("l{i}"));
        let candidates = (0..count).map(|i| (name(i), i)).collect();
        let stable = (0..count).step_by(2).map(name).collect();
        COMPARISONS.set(0);
        let kept = super::keep_stable(candidates, &stable);
        assert_eq!(kept.len(), count.div_ceil(2));
        COMPARISONS.get()
    }

    #[test]
    fn stable_filter_compares_each_local_a_bounded_number_of_times() {
        // The identifier count of `many_callback_locals_stay_linear` does not
        // see the filter: a filter that searches a list of the stable names
        // reads no identifiers, but compares each local with each name.
        for count in [1_000, 8_000, 64_000] {
            let comparisons = stable_filter_comparisons(count);
            assert!(
                comparisons <= 2 * count,
                "{count} locals took {comparisons} comparisons"
            );
        }
    }

    /// A config whose array `h.k` holds `OPTS` `copies` times, with one
    /// change of `OPTS` through `h` for each of `writes` keys.
    fn many_alias_edges(copies: usize, writes: usize) -> String {
        let elements = vec!["OPTS"; copies].join(", ");
        let changes = (0..writes)
            .map(|i| format!("h.k[0].files.f{i} = 1;\n"))
            .collect::<Vec<_>>()
            .concat();
        format!(
            "const OPTS = {{ files: [\"./a.ts\"] }};\nconst h = {{ k: [{elements}] }};\n{changes}export default {{ x: OPTS }};\n"
        )
    }

    #[test]
    fn too_many_alias_edges_or_steps_stop_and_read_the_literal_value() {
        // More aliases than the edge limit.
        // More steps than the step limit: each write follows each alias.
        for source in [many_alias_edges(25_000, 1), many_alias_edges(10_000, 30)] {
            let work = count_work(&source, |program| {
                read_each_config(program, |obj| {
                    get_nested_string_or_array(obj, &["x", "files"], PathScope::Program(program))
                })
            });
            assert_eq!(work.value, Some(vec!["./a.ts".to_string()]));
            // The parse runs the alias analysis one time, and the analysis
            // stops at its limits.
            assert!(
                work.alias_steps <= MAX_ALIAS_STEPS,
                "{} alias steps, the limit of one analysis is {MAX_ALIAS_STEPS}",
                work.alias_steps
            );
        }
        // Below both limits, the change counts.
        let source = many_alias_edges(10_000, 5);
        assert!(extract_config_string_or_array(&source, js(), &["x", "files"]).is_empty());
    }

    #[test]
    fn many_aliases_still_find_a_change_through_the_last_one() {
        let aliases = (0..=4096)
            .map(|i| format!("const a{i} = OPTS.files;"))
            .collect::<Vec<_>>()
            .join("\n");
        let read = format!(
            "const OPTS = {{ files: [\"./a.ts\"] }};\n{aliases}\nexport default {{ x: OPTS }};\n"
        );
        assert_eq!(
            extract_config_string_or_array(&read, js(), &["x", "files"]),
            vec!["./a.ts"]
        );
        let changed = format!(
            "const OPTS = {{ files: [\"./a.ts\"] }};\n{aliases}\na4096.push(\"./b.ts\");\nexport default {{ x: OPTS }};\n"
        );
        assert!(extract_config_string_or_array(&changed, js(), &["x", "files"]).is_empty());
    }

    fn linkedom() -> Vec<(String, PathBuf)> {
        vec![(
            "linkedom".to_string(),
            PathBuf::from("./src/shims/linkedom.ts"),
        )]
    }

    #[test]
    fn returned_local_with_a_local_spread_resolves() {
        let source = r#"
            const path = require("path");
            module.exports = (env, argv) => {
                const common = { resolve: { alias: { linkedom: path.resolve(__dirname, "./src/shims/linkedom.ts") } } };
                const bg = { ...common, entry: "./src/bg.ts" };
                return bg;
            };
        "#;
        assert_eq!(aliases(source), linkedom());
        assert_eq!(
            extract_config_string_or_array(source, js(), &["entry"]),
            vec!["./src/bg.ts"]
        );
    }

    #[test]
    fn function_declaration_spread_of_a_local_resolves() {
        let source = r#"
            export default function (env) {
                const common = { resolve: { alias: { linkedom: "./src/shims/linkedom.ts" } } };
                return { ...common, entry: { main: "./src/main.ts" } };
            }
        "#;
        assert_eq!(aliases(source), linkedom());
        assert_eq!(
            extract_config_string_or_array(source, js(), &["entry"]),
            vec!["./src/main.ts"]
        );
    }

    #[test]
    fn arrow_expression_body_spread_of_a_top_level_constant_resolves() {
        let source = r#"
            const common = { resolve: { alias: { linkedom: "./src/shims/linkedom.ts" } } };
            module.exports = (env) => ({ ...common, entry: "./src/main.ts" });
        "#;
        assert_eq!(aliases(source), linkedom());
    }

    #[test]
    fn member_spread_keeps_the_last_value_of_a_key() {
        let source = r#"
            module.exports = () => {
                const common = { resolve: { alias: { a: "./a.ts" }, fallback: { fs: false } } };
                return {
                    resolve: { ...common.resolve, fallback: { ...common.resolve.fallback, net: false } },
                    other: { ...common.resolve, alias: { b: "./b.ts" } },
                };
            };
        "#;
        assert_eq!(
            extract_config_path_aliases(source, js(), &["resolve", "alias"]),
            vec![("a".to_string(), PathBuf::from("./a.ts"))]
        );
        assert_eq!(
            extract_config_path_aliases(source, js(), &["other", "alias"]),
            vec![("b".to_string(), PathBuf::from("./b.ts"))]
        );
    }

    #[test]
    fn spread_after_a_literal_key_overrides_that_key() {
        let source = r#"
            module.exports = () => {
                const common = { alias: { a: "./a.ts" } };
                return { resolve: { alias: { b: "./b.ts" }, ...common } };
            };
        "#;
        assert_eq!(
            aliases(source),
            vec![("a".to_string(), PathBuf::from("./a.ts"))]
        );
    }

    #[test]
    fn local_that_an_alias_or_object_assign_can_change_does_not_resolve() {
        let cases = [
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; Object.assign(common.resolve.alias, { a: "./b.ts" }); return common; };"#,
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; const { resolve } = common; resolve.alias.a = "./b.ts"; return common; };"#,
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; const r = common.resolve; r.alias.a = "./b.ts"; return common; };"#,
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; let r; r = common.resolve; r.alias.a = "./b.ts"; return common; };"#,
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; const r = common?.resolve; r.alias.a = "./b.ts"; return common; };"#,
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; const r = common.resolve; const q = r.alias; q.a = "./b.ts"; return common; };"#,
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; Object.defineProperty(common.resolve.alias, "a", { value: "./b.ts" }); return common; };"#,
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; Reflect.set(common.resolve.alias, "a", "./b.ts"); return common; };"#,
        ];
        for source in cases {
            assert!(aliases(source).is_empty(), "{source}");
        }
    }

    #[test]
    fn local_that_an_alias_only_reads_still_resolves() {
        let source = r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; const r = common.resolve; const n = r.alias.a.length; return common; };"#;
        assert_eq!(aliases(source).len(), 1, "{source}");
    }

    #[test]
    fn top_level_returned_local_does_not_hide_a_branch_return() {
        let source = r#"
            export default defineConfig(({ mode }) => {
                const base = { resolve: { conditions: ["x"] } };
                if (mode === "test") {
                    return { ...base, test: { setupFiles: ["./src/setup.ts"] } };
                }
                return base;
            });
        "#;
        let path = Path::new("vitest.config.ts");
        assert_eq!(
            extract_config_string_or_array(source, path, &["test", "setupFiles"]),
            vec!["./src/setup.ts"]
        );
        assert_eq!(
            extract_config_string_or_array(source, path, &["resolve", "conditions"]),
            vec!["x"]
        );
    }

    #[test]
    fn branch_return_without_an_object_keeps_the_top_level_returned_local() {
        let vite = r#"
            export default defineConfig(({ command }) => {
                const config = { test: { setupFiles: ["./src/setup.ts"] } };
                if (command === "serve") {
                    return mergeConfig(config, devOverrides);
                }
                return config;
            });
        "#;
        assert_eq!(
            extract_config_string_or_array(
                vite,
                Path::new("vite.config.ts"),
                &["test", "setupFiles"]
            ),
            vec!["./src/setup.ts"]
        );
        let webpack = r#"
            module.exports = (env) => {
                const config = { entry: "./src/main.ts" };
                if (!env) return null;
                return config;
            };
        "#;
        assert_eq!(
            extract_config_string(webpack, js(), &["entry"]),
            Some("./src/main.ts".to_string())
        );
    }

    #[test]
    fn branch_return_of_an_array_keeps_the_top_level_returned_array() {
        let source = r#"
            module.exports = (env) => {
                const a = { entry: "./src/a.ts" };
                const b = { entry: "./src/b.ts" };
                const all = [a, b];
                if (env.only) return [a];
                return all;
            };
        "#;
        let entries: Vec<_> =
            super::super::extract_each_config_entries(source, js(), &["entry"], "context")
                .into_iter()
                .flat_map(|(entries, _)| entries)
                .collect();
        assert_eq!(entries, vec!["./src/a.ts", "./src/b.ts"]);
    }

    #[test]
    fn branch_return_of_an_object_still_wins_over_a_returned_array_local() {
        // A top-level array never gives an object to `find_config_object`, so
        // the inlined array keeps the multi-config reader working.
        let source = r#"
            module.exports = (env) => {
                const a = { entry: "./src/a.ts" };
                const all = [a];
                if (env.single) return { entry: "./src/single.ts" };
                return all;
            };
        "#;
        assert_eq!(
            extract_config_string(source, js(), &["entry"]),
            Some("./src/single.ts".to_string())
        );
    }

    #[test]
    fn config_function_exported_through_a_binding_resolves_locals() {
        let cases = [
            r#"const config = (env) => { const common = { resolve: { alias: { linkedom: "./src/shims/linkedom.ts" } } }; return { ...common, entry: "./src/main.ts" }; }; module.exports = config;"#,
            r#"const config = function (env) { const common = { resolve: { alias: { linkedom: "./src/shims/linkedom.ts" } } }; return { ...common, entry: "./src/main.ts" }; }; export default config;"#,
        ];
        for source in cases {
            assert_eq!(aliases(source), linkedom(), "{source}");
            assert_eq!(
                extract_config_string(source, js(), &["entry"]),
                Some("./src/main.ts".to_string()),
                "{source}"
            );
        }
    }

    #[test]
    fn returned_top_level_constant_resolves_without_a_callback_local() {
        let cases = [
            r#"const base = { entry: "./src/main.ts" }; module.exports = () => { return base; };"#,
            r#"const base = { entry: "./src/main.ts" }; module.exports = () => base;"#,
        ];
        for source in cases {
            assert_eq!(
                extract_config_string(source, js(), &["entry"]),
                Some("./src/main.ts".to_string()),
                "{source}"
            );
        }
    }

    #[test]
    fn local_that_a_hidden_alias_or_a_call_can_change_does_not_resolve() {
        let entry_cases = [
            r#"module.exports = () => { const web = { entry: "./src/old.ts" }; for (const c of [web]) c.entry = "./src/new.ts"; return [web]; };"#,
            r#"module.exports = () => { const web = { entry: "./src/old.ts" }; const list = [web]; for (const c of list) c.entry = "./src/new.ts"; return [web]; };"#,
            r#"module.exports = () => { const web = { entry: "./src/old.ts" }; const configure = (cfg) => { cfg.entry = "./src/new.ts"; }; configure(web); return [web]; };"#,
            r#"module.exports = () => { const web = { entry: "./src/old.ts" }; const all = { web }; const configure = (holder) => { holder.web.entry = "./src/new.ts"; }; configure(all); return [web]; };"#,
            r#"module.exports = () => { const web = { entry: "./src/old.ts" }; globalThis.Object.assign(web, { entry: "./src/new.ts" }); return [web]; };"#,
        ];
        for source in entry_cases {
            let entries: Vec<_> =
                super::super::extract_each_config_entries(source, js(), &["entry"], "context")
                    .into_iter()
                    .flat_map(|(entries, _)| entries)
                    .collect();
            assert!(entries.is_empty(), "{source}: {entries:?}");
        }
        let alias_cases = [
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; let r; ({ resolve: r } = common); r.alias.a = "./b.ts"; return common; };"#,
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; const list = [common]; list[0].resolve.alias.a = "./b.ts"; return common; };"#,
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; const holder = { c: common }; holder.c.resolve.alias.a = "./b.ts"; return common; };"#,
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; const web = { ...common }; web.resolve.alias.a = "./b.ts"; return common; };"#,
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; const r = common.resolve; const configure = (resolve) => { resolve.alias.a = "./b.ts"; }; configure(r); return common; };"#,
        ];
        for source in alias_cases {
            assert!(aliases(source).is_empty(), "{source}");
        }
    }

    #[test]
    fn top_level_constant_that_an_imported_or_unknown_call_gets_still_resolves() {
        // Fallow counts only a change that the file shows. A call to a
        // function that the file does not define can change nothing that
        // fallow sees.
        let cases = [
            r#"const OPTS = { files: ["./a.ts"] }; configure(OPTS); export default { x: OPTS };"#,
            r#"const OPTS = { files: ["./a.ts"] }; new Mutator(OPTS); export default { x: OPTS };"#,
            r#"const { merge } = require("lodash"); const OPTS = { files: ["./a.ts"] }; merge(OPTS, {}); export default { x: OPTS };"#,
            r#"const { assign } = Object; const OPTS = { files: ["./a.ts"] }; assign(OPTS, {}); export default { x: OPTS };"#,
        ];
        for source in cases {
            assert_eq!(
                extract_config_string_or_array(
                    source,
                    Path::new("vitest.config.ts"),
                    &["x", "files"]
                ),
                vec!["./a.ts"],
                "{source}"
            );
        }
    }

    #[test]
    fn top_level_constant_that_a_local_function_changes_does_not_resolve() {
        let source = r#"const OPTS = { files: ["./a.ts"] }; function configure(o) { o.files.push("./b.ts"); } configure(OPTS); export default { x: OPTS };"#;
        assert!(
            extract_config_string_or_array(source, Path::new("vitest.config.ts"), &["x", "files"])
                .is_empty()
        );
    }

    #[test]
    fn constant_in_a_literal_argument_or_an_exported_call_still_resolves() {
        let path = Path::new("vitest.config.ts");
        let cases = [
            r#"import { defineVitestConfig } from "@nuxt/test-utils/config"; const setupFiles = ["./test/setup.ts"]; export default defineVitestConfig({ test: { setupFiles } });"#,
            r#"import { defineConfig } from "vitest/config"; import checker from "vite-plugin-checker"; const setupFiles = ["./test/setup.ts"]; export default defineConfig({ plugins: [checker({ files: setupFiles })], test: { setupFiles } });"#,
        ];
        for source in cases {
            assert_eq!(
                extract_config_string_or_array(source, path, &["test", "setupFiles"]),
                vec!["./test/setup.ts"],
                "{source}"
            );
        }
    }

    #[test]
    fn local_that_a_read_only_call_gets_still_resolves() {
        let cases = [
            r#"module.exports = () => { const web = { entry: "./src/main.ts" }; console.log(web); return [web]; };"#,
            r#"module.exports = () => { const web = { entry: "./src/main.ts" }; const out = path.resolve(__dirname, web.entry); return [web]; };"#,
            r#"module.exports = () => { const web = { entry: "./src/main.ts" }; const keys = Object.keys(web); return [web]; };"#,
            r#"module.exports = () => { const web = { entry: "./src/main.ts" }; const merged = Object.assign({}, web); return [web]; };"#,
            r#"module.exports = () => { const ENTRY = "./src/main.ts"; check(ENTRY); const web = { entry: ENTRY }; return [web]; };"#,
        ];
        for source in cases {
            let entries: Vec<_> =
                super::super::extract_each_config_entries(source, js(), &["entry"], "context")
                    .into_iter()
                    .flat_map(|(entries, _)| entries)
                    .collect();
            assert_eq!(entries, vec!["./src/main.ts"], "{source}");
        }
    }

    #[test]
    fn unstable_or_unknown_locals_do_not_resolve() {
        let cases = [
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; common.resolve = {}; return common; };"#,
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; common.plugins.push(1); return common; };"#,
            r#"module.exports = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; const f = (common) => common; return common; };"#,
            r#"module.exports = () => { var common = { resolve: { alias: { a: "./a.ts" } } }; return common; };"#,
            r#"module.exports = () => { const common = merge(a, { resolve: { alias: { a: "./a.ts" } } }); return { ...common }; };"#,
            r#"module.exports = () => ({ ...require("./base"), entry: "./a.ts" });"#,
            r#"module.exports = () => { const helper = () => { const common = { resolve: { alias: { a: "./a.ts" } } }; return common; }; return helper(); };"#,
        ];
        for source in cases {
            assert!(aliases(source).is_empty(), "{source}");
        }
    }

    #[test]
    fn key_before_an_unresolved_spread_stays() {
        let source = r#"
            module.exports = () => {
                const base = { entry: "./base.ts" };
                return { ...base, entry: "./first.ts", ...unknown };
            };
        "#;
        assert_eq!(
            extract_config_string(source, js(), &["entry"]),
            Some("./first.ts".to_string())
        );
    }

    #[test]
    fn literal_duplicate_keys_without_a_spread_keep_the_first_match() {
        let source = r#"module.exports = { entry: "./first.ts", entry: "./second.ts" };"#;
        assert_eq!(
            extract_config_string(source, js(), &["entry"]),
            Some("./first.ts".to_string())
        );
    }

    #[test]
    fn deep_chains_stop_at_the_bound_and_self_spreads_end() {
        let source = r#"
            module.exports = () => {
                const a = { ...a, entry: "./a.ts" };
                const l1 = { x: "./deep.ts" };
                const l2 = { l1 };
                const l3 = { l2 };
                const l4 = { l3 };
                const l5 = { l4 };
                return { ...a, l5 };
            };
        "#;
        assert_eq!(
            extract_config_string(source, js(), &["entry"]),
            Some("./a.ts".to_string())
        );
        assert_eq!(
            extract_config_string(source, js(), &["l5", "l4", "l3", "l2", "l1", "x"]),
            None
        );
    }
}