forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
module_loader.zig
2989 lines (2683 loc) · 128 KB
/
module_loader.zig
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
const std = @import("std");
const is_bindgen: bool = std.meta.globalOption("bindgen", bool) orelse false;
const StaticExport = @import("./bindings/static_export.zig");
const bun = @import("root").bun;
const string = bun.string;
const Output = bun.Output;
const Global = bun.Global;
const Environment = bun.Environment;
const strings = bun.strings;
const MutableString = bun.MutableString;
const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const StoredFileDescriptorType = bun.StoredFileDescriptorType;
const Arena = @import("../mimalloc_arena.zig").Arena;
const C = bun.C;
const Allocator = std.mem.Allocator;
const IdentityContext = @import("../identity_context.zig").IdentityContext;
const Fs = @import("../fs.zig");
const Resolver = @import("../resolver/resolver.zig");
const ast = @import("../import_record.zig");
const MacroEntryPoint = bun.bundler.MacroEntryPoint;
const ParseResult = bun.bundler.ParseResult;
const logger = bun.logger;
const Api = @import("../api/schema.zig").Api;
const options = @import("../options.zig");
const Bundler = bun.Bundler;
const PluginRunner = bun.bundler.PluginRunner;
const ServerEntryPoint = bun.bundler.ServerEntryPoint;
const js_printer = bun.js_printer;
const js_parser = bun.js_parser;
const js_ast = bun.JSAst;
const NodeFallbackModules = @import("../node_fallbacks.zig");
const ImportKind = ast.ImportKind;
const Analytics = @import("../analytics/analytics_thread.zig");
const ZigString = bun.JSC.ZigString;
const Runtime = @import("../runtime.zig");
const Router = @import("./api/filesystem_router.zig");
const ImportRecord = ast.ImportRecord;
const DotEnv = @import("../env_loader.zig");
const PackageJSON = @import("../resolver/package_json.zig").PackageJSON;
const MacroRemap = @import("../resolver/package_json.zig").MacroMap;
const WebCore = bun.JSC.WebCore;
const Request = WebCore.Request;
const Response = WebCore.Response;
const Headers = WebCore.Headers;
const Fetch = WebCore.Fetch;
const FetchEvent = WebCore.FetchEvent;
const js = bun.JSC.C;
const JSC = bun.JSC;
const JSError = @import("./base.zig").JSError;
const d = @import("./base.zig").d;
const MarkedArrayBuffer = @import("./base.zig").MarkedArrayBuffer;
const getAllocator = @import("./base.zig").getAllocator;
const JSValue = bun.JSC.JSValue;
const NewClass = @import("./base.zig").NewClass;
const JSGlobalObject = bun.JSC.JSGlobalObject;
const ExceptionValueRef = bun.JSC.ExceptionValueRef;
const JSPrivateDataPtr = bun.JSC.JSPrivateDataPtr;
const ConsoleObject = bun.JSC.ConsoleObject;
const Node = bun.JSC.Node;
const ZigException = bun.JSC.ZigException;
const ZigStackTrace = bun.JSC.ZigStackTrace;
const ErrorableResolvedSource = bun.JSC.ErrorableResolvedSource;
const ResolvedSource = bun.JSC.ResolvedSource;
const JSPromise = bun.JSC.JSPromise;
const JSInternalPromise = bun.JSC.JSInternalPromise;
const JSModuleLoader = bun.JSC.JSModuleLoader;
const JSPromiseRejectionOperation = bun.JSC.JSPromiseRejectionOperation;
const Exception = bun.JSC.Exception;
const ErrorableZigString = bun.JSC.ErrorableZigString;
const ZigGlobalObject = bun.JSC.ZigGlobalObject;
const VM = bun.JSC.VM;
const JSFunction = bun.JSC.JSFunction;
const Config = @import("./config.zig");
const URL = @import("../url.zig").URL;
const Bun = JSC.API.Bun;
const EventLoop = JSC.EventLoop;
const PendingResolution = @import("../resolver/resolver.zig").PendingResolution;
const ThreadSafeFunction = JSC.napi.ThreadSafeFunction;
const PackageManager = @import("../install/install.zig").PackageManager;
const Install = @import("../install/install.zig");
const VirtualMachine = JSC.VirtualMachine;
const Dependency = @import("../install/dependency.zig");
const Async = bun.Async;
const String = bun.String;
const debug = Output.scoped(.ModuleLoader, true);
// Setting BUN_OVERRIDE_MODULE_PATH to the path to the bun repo will make it so modules are loaded
// from there instead of the ones embedded into the binary.
// In debug mode, this is set automatically for you, using the path relative to this file.
fn jsModuleFromFile(from_path: string, comptime input: string) string {
// `modules_dev` is not minified or committed. Later we could also try loading source maps for it too.
const moduleFolder = if (comptime Environment.isDebug) "modules_dev" else "modules";
const Holder = struct {
pub const file = @embedFile("../js/out/" ++ moduleFolder ++ "/" ++ input);
};
if ((comptime !Environment.allow_assert) and from_path.len == 0) {
return Holder.file;
}
var file: std.fs.File = undefined;
if ((comptime Environment.allow_assert) and from_path.len == 0) {
const absolute_path = comptime (Environment.base_path ++ (std.fs.path.dirname(std.fs.path.dirname(@src().file).?).?) ++ "/js/out/" ++ moduleFolder ++ "/" ++ input);
file = std.fs.openFileAbsoluteZ(absolute_path, .{ .mode = .read_only }) catch {
const WarnOnce = struct {
pub var warned = false;
};
if (!WarnOnce.warned) {
WarnOnce.warned = true;
Output.prettyErrorln("Could not find file: " ++ absolute_path ++ " - using embedded version", .{});
}
return Holder.file;
};
} else {
var parts = [_]string{ from_path, "src/js/out/" ++ moduleFolder ++ "/" ++ input };
var buf: [bun.MAX_PATH_BYTES]u8 = undefined;
var absolute_path_to_use = Fs.FileSystem.instance.absBuf(&parts, &buf);
buf[absolute_path_to_use.len] = 0;
file = std.fs.openFileAbsoluteZ(absolute_path_to_use[0..absolute_path_to_use.len :0], .{ .mode = .read_only }) catch {
const WarnOnce = struct {
pub var warned = false;
};
if (!WarnOnce.warned) {
WarnOnce.warned = true;
Output.prettyErrorln("Could not find file: {s}, so using embedded version", .{absolute_path_to_use});
}
return Holder.file;
};
}
const contents = file.readToEndAlloc(bun.default_allocator, std.math.maxInt(usize)) catch @panic("Cannot read file " ++ input);
file.close();
return contents;
}
inline fn jsSyntheticModule(comptime name: ResolvedSource.Tag, specifier: String) ResolvedSource {
return ResolvedSource{
.allocator = null,
.source_code = bun.String.empty,
.specifier = specifier,
.source_url = bun.String.static(@tagName(name)),
.hash = 0,
.tag = name,
.source_code_needs_deref = false,
};
}
/// Dumps the module source to a file in /tmp/bun-debug-src/{filepath}
///
/// This can technically fail if concurrent access across processes happens, or permission issues.
/// Errors here should always be ignored.
fn dumpSource(specifier: string, printer: anytype) void {
dumpSourceString(specifier, printer.ctx.getWritten());
}
fn dumpSourceString(specifier: string, written: []const u8) void {
if (!Environment.isDebug) return;
const BunDebugHolder = struct {
pub var dir: ?std.fs.Dir = null;
pub var lock: bun.Lock = bun.Lock.init();
};
BunDebugHolder.lock.lock();
defer BunDebugHolder.lock.unlock();
const dir = BunDebugHolder.dir orelse dir: {
const base_name = switch (Environment.os) {
else => "/tmp/bun-debug-src/",
.windows => brk: {
const temp = bun.fs.FileSystem.RealFS.platformTempDir();
var win_temp_buffer: [bun.MAX_PATH_BYTES]u8 = undefined;
@memcpy(win_temp_buffer[0..temp.len], temp);
const suffix = "\\bun-debug-src";
@memcpy(win_temp_buffer[temp.len .. temp.len + suffix.len], suffix);
win_temp_buffer[temp.len + suffix.len] = 0;
break :brk win_temp_buffer[0 .. temp.len + suffix.len :0];
},
};
const dir = std.fs.cwd().makeOpenPath(base_name, .{}) catch |e| {
Output.debug("Failed to dump source string: {}", .{e});
return;
};
BunDebugHolder.dir = dir;
break :dir dir;
};
if (std.fs.path.dirname(specifier)) |dir_path| {
const root_len = switch (Environment.os) {
else => "/".len,
.windows => bun.path.windowsFilesystemRoot(dir_path).len,
};
var parent = dir.makeOpenPath(dir_path[root_len..], .{}) catch |e| {
Output.debug("Failed to dump source string: makeOpenPath({s}[{d}..]) {}", .{ dir_path, root_len, e });
return;
};
defer parent.close();
parent.writeFile(std.fs.path.basename(specifier), written) catch |e| {
Output.debug("Failed to dump source string: writeFile {}", .{e});
return;
};
} else {
dir.writeFile(std.fs.path.basename(specifier), written) catch return;
}
}
fn setBreakPointOnFirstLine() bool {
const s = struct {
var set_break_point: bool = true;
};
const ret = s.set_break_point;
s.set_break_point = false;
return ret;
}
pub const RuntimeTranspilerStore = struct {
generation_number: std.atomic.Value(u32) = std.atomic.Value(u32).init(0),
store: TranspilerJob.Store,
enabled: bool = true,
queue: Queue = Queue{},
pub const Queue = bun.UnboundedQueue(TranspilerJob, .next);
pub fn init(allocator: std.mem.Allocator) RuntimeTranspilerStore {
return RuntimeTranspilerStore{
.store = TranspilerJob.Store.init(allocator),
};
}
// Thsi is run at the top of the event loop on the JS thread.
pub fn drain(this: *RuntimeTranspilerStore) void {
var batch = this.queue.popBatch();
var iter = batch.iterator();
if (iter.next()) |job| {
// we run just one job first to see if there are more
job.runFromJSThread();
} else {
return;
}
var vm = @fieldParentPtr(JSC.VirtualMachine, "transpiler_store", this);
const event_loop = vm.eventLoop();
const global = vm.global;
const jsc_vm = vm.jsc;
while (iter.next()) |job| {
// if there are more, we need to drain the microtasks from the previous run
event_loop.drainMicrotasksWithGlobal(global, jsc_vm);
job.runFromJSThread();
}
// immediately after this is called, the microtasks will be drained again.
}
pub fn transpile(
this: *RuntimeTranspilerStore,
vm: *JSC.VirtualMachine,
globalObject: *JSC.JSGlobalObject,
path: Fs.Path,
referrer: []const u8,
) *anyopaque {
var job: *TranspilerJob = this.store.get();
const owned_path = Fs.Path.init(bun.default_allocator.dupe(u8, path.text) catch unreachable);
const promise = JSC.JSInternalPromise.create(globalObject);
job.* = TranspilerJob{
.path = owned_path,
.globalThis = globalObject,
.referrer = bun.default_allocator.dupe(u8, referrer) catch unreachable,
.vm = vm,
.log = logger.Log.init(bun.default_allocator),
.loader = vm.bundler.options.loader(owned_path.name.ext),
.promise = JSC.Strong.create(JSC.JSValue.fromCell(promise), globalObject),
.poll_ref = .{},
.fetcher = TranspilerJob.Fetcher{
.file = {},
},
};
if (comptime Environment.allow_assert)
debug("transpile({s}, {s}, async)", .{ path.text, @tagName(job.loader) });
job.schedule();
return promise;
}
pub const TranspilerJob = struct {
path: Fs.Path,
referrer: []const u8,
loader: options.Loader,
promise: JSC.Strong = .{},
vm: *JSC.VirtualMachine,
globalThis: *JSC.JSGlobalObject,
fetcher: Fetcher,
poll_ref: Async.KeepAlive = .{},
generation_number: u32 = 0,
log: logger.Log,
parse_error: ?anyerror = null,
resolved_source: ResolvedSource = ResolvedSource{},
work_task: JSC.WorkPoolTask = .{ .callback = runFromWorkerThread },
next: ?*TranspilerJob = null,
pub const Store = bun.HiveArray(TranspilerJob, 64).Fallback;
pub const Fetcher = union(enum) {
virtual_module: bun.String,
file: void,
pub fn deinit(this: *@This()) void {
if (this.* == .virtual_module) {
this.virtual_module.deref();
}
}
};
pub fn deinit(this: *TranspilerJob) void {
bun.default_allocator.free(this.path.text);
bun.default_allocator.free(this.referrer);
this.poll_ref.disable();
this.fetcher.deinit();
this.loader = options.Loader.file;
this.path = Fs.Path.empty;
this.log.deinit();
this.promise.deinit();
this.globalThis = undefined;
}
threadlocal var ast_memory_store: ?*js_ast.ASTMemoryAllocator = null;
threadlocal var source_code_printer: ?*js_printer.BufferPrinter = null;
pub fn dispatchToMainThread(this: *TranspilerJob) void {
this.vm.transpiler_store.queue.push(this);
this.vm.eventLoop().enqueueTaskConcurrent(JSC.ConcurrentTask.createFrom(&this.vm.transpiler_store));
}
pub fn runFromJSThread(this: *TranspilerJob) void {
var vm = this.vm;
const promise = this.promise.swap();
const globalThis = this.globalThis;
this.poll_ref.unref(vm);
const referrer = bun.String.createUTF8(this.referrer);
var log = this.log;
this.log = logger.Log.init(bun.default_allocator);
var resolved_source = this.resolved_source;
const specifier = brk: {
if (this.parse_error != null) {
break :brk bun.String.createUTF8(this.path.text);
}
break :brk resolved_source.specifier;
};
resolved_source.tag = brk: {
if (resolved_source.commonjs_exports_len > 0) {
const actual_package_json: *PackageJSON = brk2: {
// this should already be cached virtually always so it's fine to do this
const dir_info = (vm.bundler.resolver.readDirInfo(this.path.name.dir) catch null) orelse
break :brk .javascript;
break :brk2 dir_info.package_json orelse dir_info.enclosing_package_json;
} orelse break :brk .javascript;
if (actual_package_json.module_type == .esm) {
break :brk ResolvedSource.Tag.package_json_type_module;
}
}
break :brk ResolvedSource.Tag.javascript;
};
const parse_error = this.parse_error;
if (!vm.transpiler_store.store.hive.in(this)) {
this.promise.deinit();
}
this.deinit();
_ = vm.transpiler_store.store.hive.put(this);
ModuleLoader.AsyncModule.fulfill(globalThis, promise, resolved_source, parse_error, specifier, referrer, &log);
}
pub fn schedule(this: *TranspilerJob) void {
this.poll_ref.ref(this.vm);
JSC.WorkPool.schedule(&this.work_task);
}
pub fn runFromWorkerThread(work_task: *JSC.WorkPoolTask) void {
@fieldParentPtr(TranspilerJob, "work_task", work_task).run();
}
pub fn run(this: *TranspilerJob) void {
var arena = bun.ArenaAllocator.init(bun.default_allocator);
defer arena.deinit();
const allocator = arena.allocator();
defer this.dispatchToMainThread();
if (this.generation_number != this.vm.transpiler_store.generation_number.load(.Monotonic)) {
this.parse_error = error.TranspilerJobGenerationMismatch;
return;
}
if (ast_memory_store == null) {
ast_memory_store = bun.default_allocator.create(js_ast.ASTMemoryAllocator) catch @panic("out of memory!");
ast_memory_store.?.* = js_ast.ASTMemoryAllocator{
.allocator = allocator,
.previous = null,
};
}
ast_memory_store.?.allocator = allocator;
ast_memory_store.?.reset();
ast_memory_store.?.push();
const path = this.path;
const specifier = this.path.text;
const loader = this.loader;
this.log = logger.Log.init(bun.default_allocator);
var cache = JSC.RuntimeTranspilerCache{
.output_code_allocator = allocator,
.sourcemap_allocator = bun.default_allocator,
};
var vm = this.vm;
var bundler: bun.Bundler = undefined;
bundler = vm.bundler;
bundler.setAllocator(allocator);
bundler.setLog(&this.log);
bundler.resolver.opts = bundler.options;
bundler.macro_context = null;
bundler.linker.resolver = &bundler.resolver;
var fd: ?StoredFileDescriptorType = null;
var package_json: ?*PackageJSON = null;
const hash = JSC.GenericWatcher.getHash(path.text);
switch (vm.bun_watcher) {
.hot, .watch => {
if (vm.bun_watcher.indexOf(hash)) |index| {
const _fd = vm.bun_watcher.watchlist().items(.fd)[index];
fd = if (!_fd.isStdio()) _fd else null;
package_json = vm.bun_watcher.watchlist().items(.package_json)[index];
}
},
else => {},
}
// this should be a cheap lookup because 24 bytes == 8 * 3 so it's read 3 machine words
const is_node_override = strings.hasPrefixComptime(specifier, "/bun-vfs/node_modules/");
const macro_remappings = if (vm.macro_mode or !vm.has_any_macro_remappings or is_node_override)
MacroRemap{}
else
bundler.options.macro_remap;
var fallback_source: logger.Source = undefined;
// Usually, we want to close the input file automatically.
//
// If we're re-using the file descriptor from the fs watcher
// Do not close it because that will break the kqueue-based watcher
//
var should_close_input_file_fd = fd == null;
var input_file_fd: StoredFileDescriptorType = .zero;
const is_main = vm.main.len == path.text.len and
vm.main_hash == hash and
strings.eqlLong(vm.main, path.text, false);
var parse_options = Bundler.ParseOptions{
.allocator = allocator,
.path = path,
.loader = loader,
.dirname_fd = .zero,
.file_descriptor = fd,
.file_fd_ptr = &input_file_fd,
.file_hash = hash,
.macro_remappings = macro_remappings,
.jsx = bundler.options.jsx,
.emit_decorator_metadata = bundler.options.emit_decorator_metadata,
.virtual_source = null,
.dont_bundle_twice = true,
.allow_commonjs = true,
.inject_jest_globals = bundler.options.rewrite_jest_for_tests and is_main,
.set_breakpoint_on_first_line = vm.debugger != null and
vm.debugger.?.set_breakpoint_on_first_line and
is_main and
setBreakPointOnFirstLine(),
.runtime_transpiler_cache = if (!JSC.RuntimeTranspilerCache.is_disabled) &cache else null,
.remove_cjs_module_wrapper = is_main and vm.module_loader.eval_source != null,
};
defer {
if (should_close_input_file_fd and input_file_fd != .zero) {
_ = bun.sys.close(input_file_fd);
input_file_fd = .zero;
}
}
if (is_node_override) {
if (NodeFallbackModules.contentsFromPath(specifier)) |code| {
const fallback_path = Fs.Path.initWithNamespace(specifier, "node");
fallback_source = logger.Source{ .path = fallback_path, .contents = code, .key_path = fallback_path };
parse_options.virtual_source = &fallback_source;
}
}
var parse_result: bun.bundler.ParseResult = bundler.parseMaybeReturnFileOnlyAllowSharedBuffer(
parse_options,
null,
false,
false,
) orelse {
if (vm.isWatcherEnabled()) {
if (input_file_fd != .zero) {
if (!is_node_override and std.fs.path.isAbsolute(path.text) and !strings.contains(path.text, "node_modules")) {
should_close_input_file_fd = false;
_ = vm.bun_watcher.addFile(
input_file_fd,
path.text,
hash,
loader,
.zero,
package_json,
true,
);
}
}
}
this.parse_error = error.ParseError;
return;
};
if (vm.isWatcherEnabled()) {
if (input_file_fd != .zero) {
if (!is_node_override and
std.fs.path.isAbsolute(path.text) and !strings.contains(path.text, "node_modules"))
{
should_close_input_file_fd = false;
_ = vm.bun_watcher.addFile(
input_file_fd,
path.text,
hash,
loader,
.zero,
package_json,
true,
);
}
}
}
if (cache.entry) |*entry| {
const duped = String.createUTF8(specifier);
vm.source_mappings.putMappings(parse_result.source, .{
.list = .{ .items = @constCast(entry.sourcemap), .capacity = entry.sourcemap.len },
.allocator = bun.default_allocator,
}) catch {};
if (comptime Environment.dump_source) {
dumpSourceString(specifier, entry.output_code.byteSlice());
}
this.resolved_source = ResolvedSource{
.allocator = null,
.source_code = switch (entry.output_code) {
.string => entry.output_code.string,
.utf8 => brk: {
const result = bun.String.createUTF8(entry.output_code.utf8);
cache.output_code_allocator.free(entry.output_code.utf8);
entry.output_code.utf8 = "";
break :brk result;
},
},
.specifier = duped,
.source_url = duped.createIfDifferent(path.text),
.hash = 0,
.commonjs_exports_len = if (entry.metadata.module_type == .cjs) std.math.maxInt(u32) else 0,
};
return;
}
if (parse_result.already_bundled) {
const duped = String.createUTF8(specifier);
this.resolved_source = ResolvedSource{
.allocator = null,
.source_code = bun.String.createLatin1(parse_result.source.contents),
.specifier = duped,
.source_url = duped.createIfDifferent(path.text),
.hash = 0,
};
this.resolved_source.source_code.ensureHash();
return;
}
for (parse_result.ast.import_records.slice()) |*import_record_| {
var import_record: *bun.ImportRecord = import_record_;
if (JSC.HardcodedModule.Aliases.get(import_record.path.text, bundler.options.target)) |replacement| {
import_record.path.text = replacement.path;
import_record.tag = replacement.tag;
import_record.is_external_without_side_effects = true;
continue;
}
if (bundler.options.rewrite_jest_for_tests) {
if (strings.eqlComptime(
import_record.path.text,
"@jest/globals",
) or strings.eqlComptime(
import_record.path.text,
"vitest",
)) {
import_record.path.namespace = "bun";
import_record.tag = .bun_test;
import_record.path.text = "test";
import_record.is_external_without_side_effects = true;
continue;
}
}
if (strings.hasPrefixComptime(import_record.path.text, "bun:")) {
import_record.path = Fs.Path.init(import_record.path.text["bun:".len..]);
import_record.path.namespace = "bun";
import_record.is_external_without_side_effects = true;
if (strings.eqlComptime(import_record.path.text, "test")) {
import_record.tag = .bun_test;
}
}
}
if (source_code_printer == null) {
const writer = try js_printer.BufferWriter.init(bun.default_allocator);
source_code_printer = bun.default_allocator.create(js_printer.BufferPrinter) catch unreachable;
source_code_printer.?.* = js_printer.BufferPrinter.init(writer);
source_code_printer.?.ctx.append_null_byte = false;
}
var printer = source_code_printer.?.*;
printer.ctx.reset();
{
var mapper = vm.sourceMapHandler(&printer);
defer source_code_printer.?.* = printer;
_ = bundler.printWithSourceMap(
parse_result,
@TypeOf(&printer),
&printer,
.esm_ascii,
mapper.get(),
) catch |err| {
this.parse_error = err;
return;
};
}
if (comptime Environment.dump_source) {
dumpSource(specifier, &printer);
}
const duped = String.createUTF8(specifier);
const source_code = brk: {
const written = printer.ctx.getWritten();
const result = cache.output_code orelse bun.String.createLatin1(written);
if (written.len > 1024 * 1024 * 2 or vm.smol) {
printer.ctx.buffer.deinit();
source_code_printer.?.* = printer;
}
// In a benchmarking loading @babel/standalone 100 times:
//
// After ensureHash:
// 354.00 ms 4.2% 354.00 ms WTF::StringImpl::hashSlowCase() const
//
// Before ensureHash:
// 506.00 ms 6.1% 506.00 ms WTF::StringImpl::hashSlowCase() const
//
result.ensureHash();
break :brk result;
};
this.resolved_source = ResolvedSource{
.allocator = null,
.source_code = source_code,
.specifier = duped,
.source_url = duped.createIfDifferent(path.text),
.commonjs_exports = null,
.commonjs_exports_len = if (parse_result.ast.exports_kind == .cjs)
std.math.maxInt(u32)
else
0,
.hash = 0,
};
}
};
};
pub const ModuleLoader = struct {
transpile_source_code_arena: ?*bun.ArenaAllocator = null,
eval_source: ?*logger.Source = null,
pub var is_allowed_to_use_internal_testing_apis = false;
/// This must be called after calling transpileSourceCode
pub fn resetArena(this: *ModuleLoader, jsc_vm: *VirtualMachine) void {
bun.assert(&jsc_vm.module_loader == this);
if (this.transpile_source_code_arena) |arena| {
if (jsc_vm.smol) {
_ = arena.reset(.free_all);
} else {
_ = arena.reset(.{ .retain_with_limit = 8 * 1024 * 1024 });
}
}
}
pub fn resolveEmbeddedFile(vm: *JSC.VirtualMachine, input_path: []const u8, extname: []const u8) ?[]const u8 {
if (input_path.len == 0) return null;
var graph = vm.standalone_module_graph orelse return null;
const file = graph.find(input_path) orelse return null;
if (comptime Environment.isLinux) {
// TODO: use /proc/fd/12346 instead! Avoid the copy!
}
// atomically write to a tmpfile and then move it to the final destination
var tmpname_buf: [bun.MAX_PATH_BYTES]u8 = undefined;
const tmpfilename = bun.sliceTo(bun.fs.FileSystem.instance.tmpname(extname, &tmpname_buf, bun.hash(file.name)) catch return null, 0);
const tmpdir = bun.fs.FileSystem.instance.tmpdir() catch return null;
// First we open the tmpfile, to avoid any other work in the event of failure.
const tmpfile = bun.Tmpfile.create(bun.toFD(tmpdir.fd), tmpfilename).unwrap() catch return null;
defer {
_ = bun.sys.close(tmpfile.fd);
}
switch (JSC.Node.NodeFS.writeFileWithPathBuffer(
&tmpname_buf, // not used
.{
.data = .{
.encoded_slice = JSC.ZigString.Slice.fromUTF8NeverFree(file.contents),
},
.dirfd = bun.toFD(tmpdir.fd),
.file = .{
.fd = tmpfile.fd,
},
.encoding = .buffer,
},
)) {
.err => {
return null;
},
else => {},
}
return bun.path.joinAbs(bun.fs.FileSystem.instance.fs.tmpdirPath(), .auto, tmpfilename);
}
pub const AsyncModule = struct {
// This is all the state used by the printer to print the module
parse_result: ParseResult,
// stmt_blocks: []*js_ast.Stmt.Data.Store.All.Block = &[_]*js_ast.Stmt.Data.Store.All.Block{},
// expr_blocks: []*js_ast.Expr.Data.Store.All.Block = &[_]*js_ast.Expr.Data.Store.All.Block{},
promise: JSC.Strong = .{},
path: Fs.Path,
specifier: string = "",
referrer: string = "",
string_buf: []u8 = &[_]u8{},
fd: ?StoredFileDescriptorType = null,
package_json: ?*PackageJSON = null,
loader: Api.Loader,
hash: u32 = std.math.maxInt(u32),
globalThis: *JSC.JSGlobalObject = undefined,
arena: *bun.ArenaAllocator,
// This is the specific state for making it async
poll_ref: Async.KeepAlive = .{},
any_task: JSC.AnyTask = undefined,
pub const Id = u32;
const PackageDownloadError = struct {
name: []const u8,
resolution: Install.Resolution,
err: anyerror,
url: []const u8,
};
const PackageResolveError = struct {
name: []const u8,
err: anyerror,
url: []const u8,
version: Dependency.Version,
};
pub const Queue = struct {
map: Map = .{},
scheduled: u32 = 0,
concurrent_task_count: std.atomic.Value(u32) = std.atomic.Value(u32).init(0),
const DeferredDependencyError = struct {
dependency: Dependency,
root_dependency_id: Install.DependencyID,
err: anyerror,
};
pub const Map = std.ArrayListUnmanaged(AsyncModule);
pub fn enqueue(this: *Queue, globalObject: *JSC.JSGlobalObject, opts: anytype) void {
debug("enqueue: {s}", .{opts.specifier});
var module = AsyncModule.init(opts, globalObject) catch unreachable;
module.poll_ref.ref(this.vm());
this.map.append(this.vm().allocator, module) catch unreachable;
this.vm().packageManager().drainDependencyList();
}
pub fn onDependencyError(ctx: *anyopaque, dependency: Dependency, root_dependency_id: Install.DependencyID, err: anyerror) void {
var this = bun.cast(*Queue, ctx);
debug("onDependencyError: {s}", .{this.vm().packageManager().lockfile.str(&dependency.name)});
var modules: []AsyncModule = this.map.items;
var i: usize = 0;
outer: for (modules) |module_| {
var module = module_;
const root_dependency_ids = module.parse_result.pending_imports.items(.root_dependency_id);
for (root_dependency_ids, 0..) |dep, dep_i| {
if (dep != root_dependency_id) continue;
module.resolveError(
this.vm(),
module.parse_result.pending_imports.items(.import_record_id)[dep_i],
.{
.name = this.vm().packageManager().lockfile.str(&dependency.name),
.err = err,
.url = "",
.version = dependency.version,
},
) catch unreachable;
continue :outer;
}
modules[i] = module;
i += 1;
}
this.map.items.len = i;
}
pub fn onWakeHandler(ctx: *anyopaque, _: *PackageManager) void {
debug("onWake", .{});
var this = bun.cast(*Queue, ctx);
const concurrent_task = bun.default_allocator.create(JSC.ConcurrentTask) catch @panic("OOM");
concurrent_task.* = .{
.task = JSC.Task.init(this),
.auto_delete = true,
};
this.vm().enqueueTaskConcurrent(concurrent_task);
}
pub fn onPoll(this: *Queue) void {
debug("onPoll", .{});
this.runTasks();
this.pollModules();
}
pub fn runTasks(this: *Queue) void {
var pm = this.vm().packageManager();
if (Output.enable_ansi_colors_stderr) {
pm.startProgressBarIfNone();
pm.runTasks(
*Queue,
this,
.{
.onExtract = {},
.onResolve = onResolve,
.onPackageManifestError = onPackageManifestError,
.onPackageDownloadError = onPackageDownloadError,
.progress_bar = true,
},
true,
PackageManager.Options.LogLevel.default,
) catch unreachable;
} else {
pm.runTasks(
*Queue,
this,
.{
.onExtract = {},
.onResolve = onResolve,
.onPackageManifestError = onPackageManifestError,
.onPackageDownloadError = onPackageDownloadError,
},
true,
PackageManager.Options.LogLevel.default_no_progress,
) catch unreachable;
}
}
pub fn onResolve(_: *Queue) void {
debug("onResolve", .{});
}
pub fn onPackageManifestError(
this: *Queue,
name: []const u8,
err: anyerror,
url: []const u8,
) void {
debug("onPackageManifestError: {s}", .{name});
var modules: []AsyncModule = this.map.items;
var i: usize = 0;
outer: for (modules) |module_| {
var module = module_;
const tags = module.parse_result.pending_imports.items(.tag);
for (tags, 0..) |tag, tag_i| {
if (tag == .resolve) {
const esms = module.parse_result.pending_imports.items(.esm);
const esm = esms[tag_i];
const string_bufs = module.parse_result.pending_imports.items(.string_buf);
if (!strings.eql(esm.name.slice(string_bufs[tag_i]), name)) continue;
const versions = module.parse_result.pending_imports.items(.dependency);
module.resolveError(
this.vm(),
module.parse_result.pending_imports.items(.import_record_id)[tag_i],
.{
.name = name,
.err = err,
.url = url,
.version = versions[tag_i],
},
) catch unreachable;
continue :outer;
}
}
modules[i] = module;
i += 1;
}
this.map.items.len = i;
}
pub fn onPackageDownloadError(
this: *Queue,
package_id: Install.PackageID,
name: []const u8,
resolution: *const Install.Resolution,
err: anyerror,
url: []const u8,
) void {
debug("onPackageDownloadError: {s}", .{name});
const resolution_ids = this.vm().packageManager().lockfile.buffers.resolutions.items;
var modules: []AsyncModule = this.map.items;
var i: usize = 0;
outer: for (modules) |module_| {
var module = module_;
const record_ids = module.parse_result.pending_imports.items(.import_record_id);
const root_dependency_ids = module.parse_result.pending_imports.items(.root_dependency_id);
for (root_dependency_ids, 0..) |dependency_id, import_id| {
if (resolution_ids[dependency_id] != package_id) continue;
module.downloadError(
this.vm(),
record_ids[import_id],
.{
.name = name,
.resolution = resolution.*,
.err = err,
.url = url,
},
) catch unreachable;
continue :outer;
}
modules[i] = module;
i += 1;
}
this.map.items.len = i;
}
pub fn pollModules(this: *Queue) void {
var pm = this.vm().packageManager();
if (pm.pending_tasks.load(.Monotonic) > 0) return;
var modules: []AsyncModule = this.map.items;
var i: usize = 0;
for (modules) |mod| {
var module = mod;