@sigil-dev/grimoire 0.9.23 → 0.9.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -3
- package/src/client/router.ts +31 -1
- package/src/rendering/index.ts +40 -16
- package/src/routing/router.ts +15 -8
- package/src/routing/scanner.ts +14 -3
- package/src/server/index.ts +1171 -1149
- package/src/server/plugin-routes.ts +38 -0
- package/src/server/prerender.ts +15 -3
- package/src/server/public-assets.ts +133 -0
- package/src/server/resolver.ts +5 -1
- package/src/types.ts +7 -0
- package/test/env.test.ts +4 -1
- package/test/plugin-routes.test.ts +42 -0
- package/test/prerender.test.ts +29 -4
- package/test/public-assets.test.ts +108 -0
- package/test/resolver-windows.test.ts +23 -0
- package/test/route-group-layouts.test.ts +36 -0
package/src/server/index.ts
CHANGED
|
@@ -1,1149 +1,1171 @@
|
|
|
1
|
-
import { existsSync, mkdirSync } from "node:fs";
|
|
2
|
-
import { isAbsolute, join } from "node:path";
|
|
3
|
-
import { plugin as bunPlugin, type Server, type ServerWebSocket } from "bun";
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import
|
|
23
|
-
import
|
|
24
|
-
import {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
} from "../
|
|
31
|
-
import {
|
|
32
|
-
import {
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
37
|
-
import {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
} from "./
|
|
54
|
-
import {
|
|
55
|
-
import {
|
|
56
|
-
import {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
*
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
const etag = `"${
|
|
95
|
-
etags.set(key, { stamp, etag });
|
|
96
|
-
return etag;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Serve a file from public/, or the client bundle from .grimoire/client for
|
|
101
|
-
* a /__grimoire__/ path, or return null when the path is neither.
|
|
102
|
-
*
|
|
103
|
-
* `immutable` is sent only for a URL that changes with its content, and
|
|
104
|
-
* `must-revalidate` with an ETag for everything else. That distinction is
|
|
105
|
-
* the whole point: telling a browser to cache a stylesheet for a year at a
|
|
106
|
-
* URL that never changes means a deploy which edits the CSS is invisible to
|
|
107
|
-
* anyone already holding it — the new HTML loads, and the old stylesheet
|
|
108
|
-
* stays. Unconditional `immutable` was the bug here, and it was worse than
|
|
109
|
-
* no caching at all, because it looked like it was working.
|
|
110
|
-
*
|
|
111
|
-
* Callers must not put user input in the pathname: this joins it onto
|
|
112
|
-
* public/ directly.
|
|
113
|
-
*/
|
|
114
|
-
async function servePublicAsset(
|
|
115
|
-
pathname: string,
|
|
116
|
-
search: string,
|
|
117
|
-
ifNoneMatch: string | null,
|
|
118
|
-
): Promise<Response | null> {
|
|
119
|
-
// Reject traversal before touching the filesystem.
|
|
120
|
-
if (pathname.includes("..") || pathname.includes("\0")) return null;
|
|
121
|
-
const
|
|
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
|
-
const
|
|
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
|
-
rebuilding
|
|
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
|
-
const
|
|
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
|
-
const
|
|
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
|
-
const
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
//
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
}
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
//
|
|
747
|
-
//
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
:
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
//
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
});
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
}
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
if (
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
const
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1
|
+
import { existsSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, join } from "node:path";
|
|
3
|
+
import { plugin as bunPlugin, type Server, type ServerWebSocket } from "bun";
|
|
4
|
+
import {
|
|
5
|
+
normalizeBase,
|
|
6
|
+
outsideBaseMessage,
|
|
7
|
+
setBase,
|
|
8
|
+
stripBase,
|
|
9
|
+
withBase,
|
|
10
|
+
} from "../base";
|
|
11
|
+
import { getDevModule } from "../dev/compile-module.ts";
|
|
12
|
+
import { DevGraph } from "../dev/graph.ts";
|
|
13
|
+
import { HMR_CLIENT_SOURCE } from "../dev/hmr-client.ts";
|
|
14
|
+
import { type DevContext, HmrServer, handleChange } from "../dev/hmr-server.ts";
|
|
15
|
+
import { makeDevLoader } from "../dev/loader.ts";
|
|
16
|
+
import { normalizePath } from "../dev/paths.ts";
|
|
17
|
+
import { crawlFrom } from "../dev/scan.ts";
|
|
18
|
+
import { startWatcher } from "../dev/watcher.ts";
|
|
19
|
+
import { envModuleSource } from "../env/modules";
|
|
20
|
+
import { assertRequiredEnv } from "../env/required";
|
|
21
|
+
import { log } from "../logger/instance.ts";
|
|
22
|
+
import { renderErrorPage, renderRoute } from "../rendering";
|
|
23
|
+
import { registerSSRPlugin } from "../rendering/ssrPlugin";
|
|
24
|
+
import { setServerTiming } from "../rendering/timing.ts";
|
|
25
|
+
import { matchNotFound, matchRoute } from "../routing/router";
|
|
26
|
+
import type { RouteTree } from "../routing/scanner";
|
|
27
|
+
import { isErrorResult } from "../sentinels/error.ts";
|
|
28
|
+
import { isFailResult } from "../sentinels/fail.ts";
|
|
29
|
+
import { isRedirectResult } from "../sentinels/redirect.ts";
|
|
30
|
+
import type { GrimoireConfig, GrimoirePlugin, WsRouteHandler } from "../types";
|
|
31
|
+
import { drainAfterResponse, withAfterResponse } from "./after-response.ts";
|
|
32
|
+
import { CACHE_CONTROL, cacheControlFor } from "./asset-cache";
|
|
33
|
+
import { buildProject, rebuildClient } from "./build";
|
|
34
|
+
import { clientAddressOf, trackClientAddress } from "./client-address";
|
|
35
|
+
import { CLIENT_URL, clientDir } from "./client-dir";
|
|
36
|
+
import { createCookies } from "./cookie-utils";
|
|
37
|
+
import type {
|
|
38
|
+
Handle,
|
|
39
|
+
HandleError,
|
|
40
|
+
HandleFetch,
|
|
41
|
+
InitFunction,
|
|
42
|
+
RequestEvent,
|
|
43
|
+
ResolveFunction,
|
|
44
|
+
} from "./hooks";
|
|
45
|
+
import { shadowedRouteMessage, shadowedRoutes } from "./plugin-routes";
|
|
46
|
+
import {
|
|
47
|
+
collectServices,
|
|
48
|
+
composeHandle,
|
|
49
|
+
runDeserializeLocals,
|
|
50
|
+
runHook,
|
|
51
|
+
runRequestHooks,
|
|
52
|
+
} from "./plugins";
|
|
53
|
+
import { contentHash, splitHashedCss } from "./public-assets";
|
|
54
|
+
import { RESERVED_EXPORTS } from "./reserved";
|
|
55
|
+
import { projectAliases, resolverPlugin } from "./resolver";
|
|
56
|
+
import { applyRewriters } from "./rewrite";
|
|
57
|
+
import { preloadModules, startWarming, type Warmer } from "./warm.ts";
|
|
58
|
+
import { withHeaders } from "./with-headers";
|
|
59
|
+
|
|
60
|
+
/** A plain message. Without the type, a proxy or a later rewrap can send it as a download. */
|
|
61
|
+
const TEXT = { "Content-Type": "text/plain; charset=utf-8" };
|
|
62
|
+
|
|
63
|
+
const logger = log.scope("server");
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Directories to watch in dev. `src` covers components and libs that pages
|
|
67
|
+
* import; the routes directory is added separately when it lives outside it.
|
|
68
|
+
*/
|
|
69
|
+
function watchRoots(projectRoot: string, routesDir: string): string[] {
|
|
70
|
+
const src = join(projectRoot, "src");
|
|
71
|
+
const roots = existsSync(src) ? [src] : [];
|
|
72
|
+
const key = normalizePath(routesDir);
|
|
73
|
+
if (
|
|
74
|
+
!roots.some(
|
|
75
|
+
(r) => key === normalizePath(r) || key.startsWith(`${normalizePath(r)}/`),
|
|
76
|
+
)
|
|
77
|
+
)
|
|
78
|
+
roots.push(routesDir);
|
|
79
|
+
return roots;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* ETags by file, keyed on size and modification time. Hashing the content on
|
|
84
|
+
* every request read the whole file and ran sha256 over it for each page
|
|
85
|
+
* view; the answer only changes when the file does.
|
|
86
|
+
*/
|
|
87
|
+
const etags = new Map<string, { stamp: string; etag: string }>();
|
|
88
|
+
|
|
89
|
+
async function etagFor(file: ReturnType<typeof Bun.file>): Promise<string> {
|
|
90
|
+
const key = file.name ?? "";
|
|
91
|
+
const stamp = `${file.size}:${file.lastModified}`;
|
|
92
|
+
const hit = etags.get(key);
|
|
93
|
+
if (hit && hit.stamp === stamp) return hit.etag;
|
|
94
|
+
const etag = `"${contentHash(await file.arrayBuffer())}"`;
|
|
95
|
+
etags.set(key, { stamp, etag });
|
|
96
|
+
return etag;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Serve a file from public/, or the client bundle from .grimoire/client for
|
|
101
|
+
* a /__grimoire__/ path, or return null when the path is neither.
|
|
102
|
+
*
|
|
103
|
+
* `immutable` is sent only for a URL that changes with its content, and
|
|
104
|
+
* `must-revalidate` with an ETag for everything else. That distinction is
|
|
105
|
+
* the whole point: telling a browser to cache a stylesheet for a year at a
|
|
106
|
+
* URL that never changes means a deploy which edits the CSS is invisible to
|
|
107
|
+
* anyone already holding it — the new HTML loads, and the old stylesheet
|
|
108
|
+
* stays. Unconditional `immutable` was the bug here, and it was worse than
|
|
109
|
+
* no caching at all, because it looked like it was working.
|
|
110
|
+
*
|
|
111
|
+
* Callers must not put user input in the pathname: this joins it onto
|
|
112
|
+
* public/ directly.
|
|
113
|
+
*/
|
|
114
|
+
async function servePublicAsset(
|
|
115
|
+
pathname: string,
|
|
116
|
+
search: string,
|
|
117
|
+
ifNoneMatch: string | null,
|
|
118
|
+
): Promise<Response | null> {
|
|
119
|
+
// Reject traversal before touching the filesystem.
|
|
120
|
+
if (pathname.includes("..") || pathname.includes("\0")) return null;
|
|
121
|
+
const locate = (p: string) =>
|
|
122
|
+
Bun.file(
|
|
123
|
+
p.startsWith(CLIENT_URL)
|
|
124
|
+
? join(clientDir(), p.slice(CLIENT_URL.length))
|
|
125
|
+
: join(process.cwd(), "public", p),
|
|
126
|
+
);
|
|
127
|
+
let file = locate(pathname);
|
|
128
|
+
// The hash is not in the file's name on disk: /style.<hash>.css is
|
|
129
|
+
// public/style.css. A real file with that exact name wins.
|
|
130
|
+
let stale = false;
|
|
131
|
+
if (!(await file.exists())) {
|
|
132
|
+
const hashed = pathname.startsWith(CLIENT_URL)
|
|
133
|
+
? null
|
|
134
|
+
: splitHashedCss(pathname);
|
|
135
|
+
if (!hashed) return null;
|
|
136
|
+
file = locate(hashed.plain);
|
|
137
|
+
if (!(await file.exists())) return null;
|
|
138
|
+
// A page rendered before a deploy still asks for the old hash. Serve
|
|
139
|
+
// the current content, but do not let the old URL pin it for a year.
|
|
140
|
+
stale = contentHash(await file.arrayBuffer()) !== hashed.hash;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const headers: Record<string, string> = {};
|
|
144
|
+
// Bun sets Content-Type from the extension, but be explicit for the
|
|
145
|
+
// cases where a wrong guess is expensive: a stylesheet served as
|
|
146
|
+
// text/plain is refused outright by the browser.
|
|
147
|
+
const type = file.type;
|
|
148
|
+
if (type) headers["Content-Type"] = type;
|
|
149
|
+
|
|
150
|
+
const policy = stale ? "revalidate" : cacheControlFor(pathname, search);
|
|
151
|
+
headers["Cache-Control"] = CACHE_CONTROL[policy];
|
|
152
|
+
if (policy === "revalidate") {
|
|
153
|
+
// The hash of the content, so a revalidation can be answered with
|
|
154
|
+
// 304 instead of the whole file.
|
|
155
|
+
const etag = await etagFor(file);
|
|
156
|
+
headers["ETag"] = etag;
|
|
157
|
+
|
|
158
|
+
// Compared here rather than left to Bun: a Bun.file body does not
|
|
159
|
+
// honour If-None-Match on its own, so without this the conditional
|
|
160
|
+
// request would get a 200 and re-download the whole file, and
|
|
161
|
+
// max-age=0 would cost a full transfer on every single page load.
|
|
162
|
+
//
|
|
163
|
+
// Weak comparison, and a match on `*`: both are what the HTTP spec
|
|
164
|
+
// asks for here. `W/` is stripped because these are strong ETags and
|
|
165
|
+
// a client may legitimately send the weak form of one.
|
|
166
|
+
const current = ifNoneMatch
|
|
167
|
+
?.split(",")
|
|
168
|
+
.map((v) => v.trim())
|
|
169
|
+
.some((v) => v === "*" || v.replace(/^W\//, "") === etag);
|
|
170
|
+
if (current) {
|
|
171
|
+
return new Response(null, { status: 304, headers });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
// Content-Length and Last-Modified come from the File; let Bun set them.
|
|
175
|
+
if (file.lastModified) {
|
|
176
|
+
headers["Last-Modified"] = new Date(file.lastModified).toUTCString();
|
|
177
|
+
}
|
|
178
|
+
return new Response(file, { headers });
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Try to load hooks.server.ts from the project root.
|
|
182
|
+
*/
|
|
183
|
+
async function loadHooks(projectRoot: string): Promise<{
|
|
184
|
+
handle?: Handle;
|
|
185
|
+
init?: InitFunction;
|
|
186
|
+
handleError?: HandleError;
|
|
187
|
+
handleFetch?: HandleFetch;
|
|
188
|
+
}> {
|
|
189
|
+
const hooksPath = `${projectRoot}/hooks.server.ts`;
|
|
190
|
+
// no hooks file is fine; a hooks file that fails to load is not, and
|
|
191
|
+
// swallowing that silently switched off auth and every other handle
|
|
192
|
+
if (!existsSync(hooksPath)) return {};
|
|
193
|
+
const mod = await import(hooksPath);
|
|
194
|
+
return {
|
|
195
|
+
handle: mod.handle,
|
|
196
|
+
init: mod.init,
|
|
197
|
+
handleError: mod.handleError,
|
|
198
|
+
handleFetch: mod.handleFetch,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
let resolverRegistered = false;
|
|
203
|
+
function registerServerResolver(config: GrimoireConfig): void {
|
|
204
|
+
if (resolverRegistered) return;
|
|
205
|
+
resolverRegistered = true;
|
|
206
|
+
bunPlugin(resolverPlugin(config, "server"));
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
interface _WsInternalData {
|
|
210
|
+
params: Record<string, string>;
|
|
211
|
+
// always present at runtime — optional only to satisfy TypeScript;
|
|
212
|
+
// upgrade block gates on mod.websocket before calling server.upgrade()
|
|
213
|
+
__handler?: WsRouteHandler<any>;
|
|
214
|
+
[key: string]: unknown;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Everything a server is except the socket: the request handler, the
|
|
219
|
+
* websocket handlers and the scanned route tree.
|
|
220
|
+
*
|
|
221
|
+
* Split from `createServer` so something that is not a listening server can
|
|
222
|
+
* use the real pipeline — `sigil build` prerenders by sending requests
|
|
223
|
+
* through `fetch`, which means `hooks.server.ts`, plugins and layouts run
|
|
224
|
+
* exactly as they will in production. `createServer` is this plus a port.
|
|
225
|
+
*/
|
|
226
|
+
export interface GrimoireApp {
|
|
227
|
+
/** The full request pipeline: plugins, hooks, routing, rendering. */
|
|
228
|
+
fetch(req: Request): Promise<Response>;
|
|
229
|
+
/** Handlers to hand to `Bun.serve({ websocket })`. */
|
|
230
|
+
websocket: ServerWebSocketHandlers;
|
|
231
|
+
tree: RouteTree;
|
|
232
|
+
/** `src/params/*.ts` matchers by name, for `[param=name]` routes. */
|
|
233
|
+
matchers: Record<string, (value: string) => boolean>;
|
|
234
|
+
config: GrimoireConfig;
|
|
235
|
+
plugins: GrimoirePlugin[];
|
|
236
|
+
/** Tell the app which server it runs in, so it can upgrade websockets. */
|
|
237
|
+
bind(server: Server<any>): void;
|
|
238
|
+
/**
|
|
239
|
+
* Run `onStop` and let pending after-response work finish. Begins a
|
|
240
|
+
* process-wide shutdown (`afterResponse()` rejects afterwards), so call it
|
|
241
|
+
* once, when the process is done with the app.
|
|
242
|
+
*/
|
|
243
|
+
close(
|
|
244
|
+
reason?: "shutdown" | "restart",
|
|
245
|
+
options?: { drainMs?: number },
|
|
246
|
+
): Promise<void>;
|
|
247
|
+
/** Import every route module now, so the first visitor does not pay for it. */
|
|
248
|
+
preload(): Promise<void>;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
type ServerWebSocketHandlers = {
|
|
252
|
+
open(ws: ServerWebSocket<any>): void;
|
|
253
|
+
message(ws: ServerWebSocket<any>, data: string | Buffer): void;
|
|
254
|
+
close(ws: ServerWebSocket<any>, code: number, reason?: string): void;
|
|
255
|
+
drain(ws: ServerWebSocket<any>): void;
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
export async function createApp(
|
|
259
|
+
config: GrimoireConfig = {},
|
|
260
|
+
): Promise<GrimoireApp> {
|
|
261
|
+
// run config hooks
|
|
262
|
+
let finalConfig = config;
|
|
263
|
+
const earlyPlugins = config.plugins ?? [];
|
|
264
|
+
for (const plugin of earlyPlugins) {
|
|
265
|
+
finalConfig = (await plugin.config?.(finalConfig)) ?? finalConfig;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Last word on `dev`: a plugin's config hook runs above and could have set
|
|
269
|
+
// it. The worker does the same for the same reason.
|
|
270
|
+
if (finalConfig._forceProduction)
|
|
271
|
+
finalConfig = { ...finalConfig, dev: false };
|
|
272
|
+
|
|
273
|
+
// Before the build, which can take a minute: a missing variable is the
|
|
274
|
+
// cheapest thing to find out about and the most annoying to learn late.
|
|
275
|
+
assertRequiredEnv(finalConfig);
|
|
276
|
+
|
|
277
|
+
// A base that would 404 every asset is a startup error, not a mystery.
|
|
278
|
+
const appBase = normalizeBase(finalConfig.base);
|
|
279
|
+
setBase(appBase);
|
|
280
|
+
|
|
281
|
+
const {
|
|
282
|
+
port = 3000,
|
|
283
|
+
host = "localhost",
|
|
284
|
+
plugins = [],
|
|
285
|
+
dev = false,
|
|
286
|
+
routes = "src/routes",
|
|
287
|
+
cspNonce,
|
|
288
|
+
//biome-ignore lint: not implemented yet
|
|
289
|
+
devEditor = "code",
|
|
290
|
+
_skipBuild = false,
|
|
291
|
+
} = finalConfig;
|
|
292
|
+
|
|
293
|
+
let tree: any;
|
|
294
|
+
if (!config._skipBuild) {
|
|
295
|
+
const { result, tree: _tree } = await buildProject(finalConfig, plugins);
|
|
296
|
+
if (!result.success) throw new Error("Grimoire: build failed");
|
|
297
|
+
tree = _tree;
|
|
298
|
+
} else {
|
|
299
|
+
// worker — build already done by loom, just scan routes
|
|
300
|
+
const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
|
|
301
|
+
const { scanRoutes } = await import("../routing/scanner");
|
|
302
|
+
tree = await scanRoutes(routesDir, process.cwd());
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// SSR plugin should NOT INTNERCEPT FILES BUNDLEDFOR CLIENT
|
|
306
|
+
// WHAT ARE WE DOINGGGGGGGGG
|
|
307
|
+
// $lib and config.alias in every server module, and the $env/* modules
|
|
308
|
+
registerSSRPlugin(plugins, projectAliases(finalConfig));
|
|
309
|
+
registerServerResolver(finalConfig);
|
|
310
|
+
|
|
311
|
+
// Set by bind(); the handlers below only use it once a request arrives.
|
|
312
|
+
let server: Server<any> | undefined;
|
|
313
|
+
|
|
314
|
+
const graph = new DevGraph();
|
|
315
|
+
const hmr = dev ? new HmrServer() : null;
|
|
316
|
+
|
|
317
|
+
const aliases = finalConfig.alias ?? {};
|
|
318
|
+
setServerTiming(finalConfig.serverTiming ?? dev);
|
|
319
|
+
|
|
320
|
+
if (dev) {
|
|
321
|
+
const { ensureRuntimeBundle } = await import("../dev/runtime-bundle.ts");
|
|
322
|
+
await ensureRuntimeBundle(process.cwd());
|
|
323
|
+
|
|
324
|
+
// clean dev-modules cache from previous session
|
|
325
|
+
const { rmSync, mkdirSync } = await import("node:fs");
|
|
326
|
+
const devModulesDir = join(process.cwd(), ".grimoire/dev-modules");
|
|
327
|
+
try {
|
|
328
|
+
rmSync(devModulesDir, { recursive: true, force: true });
|
|
329
|
+
} catch {}
|
|
330
|
+
mkdirSync(devModulesDir, { recursive: true });
|
|
331
|
+
|
|
332
|
+
const scanCtx = { graph, projectRoot: process.cwd(), aliases };
|
|
333
|
+
const entryFiles = () => {
|
|
334
|
+
const all = [
|
|
335
|
+
...tree.routes,
|
|
336
|
+
...tree.layouts,
|
|
337
|
+
...tree.servers,
|
|
338
|
+
...tree.errors,
|
|
339
|
+
];
|
|
340
|
+
for (const rf of all) {
|
|
341
|
+
graph.getOrCreate(rf.filePath, rf.filePath);
|
|
342
|
+
graph.markRoute(rf.filePath, rf);
|
|
343
|
+
}
|
|
344
|
+
return all.map((rf) => rf.filePath);
|
|
345
|
+
};
|
|
346
|
+
|
|
347
|
+
// crawl the whole import graph, not just each route's direct imports:
|
|
348
|
+
// an edit is traced back to the routes that render it through however
|
|
349
|
+
// many component hops lie between
|
|
350
|
+
await crawlFrom(entryFiles(), scanCtx);
|
|
351
|
+
|
|
352
|
+
const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
|
|
353
|
+
|
|
354
|
+
// one rebuild at a time; saves that land during a build fold into one
|
|
355
|
+
// follow-up pass instead of queueing a Bun.build each
|
|
356
|
+
let rebuilding: Promise<void> | null = null;
|
|
357
|
+
let rebuildQueued = false;
|
|
358
|
+
const runRebuild = (): Promise<void> => {
|
|
359
|
+
if (rebuilding) {
|
|
360
|
+
rebuildQueued = true;
|
|
361
|
+
return rebuilding;
|
|
362
|
+
}
|
|
363
|
+
rebuilding = (async () => {
|
|
364
|
+
do {
|
|
365
|
+
rebuildQueued = false;
|
|
366
|
+
const { result, tree: rescanned } = await rebuildClient(
|
|
367
|
+
finalConfig,
|
|
368
|
+
plugins,
|
|
369
|
+
);
|
|
370
|
+
if (!result.success) {
|
|
371
|
+
logger.error("client rebuild failed:", result.errors.join("\n"));
|
|
372
|
+
break;
|
|
373
|
+
}
|
|
374
|
+
// adopt the rescanned tree so routes added since startup match
|
|
375
|
+
tree = rescanned;
|
|
376
|
+
await crawlFrom(entryFiles(), scanCtx);
|
|
377
|
+
} while (rebuildQueued);
|
|
378
|
+
})().finally(() => {
|
|
379
|
+
rebuilding = null;
|
|
380
|
+
});
|
|
381
|
+
return rebuilding;
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
const devCtx: DevContext = {
|
|
385
|
+
graph,
|
|
386
|
+
hmr: hmr!,
|
|
387
|
+
projectRoot: process.cwd(),
|
|
388
|
+
aliases,
|
|
389
|
+
entries: entryFiles,
|
|
390
|
+
rebuild: runRebuild,
|
|
391
|
+
scheduleRebuild: () => {
|
|
392
|
+
runRebuild().catch((e: unknown) =>
|
|
393
|
+
logger.error("client rebuild failed:", e),
|
|
394
|
+
);
|
|
395
|
+
},
|
|
396
|
+
};
|
|
397
|
+
|
|
398
|
+
startWatcher(watchRoots(process.cwd(), routesDir), (f) =>
|
|
399
|
+
handleChange(f, devCtx),
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
const loader = dev
|
|
404
|
+
? makeDevLoader(graph, process.cwd(), { aliases })
|
|
405
|
+
: (p: string) => import(p);
|
|
406
|
+
|
|
407
|
+
// [param=matcher] validation — load src/params/*.ts once at startup
|
|
408
|
+
const paramMatcherFns: Record<string, (value: string) => boolean> = {};
|
|
409
|
+
for (const pm of tree.paramMatcherFiles ?? []) {
|
|
410
|
+
try {
|
|
411
|
+
const mod = await loader(pm.filePath);
|
|
412
|
+
if (typeof mod.match === "function") {
|
|
413
|
+
paramMatcherFns[pm.name] = mod.match;
|
|
414
|
+
}
|
|
415
|
+
} catch (e) {
|
|
416
|
+
logger.warn(`failed to load param matcher "${pm.name}":`, e);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
for (const s of shadowedRoutes(plugins, tree, paramMatcherFns)) {
|
|
420
|
+
logger.warn(shadowedRouteMessage(s));
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// Load hooks.server.ts
|
|
424
|
+
const {
|
|
425
|
+
handle: appHandle,
|
|
426
|
+
init: hooksInit,
|
|
427
|
+
handleError: hooksHandleError,
|
|
428
|
+
handleFetch: hooksHandleFetch,
|
|
429
|
+
} = await loadHooks(process.cwd());
|
|
430
|
+
|
|
431
|
+
const hooksHandle = composeHandle(plugins, appHandle);
|
|
432
|
+
|
|
433
|
+
// Resolved once at startup, not per request: services() may open a pool,
|
|
434
|
+
// and the object is immutable for the process lifetime, so building it
|
|
435
|
+
// inside handleRequest would open a connection per visitor.
|
|
436
|
+
//
|
|
437
|
+
// Before init(), so hooks.server.ts can use what plugins opened — a
|
|
438
|
+
// database for a warm-up query or a migration check is the usual case,
|
|
439
|
+
// and running init first meant it could only fail.
|
|
440
|
+
// The same hook the coordinator fires, for every process that serves
|
|
441
|
+
// requests. It used to run only in the coordinator, so `sigil dev` and a
|
|
442
|
+
// single-process `sigil start` never gave plugins their moment to look at
|
|
443
|
+
// each other.
|
|
444
|
+
await runHook(plugins, "onPluginsResolved", {
|
|
445
|
+
mode: dev ? "development" : "production",
|
|
446
|
+
plugins: new Map(plugins.map((p) => [p.name, p])),
|
|
447
|
+
logger: log.scope("plugins"),
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
const services = await collectServices(plugins);
|
|
451
|
+
|
|
452
|
+
// Run init hook if present
|
|
453
|
+
await hooksInit?.();
|
|
454
|
+
|
|
455
|
+
// onRouteRender forces the whole response to be buffered into a string,
|
|
456
|
+
// which silently disables streaming for every route a plugin touches. That
|
|
457
|
+
// is a real cost and an invisible one, so say it once at boot rather than
|
|
458
|
+
// letting someone discover it as "streaming stopped working".
|
|
459
|
+
for (const p of plugins) {
|
|
460
|
+
if (p.onRouteRender) {
|
|
461
|
+
logger.warn(
|
|
462
|
+
`plugin "${p.name}" implements onRouteRender, which buffers the full HTML response and disables streaming (including the \`loading\` shell) on every route it touches. Use rewriteHtml(rewriter) to change the HTML while it streams, or onRequest to change headers.`,
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
async function handleRequest(req: Request) {
|
|
468
|
+
// Only the coordinator is trusted to say who the user is. A server that
|
|
469
|
+
// answers the public directly ignores the header, so nobody can send
|
|
470
|
+
// their own `locals` to it.
|
|
471
|
+
const rawLocals = finalConfig._behindCoordinator
|
|
472
|
+
? req.headers.get("X-Grimoire-Locals")
|
|
473
|
+
: null;
|
|
474
|
+
const locals: App.Locals = rawLocals
|
|
475
|
+
? ((await runDeserializeLocals(plugins, rawLocals)) ?? {})
|
|
476
|
+
: {};
|
|
477
|
+
// Plugin services sit under the request's own locals: what the app
|
|
478
|
+
// set (a session, a user) always wins over what a plugin declared,
|
|
479
|
+
// so a plugin cannot clobber auth by defining a common key.
|
|
480
|
+
for (const [key, value] of Object.entries(services)) {
|
|
481
|
+
if (!(key in locals)) locals[key] = value;
|
|
482
|
+
}
|
|
483
|
+
const url = new URL(req.url);
|
|
484
|
+
|
|
485
|
+
if (dev && url.pathname === "/__grimoire__/hmr") {
|
|
486
|
+
//@ts-expect-error holy shut up
|
|
487
|
+
if (server?.upgrade(req, { data: { __hmrClient: true } })) {
|
|
488
|
+
return undefined as unknown as Response;
|
|
489
|
+
}
|
|
490
|
+
return new Response("Upgrade Required", { status: 426 });
|
|
491
|
+
}
|
|
492
|
+
if (dev && url.pathname === "/__grimoire__/hmr-client.js") {
|
|
493
|
+
return new Response(HMR_CLIENT_SOURCE, {
|
|
494
|
+
headers: { "Content-Type": "application/javascript" },
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
if (dev && url.pathname === "/__grimoire__/open") {
|
|
498
|
+
const file = url.searchParams.get("file") ?? "";
|
|
499
|
+
const line = url.searchParams.get("line") ?? "1";
|
|
500
|
+
const col = url.searchParams.get("col") ?? "1";
|
|
501
|
+
const editor = finalConfig.devEditor ?? "code";
|
|
502
|
+
//@ts-expect-error Bun spawn has werird types just shut up
|
|
503
|
+
Bun.spawn([editor, "--goto", `${file}:${line}:${col}`]);
|
|
504
|
+
return new Response(null, { status: 204 });
|
|
505
|
+
}
|
|
506
|
+
if (dev && url.pathname.startsWith("/__grimoire__/dep/")) {
|
|
507
|
+
const depName = decodeURIComponent(
|
|
508
|
+
url.pathname.slice("/__grimoire__/dep/".length).replace(/\.js$/, ""),
|
|
509
|
+
);
|
|
510
|
+
|
|
511
|
+
// grimoire shim
|
|
512
|
+
if (depName.includes("@sigil-dev__grimoire")) {
|
|
513
|
+
return Response.redirect("/__grimoire__/grimoire-client.js", 302);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// convert URL-safe name back to package name
|
|
517
|
+
// @codex__shared → @codex/shared
|
|
518
|
+
const pkgName = depName.startsWith("@")
|
|
519
|
+
? depName.replace("__", "/")
|
|
520
|
+
: depName;
|
|
521
|
+
|
|
522
|
+
const depsDir = join(process.cwd(), ".grimoire/deps");
|
|
523
|
+
mkdirSync(depsDir, { recursive: true });
|
|
524
|
+
const outFile = join(depsDir, `${depName}.js`);
|
|
525
|
+
|
|
526
|
+
if (!(await Bun.file(outFile).exists())) {
|
|
527
|
+
logger.debug("bundling dep:", pkgName);
|
|
528
|
+
try {
|
|
529
|
+
const entry = Bun.resolveSync(pkgName, process.cwd());
|
|
530
|
+
const result = await Bun.build({
|
|
531
|
+
entrypoints: [entry],
|
|
532
|
+
outdir: depsDir,
|
|
533
|
+
naming: `${depName}.js`,
|
|
534
|
+
target: "browser",
|
|
535
|
+
format: "esm",
|
|
536
|
+
minify: false,
|
|
537
|
+
external: ["@sigil-dev/runtime"],
|
|
538
|
+
});
|
|
539
|
+
if (!result.success) {
|
|
540
|
+
logger.error("dep bundle failed:", pkgName, result.logs);
|
|
541
|
+
return new Response(
|
|
542
|
+
`throw new Error("failed to bundle dep: ${pkgName}")`,
|
|
543
|
+
{ headers: { "Content-Type": "application/javascript" } },
|
|
544
|
+
);
|
|
545
|
+
}
|
|
546
|
+
logger.debug("bundled dep:", pkgName);
|
|
547
|
+
} catch (e: any) {
|
|
548
|
+
return new Response(
|
|
549
|
+
`throw new Error("dep not found: ${pkgName}: ${e.message}")`,
|
|
550
|
+
{ headers: { "Content-Type": "application/javascript" } },
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
return new Response(Bun.file(outFile), {
|
|
556
|
+
headers: {
|
|
557
|
+
"Content-Type": "application/javascript",
|
|
558
|
+
"Cache-Control": "no-store",
|
|
559
|
+
},
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
if (dev && url.pathname.startsWith("/__grimoire__/env/")) {
|
|
564
|
+
const specifier = `$env/${url.pathname.slice("/__grimoire__/env/".length).replace(/\.js$/, "")}`;
|
|
565
|
+
let js: string;
|
|
566
|
+
try {
|
|
567
|
+
js = envModuleSource(specifier, "browser");
|
|
568
|
+
} catch (e: unknown) {
|
|
569
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
570
|
+
js = `throw new Error(${JSON.stringify(message)})`;
|
|
571
|
+
}
|
|
572
|
+
return new Response(js, {
|
|
573
|
+
headers: {
|
|
574
|
+
"Content-Type": "application/javascript",
|
|
575
|
+
"Cache-Control": "no-store",
|
|
576
|
+
},
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
if (dev && url.pathname.startsWith("/__grimoire__/m/")) {
|
|
581
|
+
const clientPath = decodeURIComponent(
|
|
582
|
+
url.pathname.slice("/__grimoire__/m/".length),
|
|
583
|
+
);
|
|
584
|
+
const absPath = join(process.cwd(), clientPath.replace(/\.js$/, ""));
|
|
585
|
+
try {
|
|
586
|
+
// compiled at the module's current graph version, which is what
|
|
587
|
+
// the `?v=` in the URL was derived from
|
|
588
|
+
const { js } = await getDevModule(absPath, {
|
|
589
|
+
projectRoot: process.cwd(),
|
|
590
|
+
aliases,
|
|
591
|
+
graph,
|
|
592
|
+
});
|
|
593
|
+
return new Response(js, {
|
|
594
|
+
headers: {
|
|
595
|
+
"Content-Type": "application/javascript",
|
|
596
|
+
"Cache-Control": "no-store",
|
|
597
|
+
},
|
|
598
|
+
});
|
|
599
|
+
} catch (e: unknown) {
|
|
600
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
601
|
+
return new Response(`throw new Error(${JSON.stringify(message)})`, {
|
|
602
|
+
headers: { "Content-Type": "application/javascript" },
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// Static files are served BEFORE the plugin pipeline. A CSS file or
|
|
608
|
+
// an image has nothing to do with a plugin's onRequest hook, and
|
|
609
|
+
// running them through it costs a hook round-trip plus a stat on
|
|
610
|
+
// every asset request.
|
|
611
|
+
//
|
|
612
|
+
// Caching rule, decided per asset by servePublicAsset: the document
|
|
613
|
+
// is never cached, a content-addressed URL is immutable, and
|
|
614
|
+
// anything else revalidates against an ETag.
|
|
615
|
+
const staticAsset = await servePublicAsset(
|
|
616
|
+
url.pathname,
|
|
617
|
+
url.search,
|
|
618
|
+
req.headers.get("if-none-match"),
|
|
619
|
+
);
|
|
620
|
+
if (staticAsset) return staticAsset;
|
|
621
|
+
|
|
622
|
+
return runRequestHooks(plugins, req, async () => {
|
|
623
|
+
const HTTP_METHODS = [
|
|
624
|
+
"GET",
|
|
625
|
+
"POST",
|
|
626
|
+
"PUT",
|
|
627
|
+
"PATCH",
|
|
628
|
+
"DELETE",
|
|
629
|
+
"HEAD",
|
|
630
|
+
"OPTIONS",
|
|
631
|
+
] as const;
|
|
632
|
+
|
|
633
|
+
// Build event BEFORE matching — handle() runs pre-match like SvelteKit
|
|
634
|
+
trackClientAddress(req, server);
|
|
635
|
+
const cookieHeader = req.headers.get("cookie") ?? "";
|
|
636
|
+
const cookies = createCookies(cookieHeader);
|
|
637
|
+
const setHeadersMap: Record<string, string> = {};
|
|
638
|
+
|
|
639
|
+
const event: RequestEvent = {
|
|
640
|
+
request: req,
|
|
641
|
+
url,
|
|
642
|
+
params: {},
|
|
643
|
+
locals,
|
|
644
|
+
cookies,
|
|
645
|
+
route: { id: "" },
|
|
646
|
+
fetch: globalThis.fetch,
|
|
647
|
+
setHeaders: (headers) => Object.assign(setHeadersMap, headers),
|
|
648
|
+
getClientAddress: () => clientAddressOf(req),
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
if (hooksHandleFetch) {
|
|
652
|
+
event.fetch = (reqInfo: RequestInfo | URL, init?: RequestInit) => {
|
|
653
|
+
const r = new Request(reqInfo, init);
|
|
654
|
+
return Promise.resolve(
|
|
655
|
+
hooksHandleFetch({ request: r, fetch: globalThis.fetch, event }),
|
|
656
|
+
);
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
const patchedFetch: typeof fetch = (input, init) => {
|
|
660
|
+
const resolved =
|
|
661
|
+
typeof input === "string" && input.startsWith("/")
|
|
662
|
+
? new URL(input, url.origin).toString()
|
|
663
|
+
: input;
|
|
664
|
+
return globalThis.fetch(resolved as any, init);
|
|
665
|
+
};
|
|
666
|
+
const resolve: ResolveFunction = async (evt) => {
|
|
667
|
+
// matching happens here — after handle() has run
|
|
668
|
+
let matched = matchRoute(tree, evt.url, paramMatcherFns);
|
|
669
|
+
if (!matched) {
|
|
670
|
+
// the nearest +error.tsx inside the layouts that cover the
|
|
671
|
+
// address, like a page whose load throws error(404)
|
|
672
|
+
return renderRoute(
|
|
673
|
+
matchNotFound(tree, evt.url),
|
|
674
|
+
evt.request,
|
|
675
|
+
tree.errors,
|
|
676
|
+
loader,
|
|
677
|
+
evt.locals,
|
|
678
|
+
plugins,
|
|
679
|
+
cspNonce,
|
|
680
|
+
dev,
|
|
681
|
+
patchedFetch,
|
|
682
|
+
);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
// patch event with match results so handle() epilogue can read them
|
|
686
|
+
evt.params = matched.params;
|
|
687
|
+
evt.route = { id: matched.route.path };
|
|
688
|
+
|
|
689
|
+
// API routes (+server.ts)
|
|
690
|
+
if (matched.route.type === "server") {
|
|
691
|
+
const mod = await loader(matched.route.filePath);
|
|
692
|
+
|
|
693
|
+
const isWsUpgrade =
|
|
694
|
+
evt.request.headers.get("upgrade")?.toLowerCase() === "websocket";
|
|
695
|
+
if (isWsUpgrade && mod.websocket) {
|
|
696
|
+
let extraData: Record<string, unknown> = {};
|
|
697
|
+
if (mod.upgrade) {
|
|
698
|
+
try {
|
|
699
|
+
const result = await mod.upgrade({
|
|
700
|
+
request: evt.request,
|
|
701
|
+
params: matched.params,
|
|
702
|
+
url: evt.url,
|
|
703
|
+
locals: evt.locals,
|
|
704
|
+
});
|
|
705
|
+
if (result && typeof result === "object") extraData = result;
|
|
706
|
+
} catch {
|
|
707
|
+
return new Response("Upgrade Required", { status: 426 });
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
const wsData: _WsInternalData = {
|
|
711
|
+
params: matched.params,
|
|
712
|
+
__handler: mod.websocket,
|
|
713
|
+
...extraData,
|
|
714
|
+
};
|
|
715
|
+
//@ts-expect-error i dont know what you are talking about please
|
|
716
|
+
if (server?.upgrade(req, { data: wsData })) {
|
|
717
|
+
return undefined as unknown as Response;
|
|
718
|
+
}
|
|
719
|
+
return new Response("Upgrade Required", { status: 426 });
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
const handler = mod[evt.request.method];
|
|
723
|
+
if (handler) {
|
|
724
|
+
try {
|
|
725
|
+
return await handler({
|
|
726
|
+
request: evt.request,
|
|
727
|
+
params: matched.params,
|
|
728
|
+
url: evt.url,
|
|
729
|
+
locals: evt.locals,
|
|
730
|
+
fetch: patchedFetch,
|
|
731
|
+
cookies,
|
|
732
|
+
setHeaders: (headers) => Object.assign(setHeadersMap, headers),
|
|
733
|
+
getClientAddress: () => clientAddressOf(evt.request),
|
|
734
|
+
});
|
|
735
|
+
} catch (e) {
|
|
736
|
+
// `throw redirect(303, "/login")` works here as in an action
|
|
737
|
+
if (isRedirectResult(e)) {
|
|
738
|
+
return new Response(null, {
|
|
739
|
+
status: e.status,
|
|
740
|
+
headers: { Location: e.location },
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
throw e;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
// no handler for this method: a page at the same URL (say a
|
|
747
|
+
// chat page next to its WebSocket endpoint) takes the request
|
|
748
|
+
const page = matchRoute(
|
|
749
|
+
{ ...tree, servers: [] },
|
|
750
|
+
evt.url,
|
|
751
|
+
paramMatcherFns,
|
|
752
|
+
);
|
|
753
|
+
if (!page) {
|
|
754
|
+
return new Response("Method Not Allowed", { status: 405 });
|
|
755
|
+
}
|
|
756
|
+
matched = page;
|
|
757
|
+
evt.params = page.params;
|
|
758
|
+
evt.route = { id: page.route.path };
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
// form actions (+page.server.ts)
|
|
762
|
+
if (
|
|
763
|
+
matched.pageServer &&
|
|
764
|
+
HTTP_METHODS.includes(evt.request.method as any)
|
|
765
|
+
) {
|
|
766
|
+
const mod = await loader(matched.pageServer.filePath);
|
|
767
|
+
|
|
768
|
+
// named actions: ?/create dispatches export `create`. Only for
|
|
769
|
+
// non-GET requests: a GET must never run an action, or any link
|
|
770
|
+
// or <img> on another site could trigger one with the visitor's
|
|
771
|
+
// cookies and no CSRF check (GET skips it)
|
|
772
|
+
const isRead =
|
|
773
|
+
evt.request.method === "GET" || evt.request.method === "HEAD";
|
|
774
|
+
const actionName = isRead
|
|
775
|
+
? undefined
|
|
776
|
+
: [...evt.url.searchParams.keys()]
|
|
777
|
+
.find((k) => k.startsWith("/"))
|
|
778
|
+
?.slice(1);
|
|
779
|
+
// every other function export is callable by name, but the
|
|
780
|
+
// module's own hooks are not actions
|
|
781
|
+
const reserved =
|
|
782
|
+
actionName !== undefined && RESERVED_EXPORTS.has(actionName);
|
|
783
|
+
// reads render the page; an exported GET is not an action either
|
|
784
|
+
const handler =
|
|
785
|
+
reserved || isRead
|
|
786
|
+
? undefined
|
|
787
|
+
: actionName
|
|
788
|
+
? mod[actionName]
|
|
789
|
+
: mod[evt.request.method];
|
|
790
|
+
if (actionName && typeof handler !== "function") {
|
|
791
|
+
return new Response("Not Found", { status: 404 });
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
if (mod.csrf !== false && !isRead) {
|
|
795
|
+
const cookieToken = cookies.get("_csrf");
|
|
796
|
+
const formData = await evt.request
|
|
797
|
+
.clone()
|
|
798
|
+
.formData()
|
|
799
|
+
.catch(() => null);
|
|
800
|
+
const bodyToken = formData?.get("_csrf");
|
|
801
|
+
if (!cookieToken || cookieToken !== String(bodyToken)) {
|
|
802
|
+
return new Response("Forbidden", { status: 403 });
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
// enhance() submits with fetch, which follows a 303 on its own
|
|
806
|
+
// and can't read where it went; it asks for the outcome as JSON
|
|
807
|
+
// instead and navigates itself
|
|
808
|
+
const enhanced = evt.request.headers.get("x-grimoire-form") === "1";
|
|
809
|
+
if (handler) {
|
|
810
|
+
let result: any;
|
|
811
|
+
try {
|
|
812
|
+
result = await handler({
|
|
813
|
+
request: evt.request,
|
|
814
|
+
params: matched.params,
|
|
815
|
+
url: evt.url,
|
|
816
|
+
locals: evt.locals,
|
|
817
|
+
fetch: patchedFetch,
|
|
818
|
+
cookies,
|
|
819
|
+
getClientAddress: () => clientAddressOf(evt.request),
|
|
820
|
+
});
|
|
821
|
+
} catch (e) {
|
|
822
|
+
// A thrown Response is the reply, like a returned one: it
|
|
823
|
+
// used to fall through to the 500 path and be swallowed.
|
|
824
|
+
if (e instanceof Response) return e;
|
|
825
|
+
if (isRedirectResult(e)) {
|
|
826
|
+
if (enhanced) {
|
|
827
|
+
return Response.json({
|
|
828
|
+
type: "redirect",
|
|
829
|
+
status: e.status,
|
|
830
|
+
location: e.location,
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
return new Response(null, {
|
|
834
|
+
status: e.status,
|
|
835
|
+
headers: { Location: e.location },
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
if (isErrorResult(e)) {
|
|
839
|
+
const isApi =
|
|
840
|
+
enhanced ||
|
|
841
|
+
evt.request.headers
|
|
842
|
+
.get("accept")
|
|
843
|
+
?.includes("application/json");
|
|
844
|
+
if (isApi) {
|
|
845
|
+
return Response.json(
|
|
846
|
+
{ error: true, status: e.status, message: e.message },
|
|
847
|
+
{ status: e.status },
|
|
848
|
+
);
|
|
849
|
+
}
|
|
850
|
+
const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
|
|
851
|
+
// no layoutPairs here: layout data comes from the load
|
|
852
|
+
// pipeline in renderRoute, which a form action bypasses —
|
|
853
|
+
// wrapping layouts without their data would crash them
|
|
854
|
+
return (
|
|
855
|
+
(await renderErrorPage(
|
|
856
|
+
tree.errors,
|
|
857
|
+
evt.url.pathname,
|
|
858
|
+
e.status,
|
|
859
|
+
e.message,
|
|
860
|
+
e,
|
|
861
|
+
loader,
|
|
862
|
+
{ params: matched.params, nonceAttr, dev },
|
|
863
|
+
)) ??
|
|
864
|
+
new Response(e.message, { status: e.status, headers: TEXT })
|
|
865
|
+
);
|
|
866
|
+
}
|
|
867
|
+
throw e;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
if (result instanceof Response) return result;
|
|
871
|
+
|
|
872
|
+
if (isFailResult(result)) {
|
|
873
|
+
if (enhanced) {
|
|
874
|
+
return Response.json(
|
|
875
|
+
{ fail: true, status: result.status, data: result.data },
|
|
876
|
+
{ status: result.status },
|
|
877
|
+
);
|
|
878
|
+
}
|
|
879
|
+
// a plain form post (no JavaScript): show the page again,
|
|
880
|
+
// with the failure as its `form` prop
|
|
881
|
+
return renderRoute(
|
|
882
|
+
matched,
|
|
883
|
+
evt.request,
|
|
884
|
+
tree.errors,
|
|
885
|
+
loader,
|
|
886
|
+
evt.locals,
|
|
887
|
+
plugins,
|
|
888
|
+
cspNonce,
|
|
889
|
+
dev,
|
|
890
|
+
patchedFetch,
|
|
891
|
+
{ status: result.status, data: result.data },
|
|
892
|
+
);
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
const redirectTo =
|
|
896
|
+
result?.redirect ??
|
|
897
|
+
evt.request.headers.get("referer") ??
|
|
898
|
+
withBase("/");
|
|
899
|
+
if (enhanced) {
|
|
900
|
+
return Response.json({
|
|
901
|
+
type: "success",
|
|
902
|
+
location: redirectTo,
|
|
903
|
+
data: result ?? null,
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
return new Response(null, {
|
|
907
|
+
status: 303,
|
|
908
|
+
headers: { Location: redirectTo },
|
|
909
|
+
});
|
|
910
|
+
}
|
|
911
|
+
if (!actionName && !isRead) {
|
|
912
|
+
return new Response("Method Not Allowed", { status: 405 });
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
// page routes
|
|
917
|
+
const response = await renderRoute(
|
|
918
|
+
matched,
|
|
919
|
+
evt.request,
|
|
920
|
+
tree.errors,
|
|
921
|
+
loader,
|
|
922
|
+
evt.locals,
|
|
923
|
+
plugins,
|
|
924
|
+
cspNonce,
|
|
925
|
+
dev,
|
|
926
|
+
patchedFetch,
|
|
927
|
+
);
|
|
928
|
+
|
|
929
|
+
if (evt.request.headers.get("x-grimoire-navigate") === "1") {
|
|
930
|
+
return response;
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
// Streaming-safe rewrites first, then the buffered legacy hook.
|
|
934
|
+
const rewritten = await applyRewriters(response, plugins, {
|
|
935
|
+
route: matched.route,
|
|
936
|
+
request: evt.request,
|
|
937
|
+
params: matched.params,
|
|
938
|
+
data: undefined,
|
|
939
|
+
});
|
|
940
|
+
const hasRenderPlugins = plugins.some((p) => p.onRouteRender);
|
|
941
|
+
if (!hasRenderPlugins) return rewritten;
|
|
942
|
+
let html = await rewritten.text();
|
|
943
|
+
for (const plugin of plugins) {
|
|
944
|
+
html =
|
|
945
|
+
(await plugin.onRouteRender?.(html, {
|
|
946
|
+
route: matched.route,
|
|
947
|
+
request: evt.request,
|
|
948
|
+
params: matched.params,
|
|
949
|
+
data: undefined,
|
|
950
|
+
})) ?? html;
|
|
951
|
+
}
|
|
952
|
+
// Carry the original headers over. Rebuilding with a fixed set
|
|
953
|
+
// dropped Vary and the _csrf Set-Cookie, so any onRouteRender
|
|
954
|
+
// plugin silently broke form actions and cache correctness.
|
|
955
|
+
const headers = new Headers(rewritten.headers);
|
|
956
|
+
headers.set("Content-Type", "text/html");
|
|
957
|
+
return new Response(html, {
|
|
958
|
+
status: rewritten.status,
|
|
959
|
+
statusText: rewritten.statusText,
|
|
960
|
+
headers,
|
|
961
|
+
});
|
|
962
|
+
};
|
|
963
|
+
|
|
964
|
+
let response: Response;
|
|
965
|
+
try {
|
|
966
|
+
if (!hooksHandle) {
|
|
967
|
+
response = await resolve(event);
|
|
968
|
+
} else {
|
|
969
|
+
response = await hooksHandle({ event, resolve });
|
|
970
|
+
}
|
|
971
|
+
} catch (err) {
|
|
972
|
+
logger.error(
|
|
973
|
+
`${event.request.method} ${event.url.pathname} failed:`,
|
|
974
|
+
err,
|
|
975
|
+
);
|
|
976
|
+
await hooksHandleError?.({
|
|
977
|
+
error: err,
|
|
978
|
+
event,
|
|
979
|
+
status: 500,
|
|
980
|
+
message: "Internal Server Error",
|
|
981
|
+
});
|
|
982
|
+
// an unexpected error gets the nearest +error.tsx too, with a
|
|
983
|
+
// generic message: details stay in the log
|
|
984
|
+
try {
|
|
985
|
+
const page = await renderErrorPage(
|
|
986
|
+
tree.errors,
|
|
987
|
+
event.url.pathname,
|
|
988
|
+
500,
|
|
989
|
+
"Internal Server Error",
|
|
990
|
+
process.env.NODE_ENV === "production" ? null : err,
|
|
991
|
+
loader,
|
|
992
|
+
{ nonceAttr: cspNonce ? ` nonce="${cspNonce}"` : "", dev },
|
|
993
|
+
);
|
|
994
|
+
if (page) return page;
|
|
995
|
+
} catch (pageErr) {
|
|
996
|
+
logger.error("+error.tsx failed while rendering an error:", pageErr);
|
|
997
|
+
}
|
|
998
|
+
const errorHtmlPath = `${process.cwd()}/error.html`;
|
|
999
|
+
try {
|
|
1000
|
+
const errorFile = Bun.file(errorHtmlPath);
|
|
1001
|
+
if (await errorFile.exists()) {
|
|
1002
|
+
return new Response(errorFile, {
|
|
1003
|
+
status: 500,
|
|
1004
|
+
headers: { "Content-Type": "text/html" },
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
} catch {}
|
|
1008
|
+
const message =
|
|
1009
|
+
process.env.NODE_ENV === "production"
|
|
1010
|
+
? "Internal Server Error"
|
|
1011
|
+
: `${err instanceof Error ? `${err.message}\n${err.stack}` : String(err)}`;
|
|
1012
|
+
return new Response(message, { status: 500, headers: TEXT });
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
const setCookieHeaders = cookies.toHeaders();
|
|
1016
|
+
if (
|
|
1017
|
+
!response ||
|
|
1018
|
+
(setCookieHeaders.length === 0 &&
|
|
1019
|
+
Object.keys(setHeadersMap).length === 0)
|
|
1020
|
+
) {
|
|
1021
|
+
return response;
|
|
1022
|
+
}
|
|
1023
|
+
return withHeaders(
|
|
1024
|
+
response,
|
|
1025
|
+
Object.entries(setHeadersMap),
|
|
1026
|
+
setCookieHeaders.map((sc) => ["Set-Cookie", sc] as [string, string]),
|
|
1027
|
+
);
|
|
1028
|
+
});
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
const websocket: ServerWebSocketHandlers = {
|
|
1032
|
+
open(ws: ServerWebSocket<any>) {
|
|
1033
|
+
if (ws.data.__hmrClient) {
|
|
1034
|
+
hmr?.addClient(ws);
|
|
1035
|
+
return;
|
|
1036
|
+
}
|
|
1037
|
+
(ws.data as _WsInternalData).__handler?.open?.(ws);
|
|
1038
|
+
},
|
|
1039
|
+
message(ws: ServerWebSocket<any>, data: string | Buffer) {
|
|
1040
|
+
if (ws.data.__hmrClient) return;
|
|
1041
|
+
(ws.data as _WsInternalData).__handler?.message?.(ws, data);
|
|
1042
|
+
},
|
|
1043
|
+
close(ws: ServerWebSocket<any>, code: number, reason?: string) {
|
|
1044
|
+
if (ws.data.__hmrClient) {
|
|
1045
|
+
hmr?.removeClient(ws);
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
(ws.data as _WsInternalData).__handler?.close?.(ws, code, reason);
|
|
1049
|
+
},
|
|
1050
|
+
drain(ws: ServerWebSocket<any>) {
|
|
1051
|
+
if (ws.data.__hmrClient) return;
|
|
1052
|
+
(ws.data as _WsInternalData).__handler?.drain?.(ws);
|
|
1053
|
+
},
|
|
1054
|
+
};
|
|
1055
|
+
|
|
1056
|
+
// Wrapping is what makes afterResponse() mean "after the response",
|
|
1057
|
+
// including for streaming responses: the tasks fire when the body
|
|
1058
|
+
// finishes, not when the handler returns.
|
|
1059
|
+
const fetchHandler = (req: Request) => withAfterResponse(req, handleRequest);
|
|
1060
|
+
|
|
1061
|
+
// Under a base, the request is stripped to a route path once, here, so
|
|
1062
|
+
// nothing past this point has to know about it.
|
|
1063
|
+
const fetchUnderBase = (req: Request): Promise<Response> | Response => {
|
|
1064
|
+
if (!appBase) return fetchHandler(req);
|
|
1065
|
+
const url = new URL(req.url);
|
|
1066
|
+
if (url.pathname === appBase) {
|
|
1067
|
+
return new Response(null, {
|
|
1068
|
+
status: 308,
|
|
1069
|
+
headers: { Location: `${appBase}/${url.search}` },
|
|
1070
|
+
});
|
|
1071
|
+
}
|
|
1072
|
+
const route = stripBase(url.pathname, appBase);
|
|
1073
|
+
if (route === null) {
|
|
1074
|
+
// dev modules import each other root-relative
|
|
1075
|
+
if (dev && url.pathname.startsWith("/__grimoire__/")) {
|
|
1076
|
+
return fetchHandler(req);
|
|
1077
|
+
}
|
|
1078
|
+
return new Response(outsideBaseMessage(url.pathname, appBase, dev), {
|
|
1079
|
+
status: 404,
|
|
1080
|
+
headers: { "Content-Type": "text/plain" },
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
url.pathname = route;
|
|
1084
|
+
return fetchHandler(new Request(url, req));
|
|
1085
|
+
};
|
|
1086
|
+
|
|
1087
|
+
const preload = async () => {
|
|
1088
|
+
if (dev || finalConfig.warm?.preload === false) return;
|
|
1089
|
+
const files = [
|
|
1090
|
+
...tree.routes,
|
|
1091
|
+
...tree.layouts,
|
|
1092
|
+
...tree.servers,
|
|
1093
|
+
...tree.errors,
|
|
1094
|
+
].map((rf: { filePath: string }) => rf.filePath);
|
|
1095
|
+
const t0 = performance.now();
|
|
1096
|
+
const loaded = await preloadModules(files, loader, (msg, err) =>
|
|
1097
|
+
logger.warn(msg, err),
|
|
1098
|
+
);
|
|
1099
|
+
logger.info(
|
|
1100
|
+
`preloaded ${loaded}/${new Set(files).size} route modules in ${Math.round(performance.now() - t0)}ms`,
|
|
1101
|
+
);
|
|
1102
|
+
};
|
|
1103
|
+
|
|
1104
|
+
return {
|
|
1105
|
+
fetch: fetchUnderBase,
|
|
1106
|
+
websocket,
|
|
1107
|
+
tree,
|
|
1108
|
+
matchers: paramMatcherFns,
|
|
1109
|
+
config: finalConfig,
|
|
1110
|
+
plugins,
|
|
1111
|
+
bind(s) {
|
|
1112
|
+
server = s;
|
|
1113
|
+
},
|
|
1114
|
+
preload,
|
|
1115
|
+
async close(reason = "shutdown", options) {
|
|
1116
|
+
await runHook(plugins, "onStop", reason);
|
|
1117
|
+
// Drain before stopping, so a task already registered for a response
|
|
1118
|
+
// that has been sent gets to finish rather than being killed with the
|
|
1119
|
+
// process. Bounded: a hung task must not block a deploy forever.
|
|
1120
|
+
await drainAfterResponse(options?.drainMs);
|
|
1121
|
+
},
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
export async function createServer(config: GrimoireConfig = {}) {
|
|
1126
|
+
const app = await createApp(config);
|
|
1127
|
+
const { plugins, config: finalConfig } = app;
|
|
1128
|
+
const { port = 3000, host = "localhost", dev = false } = finalConfig;
|
|
1129
|
+
|
|
1130
|
+
// Before the port opens, so the first visitor never pays for compiling a
|
|
1131
|
+
// route: a worker only reports ready once this has finished.
|
|
1132
|
+
await app.preload();
|
|
1133
|
+
|
|
1134
|
+
const server = Bun.serve({
|
|
1135
|
+
port,
|
|
1136
|
+
hostname: host,
|
|
1137
|
+
fetch: app.fetch,
|
|
1138
|
+
websocket: app.websocket,
|
|
1139
|
+
});
|
|
1140
|
+
app.bind(server);
|
|
1141
|
+
|
|
1142
|
+
const warmConfig = finalConfig.warm;
|
|
1143
|
+
let warmer: Warmer | null = null;
|
|
1144
|
+
if (!dev && warmConfig?.paths?.length) {
|
|
1145
|
+
warmer = startWarming({
|
|
1146
|
+
paths: warmConfig.paths,
|
|
1147
|
+
every: warmConfig.every,
|
|
1148
|
+
origin: `http://${host}:${server.port}`,
|
|
1149
|
+
headers: finalConfig._warmHeaders,
|
|
1150
|
+
handle: async (req) => app.fetch(req),
|
|
1151
|
+
log: (msg) => logger.info(msg),
|
|
1152
|
+
});
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
let stopping = false;
|
|
1156
|
+
const handleShutdown = async () => {
|
|
1157
|
+
if (stopping) return;
|
|
1158
|
+
stopping = true;
|
|
1159
|
+
warmer?.stop();
|
|
1160
|
+
await app.close("shutdown");
|
|
1161
|
+
// stop(true), not stop(): the graceful form waits for open connections,
|
|
1162
|
+
// and a dev HMR websocket never closes on its own, so shutdown hangs.
|
|
1163
|
+
server.stop(true);
|
|
1164
|
+
process.exit(0);
|
|
1165
|
+
};
|
|
1166
|
+
process.on("SIGINT", handleShutdown);
|
|
1167
|
+
process.on("SIGTERM", handleShutdown);
|
|
1168
|
+
|
|
1169
|
+
await runHook(plugins, "onStart", server);
|
|
1170
|
+
return server;
|
|
1171
|
+
}
|