forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbundler.zig
1899 lines (1679 loc) · 75.7 KB
/
bundler.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 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 FeatureFlags = bun.FeatureFlags;
const C = bun.C;
const std = @import("std");
const lex = bun.js_lexer;
const logger = @import("root").bun.logger;
const options = @import("options.zig");
const js_parser = bun.js_parser;
const json_parser = bun.JSON;
const js_printer = bun.js_printer;
const js_ast = bun.JSAst;
const linker = @import("linker.zig");
const Ref = @import("ast/base.zig").Ref;
const Define = @import("defines.zig").Define;
const DebugOptions = @import("./cli.zig").Command.DebugOptions;
const ThreadPoolLib = @import("./thread_pool.zig");
const Fs = @import("fs.zig");
const schema = @import("api/schema.zig");
const Api = schema.Api;
const _resolver = @import("./resolver/resolver.zig");
const sync = @import("sync.zig");
const ImportRecord = @import("./import_record.zig").ImportRecord;
const allocators = @import("./allocators.zig");
const MimeType = @import("./http/mime_type.zig");
const resolve_path = @import("./resolver/resolve_path.zig");
const runtime = @import("./runtime.zig");
const PackageJSON = @import("./resolver/package_json.zig").PackageJSON;
const MacroRemap = @import("./resolver/package_json.zig").MacroMap;
const DebugLogs = _resolver.DebugLogs;
const NodeModuleBundle = @import("./node_module_bundle.zig").NodeModuleBundle;
const Router = @import("./router.zig");
const isPackagePath = _resolver.isPackagePath;
const Css = @import("css_scanner.zig");
const DotEnv = @import("./env_loader.zig");
const Lock = @import("./lock.zig").Lock;
const NodeFallbackModules = @import("./node_fallbacks.zig");
const CacheEntry = @import("./cache.zig").FsCacheEntry;
const Analytics = @import("./analytics/analytics_thread.zig");
const URL = @import("./url.zig").URL;
const Report = @import("./report.zig");
const Linker = linker.Linker;
const Resolver = _resolver.Resolver;
const TOML = @import("./toml/toml_parser.zig").TOML;
const JSC = @import("root").bun.JSC;
const PackageManager = @import("./install/install.zig").PackageManager;
pub fn MacroJSValueType_() type {
if (comptime JSC.is_bindgen) {
return struct {
pub const zero = @This(){};
};
}
return JSC.JSValue;
}
pub const MacroJSValueType = MacroJSValueType_();
const default_macro_js_value = if (JSC.is_bindgen) MacroJSValueType{} else JSC.JSValue.zero;
const EntryPoints = @import("./bundler/entry_points.zig");
const SystemTimer = @import("./system_timer.zig").Timer;
pub usingnamespace EntryPoints;
// How it works end-to-end
// 1. Resolve a file path from input using the resolver
// 2. Look at the extension of that file path, and determine a loader
// 3. If the loader is .js, .jsx, .ts, .tsx, or .json, run it through our JavaScript Parser
// IF serving via HTTP and it's parsed without errors:
// 4. If parsed without errors, generate a strong ETag & write the output to a buffer that sends to the in the Printer.
// 4. Else, write any errors to error page (which doesn't exist yet)
// IF writing to disk AND it's parsed without errors:
// 4. Write the output to a temporary file.
// Why? Two reasons.
// 1. At this point, we don't know what the best output path is.
// Most of the time, you want the shortest common path, which you can't know until you've
// built & resolved all paths.
// Consider this directory tree:
// - /Users/jarred/Code/app/src/index.tsx
// - /Users/jarred/Code/app/src/Button.tsx
// - /Users/jarred/Code/app/assets/logo.png
// - /Users/jarred/Code/app/src/Button.css
// - /Users/jarred/Code/app/node_modules/react/index.js
// - /Users/jarred/Code/app/node_modules/react/cjs/react.development.js
// Remember that we cannot know which paths need to be resolved without parsing the JavaScript.
// If we stopped here: /Users/jarred/Code/app/src/Button.tsx
// We would choose /Users/jarred/Code/app/src/ as the directory
// Then, that would result in a directory structure like this:
// - /Users/jarred/Code/app/src/Users/jarred/Code/app/node_modules/react/cjs/react.development.js
// Which is absolutely insane
//
// 2. We will need to write to disk at some point!
// - If we delay writing to disk, we need to print & allocate a potentially quite large
// buffer (react-dom.development.js is 550 KB)
// ^ This is how it used to work!
// - If we delay printing, we need to keep the AST around. Which breaks all our
// memory-saving recycling logic since that could be many many ASTs.
// 5. Once all files are written, determine the shortest common path
// 6. Move all the temporary files to their intended destinations
// IF writing to disk AND it's a file-like loader
// 4. Hash the contents
// - rewrite_paths.put(absolute_path, hash(file(absolute_path)))
// 5. Resolve any imports of this file to that hash(file(absolute_path))
// 6. Append to the files array with the new filename
// 7. When parsing & resolving is over, just copy the file.
// - on macOS, ensure it does an APFS shallow clone so that doesn't use disk space (only possible if file doesn't already exist)
// fclonefile
// IF serving via HTTP AND it's a file-like loader:
// 4. Use os.sendfile so copying/reading the file happens in the kernel instead of in bun.
// This unfortunately means content hashing for HTTP server is unsupported, but metadata etags work
// For each imported file, GOTO 1.
pub const ParseResult = struct {
source: logger.Source,
loader: options.Loader,
ast: js_ast.Ast,
already_bundled: bool = false,
input_fd: ?StoredFileDescriptorType = null,
empty: bool = false,
pending_imports: _resolver.PendingResolution.List = .{},
pub fn isPendingImport(this: *const ParseResult, id: u32) bool {
const import_record_ids = this.pending_imports.items(.import_record_id);
return std.mem.indexOfScalar(u32, import_record_ids, id) != null;
}
/// **DO NOT CALL THIS UNDER NORMAL CIRCUMSTANCES**
/// Normally, we allocate each AST in an arena and free all at once
/// So this function only should be used when we globally allocate an AST
pub fn deinit(this: *ParseResult) void {
_resolver.PendingResolution.deinitListItems(this.pending_imports, bun.default_allocator);
this.pending_imports.deinit(bun.default_allocator);
this.ast.deinit();
bun.default_allocator.free(bun.constStrToU8(this.source.contents));
}
};
const cache_files = false;
pub const PluginRunner = struct {
global_object: *JSC.JSGlobalObject,
allocator: std.mem.Allocator,
pub fn extractNamespace(specifier: string) string {
const colon = strings.indexOfChar(specifier, ':') orelse return "";
return specifier[0..colon];
}
pub fn couldBePlugin(specifier: string) bool {
if (strings.lastIndexOfChar(specifier, '.')) |last_dor| {
const ext = specifier[last_dor + 1 ..];
// '.' followed by either a letter or a non-ascii character
// maybe there are non-ascii file extensions?
// we mostly want to cheaply rule out "../" and ".." and "./"
if (ext.len > 0 and ((ext[0] >= 'a' and ext[0] <= 'z') or (ext[0] >= 'A' and ext[0] <= 'Z') or ext[0] > 127))
return true;
}
return (!std.fs.path.isAbsolute(specifier) and strings.containsChar(specifier, ':'));
}
pub fn onResolve(
this: *PluginRunner,
specifier: []const u8,
importer: []const u8,
log: *logger.Log,
loc: logger.Loc,
target: JSC.JSGlobalObject.BunPluginTarget,
) ?Fs.Path {
var global = this.global_object;
const namespace_slice = extractNamespace(specifier);
const namespace = if (namespace_slice.len > 0 and !strings.eqlComptime(namespace_slice, "file"))
bun.String.init(namespace_slice)
else
bun.String.empty;
const on_resolve_plugin = global.runOnResolvePlugins(
namespace,
bun.String.init(specifier).substring(if (namespace.length() > 0) namespace.length() + 1 else 0),
bun.String.init(importer),
target,
) orelse return null;
const path_value = on_resolve_plugin.get(global, "path") orelse return null;
if (path_value.isEmptyOrUndefinedOrNull()) return null;
if (!path_value.isString()) {
log.addError(null, loc, "Expected \"path\" to be a string") catch unreachable;
return null;
}
var file_path = path_value.toBunString(global);
if (file_path.length() == 0) {
log.addError(
null,
loc,
"Expected \"path\" to be a non-empty string in onResolve plugin",
) catch unreachable;
return null;
} else if
// TODO: validate this better
(file_path.eqlComptime(".") or
file_path.eqlComptime("..") or
file_path.eqlComptime("...") or
file_path.eqlComptime(" "))
{
log.addError(
null,
loc,
"Invalid file path from onResolve plugin",
) catch unreachable;
return null;
}
var static_namespace = true;
const user_namespace: bun.String = brk: {
if (on_resolve_plugin.get(global, "namespace")) |namespace_value| {
if (!namespace_value.isString()) {
log.addError(null, loc, "Expected \"namespace\" to be a string") catch unreachable;
return null;
}
const namespace_str = namespace_value.toBunString(global);
if (namespace_str.length() == 0) {
break :brk bun.String.init("file");
}
if (namespace_str.eqlComptime("file")) {
break :brk bun.String.init("file");
}
if (namespace_str.eqlComptime("bun")) {
break :brk bun.String.init("bun");
}
if (namespace_str.eqlComptime("node")) {
break :brk bun.String.init("node");
}
static_namespace = false;
break :brk namespace_str;
}
break :brk bun.String.init("file");
};
if (static_namespace) {
return Fs.Path.initWithNamespace(
std.fmt.allocPrint(this.allocator, "{any}", .{file_path}) catch unreachable,
user_namespace.byteSlice(),
);
} else {
return Fs.Path.initWithNamespace(
std.fmt.allocPrint(this.allocator, "{any}", .{file_path}) catch unreachable,
std.fmt.allocPrint(this.allocator, "{any}", .{user_namespace}) catch unreachable,
);
}
}
pub fn onResolveJSC(
this: *const PluginRunner,
namespace: bun.String,
specifier: bun.String,
importer: bun.String,
target: JSC.JSGlobalObject.BunPluginTarget,
) ?JSC.ErrorableString {
var global = this.global_object;
const on_resolve_plugin = global.runOnResolvePlugins(
if (namespace.length() > 0 and !namespace.eqlComptime("file"))
namespace
else
bun.String.static(""),
specifier,
importer,
target,
) orelse return null;
const path_value = on_resolve_plugin.get(global, "path") orelse return null;
if (path_value.isEmptyOrUndefinedOrNull()) return null;
if (!path_value.isString()) {
return JSC.ErrorableString.err(
error.JSErrorObject,
bun.String.static("Expected \"path\" to be a string in onResolve plugin").toErrorInstance(this.global_object).asVoid(),
);
}
const file_path = path_value.toBunString(global);
if (file_path.length() == 0) {
return JSC.ErrorableString.err(
error.JSErrorObject,
bun.String.static("Expected \"path\" to be a non-empty string in onResolve plugin").toErrorInstance(this.global_object).asVoid(),
);
} else if
// TODO: validate this better
(file_path.eqlComptime(".") or
file_path.eqlComptime("..") or
file_path.eqlComptime("...") or
file_path.eqlComptime(" "))
{
return JSC.ErrorableString.err(
error.JSErrorObject,
bun.String.static("\"path\" is invalid in onResolve plugin").toErrorInstance(this.global_object).asVoid(),
);
}
var static_namespace = true;
const user_namespace: bun.String = brk: {
if (on_resolve_plugin.get(global, "namespace")) |namespace_value| {
if (!namespace_value.isString()) {
return JSC.ErrorableString.err(
error.JSErrorObject,
bun.String.static("Expected \"namespace\" to be a string").toErrorInstance(this.global_object).asVoid(),
);
}
const namespace_str = namespace_value.toBunString(global);
if (namespace_str.length() == 0) {
break :brk bun.String.static("file");
}
if (namespace_str.eqlComptime("file")) {
break :brk bun.String.static("file");
}
if (namespace_str.eqlComptime("bun")) {
break :brk bun.String.static("bun");
}
if (namespace_str.eqlComptime("node")) {
break :brk bun.String.static("node");
}
static_namespace = false;
break :brk namespace_str;
}
break :brk bun.String.static("file");
};
// Our super slow way of cloning the string into memory owned by JSC
var combined_string = std.fmt.allocPrint(
this.allocator,
"{any}:{any}",
.{ user_namespace, file_path },
) catch unreachable;
var out_ = bun.String.init(combined_string);
const out = out_.toJS(this.global_object).toBunString(this.global_object);
this.allocator.free(combined_string);
return JSC.ErrorableString.ok(out);
}
};
pub const Bundler = struct {
options: options.BundleOptions,
log: *logger.Log,
allocator: std.mem.Allocator,
result: options.TransformResult = undefined,
resolver: Resolver,
fs: *Fs.FileSystem,
output_files: std.ArrayList(options.OutputFile),
resolve_results: *ResolveResults,
resolve_queue: ResolveQueue,
elapsed: u64 = 0,
needs_runtime: bool = false,
router: ?Router = null,
source_map: options.SourceMapOption = .none,
linker: Linker,
timer: SystemTimer = undefined,
env: *DotEnv.Loader,
macro_context: ?js_ast.Macro.MacroContext = null,
pub const isCacheEnabled = cache_files;
pub fn clone(this: *Bundler, allocator: std.mem.Allocator, to: *Bundler) !void {
to.* = this.*;
to.setAllocator(allocator);
to.log = try allocator.create(logger.Log);
to.log.* = logger.Log.init(allocator);
to.setLog(to.log);
to.macro_context = null;
to.linker.resolver = &to.resolver;
}
pub inline fn getPackageManager(this: *Bundler) *PackageManager {
return this.resolver.getPackageManager();
}
pub fn setLog(this: *Bundler, log: *logger.Log) void {
this.log = log;
this.linker.log = log;
this.resolver.log = log;
}
pub fn setAllocator(this: *Bundler, allocator: std.mem.Allocator) void {
this.allocator = allocator;
this.linker.allocator = allocator;
this.resolver.allocator = allocator;
}
pub inline fn resolveEntryPoint(bundler: *Bundler, entry_point: string) anyerror!_resolver.Result {
return bundler.resolver.resolve(bundler.fs.top_level_dir, entry_point, .entry_point) catch |err| {
const has_dot_slash_form = !strings.hasPrefix(entry_point, "./") and brk: {
return bundler.resolver.resolve(bundler.fs.top_level_dir, try strings.append(bundler.allocator, "./", entry_point), .entry_point) catch break :brk false;
};
_ = has_dot_slash_form;
bundler.log.addErrorFmt(null, logger.Loc.Empty, bundler.allocator, "{s} resolving \"{s}\" (entry point)", .{ @errorName(err), entry_point }) catch unreachable;
return err;
};
}
pub fn init(
allocator: std.mem.Allocator,
log: *logger.Log,
opts: Api.TransformOptions,
existing_bundle: ?*NodeModuleBundle,
env_loader_: ?*DotEnv.Loader,
) !Bundler {
js_ast.Expr.Data.Store.create(allocator);
js_ast.Stmt.Data.Store.create(allocator);
var fs = try Fs.FileSystem.init(
opts.absolute_working_dir,
);
const bundle_options = try options.BundleOptions.fromApi(
allocator,
fs,
log,
opts,
existing_bundle,
);
var env_loader: *DotEnv.Loader = env_loader_ orelse DotEnv.instance orelse brk: {
var map = try allocator.create(DotEnv.Map);
map.* = DotEnv.Map.init(allocator);
var loader = try allocator.create(DotEnv.Loader);
loader.* = DotEnv.Loader.init(map, allocator);
break :brk loader;
};
if (DotEnv.instance == null) {
DotEnv.instance = env_loader;
}
env_loader.quiet = !log.level.atLeast(.warn);
// var pool = try allocator.create(ThreadPool);
// try pool.init(ThreadPool.InitConfig{
// .allocator = allocator,
// });
var resolve_results = try allocator.create(ResolveResults);
resolve_results.* = ResolveResults.init(allocator);
return Bundler{
.options = bundle_options,
.fs = fs,
.allocator = allocator,
.timer = SystemTimer.start() catch @panic("Timer fail"),
.resolver = Resolver.init1(allocator, log, fs, bundle_options),
.log = log,
// .thread_pool = pool,
.linker = undefined,
.result = options.TransformResult{ .outbase = bundle_options.output_dir },
.resolve_results = resolve_results,
.resolve_queue = ResolveQueue.init(allocator),
.output_files = std.ArrayList(options.OutputFile).init(allocator),
.env = env_loader,
};
}
pub fn configureLinkerWithAutoJSX(bundler: *Bundler, auto_jsx: bool) void {
bundler.linker = Linker.init(
bundler.allocator,
bundler.log,
&bundler.resolve_queue,
&bundler.options,
&bundler.resolver,
bundler.resolve_results,
bundler.fs,
);
if (auto_jsx) {
// If we don't explicitly pass JSX, try to get it from the root tsconfig
if (bundler.options.transform_options.jsx == null) {
// Most of the time, this will already be cached
if (bundler.resolver.readDirInfo(bundler.fs.top_level_dir) catch null) |root_dir| {
if (root_dir.tsconfig_json) |tsconfig| {
bundler.options.jsx = tsconfig.jsx;
}
}
}
}
}
pub fn configureLinker(bundler: *Bundler) void {
bundler.configureLinkerWithAutoJSX(true);
}
pub fn runEnvLoader(this: *Bundler) !void {
switch (this.options.env.behavior) {
.prefix, .load_all => {
// Step 1. Load the project root.
const dir_info = this.resolver.readDirInfo(this.fs.top_level_dir) catch return orelse return;
if (dir_info.tsconfig_json) |tsconfig| {
this.options.jsx = tsconfig.mergeJSX(this.options.jsx);
}
var dir = dir_info.getEntries(this.resolver.generation) orelse return;
// Process always has highest priority.
const was_production = this.options.production;
this.env.loadProcess();
const has_production_env = this.env.isProduction();
if (!was_production and has_production_env) {
this.options.setProduction(true);
}
if (!has_production_env and this.options.isTest()) {
try this.env.load(&this.fs.fs, dir, .@"test");
} else if (this.options.production) {
try this.env.load(&this.fs.fs, dir, .production);
} else {
try this.env.load(&this.fs.fs, dir, .development);
}
},
.disable => {
this.env.loadProcess();
if (this.env.isProduction()) {
this.options.setProduction(true);
}
},
else => {},
}
if (this.env.map.get("DO_NOT_TRACK")) |dnt| {
// https://do-not-track.dev/
if (strings.eqlComptime(dnt, "1")) {
Analytics.disabled = true;
}
}
Analytics.is_ci = Analytics.is_ci or this.env.isCI();
if (strings.eqlComptime(this.env.map.get("BUN_DISABLE_TRANSPILER") orelse "0", "1")) {
this.options.disable_transpilation = true;
}
Analytics.disabled = Analytics.disabled or this.env.map.get("HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET") != null;
}
// This must be run after a framework is configured, if a framework is enabled
pub fn configureDefines(this: *Bundler) !void {
if (this.options.defines_loaded) {
return;
}
if (this.options.target == .bun_macro) {
this.options.env.behavior = .prefix;
this.options.env.prefix = "BUN_";
}
try this.runEnvLoader();
this.options.jsx.setProduction(this.env.isProduction());
js_ast.Expr.Data.Store.create(this.allocator);
js_ast.Stmt.Data.Store.create(this.allocator);
defer js_ast.Expr.Data.Store.reset();
defer js_ast.Stmt.Data.Store.reset();
if (this.options.framework) |framework| {
if (this.options.target.isClient()) {
try this.options.loadDefines(this.allocator, this.env, &framework.client.env);
} else {
try this.options.loadDefines(this.allocator, this.env, &framework.server.env);
}
} else {
try this.options.loadDefines(this.allocator, this.env, &this.options.env);
}
if (this.options.define.dots.get("NODE_ENV")) |NODE_ENV| {
if (NODE_ENV.len > 0 and NODE_ENV[0].data.value == .e_string and NODE_ENV[0].data.value.e_string.eqlComptime("production")) {
this.options.production = true;
if (this.options.target.isBun()) {
if (strings.eqlComptime(this.options.jsx.package_name, "react")) {
if (this.options.jsx_optimization_inline == null) {
this.options.jsx_optimization_inline = true;
}
if (this.options.jsx_optimization_hoist == null and (this.options.jsx_optimization_inline orelse false)) {
this.options.jsx_optimization_hoist = true;
}
}
}
}
}
}
pub fn configureFramework(
this: *Bundler,
comptime load_defines: bool,
) !void {
if (this.options.framework) |*framework| {
if (framework.needsResolveFromPackage()) {
var route_config = this.options.routes;
var pair = PackageJSON.FrameworkRouterPair{ .framework = framework, .router = &route_config };
if (framework.development) {
try this.resolver.resolveFramework(framework.package, &pair, .development, load_defines);
} else {
try this.resolver.resolveFramework(framework.package, &pair, .production, load_defines);
}
if (this.options.areDefinesUnset()) {
if (this.options.target.isClient()) {
this.options.env = framework.client.env;
} else {
this.options.env = framework.server.env;
}
}
if (pair.loaded_routes) {
this.options.routes = route_config;
}
framework.resolved = true;
this.options.framework = framework.*;
} else if (!framework.resolved) {
Global.panic("directly passing framework path is not implemented yet!", .{});
}
}
}
pub fn configureFrameworkWithResolveResult(this: *Bundler, comptime client: bool) !?_resolver.Result {
if (this.options.framework != null) {
try this.configureFramework(true);
if (comptime client) {
if (this.options.framework.?.client.isEnabled()) {
return try this.resolver.resolve(this.fs.top_level_dir, this.options.framework.?.client.path, .stmt);
}
if (this.options.framework.?.fallback.isEnabled()) {
return try this.resolver.resolve(this.fs.top_level_dir, this.options.framework.?.fallback.path, .stmt);
}
} else {
if (this.options.framework.?.server.isEnabled()) {
return try this.resolver.resolve(this.fs.top_level_dir, this.options.framework.?.server, .stmt);
}
}
}
return null;
}
pub fn configureRouter(this: *Bundler, comptime load_defines: bool) !void {
try this.configureFramework(load_defines);
defer {
if (load_defines) {
this.configureDefines() catch {};
}
}
// if you pass just a directory, activate the router configured for the pages directory
// for now:
// - "." is not supported
// - multiple pages directories is not supported
if (!this.options.routes.routes_enabled and this.options.entry_points.len == 1 and !this.options.serve) {
// When inferring:
// - pages directory with a file extension is not supported. e.g. "pages.app/" won't work.
// This is a premature optimization to avoid this magical auto-detection we do here from meaningfully increasing startup time if you're just passing a file
// readDirInfo is a recursive lookup, top-down instead of bottom-up. It opens each folder handle and potentially reads the package.jsons
// So it is not fast! Unless it's already cached.
var paths = [_]string{std.mem.trimLeft(u8, this.options.entry_points[0], "./")};
if (std.mem.indexOfScalar(u8, paths[0], '.') == null) {
var pages_dir_buf: [bun.MAX_PATH_BYTES]u8 = undefined;
var entry = this.fs.absBuf(&paths, &pages_dir_buf);
if (std.fs.path.extension(entry).len == 0) {
bun.constStrToU8(entry).ptr[entry.len] = '/';
// Only throw if they actually passed in a route config and the directory failed to load
var dir_info_ = this.resolver.readDirInfo(entry) catch return;
var dir_info = dir_info_ orelse return;
this.options.routes.dir = dir_info.abs_path;
this.options.routes.extensions = options.RouteConfig.DefaultExtensions[0..];
this.options.routes.routes_enabled = true;
this.router = try Router.init(this.fs, this.allocator, this.options.routes);
try this.router.?.loadRoutes(
this.log,
dir_info,
Resolver,
&this.resolver,
this.fs.top_level_dir,
);
this.router.?.routes.client_framework_enabled = this.options.isFrontendFrameworkEnabled();
return;
}
}
} else if (this.options.routes.routes_enabled) {
var dir_info_ = try this.resolver.readDirInfo(this.options.routes.dir);
var dir_info = dir_info_ orelse return error.MissingRoutesDir;
this.options.routes.dir = dir_info.abs_path;
this.router = try Router.init(this.fs, this.allocator, this.options.routes);
try this.router.?.loadRoutes(
this.log,
dir_info,
Resolver,
&this.resolver,
this.fs.top_level_dir,
);
this.router.?.routes.client_framework_enabled = this.options.isFrontendFrameworkEnabled();
return;
}
// If we get this far, it means they're trying to run the bundler without a preconfigured router
if (this.options.entry_points.len > 0) {
this.options.routes.routes_enabled = false;
}
if (this.router) |*router| {
router.routes.client_framework_enabled = this.options.isFrontendFrameworkEnabled();
}
}
pub fn resetStore(_: *const Bundler) void {
js_ast.Expr.Data.Store.reset();
js_ast.Stmt.Data.Store.reset();
}
pub noinline fn dumpEnvironmentVariables(bundler: *const Bundler) void {
@setCold(true);
const opts = std.json.StringifyOptions{
.whitespace = std.json.StringifyOptions.Whitespace{
.separator = true,
},
};
Output.flush();
std.json.stringify(bundler.env.map.*, opts, Output.writer()) catch unreachable;
Output.flush();
}
pub const BuildResolveResultPair = struct {
written: usize,
input_fd: ?StoredFileDescriptorType,
empty: bool = false,
};
pub fn buildWithResolveResult(
bundler: *Bundler,
resolve_result: _resolver.Result,
allocator: std.mem.Allocator,
loader: options.Loader,
comptime Writer: type,
writer: Writer,
comptime import_path_format: options.BundleOptions.ImportPathFormat,
file_descriptor: ?StoredFileDescriptorType,
filepath_hash: u32,
comptime WatcherType: type,
watcher: *WatcherType,
client_entry_point: ?*EntryPoints.ClientEntryPoint,
origin: URL,
comptime is_source_map: bool,
source_map_handler: ?js_printer.SourceMapHandler,
) !BuildResolveResultPair {
if (resolve_result.is_external) {
return BuildResolveResultPair{
.written = 0,
.input_fd = null,
};
}
errdefer bundler.resetStore();
var file_path = (resolve_result.pathConst() orelse {
return BuildResolveResultPair{
.written = 0,
.input_fd = null,
};
}).*;
if (strings.indexOf(file_path.text, bundler.fs.top_level_dir)) |i| {
file_path.pretty = file_path.text[i + bundler.fs.top_level_dir.len ..];
} else if (!file_path.is_symlink) {
file_path.pretty = allocator.dupe(u8, bundler.fs.relativeTo(file_path.text)) catch unreachable;
}
var old_bundler_allocator = bundler.allocator;
bundler.allocator = allocator;
defer bundler.allocator = old_bundler_allocator;
var old_linker_allocator = bundler.linker.allocator;
defer bundler.linker.allocator = old_linker_allocator;
bundler.linker.allocator = allocator;
switch (loader) {
.css => {
const CSSBundlerHMR = Css.NewBundler(
Writer,
@TypeOf(&bundler.linker),
@TypeOf(&bundler.resolver.caches.fs),
WatcherType,
@TypeOf(bundler.fs),
true,
import_path_format,
);
const CSSBundler = Css.NewBundler(
Writer,
@TypeOf(&bundler.linker),
@TypeOf(&bundler.resolver.caches.fs),
WatcherType,
@TypeOf(bundler.fs),
false,
import_path_format,
);
const written = brk: {
if (bundler.options.hot_module_reloading) {
break :brk (try CSSBundlerHMR.bundle(
file_path.text,
bundler.fs,
writer,
watcher,
&bundler.resolver.caches.fs,
filepath_hash,
file_descriptor,
allocator,
bundler.log,
&bundler.linker,
origin,
)).written;
} else {
break :brk (try CSSBundler.bundle(
file_path.text,
bundler.fs,
writer,
watcher,
&bundler.resolver.caches.fs,
filepath_hash,
file_descriptor,
allocator,
bundler.log,
&bundler.linker,
origin,
)).written;
}
};
return BuildResolveResultPair{
.written = written,
.input_fd = file_descriptor,
};
},
else => {
var result = bundler.parse(
ParseOptions{
.allocator = allocator,
.path = file_path,
.loader = loader,
.dirname_fd = resolve_result.dirname_fd,
.file_descriptor = file_descriptor,
.file_hash = filepath_hash,
.macro_remappings = bundler.options.macro_remap,
.jsx = resolve_result.jsx,
},
client_entry_point,
) orelse {
bundler.resetStore();
return BuildResolveResultPair{
.written = 0,
.input_fd = null,
};
};
if (result.empty) {
return BuildResolveResultPair{ .written = 0, .input_fd = result.input_fd, .empty = true };
}
if (bundler.options.target.isBun()) {
if (!bundler.options.transform_only) {
try bundler.linker.link(file_path, &result, origin, import_path_format, false, true);
}
return BuildResolveResultPair{
.written = switch (result.ast.exports_kind) {
.esm => try bundler.printWithSourceMapMaybe(
result.ast,
&result.source,
Writer,
writer,
.esm_ascii,
is_source_map,
source_map_handler,
),
.cjs => try bundler.printWithSourceMapMaybe(
result.ast,
&result.source,
Writer,
writer,
.cjs_ascii,
is_source_map,
source_map_handler,
),
else => unreachable,
},
.input_fd = result.input_fd,
};
}
if (!bundler.options.transform_only) {
try bundler.linker.link(file_path, &result, origin, import_path_format, false, false);
}
return BuildResolveResultPair{
.written = switch (result.ast.exports_kind) {
.none, .esm => try bundler.printWithSourceMapMaybe(
result.ast,
&result.source,
Writer,
writer,
.esm,
is_source_map,
source_map_handler,
),
.cjs => try bundler.printWithSourceMapMaybe(
result.ast,
&result.source,
Writer,
writer,
.cjs,
is_source_map,
source_map_handler,
),
else => unreachable,
},
.input_fd = result.input_fd,
};
},
}
}
pub fn buildWithResolveResultEager(
bundler: *Bundler,
resolve_result: _resolver.Result,
comptime import_path_format: options.BundleOptions.ImportPathFormat,
comptime Outstream: type,
outstream: Outstream,
client_entry_point_: ?*EntryPoints.ClientEntryPoint,
) !?options.OutputFile {
if (resolve_result.is_external) {
return null;
}
var file_path = (resolve_result.pathConst() orelse return null).*;
// Step 1. Parse & scan
const loader = bundler.options.loader(file_path.name.ext);
if (client_entry_point_) |client_entry_point| {
file_path = client_entry_point.source.path;
}
file_path.pretty = Linker.relative_paths_list.append(string, bundler.fs.relativeTo(file_path.text)) catch unreachable;
var output_file = options.OutputFile{
.src_path = file_path,
.loader = loader,
.value = undefined,
};
switch (loader) {
.jsx, .tsx, .js, .ts, .json, .toml, .text => {
var result = bundler.parse(
ParseOptions{
.allocator = bundler.allocator,
.path = file_path,
.loader = loader,
.dirname_fd = resolve_result.dirname_fd,
.file_descriptor = null,
.file_hash = null,
.macro_remappings = bundler.options.macro_remap,
.jsx = resolve_result.jsx,
},
client_entry_point_,
) orelse {
return null;
};
if (!bundler.options.transform_only) {
if (!bundler.options.target.isBun())
try bundler.linker.link(