bun_bundler 0.1.0

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
use crate::bundled_ast;
use crate::mal_prelude::*;
use bun_alloc::Arena;
use bun_ast::ImportKind;
use bun_ast::base::RefTag;
use bun_ast::server_component_boundary;
use bun_ast::symbol;
use bun_ast::{DeclaredSymbol, DeclaredSymbolList, Dependency, Symbol};
use bun_collections::{AutoBitSet, DynamicBitSetUnmanaged as BitSet, MultiArrayList, VecExt};
use bun_core::PathString;

use crate::IndexStringMap::IndexStringMap;
use crate::{ImportTracker, Index, JSAst, Part, Ref, UseDirective, import_record, index, part};
// `items_<field>()` column accessors — bring the `*ListExt` traits into scope.
// PORT NOTE: `BundledAstColumns` is emitted by ``
// on `BundledAst`; un-gating here is paired with that derive landing in
// `crate::bundled_ast` (same dependency `scanImportsAndExports.rs`
// already imports as `BundledAstField`).
bun_core::declare_scope!(LinkerGraph, visible);

pub mod entry_point {
    use bun_collections::MultiArrayList;
    use bun_core::PathString;

    #[derive(Default)]
    pub struct EntryPoint {
        pub output_path: PathString,
        pub source_index: crate::IndexInt,
        pub output_path_was_auto_generated: bool,
    }

    pub type List = MultiArrayList<EntryPoint>;

    bun_collections::multi_array_columns! {
        pub trait EntryPointColumns for EntryPoint {
            output_path: PathString,
            source_index: crate::IndexInt,
            output_path_was_auto_generated: bool,
        }
    }

    impl EntryPoint {
        pub type Kind = Kind;
    }

    #[repr(u8)]
    #[derive(Clone, Copy, PartialEq, Eq, Default)]
    pub enum Kind {
        #[default]
        None,
        UserSpecified,
        DynamicImport,
        Html,
    }
    impl Kind {
        #[inline]
        pub fn is_entry_point(self) -> bool {
            self != Self::None
        }
        #[inline]
        pub fn is_user_specified_entry_point(self) -> bool {
            self == Self::UserSpecified
        }
        #[inline]
        pub fn is_server_entry_point(self) -> bool {
            self == Self::UserSpecified
        }
        #[inline]
        pub fn output_kind(self) -> crate::options::OutputKind {
            match self {
                Self::UserSpecified => crate::options::OutputKind::EntryPoint,
                _ => crate::options::OutputKind::Chunk,
            }
        }
    }
}

pub mod js_meta {
    use bun_alloc::{AstAlloc, AstVec};
    use bun_ast::{Dependency, Ref};
    use bun_collections::array_hash_map::StringContext;
    use bun_collections::{ArrayHashMap, AutoContext, StringArrayHashMap};

    use crate::{ImportTracker, Index, WrapKind};

    pub struct ImportData {
        pub re_exports: AstVec<Dependency>,
        pub data: ImportTracker,
    }
    impl Default for ImportData {
        fn default() -> Self {
            Self {
                re_exports: AstAlloc::vec(),
                data: ImportTracker::default(),
            }
        }
    }
    pub(crate) type ImportToBind = ImportData;

    pub struct ExportData {
        pub potentially_ambiguous_export_star_refs: AstVec<ImportData>,
        pub data: ImportTracker,
    }
    impl Default for ExportData {
        fn default() -> Self {
            Self {
                potentially_ambiguous_export_star_refs: AstAlloc::vec(),
                data: ImportTracker::default(),
            }
        }
    }
    pub(crate) type ResolvedExport = ExportData;

    pub type RefImportData = ArrayHashMap<Ref, ImportData, AutoContext, AstAlloc>;
    pub type ResolvedExports = StringArrayHashMap<ExportData, StringContext, AstAlloc>;
    pub type ProbablyTypescriptType = ArrayHashMap<Ref, (), AutoContext, AstAlloc>;
    pub type SortedAndFilteredExportAliases = AstVec<Box<[u8], AstAlloc>>;
    pub type CjsExportCopies = AstVec<Ref>;
    pub type TopLevelSymbolToParts = bun_ast::ast_result::TopLevelSymbolToParts;

    #[derive(Clone, Copy, Default)]
    pub struct Flags {
        pub is_async_or_has_async_dependency: bool,
        pub needs_exports_variable: bool,
        pub force_include_exports_for_entry_point: bool,
        pub needs_export_symbol_from_runtime: bool,
        pub did_wrap_dependencies: bool,
        pub needs_synthetic_default_export: bool,
        pub wrap: WrapKind,
    }
    pub use crate::WrapKind as Wrap;

    pub struct JSMeta {
        pub probably_typescript_type: ProbablyTypescriptType,
        pub imports_to_bind: RefImportData,
        pub resolved_exports: ResolvedExports,
        pub resolved_export_star: ExportData,
        pub sorted_and_filtered_export_aliases: SortedAndFilteredExportAliases,
        pub top_level_symbol_to_parts_overlay: TopLevelSymbolToParts,
        pub cjs_export_copies: CjsExportCopies,
        pub wrapper_part_index: Index,
        pub entry_point_part_index: Index,
        pub flags: Flags,
    }

    impl Default for JSMeta {
        fn default() -> Self {
            Self {
                probably_typescript_type: ProbablyTypescriptType::default(),
                imports_to_bind: RefImportData::default(),
                resolved_exports: ResolvedExports::default(),
                resolved_export_star: ExportData::default(),
                sorted_and_filtered_export_aliases: AstAlloc::vec(),
                top_level_symbol_to_parts_overlay: TopLevelSymbolToParts::default(),
                cjs_export_copies: AstAlloc::vec(),
                wrapper_part_index: Index::default(),
                entry_point_part_index: Index::default(),
                flags: Flags::default(),
            }
        }
    }

    bun_collections::multi_array_columns! {
        pub trait JSMetaColumns for JSMeta {
            probably_typescript_type: ProbablyTypescriptType,
            imports_to_bind: RefImportData,
            resolved_exports: ResolvedExports,
            resolved_export_star: ExportData,
            sorted_and_filtered_export_aliases: SortedAndFilteredExportAliases,
            top_level_symbol_to_parts_overlay: TopLevelSymbolToParts,
            cjs_export_copies: CjsExportCopies,
            wrapper_part_index: Index,
            entry_point_part_index: Index,
            flags: Flags,
        }
    }

    impl JSMeta {
        pub type Flags = Flags;
        pub type Wrap = crate::WrapKind;
    }
}

pub use entry_point::EntryPoint;
pub use js_meta::{
    ExportData, ImportData, JSMeta, RefImportData, ResolvedExports, TopLevelSymbolToParts,
};

pub struct LinkerGraph<'a> {
    pub files: FileList,
    pub files_live: BitSet,
    /// Per-part liveness — `parts_live[source_index].is_set(part_index)`.
    /// One bitset per source file, sized to that file's `parts.len()`.
    /// Populated by `tree_shaking_and_code_splitting` (regular link) or by
    /// the DevServer chunk path (which marks every JS-file part live);
    /// read-only thereafter. Replaces the former `Part::is_live: bool` so the
    /// tree-shaking visited-check doesn't pull a full 272-byte `Part` into
    /// cache for a 1-bit answer.
    pub parts_live: Vec<AutoBitSet>,
    pub entry_points: entry_point::List,
    pub symbols: symbol::Map,

    // PORT NOTE: lifetime-erased. Zig stores `std.mem.Allocator`; the Rust
    // arena is owned by `BundleV2` and outlives every `LinkerGraph` — kept as
    // a raw pointer (matching `LinkerContext.parse_graph: *mut Graph`) so the
    // struct stays `'static`-ish and `LinkerContext`/`Chunk` callers don't
    // grow a `'bump` parameter yet. TODO(refactor): thread `'bump` once `Chunk`
    // and `html_import_manifest` gain lifetimes.
    pub bump: bun_ptr::BackRef<Arena>,

    pub code_splitting: bool,

    // This is an alias from Graph
    // it is not a clone!
    pub ast: MultiArrayList<JSAst<'a>>,
    pub meta: MultiArrayList<JSMeta>,

    /// We should avoid traversing all files in the bundle, because the linker
    /// should be able to run a linking operation on a large bundle where only
    /// a few files are needed (e.g. an incremental compilation scenario). This
    /// holds all files that could possibly be reached through the entry points.
    /// If you need to iterate over all files in the linking operation, iterate
    /// over this array. This array is also sorted in a deterministic ordering
    /// to help ensure deterministic builds (source indices are random).
    pub reachable_files: Vec<Index>,

    /// Index from `.parse_graph.input_files` to index in `.files`
    pub stable_source_indices: Vec<u32>,

    pub is_scb_bitset: BitSet,

    /// This is for cross-module inlining of detected inlinable constants
    // const_values: bun_ast::Ast::ConstValuesMap,
    /// This is for cross-module inlining of TypeScript enum constants
    pub ts_enums: bun_ast::ast_result::TsEnumsMap,
}

// SAFETY: `LinkerGraph` is shared read-mostly across worker threads during
// linking (matches Zig, which has no Send/Sync). What makes `&LinkerGraph`
// sound to hold concurrently:
//
// - `bump: *const Arena` is a backref into `BundleV2`; the arena is frozen
//   (no new allocations) for the duration of any worker-pool fan-out that
//   holds `&LinkerGraph`.
// - `files_live` / `parts_live` / `is_scb_bitset` / `reachable_files` /
//   `stable_source_indices` / `code_splitting` / `ts_enums` are populated
//   before fan-out and only read by workers.
// - `ast` / `meta` / `files` columns that workers mutate are split out via
//   `split_mut()` into disjoint `&mut [_]` *before* the pool runs (see
//   `compute_cross_chunk_dependencies`); workers never reach those columns
//   through `&LinkerGraph`.
// - `symbols: symbol::Map` IS written by workers
//   (`Map::assign_chunk_index`), but the written field is
//   `Symbol.chunk_index: AtomicU32` — interior-mutable, Relaxed store — so
//   the write is sound through `&Map`. All other `Symbol` fields are
//   read-only during worker fan-out.
//
// `Send` is required because `LinkerGraph` is moved into `LinkerContext`
// which is itself sent to the link task; the only `!Send` constituent is the
// raw `*const Arena`, whose pointee is `Sync` and outlives the graph.
unsafe impl Send for LinkerGraph<'_> {}
// SAFETY: see the block above — every field reachable through `&LinkerGraph`
// during worker fan-out is either frozen before the pool runs, split out as a
// disjoint `&mut [_]` column beforehand, or written only via
// `Symbol.chunk_index: AtomicU32` (interior-mutable), so shared `&Self` is sound.
unsafe impl Sync for LinkerGraph<'_> {}

impl<'a> LinkerGraph<'a> {
    /// `&Arena` accessor — `bump` is a raw backref into `BundleV2`.
    #[inline]
    pub fn arena(&self) -> &Arena {
        // `bump` is a `BackRef` into `BundleV2.graph.arena`, valid for the
        // lifetime of the link step that constructed this LinkerGraph.
        self.bump.get()
    }
}

impl<'a> LinkerGraph<'a> {
    pub fn init(bump: &Arena, file_count: usize) -> Result<Self, bun_core::Error> {
        // TODO(port): narrow error set
        Ok(LinkerGraph {
            files: FileList::default(),
            files_live: BitSet::init_empty(file_count)?,
            parts_live: Vec::new(),
            entry_points: entry_point::List::default(),
            symbols: symbol::Map::default(),
            bump: bun_ptr::BackRef::new(bump),
            code_splitting: false,
            ast: MultiArrayList::default(),
            meta: MultiArrayList::default(),
            reachable_files: Vec::new(),
            stable_source_indices: Vec::new(),
            is_scb_bitset: BitSet::default(),
            ts_enums: bun_ast::ast_result::TsEnumsMap::default(),
        })
    }
}

impl Default for LinkerGraph<'_> {
    fn default() -> Self {
        LinkerGraph {
            files: FileList::default(),
            files_live: BitSet::default(),
            parts_live: Vec::new(),
            entry_points: entry_point::List::default(),
            symbols: symbol::Map::default(),
            // PORT NOTE: `bump` is a backref assigned in `init`/`LinkerContext::load`;
            // dangling sentinel mirrors Zig's `undefined` (never read before assignment).
            bump: bun_ptr::BackRef::from(core::ptr::NonNull::dangling()),
            code_splitting: false,
            ast: MultiArrayList::default(),
            meta: MultiArrayList::default(),
            reachable_files: Vec::new(),
            stable_source_indices: Vec::new(),
            is_scb_bitset: BitSet::default(),
            ts_enums: bun_ast::ast_result::TsEnumsMap::default(),
        }
    }
}

// ──────────────────────────────────────────────────────────────────────────
// Symbol/part graph mutation surface needed by
// `linker_context/scanImportsAndExports.rs` and `LinkerContext::do_step5`.
//
// Expressed as free fns over individual SoA column slices so callers that
// already hold a `BundledAstColumnsMut` / `JSMetaColumnsMut` split-borrow
// can hand in just the columns these touch without re-borrowing
// `&mut LinkerGraph` (RUST_IDIOMS_AUDIT.md §3). The `&mut self` methods are
// thin forwarders for call sites that don't have a split in hand.
// ──────────────────────────────────────────────────────────────────────────

pub(crate) fn runtime_function(named_exports: &[bundled_ast::NamedExports], name: &[u8]) -> Ref {
    named_exports[Index::RUNTIME.get() as usize]
        .get(name)
        .expect("runtime function must be a named export of the runtime module")
        .ref_
}

pub fn generate_new_symbol(
    symbols: &mut symbol::Map,
    module_scopes: &mut [bun_ast::Scope],
    source_index: u32,
    kind: symbol::Kind,
    original_name: &[u8],
) -> Ref {
    let source_symbols = &mut symbols.symbols_for_source.slice_mut()[source_index as usize];

    // PORT NOTE: Zig built `Ref.init(..)` then assigned `ref.tag = .symbol`.
    // The Rust `Ref` is a packed `u64` with no public `tag` field, so use
    // the `Ref::new` constructor that takes the tag explicitly.
    let ref_ = Ref::new(
        source_symbols.len() as u32, // @truncate (u32 → u31 in pack())
        source_index,                // @truncate
        RefTag::Symbol,
    );

    // TODO: will this crash on resize due to using threadlocal mimalloc heap?
    source_symbols.push(Symbol {
        kind,
        // PORT NOTE: `Symbol.original_name` is a `StoreStr` —
        // arena-owned slice whose lifetime is erased (matches the Zig
        // `[]const u8`); caller guarantees it outlives the symbol table.
        original_name: bun_ast::StoreStr::new(original_name),
        ..Default::default()
    });

    module_scopes[source_index as usize].generated.push(ref_);
    ref_
}

pub(crate) fn top_level_symbol_to_parts<'a>(
    top_level_symbol_to_parts_overlay: &'a [TopLevelSymbolToParts],
    top_level_symbols_to_parts: &'a [bundled_ast::TopLevelSymbolToParts],
    id: u32,
    ref_: Ref,
) -> &'a [u32] {
    if let Some(overlay) = top_level_symbol_to_parts_overlay[id as usize].get(&ref_) {
        return overlay.slice();
    }
    if let Some(list) = top_level_symbols_to_parts[id as usize].get(&ref_) {
        return list.slice();
    }
    &[]
}

pub(crate) fn add_part_to_file(
    parts: &mut [part::List<'_>],
    top_level_symbol_to_parts_overlay: &mut [TopLevelSymbolToParts],
    top_level_symbols_to_parts: &[bundled_ast::TopLevelSymbolToParts],
    id: u32,
    part: Part,
) -> Result<u32, bun_alloc::AllocError> {
    let part_id = parts[id as usize].len() as u32; // @truncate (u32)
    parts[id as usize].push(part);

    // PORT NOTE: borrowck reshape. The Zig closure simultaneously holds
    //   * `&mut parts[part_id].declared_symbols`   (column `parts` of `ast`)
    //   * `&meta.top_level_symbol_to_parts_overlay[id]` (`meta`)
    //   * `&ast.top_level_symbols_to_parts[id]`    (another `ast` column)
    // and additionally caches `*?*TopLevelSymbolToParts` across calls.
    // The two `ast` columns now arrive pre-split, so no detach/reattach is
    // needed. The overlay-pointer cache is dropped — re-index `meta` each
    // call (O(1); the cache was a Zig micro-opt that does not survive
    // Stacked Borrows).
    let declared_symbols: &mut DeclaredSymbolList =
        &mut parts[id as usize][part_id as usize].declared_symbols;

    struct Ctx<'a> {
        overlay: &'a mut [TopLevelSymbolToParts],
        ast_tlsp: &'a [bundled_ast::TopLevelSymbolToParts],
        id: u32,
        part_id: u32,
    }
    let mut ctx = Ctx {
        overlay: top_level_symbol_to_parts_overlay,
        ast_tlsp: top_level_symbols_to_parts,
        id,
        part_id,
    };

    DeclaredSymbol::for_each_top_level_symbol(declared_symbols, &mut ctx, |ctx, ref_| {
        let id = ctx.id;
        let part_id = ctx.part_id;
        let slot = ctx.overlay[id as usize].entry(ref_).or_insert_with(|| {
            if let Some(original_parts) = ctx.ast_tlsp[id as usize].get(&ref_) {
                original_parts.clone()
            } else {
                bun_alloc::AstAlloc::vec()
            }
        });
        slot.push(part_id);
    });

    Ok(part_id)
}

#[allow(clippy::too_many_arguments)]
pub fn generate_symbol_import_and_use(
    parts: &mut [part::List<'_>],
    ast_flags: &mut [bundled_ast::Flags],
    exports_ref: &[Ref],
    module_ref: &[Ref],
    top_level_symbols_to_parts: &[bundled_ast::TopLevelSymbolToParts],
    imports_to_bind: &mut [js_meta::RefImportData],
    top_level_symbol_to_parts_overlay: &[TopLevelSymbolToParts],
    source_index: u32,
    part_index: u32,
    ref_: Ref,
    use_count: u32,
    // PORT NOTE: callers are split between `crate::Index` (options_types)
    // and the structurally identical `bun_ast::Index` until the two newtypes
    // unify. Accept either via `Into` and normalize once.
    source_index_to_import_from: impl Into<Index>,
) -> Result<(), bun_alloc::AllocError> {
    let source_index_to_import_from: Index = source_index_to_import_from.into();
    if use_count == 0 {
        return Ok(());
    }

    let exports_ref_v = exports_ref[source_index as usize];
    let module_ref_v = module_ref[source_index as usize];

    // Mark this symbol as used by this part
    {
        let part: &mut Part = &mut parts[source_index as usize].as_mut_slice()[part_index as usize];
        let uses_entry = part.symbol_uses.get_or_put(ref_)?;
        if !uses_entry.found_existing {
            *uses_entry.value_ptr = symbol::Use {
                count_estimate: use_count,
            };
        } else {
            uses_entry.value_ptr.count_estimate += use_count;
        }
    }

    if !exports_ref_v.is_empty() && ref_.eql(exports_ref_v) {
        ast_flags[source_index as usize].insert(bundled_ast::Flags::USES_EXPORTS_REF);
    }

    if !module_ref_v.is_empty() && ref_.eql(module_ref_v) {
        ast_flags[source_index as usize].insert(bundled_ast::Flags::USES_MODULE_REF);
    }

    // null ref shouldn't be there.
    debug_assert!(!ref_.is_empty());

    // Track that this specific symbol was imported
    if source_index_to_import_from.get() != source_index {
        imports_to_bind[source_index as usize].put(
            ref_,
            js_meta::ImportToBind {
                data: ImportTracker {
                    source_index: source_index_to_import_from,
                    import_ref: ref_,
                    ..Default::default()
                },
                ..Default::default()
            },
        )?;
    }

    // Pull in all parts that declare this symbol
    let part_ids = top_level_symbol_to_parts(
        top_level_symbol_to_parts_overlay,
        top_level_symbols_to_parts,
        source_index_to_import_from.get(),
        ref_,
    );
    let dependencies =
        &mut parts[source_index as usize].as_mut_slice()[part_index as usize].dependencies;
    // SAFETY: every element of `new_dependencies` is overwritten in the
    // zip-loop immediately below before any read/drop.
    let new_dependencies = unsafe { dependencies.writable_slice(part_ids.len()) };
    debug_assert_eq!(part_ids.len(), new_dependencies.len());
    for (part_id, dependency) in part_ids.iter().zip(new_dependencies.iter_mut()) {
        *dependency = Dependency {
            // PORT NOTE: `Dependency.source_index` is the structurally
            // identical `bun_ast::Index`; convert by value until the
            // two `Index` newtypes unify.
            source_index: bun_ast::Index::init(source_index_to_import_from.get()),
            part_index: *part_id, // @truncate (already u32)
        };
    }
    Ok(())
}

impl<'a> LinkerGraph<'a> {
    pub fn runtime_function(&self, name: &[u8]) -> Ref {
        runtime_function(self.ast.items_named_exports(), name)
    }

    /// Shared-ref view of a symbol that is known to exist (the `Ref` was
    /// produced by the symbol table itself). Thin wrapper over
    /// [`symbol::Map::get_const`]; callers previously open-coded
    /// `unsafe { &*graph.symbols.get(r).expect(..) }`.
    #[inline]
    pub fn symbol(&self, ref_: Ref) -> &Symbol {
        self.symbols
            .get_const(ref_)
            .expect("infallible: ref in symbol table")
    }

    /// Mutable view of a symbol that is known to exist. Takes `&self` (not
    /// `&mut self`): the linker mutates per-symbol fields (`link`,
    /// `namespace_alias`, `import_item_status`, ...) through shared
    /// `&LinkerContext`/`&LinkerGraph` paths while iterating disjoint graph
    /// columns, mirroring the prior open-coded `unsafe { &mut *get(r) }`.
    ///
    /// # Safety
    /// Caller must ensure no other live `&`/`&mut` borrow aliases the same
    /// symbol slot for the returned reference's lifetime (the `&self` signature
    /// alone cannot enforce this — two calls with the same `Ref` while both
    /// results are live is UB). Mirrors the prior open-coded
    /// `unsafe { &mut *get(r) }` call-site obligation.
    #[inline]
    #[allow(clippy::mut_from_ref)]
    pub unsafe fn symbol_mut(&self, ref_: Ref) -> &mut Symbol {
        // SAFETY: see `symbol` for liveness/validity; caller guarantees the
        // mutated slot is disjoint from any other borrow held at the call site.
        unsafe {
            &mut *self
                .symbols
                .get(ref_)
                .expect("infallible: ref in symbol table")
        }
    }

    pub fn generate_new_symbol(
        &mut self,
        source_index: u32,
        kind: symbol::Kind,
        original_name: &[u8],
    ) -> Ref {
        generate_new_symbol(
            &mut self.symbols,
            self.ast.items_module_scope_mut(),
            source_index,
            kind,
            original_name,
        )
    }

    pub fn generate_runtime_symbol_import_and_use(
        &mut self,
        source_index: index::Int,
        entry_point_part_index: Index,
        name: &[u8],
        count: u32,
    ) -> Result<(), bun_alloc::AllocError> {
        if count == 0 {
            return Ok(());
        }
        bun_core::scoped_log!(
            LinkerGraph,
            "generateRuntimeSymbolImportAndUse({}) for {}",
            bstr::BStr::new(name),
            source_index
        );

        let ref_ = self.runtime_function(name);
        self.generate_symbol_import_and_use(
            source_index,
            entry_point_part_index.get(),
            ref_,
            count,
            Index::RUNTIME,
        )
    }

    pub fn add_part_to_file(&mut self, id: u32, part: Part) -> Result<u32, bun_alloc::AllocError> {
        let ast = self.ast.split_mut();
        add_part_to_file(
            ast.parts,
            self.meta.items_top_level_symbol_to_parts_overlay_mut(),
            ast.top_level_symbols_to_parts,
            id,
            part,
        )
    }

    pub fn generate_symbol_import_and_use(
        &mut self,
        source_index: u32,
        part_index: u32,
        ref_: Ref,
        use_count: u32,
        source_index_to_import_from: impl Into<Index>,
    ) -> Result<(), bun_alloc::AllocError> {
        let ast = self.ast.split_mut();
        let meta = self.meta.split_mut();
        generate_symbol_import_and_use(
            ast.parts,
            ast.flags,
            ast.exports_ref,
            ast.module_ref,
            ast.top_level_symbols_to_parts,
            meta.imports_to_bind,
            meta.top_level_symbol_to_parts_overlay,
            source_index,
            part_index,
            ref_,
            use_count,
            source_index_to_import_from,
        )
    }

    pub fn top_level_symbol_to_parts(&self, id: u32, ref_: Ref) -> &[u32] {
        top_level_symbol_to_parts(
            self.meta.items_top_level_symbol_to_parts_overlay(),
            self.ast.items_top_level_symbols_to_parts(),
            id,
            ref_,
        )
    }
}

impl<'a> LinkerGraph<'a> {
    pub fn load(
        &mut self,
        entry_points: &[Index],
        sources: &[bun_ast::Source],
        server_component_boundaries: &server_component_boundary::List,
        dynamic_import_entry_points: &[index::Int],
        entry_point_original_names: &IndexStringMap,
    ) -> Result<(), bun_core::Error> {
        // TODO(port): narrow error set
        let scb = server_component_boundaries.slice();
        self.files.set_capacity(sources.len())?;
        self.files.zero();
        self.files_live = BitSet::init_empty(sources.len())?;
        // SAFETY: capacity reserved above; columns zeroed by `zero()`.
        unsafe { self.files.set_len(sources.len()) };

        // PORT NOTE: `Slice<T>` caches raw column pointers and does not borrow
        // `self.files`, so the `split_mut()` borrows (tied to the local
        // `files_slice`) can stay live across other `&mut self.*` accesses
        // below. The columns are not reallocated during `load`.
        let mut files_slice = self.files.slice();
        let files_cols = files_slice.split_mut();
        let entry_point_kinds: &mut [entry_point::Kind] = files_cols.entry_point_kind;
        entry_point_kinds.fill(entry_point::Kind::None);

        // Setup entry points
        {
            self.entry_points.set_capacity(
                entry_points.len()
                    + server_component_boundaries.list.len()
                    + dynamic_import_entry_points.len(),
            )?;
            // SAFETY: capacity reserved; columns initialized below.
            unsafe { self.entry_points.set_len(entry_points.len()) };

            // PORT NOTE: borrowck reshape — Zig held `source_indices` /
            // `path_strings` / `output_path_was_auto_generated` simultaneously
            // (disjoint columns of the same `MultiArrayList`). `split_mut()`
            // hands out all three at once; `self.entry_points` is not
            // reallocated until after `path_strings`/`source_indices` are done
            // with (the next `append_assume_capacity` is within the
            // pre-reserved capacity, so no realloc).
            let mut ep_slice = self.entry_points.slice();
            let ep_cols = ep_slice.split_mut();
            let source_indices: &mut [index::Int] = ep_cols.source_index;
            let path_strings: &mut [PathString] = ep_cols.output_path;
            ep_cols.output_path_was_auto_generated.fill(false);

            debug_assert_eq!(entry_points.len(), path_strings.len());
            debug_assert_eq!(entry_points.len(), source_indices.len());
            for ((i, path_string), source_index) in entry_points
                .iter()
                .zip(path_strings.iter_mut())
                .zip(source_indices.iter_mut())
            {
                let source = &sources[i.get() as usize];
                if cfg!(debug_assertions) {
                    debug_assert!(source.index.0 == i.get());
                }
                entry_point_kinds[source.index.0 as usize] = entry_point::Kind::UserSpecified;

                // Check if this entry point has an original name (from virtual entry resolution)
                if let Some(original_name) = entry_point_original_names.get(i.get()) {
                    *path_string = PathString::init(original_name);
                } else {
                    *path_string = PathString::init(source.path.text);
                }

                *source_index = source.index.0;
            }

            for &id in dynamic_import_entry_points {
                debug_assert!(self.code_splitting); // this should never be a thing without code splitting

                if entry_point_kinds[id as usize] != entry_point::Kind::None {
                    // You could dynamic import a file that is already an entry point
                    continue;
                }

                let source = &sources[id as usize];
                entry_point_kinds[id as usize] = entry_point::Kind::DynamicImport;

                self.entry_points.append_assume_capacity(EntryPoint {
                    source_index: id,
                    output_path: PathString::init(source.path.text),
                    output_path_was_auto_generated: true,
                });
            }

            let import_records_len = self.ast.items_import_records().len();
            self.meta.set_capacity(import_records_len)?;
            // PORT NOTE: Zig does `meta.len = ast.len; meta.zero()` — a raw
            // memset(0) is the valid empty state for Zig's unmanaged
            // containers. Rust `Vec`/`Box` require a non-null dangling
            // pointer when empty, so zeroed bytes violate their invariants
            // (`slice::from_raw_parts` null-check trips on first read). Fill
            // each slot with `Default` instead.
            let ast_len = self.ast.len();
            debug_assert!(ast_len <= import_records_len);
            for _ in 0..ast_len {
                self.meta.append_assume_capacity(JSMeta::default());
            }

            if scb.list.len() > 0 {
                self.is_scb_bitset = BitSet::init_empty(self.files.len()).expect("unreachable");

                // Index all SCBs into the bitset. This is needed so chunking
                // can track the chunks that SCBs belong to.
                debug_assert_eq!(
                    scb.list.items_use_directive().len(),
                    scb.list.items_source_index().len()
                );
                debug_assert_eq!(
                    scb.list.items_use_directive().len(),
                    scb.list.items_reference_source_index().len()
                );
                for ((use_, original_id), ref_id) in scb
                    .list
                    .items_use_directive()
                    .iter()
                    .zip(scb.list.items_source_index().iter())
                    .zip(scb.list.items_reference_source_index().iter())
                {
                    match use_ {
                        UseDirective::None => {}
                        UseDirective::Client => {
                            self.is_scb_bitset.set(*original_id as usize);
                            self.is_scb_bitset.set(*ref_id as usize);
                        }
                        UseDirective::Server => {
                            bun_core::todo_panic!("um");
                        }
                    }
                }

                // For client components, the import record index currently points to the original source index, instead of the reference source index.
                let import_records_list: &mut [import_record::List<'_>] =
                    self.ast.items_import_records_mut();
                for source_id in self.reachable_files.slice() {
                    for import_record in import_records_list[source_id.get() as usize]
                        .as_mut_slice()
                        .iter_mut()
                    {
                        if import_record.source_index.is_valid()
                            && self
                                .is_scb_bitset
                                .is_set(import_record.source_index.get() as usize)
                        {
                            // Only rewrite if this is an original SCB file, not a reference file
                            if let Some(ref_index) =
                                scb.get_reference_source_index(import_record.source_index.get())
                            {
                                import_record.source_index = Index::init(ref_index);
                                debug_assert!(import_record.source_index.is_valid());
                                // did not generate
                            }
                            // If it's already a reference file, leave it as-is
                        }
                    }
                }
            } else {
                self.is_scb_bitset = BitSet::default();
            }
        }

        // Setup files
        {
            // set it to max value so that if we access an invalid one, it crashes
            // PORT NOTE: Zig used `@memset(sliceAsBytes(...), 255)` to fill raw
            // bytes; here we fill with `Index::INVALID` whose bytes are all
            // 0xFF (`#[repr(transparent)]` over `u32::MAX`).
            let stable_source_indices = self
                .arena()
                .alloc_slice_fill_copy(sources.len() + 1, Index::INVALID);

            for (i, source_index) in self.reachable_files.slice().iter().enumerate() {
                stable_source_indices[source_index.get() as usize] = Index::source(i as u32);
            }

            let distances: &mut [u32] = files_cols.distance_from_entry_point;
            distances.fill(File::default().distance_from_entry_point);
            // `Index` is `#[repr(transparent)]` over `u32`; the field stores
            // raw `u32` so unwrap via `.get()` (no slice reinterpret needed).
            self.stable_source_indices = stable_source_indices.iter().map(|i| i.get()).collect();
        }

        {
            // PORT NOTE: Zig built a borrowed `Symbol.NestedList` over the
            // `ast.items(.symbols)` column then `clone`d it (memcpy). The Rust
            // `Vec::clone` requires `T: Clone` which `Symbol` does not
            // derive (it carries a raw `*const [u8]`), so spell out the
            // bitwise copy explicitly — `Symbol` has no `Drop` impl.
            let src_symbols: &[symbol::List] = self.ast.items_symbols();
            let mut symbols: symbol::NestedList = Vec::with_capacity(src_symbols.len());
            for src in src_symbols {
                let n = src.len();
                let mut dest: Vec<symbol::Symbol> = Vec::with_capacity(n);
                // SAFETY: `dest` has capacity `n`; `src` is `n` initialized
                // `Symbol`s; `Symbol` is bitwise-copyable (no `Drop`).
                unsafe {
                    core::ptr::copy_nonoverlapping(src.as_ptr(), dest.as_mut_ptr(), n);
                    dest.set_len(n);
                }
                symbols.push(dest);
            }
            self.symbols = symbol::Map::init_list(symbols);
        }

        // TODO: const_values
        // {
        //     var const_values = this.const_values;
        //     var count: usize = 0;
        //
        //     for (this.ast.items(.const_values)) |const_value| {
        //         count += const_value.count();
        //     }
        //
        //     if (count > 0) {
        //         try const_values.ensureTotalCapacity(this.arena, count);
        //         for (this.ast.items(.const_values)) |const_value| {
        //             for (const_value.keys(), const_value.values()) |key, value| {
        //                 const_values.putAssumeCapacityNoClobber(key, value);
        //             }
        //         }
        //     }
        //
        //     this.const_values = const_values;
        // }

        {
            let mut count: usize = 0;
            for ts_enums in self.ast.items_ts_enums().iter() {
                count += ts_enums.count();
            }
            if count > 0 {
                self.ts_enums.ensure_total_capacity(count)?;
                for ts_enums in self.ast.items_ts_enums().iter() {
                    debug_assert_eq!(ts_enums.keys().len(), ts_enums.values().len());
                    for (key, value) in ts_enums.keys().iter().zip(ts_enums.values().iter()) {
                        // PERF(port): was assume_capacity_no_clobber
                        // PORT NOTE: Zig copied the inner `StringHashMap` by
                        // value (shallow struct copy). Rust clones the backing
                        // `HashMap`; the per-file maps are not mutated after
                        // this point so aliasing is not required.
                        self.ts_enums.put_assume_capacity(*key, value.clone());
                    }
                }
            }
        }

        let src_named_exports: &[bundled_ast::NamedExports] = self.ast.items_named_exports();
        let dest_resolved_exports: &mut [ResolvedExports] = self.meta.items_resolved_exports_mut();
        debug_assert_eq!(src_named_exports.len(), dest_resolved_exports.len());
        for (source_index, (src, dest)) in src_named_exports
            .iter()
            .zip(dest_resolved_exports.iter_mut())
            .enumerate()
        {
            let mut resolved = ResolvedExports::default();
            resolved
                .ensure_total_capacity(src.count())
                .expect("unreachable");
            debug_assert_eq!(src.keys().len(), src.values().len());
            for (key, value) in src.keys().iter().zip(src.values().iter()) {
                // PERF(port): was assume_capacity_no_clobber
                resolved.put_assume_capacity(
                    key,
                    js_meta::ResolvedExport {
                        data: ImportTracker {
                            import_ref: value.ref_,
                            name_loc: value.alias_loc,
                            source_index: Index::source(source_index as u32),
                        },
                        ..Default::default()
                    },
                );
            }
            *dest = resolved;
        }
        Ok(())
    }

    /// Port of `LinkerGraph.zig:takeAstOwnership`. `clone_ast` left each
    /// `PartList`/import-record list with its allocator handle pointing at
    /// the per-worker `mi_heap` that built it; re-tag to `heap` (the
    /// bundle-thread arena) so linker-side `add_part_to_file` pushes call
    /// `mi_heap_realloc_aligned(heap, worker_ptr, ..)` from the thread that
    /// owns `heap`. Zero-copy: only files the linker actually grows pay a
    /// (lazy, mimalloc-internal) cross-heap migration on first realloc.
    ///
    /// Zig is a release no-op because `BabyList` passes the allocator at each
    /// `append` call site; the Rust `Vec<T, &Arena>` stores it, so swap here.
    /// Zig also transfers `part.dependencies` and `symbols`; the Rust port's
    /// `DependencyList` is `Vec<_, AstAlloc>` (linker-side grows just route
    /// through whichever thread's `AstAlloc` state is active — `AstAlloc` is a
    /// ZST, so there is nothing to retag) and new symbols feed through
    /// `self.symbols: symbol::Map` (global) — neither needs transfer here.
    pub fn take_ast_ownership(&mut self, heap: &'a Arena) {
        for v in self.ast.items_import_records_mut() {
            bun_alloc::transfer_arena(v, heap);
        }
        for v in self.ast.items_parts_mut() {
            bun_alloc::transfer_arena(v, heap);
        }
    }

    pub fn propagate_async_dependencies(&mut self) -> Result<(), bun_core::Error> {
        // TODO(port): narrow error set
        struct State<'a> {
            visited: AutoBitSet,
            import_records: &'a [import_record::List<'a>],
            flags: &'a mut [js_meta::Flags],
        }

        impl<'a> State<'a> {
            pub(crate) fn visit_all(&mut self) {
                for i in 0..self.import_records.len() {
                    self.visit(i);
                }
            }

            fn visit(&mut self, index: usize) {
                if self.visited.is_set(index) {
                    return;
                }
                self.visited.set(index);
                if self.flags[index].is_async_or_has_async_dependency {
                    return;
                }

                for import_record in self.import_records[index].as_slice().iter() {
                    match import_record.kind {
                        ImportKind::Stmt => {}

                        // Any use of `import()` that makes the parent async will necessarily use
                        // top-level await, so this will have already been detected by `validateTLA`,
                        // and `is_async_or_has_async_dependency` will already be true.
                        //
                        // We don't want to process these imports here because `import()` can appear in
                        // non-top-level contexts (like inside an async function) or in contexts that
                        // don't use `await`, which don't necessarily make the parent module async.
                        ImportKind::Dynamic => continue,

                        // `require()` cannot import async modules.
                        ImportKind::Require | ImportKind::RequireResolve => continue,

                        // Entry points; not imports from JS
                        ImportKind::EntryPointRun | ImportKind::EntryPointBuild => continue,
                        // CSS imports
                        ImportKind::At
                        | ImportKind::AtConditional
                        | ImportKind::Url
                        | ImportKind::Composes => continue,
                        // Other non-JS imports
                        ImportKind::HtmlManifest | ImportKind::Internal => continue,
                    }

                    let import_index: usize = import_record.source_index.get() as usize;
                    if import_index >= self.import_records.len() {
                        continue;
                    }
                    self.visit(import_index);

                    if self.flags[import_index].is_async_or_has_async_dependency {
                        self.flags[index].is_async_or_has_async_dependency = true;
                        break;
                    }
                }
            }
        }

        let mut state = State {
            visited: AutoBitSet::init_empty(self.ast.len())?,
            import_records: self.ast.items_import_records(),
            flags: self.meta.items_flags_mut(),
        };
        state.visit_all();
        Ok(())
    }
}

pub struct File {
    pub entry_bits: AutoBitSet,

    pub input_file: Index,

    /// The minimum number of links in the module graph to get from an entry point
    /// to this file
    pub distance_from_entry_point: u32,

    /// This file is an entry point if and only if this is not ".none".
    /// Note that dynamically-imported files are allowed to also be specified by
    /// the user as top-level entry points, so some dynamically-imported files
    /// may be ".user_specified" instead of ".dynamic_import".
    pub entry_point_kind: EntryPoint::Kind,

    /// If "entry_point_kind" is not ".none", this is the index of the
    /// corresponding entry point chunk.
    ///
    /// This is also initialized for files that are a SCB's generated
    /// reference, pointing to its destination. This forms a lookup map from
    /// a Source.Index to its output path inb reakOutputIntoPieces
    pub entry_point_chunk_index: u32,

    pub line_offset_table: bun_sourcemap::line_offset_table::List<bun_alloc::AstAlloc>,
    pub quoted_source_contents: Option<bun_alloc::AstVec<u8>>,
}

impl File {
    pub fn is_entry_point(&self) -> bool {
        self.entry_point_kind.is_entry_point()
    }

    pub fn is_user_specified_entry_point(&self) -> bool {
        self.entry_point_kind.is_user_specified_entry_point()
    }
}

impl Default for File {
    fn default() -> Self {
        Self {
            // PORT NOTE: Zig had `entry_bits: AutoBitSet = undefined` — using an
            // empty static-arm bitset here; load() overwrites before any read.
            entry_bits: AutoBitSet::init_empty(0).expect("static AutoBitSet"),
            input_file: Index::source(0u32),
            distance_from_entry_point: u32::MAX,
            entry_point_kind: EntryPoint::Kind::None,
            entry_point_chunk_index: u32::MAX,
            line_offset_table: bun_sourcemap::line_offset_table::List::new_in(bun_alloc::AstAlloc),
            quoted_source_contents: None,
        }
    }
}

pub(crate) type FileList = MultiArrayList<File>;

bun_collections::multi_array_columns! {
    pub trait FileColumns for File {
        entry_bits: AutoBitSet,
        input_file: Index,
        distance_from_entry_point: u32,
        entry_point_kind: EntryPoint::Kind,
        entry_point_chunk_index: u32,
        line_offset_table: bun_sourcemap::line_offset_table::List<bun_alloc::AstAlloc>,
        quoted_source_contents: Option<bun_alloc::AstVec<u8>>,
    }
}

// ported from: src/bundler/LinkerGraph.zig