forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.zig
1920 lines (1635 loc) · 69.8 KB
/
router.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
// This is a Next.js-compatible file-system router.
// It uses the filesystem to infer entry points.
// Despite being Next.js-compatible, it's not tied to Next.js.
// It does not handle the framework parts of rendering pages.
// All it does is resolve URL paths to the appropriate entry point and parse URL params/query.
const Router = @This();
const Api = @import("./api/schema.zig").Api;
const std = @import("std");
const bun = @import("root").bun;
const string = bun.string;
const Output = bun.Output;
const Global = bun.Global;
const PathString = bun.PathString;
const HashedString = bun.HashedString;
const Environment = bun.Environment;
const strings = bun.strings;
const MutableString = bun.MutableString;
const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const C = bun.C;
const StoredFileDescriptorType = bun.StoredFileDescriptorType;
const DirInfo = @import("./resolver/dir_info.zig");
const Fs = @import("./fs.zig");
const Options = @import("./options.zig");
const allocators = @import("./allocators.zig");
const URLPath = @import("./http/url_path.zig");
const PathnameScanner = @import("./url.zig").PathnameScanner;
const CodepointIterator = @import("./string_immutable.zig").CodepointIterator;
const index_route_hash = @as(u32, @truncate(bun.hash("$$/index-route$$-!(@*@#&*%-901823098123")));
const arbitrary_max_route = 4096;
pub const Param = struct {
name: string,
value: string,
pub const List = std.MultiArrayList(Param);
};
dir: StoredFileDescriptorType = .zero,
routes: Routes,
loaded_routes: bool = false,
allocator: std.mem.Allocator,
fs: *Fs.FileSystem,
config: Options.RouteConfig,
pub fn init(
fs: *Fs.FileSystem,
allocator: std.mem.Allocator,
config: Options.RouteConfig,
) !Router {
return Router{
.routes = Routes{
.config = config,
.allocator = allocator,
.static = bun.StringHashMap(*Route).init(allocator),
},
.fs = fs,
.allocator = allocator,
.config = config,
};
}
pub fn deinit(this: *Router) void {
if (comptime Environment.isWindows) {
for (this.routes.list.items(.filepath)) |abs_path| {
this.allocator.free(abs_path);
}
}
}
pub fn getEntryPoints(this: *const Router) ![]const string {
return this.routes.list.items(.filepath);
}
pub fn getPublicPaths(this: *const Router) ![]const string {
return this.routes.list.items(.public_path);
}
pub fn routeIndexByHash(this: *const Router, hash: u32) ?usize {
if (hash == index_route_hash) {
return this.routes.index_id;
}
return std.mem.indexOfScalar(u32, this.routes.list.items(.hash), hash);
}
pub fn getNames(this: *const Router) ![]const string {
return this.routes.list.items(.name);
}
const banned_dirs = [_]string{
"node_modules",
};
const RouteIndex = struct {
route: *Route,
name: string,
match_name: string,
filepath: string,
public_path: string,
hash: u32,
pub const List = std.MultiArrayList(RouteIndex);
};
pub const Routes = struct {
list: RouteIndex.List = RouteIndex.List{},
dynamic: []*Route = &[_]*Route{},
dynamic_names: []string = &[_]string{},
dynamic_match_names: []string = &[_]string{},
/// completely static children of indefinite depth
/// `"blog/posts"`
/// `"dashboard"`
/// `"profiles"`
/// this is a fast path?
static: bun.StringHashMap(*Route),
/// Corresponds to "index.js" on the filesystem
index: ?*Route = null,
index_id: ?usize = 0,
allocator: std.mem.Allocator,
config: Options.RouteConfig,
// This is passed here and propagated through Match
// We put this here to avoid loading the FrameworkConfig for the client, on the server.
client_framework_enabled: bool = false,
pub fn matchPageWithAllocator(this: *Routes, _: string, url_path: URLPath, params: *Param.List, allocator: std.mem.Allocator) ?Match {
// Trim trailing slash
var path = url_path.path;
var redirect = false;
// Normalize trailing slash
// "/foo/bar/index/" => "/foo/bar/index"
if (path.len > 0 and path[path.len - 1] == '/') {
path = path[0 .. path.len - 1];
redirect = true;
}
// Normal case: "/foo/bar/index" => "/foo/bar"
// Pathological: "/foo/bar/index/index/index/index/index/index" => "/foo/bar"
// Extremely pathological: "/index/index/index/index/index/index/index" => "index"
while (strings.endsWith(path, "/index")) {
path = path[0 .. path.len - "/index".len];
redirect = true;
}
if (strings.eqlComptime(path, "index")) {
path = "";
redirect = true;
}
// one final time, trim trailing slash
while (path.len > 0 and path[path.len - 1] == '/') {
path = path[0 .. path.len - 1];
redirect = true;
}
if (strings.eqlComptime(path, ".")) {
path = "";
redirect = false;
}
if (path.len == 0) {
if (this.index) |index| {
return Match{
.params = params,
.name = index.name,
.path = index.abs_path.slice(),
.pathname = url_path.pathname,
.basename = index.basename,
.hash = index_route_hash,
.file_path = index.abs_path.slice(),
.query_string = url_path.query_string,
.client_framework_enabled = this.client_framework_enabled,
};
}
return null;
}
const MatchContextType = struct {
params: Param.List,
};
var matcher = MatchContextType{ .params = params.* };
defer params.* = matcher.params;
if (this.match(allocator, path, *MatchContextType, &matcher)) |route| {
return Match{
.params = params,
.name = route.name,
.path = route.abs_path.slice(),
.pathname = url_path.pathname,
.basename = route.basename,
.hash = route.full_hash,
.file_path = route.abs_path.slice(),
.query_string = url_path.query_string,
.client_framework_enabled = this.client_framework_enabled,
};
}
return null;
}
pub fn matchPage(this: *Routes, _: string, url_path: URLPath, params: *Param.List) ?Match {
return this.matchPageWithAllocator("", url_path, params, this.allocator);
}
fn matchDynamic(this: *Routes, allocator: std.mem.Allocator, path: string, comptime MatchContext: type, ctx: MatchContext) ?*Route {
// its cleaned, so now we search the big list of strings
for (this.dynamic_names, this.dynamic_match_names, this.dynamic) |case_sensitive_name, name, route| {
if (Pattern.match(path, case_sensitive_name[1..], name, allocator, *@TypeOf(ctx.params), &ctx.params, true)) {
return route;
}
}
return null;
}
fn match(this: *Routes, allocator: std.mem.Allocator, pathname_: string, comptime MatchContext: type, ctx: MatchContext) ?*Route {
const pathname = std.mem.trimLeft(u8, pathname_, "/");
if (pathname.len == 0) {
return this.index;
}
return this.static.get(pathname) orelse
this.matchDynamic(allocator, pathname, MatchContext, ctx);
}
};
const RouteLoader = struct {
allocator: std.mem.Allocator,
fs: *FileSystem,
config: Options.RouteConfig,
route_dirname_len: u16 = 0,
dedupe_dynamic: std.AutoArrayHashMap(u32, string),
log: *Logger.Log,
index: ?*Route = null,
static_list: bun.StringHashMap(*Route),
all_routes: std.ArrayListUnmanaged(*Route),
pub fn appendRoute(this: *RouteLoader, route: Route) void {
// /index.js
if (route.full_hash == index_route_hash) {
const new_route = this.allocator.create(Route) catch unreachable;
this.index = new_route;
new_route.* = route;
this.all_routes.append(this.allocator, new_route) catch unreachable;
return;
}
// static route
if (route.param_count == 0) {
const entry = this.static_list.getOrPut(route.match_name.slice()) catch unreachable;
if (entry.found_existing) {
const source = Logger.Source.initEmptyFile(route.abs_path.slice());
this.log.addErrorFmt(
&source,
Logger.Loc.Empty,
this.allocator,
"Route \"{s}\" is already defined by {s}",
.{ route.name, entry.value_ptr.*.abs_path.slice() },
) catch unreachable;
return;
}
const new_route = this.allocator.create(Route) catch unreachable;
new_route.* = route;
// Handle static routes with uppercase characters by ensuring exact case still matches
// Longer-term:
// - We should have an option for controlling this behavior
// - We should have an option for allowing case-sensitive matching
// - But the default should be case-insensitive matching
// This hack is below the engineering quality bar I'm happy with.
// It will cause unexpected behavior.
if (route.has_uppercase) {
const static_entry = this.static_list.getOrPut(route.name[1..]) catch unreachable;
if (static_entry.found_existing) {
const source = Logger.Source.initEmptyFile(route.abs_path.slice());
this.log.addErrorFmt(
&source,
Logger.Loc.Empty,
this.allocator,
"Route \"{s}\" is already defined by {s}",
.{ route.name, static_entry.value_ptr.*.abs_path.slice() },
) catch unreachable;
return;
}
static_entry.value_ptr.* = new_route;
}
entry.value_ptr.* = new_route;
this.all_routes.append(this.allocator, new_route) catch unreachable;
return;
}
{
const entry = this.dedupe_dynamic.getOrPutValue(route.full_hash, route.abs_path.slice()) catch unreachable;
if (entry.found_existing) {
const source = Logger.Source.initEmptyFile(route.abs_path.slice());
this.log.addErrorFmt(
&source,
Logger.Loc.Empty,
this.allocator,
"Route \"{s}\" is already defined by {s}",
.{ route.name, entry.value_ptr.* },
) catch unreachable;
return;
}
}
{
const new_route = this.allocator.create(Route) catch unreachable;
new_route.* = route;
this.all_routes.append(this.allocator, new_route) catch unreachable;
}
}
pub fn loadAll(
allocator: std.mem.Allocator,
config: Options.RouteConfig,
log: *Logger.Log,
comptime ResolverType: type,
resolver: *ResolverType,
root_dir_info: *const DirInfo,
base_dir: []const u8,
) Routes {
var route_dirname_len: u16 = 0;
const relative_dir = FileSystem.instance.relative(base_dir, config.dir);
if (!strings.hasPrefixComptime(relative_dir, "..")) {
route_dirname_len = @as(u16, @truncate(relative_dir.len + @as(usize, @intFromBool(config.dir[config.dir.len - 1] != std.fs.path.sep))));
}
var this = RouteLoader{
.allocator = allocator,
.log = log,
.fs = resolver.fs,
.config = config,
.static_list = bun.StringHashMap(*Route).init(allocator),
.dedupe_dynamic = std.AutoArrayHashMap(u32, string).init(allocator),
.all_routes = .{},
.route_dirname_len = route_dirname_len,
};
defer this.dedupe_dynamic.deinit();
this.load(ResolverType, resolver, root_dir_info, base_dir);
if (this.all_routes.items.len == 0) return Routes{
.static = this.static_list,
.config = config,
.allocator = allocator,
};
std.sort.pdq(*Route, this.all_routes.items, Route.Sorter{}, Route.Sorter.sortByName);
var route_list = RouteIndex.List{};
route_list.setCapacity(allocator, this.all_routes.items.len) catch unreachable;
var dynamic_start: ?usize = null;
var index_id: ?usize = null;
for (this.all_routes.items, 0..) |route, i| {
if (@intFromEnum(route.kind) > @intFromEnum(Pattern.Tag.static) and dynamic_start == null) {
dynamic_start = i;
}
if (route.full_hash == index_route_hash) index_id = i;
route_list.appendAssumeCapacity(.{
.name = route.name,
.filepath = route.abs_path.slice(),
.match_name = route.match_name.slice(),
.public_path = route.public_path.slice(),
.route = route,
.hash = route.full_hash,
});
}
var dynamic: []*Route = &[_]*Route{};
var dynamic_names: []string = &[_]string{};
var dynamic_match_names: []string = &[_]string{};
if (dynamic_start) |dynamic_i| {
dynamic = route_list.items(.route)[dynamic_i..];
dynamic_names = route_list.items(.name)[dynamic_i..];
dynamic_match_names = route_list.items(.match_name)[dynamic_i..];
if (index_id) |index_i| {
if (index_i > dynamic_i) {
// Due to the sorting order, the index route can be the last route.
// We don't want to attempt to match the index route or different stuff will break.
dynamic = dynamic[0 .. dynamic.len - 1];
dynamic_names = dynamic_names[0 .. dynamic_names.len - 1];
dynamic_match_names = dynamic_match_names[0 .. dynamic_match_names.len - 1];
}
}
}
return Routes{
.list = route_list,
.dynamic = dynamic,
.dynamic_names = dynamic_names,
.dynamic_match_names = dynamic_match_names,
.static = this.static_list,
.index = this.index,
.config = config,
.allocator = allocator,
.index_id = index_id,
};
}
pub fn load(
this: *RouteLoader,
comptime ResolverType: type,
resolver: *ResolverType,
root_dir_info: *const DirInfo,
base_dir: []const u8,
) void {
var fs = this.fs;
if (root_dir_info.getEntriesConst()) |entries| {
var iter = entries.data.iterator();
outer: while (iter.next()) |entry_ptr| {
const entry = entry_ptr.value_ptr.*;
if (entry.base()[0] == '.') {
continue :outer;
}
switch (entry.kind(&fs.fs, false)) {
.dir => {
inline for (banned_dirs) |banned_dir| {
if (strings.eqlComptime(entry.base(), comptime banned_dir)) {
continue :outer;
}
}
var abs_parts = [_]string{ entry.dir, entry.base() };
if (resolver.readDirInfoIgnoreError(fs.abs(&abs_parts))) |_dir_info| {
const dir_info: *const DirInfo = _dir_info;
this.load(
ResolverType,
resolver,
dir_info,
base_dir,
);
}
},
.file => {
const extname = std.fs.path.extension(entry.base());
// exclude "." or ""
if (extname.len < 2) continue;
for (this.config.extensions) |_extname| {
if (strings.eql(extname[1..], _extname)) {
// length is extended by one
// entry.dir is a string with a trailing slash
if (comptime Environment.isDebug) {
bun.assert(bun.path.isSepAny(entry.dir[base_dir.len - 1]));
}
const public_dir = entry.dir.ptr[base_dir.len - 1 .. entry.dir.len];
if (Route.parse(
entry.base(),
extname,
entry,
this.log,
this.allocator,
public_dir,
this.route_dirname_len,
)) |route| {
this.appendRoute(route);
}
break;
}
}
},
}
}
}
}
};
// This loads routes recursively, in depth-first order.
// it does not currently handle duplicate exact route matches. that's undefined behavior, for now.
pub fn loadRoutes(
this: *Router,
log: *Logger.Log,
root_dir_info: *const DirInfo,
comptime ResolverType: type,
resolver: *ResolverType,
base_dir: []const u8,
) anyerror!void {
if (this.loaded_routes) return;
this.routes = RouteLoader.loadAll(this.allocator, this.config, log, ResolverType, resolver, root_dir_info, base_dir);
this.loaded_routes = true;
}
pub const TinyPtr = packed struct {
offset: u16 = 0,
len: u16 = 0,
pub inline fn str(this: TinyPtr, slice: string) string {
return if (this.len > 0) slice[this.offset .. this.offset + this.len] else "";
}
pub inline fn toStringPointer(this: TinyPtr) Api.StringPointer {
return Api.StringPointer{ .offset = this.offset, .length = this.len };
}
pub inline fn eql(a: TinyPtr, b: TinyPtr) bool {
return @as(u32, @bitCast(a)) == @as(u32, @bitCast(b));
}
pub fn from(parent: string, in: string) TinyPtr {
if (in.len == 0 or parent.len == 0) return TinyPtr{};
const right = @intFromPtr(in.ptr) + in.len;
const end = @intFromPtr(parent.ptr) + parent.len;
if (comptime Environment.isDebug) {
bun.assert(end < right);
}
const length = @max(end, right) - right;
const offset = @max(@intFromPtr(in.ptr), @intFromPtr(parent.ptr)) - @intFromPtr(parent.ptr);
return TinyPtr{ .offset = @as(u16, @truncate(offset)), .len = @as(u16, @truncate(length)) };
}
};
pub const Route = struct {
/// Public display name for the route.
/// "/", "/index" is "/"
/// "/foo/index.js" becomes "/foo"
/// case-sensitive, has leading slash
name: string,
/// Name used for matching.
/// - Omits leading slash
/// - Lowercased
/// This is [inconsistent with Next.js](https://github.com/vercel/next.js/issues/21498)
match_name: PathString,
basename: string,
full_hash: u32,
param_count: u16,
// On windows we need to normalize this path to have forward slashes.
// To avoid modifying memory we do not own, allocate another buffer
abs_path: if (Environment.isWindows) struct {
path: string,
pub fn slice(this: @This()) string {
return this.path;
}
pub fn isEmpty(this: @This()) bool {
return this.path.len == 0;
}
} else PathString,
/// URL-safe path for the route's transpiled script relative to project's top level directory
/// - It might not share a prefix with the absolute path due to symlinks.
/// - It has a leading slash
public_path: PathString,
kind: Pattern.Tag = Pattern.Tag.static,
has_uppercase: bool = false,
pub const Ptr = TinyPtr;
pub const index_route_name: string = "/";
threadlocal var route_file_buf: bun.PathBuffer = undefined;
threadlocal var second_route_file_buf: bun.PathBuffer = undefined;
threadlocal var normalized_abs_path_buf: bun.windows.PathBuffer = undefined;
pub const Sorter = struct {
const sort_table: [std.math.maxInt(u8)]u8 = brk: {
var table: [std.math.maxInt(u8)]u8 = undefined;
for (&table, 0..) |*t, i| t.* = @as(u8, @intCast(i));
// move dynamic routes to the bottom
table['['] = 252;
table[']'] = 253;
// of each segment
table['/'] = 254;
break :brk table;
};
pub fn sortByNameString(_: @This(), lhs: string, rhs: string) bool {
const math = std.math;
const n = @min(lhs.len, rhs.len);
for (lhs[0..n], rhs[0..n]) |lhs_i, rhs_i| {
switch (math.order(sort_table[lhs_i], sort_table[rhs_i])) {
.eq => continue,
.lt => return true,
.gt => return false,
}
}
return math.order(lhs.len, rhs.len) == .lt;
}
pub fn sortByName(ctx: @This(), a: *Route, b: *Route) bool {
const a_name = a.match_name.slice();
const b_name = b.match_name.slice();
// route order determines route match order
// - static routes go first because we match those first
// - dynamic, catch-all, and optional catch all routes are sorted lexicographically, except "[", "]" appear last so that deepest routes are tested first
// - catch-all & optional catch-all appear at the end because we want to test those at the end.
return switch (std.math.order(@intFromEnum(a.kind), @intFromEnum(b.kind))) {
.eq => switch (a.kind) {
// static + dynamic are sorted alphabetically
.static, .dynamic => @call(
.always_inline,
sortByNameString,
.{
ctx,
a_name,
b_name,
},
),
// catch all and optional catch all must appear below dynamic
.catch_all, .optional_catch_all => switch (std.math.order(a.param_count, b.param_count)) {
.eq => @call(
.always_inline,
sortByNameString,
.{
ctx,
a_name,
b_name,
},
),
.lt => false,
.gt => true,
},
},
.lt => true,
.gt => false,
};
}
};
pub fn parse(
base_: string,
extname: string,
entry: *Fs.FileSystem.Entry,
log: *Logger.Log,
allocator: std.mem.Allocator,
public_dir_: string,
routes_dirname_len: u16,
) ?Route {
var abs_path_str: string = if (entry.abs_path.isEmpty())
""
else
entry.abs_path.slice();
const base = base_[0 .. base_.len - extname.len];
const public_dir = std.mem.trim(u8, public_dir_, std.fs.path.sep_str);
// this is a path like
// "/pages/index.js"
// "/pages/foo/index.ts"
// "/pages/foo/bar.tsx"
// the name we actually store will often be this one
var public_path: string = brk: {
if (base.len == 0) break :brk public_dir;
var buf: []u8 = &route_file_buf;
if (public_dir.len > 0) {
route_file_buf[0] = '/';
buf = buf[1..];
bun.copy(u8, buf, public_dir);
}
buf[public_dir.len] = '/';
buf = buf[public_dir.len + 1 ..];
bun.copy(u8, buf, base);
buf = buf[base.len..];
bun.copy(u8, buf, extname);
buf = buf[extname.len..];
if (comptime Environment.isWindows) {
bun.path.platformToPosixInPlace(u8, route_file_buf[0 .. @intFromPtr(buf.ptr) - @intFromPtr(&route_file_buf)]);
}
break :brk route_file_buf[0 .. @intFromPtr(buf.ptr) - @intFromPtr(&route_file_buf)];
};
var name = public_path[0 .. public_path.len - extname.len];
while (name.len > 1 and name[name.len - 1] == '/') {
name = name[0 .. name.len - 1];
}
name = name[routes_dirname_len..];
if (strings.endsWith(name, "/index")) {
name = name[0 .. name.len - 6];
}
name = std.mem.trimRight(u8, name, "/");
var match_name: string = name;
var validation_result = Pattern.ValidationResult{};
const is_index = name.len == 0;
var has_uppercase = false;
if (name.len > 0) {
validation_result = Pattern.validate(
name[1..],
allocator,
log,
) orelse return null;
var name_i: usize = 0;
while (!has_uppercase and name_i < public_path.len) : (name_i += 1) {
has_uppercase = public_path[name_i] >= 'A' and public_path[name_i] <= 'Z';
}
const name_offset = @intFromPtr(name.ptr) - @intFromPtr(public_path.ptr);
if (has_uppercase) {
public_path = FileSystem.DirnameStore.instance.append(@TypeOf(public_path), public_path) catch unreachable;
name = public_path[name_offset..][0..name.len];
match_name = FileSystem.DirnameStore.instance.appendLowerCase(@TypeOf(name[1..]), name[1..]) catch unreachable;
} else {
public_path = FileSystem.DirnameStore.instance.append(@TypeOf(public_path), public_path) catch unreachable;
name = public_path[name_offset..][0..name.len];
match_name = name[1..];
}
if (Environment.allow_assert) bun.assert(match_name[0] != '/');
if (Environment.allow_assert) bun.assert(name[0] == '/');
} else {
name = Route.index_route_name;
match_name = Route.index_route_name;
public_path = FileSystem.DirnameStore.instance.append(@TypeOf(public_path), public_path) catch unreachable;
}
if (abs_path_str.len == 0) {
var file: std.fs.File = undefined;
var needs_close = false;
defer if (needs_close) file.close();
if (entry.cache.fd != .zero) {
file = entry.cache.fd.asFile();
} else {
var parts = [_]string{ entry.dir, entry.base() };
abs_path_str = FileSystem.instance.absBuf(&parts, &route_file_buf);
route_file_buf[abs_path_str.len] = 0;
const buf = route_file_buf[0..abs_path_str.len :0];
file = std.fs.openFileAbsoluteZ(buf, .{ .mode = .read_only }) catch |err| {
log.addErrorFmt(null, Logger.Loc.Empty, allocator, "{s} opening route: {s}", .{ @errorName(err), abs_path_str }) catch unreachable;
return null;
};
FileSystem.setMaxFd(file.handle);
needs_close = FileSystem.instance.fs.needToCloseFiles();
if (!needs_close) entry.cache.fd = bun.toFD(file.handle);
}
const _abs = bun.getFdPath(file.handle, &route_file_buf) catch |err| {
log.addErrorFmt(null, Logger.Loc.Empty, allocator, "{s} resolving route: {s}", .{ @errorName(err), abs_path_str }) catch unreachable;
return null;
};
abs_path_str = FileSystem.DirnameStore.instance.append(@TypeOf(_abs), _abs) catch unreachable;
entry.abs_path = PathString.init(abs_path_str);
}
const abs_path = if (comptime Environment.isWindows)
allocator.dupe(u8, bun.path.platformToPosixBuf(u8, abs_path_str, &normalized_abs_path_buf)) catch bun.outOfMemory()
else
PathString.init(abs_path_str);
if (comptime Environment.allow_assert and Environment.isWindows) {
bun.assert(!strings.containsChar(name, '\\'));
bun.assert(!strings.containsChar(public_path, '\\'));
bun.assert(!strings.containsChar(match_name, '\\'));
bun.assert(!strings.containsChar(abs_path, '\\'));
bun.assert(!strings.containsChar(entry.base(), '\\'));
}
return Route{
.name = name,
.basename = entry.base(),
.public_path = PathString.init(public_path),
.match_name = PathString.init(match_name),
.full_hash = if (is_index)
index_route_hash
else
@as(u32, @truncate(bun.hash(name))),
.param_count = validation_result.param_count,
.kind = validation_result.kind,
.abs_path = if (comptime Environment.isWindows) .{
.path = abs_path,
} else abs_path,
.has_uppercase = has_uppercase,
};
}
};
threadlocal var params_list: Param.List = undefined;
pub fn match(app: *Router, comptime Server: type, server: Server, comptime RequestContextType: type, ctx: *RequestContextType) !void {
ctx.matched_route = null;
// If there's an extname assume it's an asset and not a page
switch (ctx.url.extname.len) {
0 => {},
// json is used for updating the route client-side without a page reload
"json".len => {
if (!strings.eqlComptime(ctx.url.extname, "json")) {
try ctx.handleRequest();
return;
}
},
else => {
try ctx.handleRequest();
return;
},
}
params_list.shrinkRetainingCapacity(0);
if (app.routes.matchPage(app.config.dir, ctx.url, ¶ms_list)) |route| {
if (route.redirect_path) |redirect| {
try ctx.handleRedirect(redirect);
return;
}
bun.assert(route.path.len > 0);
if (comptime @hasField(std.meta.Child(Server), "watcher")) {
if (server.watcher.watchloop_handle == null) {
server.watcher.start() catch {};
}
}
// ctx.matched_route = route;
// RequestContextType.JavaScriptHandler.enqueue(ctx, server, ¶ms_list) catch {
// server.javascript_enabled = false;
// };
}
if (!ctx.controlled and !ctx.has_called_done) {
try ctx.handleRequest();
}
}
pub const Match = struct {
/// normalized url path from the request
path: string,
/// raw url path from the request
pathname: string,
/// absolute filesystem path to the entry point
file_path: string,
/// route name, like `"posts/[id]"`
name: string,
client_framework_enabled: bool = false,
/// basename of the route in the file system, including file extension
basename: string,
hash: u32,
params: *Param.List,
redirect_path: ?string = null,
query_string: string = "",
pub inline fn hasParams(this: Match) bool {
return this.params.len > 0;
}
pub fn paramsIterator(this: *const Match) PathnameScanner {
return PathnameScanner.init(this.pathname, this.name, this.params);
}
pub fn nameWithBasename(file_path: string, dir: string) string {
var name = file_path;
if (strings.indexOf(name, dir)) |i| {
name = name[i + dir.len ..];
}
return name[0 .. name.len - std.fs.path.extension(name).len];
}
pub fn pathnameWithoutLeadingSlash(this: *const Match) string {
return std.mem.trimLeft(u8, this.pathname, "/");
}
};
const FileSystem = Fs.FileSystem;
const MockRequestContextType = struct {
controlled: bool = false,
url: URLPath,
match_file_path_buf: [1024]u8 = undefined,
handle_request_called: bool = false,
redirect_called: bool = false,
matched_route: ?Match = null,
has_called_done: bool = false,
pub fn handleRequest(this: *MockRequestContextType) !void {
this.handle_request_called = true;
}
pub fn handleRedirect(this: *MockRequestContextType, _: string) !void {
this.redirect_called = true;
}
pub const JavaScriptHandler = struct {
pub fn enqueue(_: *MockRequestContextType, _: *MockServer, _: *Router.Param.List) !void {}
};
};
pub const MockServer = struct {
watchloop_handle: ?StoredFileDescriptorType = null,
watcher: Watcher = Watcher{},
pub const Watcher = struct {
watchloop_handle: ?StoredFileDescriptorType = null,
pub fn start(_: *Watcher) anyerror!void {}
};
};
fn makeTest(cwd_path: string, data: anytype) !void {
Output.initTest();
bun.assert(cwd_path.len > 1 and !strings.eql(cwd_path, "/") and !strings.endsWith(cwd_path, "bun"));
const bun_tests_dir = try std.fs.cwd().makeOpenPath("bun-test-scratch", .{});
bun_tests_dir.deleteTree(cwd_path) catch {};
const cwd = try bun_tests_dir.makeOpenPath(cwd_path, .{});
try cwd.setAsCwd();
const Data = @TypeOf(data);
const fields: []const std.builtin.Type.StructField = comptime std.meta.fields(Data);
inline for (fields) |field| {
@setEvalBranchQuota(9999);
const value = @field(data, field.name);
if (std.fs.path.dirname(field.name)) |dir| {
try cwd.makePath(dir);
}
var file = try cwd.createFile(field.name, .{ .truncate = true });
try file.writeAll(value);
file.close();
}
}
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
const expectStr = std.testing.expectEqualStrings;
const Logger = bun.logger;
pub const Test = struct {
pub fn makeRoutes(comptime testName: string, data: anytype) !Routes {
Output.initTest();
try makeTest(testName, data);
const JSAst = bun.JSAst;
JSAst.Expr.Data.Store.create(default_allocator);
JSAst.Stmt.Data.Store.create(default_allocator);
const fs = try FileSystem.init(null);
const top_level_dir = fs.top_level_dir;
var pages_parts = [_]string{ top_level_dir, "pages" };
const pages_dir = try Fs.FileSystem.instance.absAlloc(default_allocator, &pages_parts);
// _ = try std.fs.makeDirAbsolute(
// pages_dir,
// );
const router = try Router.init(&FileSystem.instance, default_allocator, Options.RouteConfig{
.dir = pages_dir,
.routes_enabled = true,
.extensions = &.{"js"},
});
const Resolver = @import("./resolver/resolver.zig").Resolver;
var logger = Logger.Log.init(default_allocator);
errdefer {
logger.print(Output.errorWriter()) catch {};
}
const opts = Options.BundleOptions{
.target = .browser,