@sigil-dev/grimoire 0.9.20 → 0.9.22
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/README.md +83 -83
- package/index.ts +50 -48
- package/package.json +16 -5
- package/public/__grimoire__/grimoire-client.js +12 -0
- package/public/__grimoire__/runtime.js +1241 -0
- package/server.ts +22 -20
- package/src/adapters/bun.ts +17 -0
- package/src/adapters/static.ts +41 -0
- package/src/adapters/types.ts +36 -0
- package/src/base.ts +91 -0
- package/src/client/csrf.ts +47 -47
- package/src/client/deferred.ts +179 -179
- package/src/client/enhance.ts +160 -160
- package/src/client/router.ts +870 -833
- package/src/dev/compile-module.ts +211 -211
- package/src/dev/loader.ts +141 -141
- package/src/dev/resolve.ts +70 -70
- package/src/dev/runtime-bundle.ts +51 -51
- package/src/env/modules.ts +62 -62
- package/src/env/required.ts +42 -0
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +105 -114
- package/src/logger/transports.ts +117 -117
- package/src/rendering/head.ts +49 -49
- package/src/rendering/hydrate.ts +161 -161
- package/src/rendering/images.ts +43 -43
- package/src/rendering/index.ts +755 -745
- package/src/rendering/preload.ts +101 -95
- package/src/rendering/ssrPlugin.ts +108 -108
- package/src/rendering/timing.ts +40 -40
- package/src/routing/router.ts +186 -186
- package/src/routing/scanner.ts +225 -196
- package/src/routing/transform-routes.ts +102 -102
- package/src/server/after-response.ts +206 -194
- package/src/server/asset-cache.ts +57 -55
- package/src/server/build.ts +262 -249
- package/src/server/cached.ts +114 -114
- package/src/server/client-address.ts +82 -82
- package/src/server/client-dir.ts +57 -57
- package/src/server/client-entry.ts +44 -0
- package/src/server/cookie-utils.ts +80 -80
- package/src/server/coordinator.ts +476 -471
- package/src/server/hooks.ts +122 -122
- package/src/server/index.ts +1138 -1022
- package/src/server/plugins.ts +172 -172
- package/src/server/prerender.ts +444 -0
- package/src/server/reserved.ts +17 -0
- package/src/server/resolver.ts +98 -98
- package/src/server/rewrite.ts +28 -0
- package/src/server/warm.ts +91 -91
- package/src/server/with-headers.ts +27 -0
- package/src/server/worker.ts +74 -72
- package/src/testing/dom.ts +73 -0
- package/src/testing/index.ts +169 -0
- package/src/testing/server.ts +162 -0
- package/src/typegen/index.ts +450 -450
- package/src/types.ts +501 -432
- package/test/after-response.test.ts +132 -113
- package/test/asset-cache-policy.test.ts +96 -96
- package/test/base.test.ts +134 -0
- package/test/cached.test.ts +126 -126
- package/test/client-address.test.ts +78 -78
- package/test/client-csrf.test.ts +61 -61
- package/test/client-dir.test.ts +101 -69
- package/test/client-router.test.ts +789 -734
- package/test/coordinator.test.ts +96 -94
- package/test/deferred.test.ts +256 -256
- package/test/dev-loader.test.ts +30 -30
- package/test/env.test.ts +168 -168
- package/test/force-production.test.ts +44 -0
- package/test/images.test.ts +49 -49
- package/test/locals-header.test.ts +61 -0
- package/test/middleware.test.ts +243 -243
- package/test/parser-plugins.test.ts +92 -92
- package/test/plugin-handle.test.ts +62 -62
- package/test/plugin-services-context.test.ts +97 -97
- package/test/preload.test.ts +48 -48
- package/test/prerender.test.ts +353 -0
- package/test/rendering.test.ts +798 -798
- package/test/required-env.test.ts +32 -0
- package/test/rewrite-html.test.ts +90 -0
- package/test/scanning.test.ts +349 -314
- package/test/server.test.ts +640 -619
- package/test/services.test.ts +90 -90
- package/test/streaming.test.ts +378 -378
- package/test/testing-helpers.test.ts +166 -0
- package/test/typegen.test.ts +805 -799
- package/test/warm.test.ts +96 -96
- package/test/worker-context.test.ts +59 -59
- package/test/workspace-files.test.ts +149 -146
- package/test/workspace-versions.test.ts +131 -131
- package/.grimoire/_routes.ts +0 -4
- package/public/__grimoire__/client.js +0 -55
- package/public/__grimoire__/hydrate.js +0 -63
package/src/rendering/index.ts
CHANGED
|
@@ -1,745 +1,755 @@
|
|
|
1
|
-
import { randomBytes } from "node:crypto";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import
|
|
16
|
-
import {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
type
|
|
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
|
-
return
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
return
|
|
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
|
-
return
|
|
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
|
-
const
|
|
307
|
-
|
|
308
|
-
const
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
const
|
|
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
|
-
const
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
const
|
|
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
|
-
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { SafeHtml } from "@sigil-dev/runtime";
|
|
3
|
+
import { startCollecting, stopCollecting } from "../client/deps";
|
|
4
|
+
import { filterPublic } from "../env/index";
|
|
5
|
+
import { findClosestError, type MatchedRoute } from "../routing/router";
|
|
6
|
+
import type { RouteFile } from "../routing/scanner";
|
|
7
|
+
import { isErrorResult } from "../sentinels/error.ts";
|
|
8
|
+
import { isRedirectResult } from "../sentinels/redirect.ts";
|
|
9
|
+
import { clientAddressOf } from "../server/client-address";
|
|
10
|
+
import { hydrateEntry } from "../server/client-entry";
|
|
11
|
+
import { runWithContext } from "../server/context";
|
|
12
|
+
import { base, withBase } from "../base";
|
|
13
|
+
import { runHook } from "../server/plugins";
|
|
14
|
+
import type { GrimoirePlugin, LoadContext, Route } from "../types";
|
|
15
|
+
import { collectHead, initHead } from "./head";
|
|
16
|
+
import { optimizeImages } from "./images.ts";
|
|
17
|
+
import { preloadLinks } from "./preload.ts";
|
|
18
|
+
import { createTimer } from "./timing.ts";
|
|
19
|
+
|
|
20
|
+
/** A plain message. Without the type, a proxy or a later rewrap can send it as a download. */
|
|
21
|
+
const TEXT = { "Content-Type": "text/plain; charset=utf-8" };
|
|
22
|
+
|
|
23
|
+
export type ModuleLoader = (path: string) => Promise<any>;
|
|
24
|
+
|
|
25
|
+
type LayoutPair = { layout: RouteFile; mod: any; data: unknown };
|
|
26
|
+
|
|
27
|
+
/** Placeholder for a top-level server-load promise still in flight. SSR text
|
|
28
|
+
* interpolation renders it as an empty string via the normal String(v) path. */
|
|
29
|
+
class DeferredMarker {
|
|
30
|
+
constructor(
|
|
31
|
+
public uid: string,
|
|
32
|
+
public key: string,
|
|
33
|
+
) {}
|
|
34
|
+
toString() {
|
|
35
|
+
return "";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type DeferredEntry = { promise: Promise<unknown>; key: string; uid: string };
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Request header the client router sets to ask for the JSON navigate payload
|
|
43
|
+
* instead of an HTML document. Both representations live at the same URL, so
|
|
44
|
+
* every response that depends on it MUST also send it in `Vary`.
|
|
45
|
+
*/
|
|
46
|
+
export const NAVIGATE_HEADER = "x-grimoire-navigate";
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Serialize the hydration state payload for embedding inside a
|
|
50
|
+
* `<script type="application/json">` tag. Escapes every `<` so a data value
|
|
51
|
+
* like `"</script><script>alert(1)</script>"` cannot close the state script
|
|
52
|
+
* early and inject markup. JSON.parse reads `\u003c` back as `<`.
|
|
53
|
+
* DeferredMarkers serialize to `{ __deferred: uid }`.
|
|
54
|
+
*/
|
|
55
|
+
const safeStateJson = (value: unknown): string =>
|
|
56
|
+
JSON.stringify(value, (_k, v) =>
|
|
57
|
+
v instanceof DeferredMarker ? { __deferred: v.uid } : v,
|
|
58
|
+
).replace(/</g, "\\u003c");
|
|
59
|
+
|
|
60
|
+
/** Replace every own top-level promise property with a marker and record the
|
|
61
|
+
* promise for late flush. Nested promises are awaited by the load itself. */
|
|
62
|
+
function extractDeferred(
|
|
63
|
+
data: unknown,
|
|
64
|
+
deferred: DeferredEntry[],
|
|
65
|
+
counter: { n: number },
|
|
66
|
+
): void {
|
|
67
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return;
|
|
68
|
+
const record = data as Record<string, unknown>;
|
|
69
|
+
for (const key of Object.keys(record)) {
|
|
70
|
+
const value = record[key];
|
|
71
|
+
if (value instanceof Promise) {
|
|
72
|
+
const uid = `gd-${counter.n++}`;
|
|
73
|
+
record[key] = new DeferredMarker(uid, key);
|
|
74
|
+
deferred.push({ promise: value, key, uid });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The data a component renders with on the server: a value still in flight
|
|
81
|
+
* reads as `undefined`, so `{data.reviews ?? "Loading…"}` shows its
|
|
82
|
+
* fallback. The state script keeps the markers, and the settled values
|
|
83
|
+
* reach the browser before it hydrates.
|
|
84
|
+
*/
|
|
85
|
+
function renderable(data: unknown): unknown {
|
|
86
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return data;
|
|
87
|
+
const values = Object.values(data as Record<string, unknown>);
|
|
88
|
+
if (!values.some((v) => v instanceof DeferredMarker)) return data;
|
|
89
|
+
const out: Record<string, unknown> = {};
|
|
90
|
+
for (const [k, v] of Object.entries(data as Record<string, unknown>)) {
|
|
91
|
+
out[k] = v instanceof DeferredMarker ? undefined : v;
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Template + patch script for one settled deferred value. */
|
|
97
|
+
function deferredChunk(key: string, value: unknown, error: boolean): string {
|
|
98
|
+
const keyJson = JSON.stringify(key);
|
|
99
|
+
// The value rides inline (safeStateJson escapes `<`, so the script cannot
|
|
100
|
+
// be broken out of). No DOM lookups: trailing chunks arrive after </html>,
|
|
101
|
+
// where element timing is unreliable across parsers.
|
|
102
|
+
return `<script>(function(){var value=${safeStateJson(value)};var tag=document.getElementById("__grimoire_state__");if(tag){try{var s=JSON.parse(tag.textContent);s.data[${keyJson}]=value;tag.textContent=JSON.stringify(s)}catch(e){}}var w=window.__grimoire_state__;if(!w||w.nodeType)w=window.__grimoire_state__={data:{}};if(!w.data)w.data={};w.data[${keyJson}]=value;window.dispatchEvent(new CustomEvent("grimoire:deferred",{detail:{key:${keyJson},error:${error ? "true" : "false"}}}))})()</script>`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* PUBLIC_ environment variables for `$env/dynamic/public` in the browser,
|
|
107
|
+
* as the server sees them now.
|
|
108
|
+
*/
|
|
109
|
+
function publicEnvScript(nonceAttr: string): string {
|
|
110
|
+
const env = filterPublic(process.env);
|
|
111
|
+
if (Object.keys(env).length === 0) return "";
|
|
112
|
+
return `\n <script${nonceAttr}>window.__grimoire_env__=${safeStateJson(env)}</script>`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function buildHtmlSkeleton(nonceAttr: string, dev?: boolean): string {
|
|
116
|
+
// a meta tag, not a script: the base has to reach the router under a CSP
|
|
117
|
+
// nonce too, and the bundle reads it so one build works under any base
|
|
118
|
+
const baseMeta = base
|
|
119
|
+
? `\n <meta name="grimoire-base" content="${base}" />`
|
|
120
|
+
: "";
|
|
121
|
+
return `<!DOCTYPE html>
|
|
122
|
+
<html>
|
|
123
|
+
<head>
|
|
124
|
+
<meta charset="UTF-8" />
|
|
125
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />${publicEnvScript(nonceAttr)}
|
|
126
|
+
<script type="module" src="/__grimoire__/${hydrateEntry()}"${nonceAttr}></script>
|
|
127
|
+
${dev ? `<script src="/__grimoire__/hmr-client.js"${nonceAttr}></script>` : ""}`;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Copy `<link rel="stylesheet">` tags found in rendered body HTML so they can
|
|
132
|
+
* be emitted in <head>, where they are render-blocking. Components declare
|
|
133
|
+
* stylesheets inline in JSX (usually in a layout), which lands them in the
|
|
134
|
+
* body — the browser paints the unstyled document before body CSS applies,
|
|
135
|
+
* causing a white flash on every full-document load. The body originals are
|
|
136
|
+
* left in place so hydration can still claim them; the head copy shares the
|
|
137
|
+
* same URL, so the browser only fetches once.
|
|
138
|
+
*/
|
|
139
|
+
function hoistStylesheets(bodyHtml: string): string {
|
|
140
|
+
const links = new Set<string>();
|
|
141
|
+
for (const m of bodyHtml.matchAll(
|
|
142
|
+
/<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi,
|
|
143
|
+
)) {
|
|
144
|
+
links.add(m[0]);
|
|
145
|
+
}
|
|
146
|
+
return [...links].join("\n ");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* <style> tags for the scoped CSS of every component file whose scope class
|
|
151
|
+
* appears in `html`. Server builds register each file's CSS by hash (see
|
|
152
|
+
* serverStyleSnippet in the compiler), so a server-rendered page is styled
|
|
153
|
+
* before any script runs; the browser build's own injection sees the id and
|
|
154
|
+
* skips it.
|
|
155
|
+
*/
|
|
156
|
+
function scopedStyles(html: string, nonceAttr: string): string {
|
|
157
|
+
const registry = (globalThis as { __sigil_css__?: Map<string, string> })
|
|
158
|
+
.__sigil_css__;
|
|
159
|
+
if (!registry) return "";
|
|
160
|
+
let out = "";
|
|
161
|
+
for (const [hash, css] of registry) {
|
|
162
|
+
if (!html.includes(hash)) continue;
|
|
163
|
+
out += `<style id="sigil-${hash}"${nonceAttr}>${css.replace(/<\/style/gi, "<\\/style")}</style>`;
|
|
164
|
+
}
|
|
165
|
+
return out;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* The CSRF token for this response: the visitor's existing `_csrf` cookie
|
|
170
|
+
* when it holds a well-formed token, so pages open in other tabs keep
|
|
171
|
+
* working, otherwise a fresh one.
|
|
172
|
+
*/
|
|
173
|
+
function csrfTokenFor(req: Request): string {
|
|
174
|
+
const m = /(?:^|;\s*)_csrf=([0-9a-f]{64})(?:;|$)/.exec(
|
|
175
|
+
req.headers.get("cookie") ?? "",
|
|
176
|
+
);
|
|
177
|
+
return m?.[1] ?? randomBytes(32).toString("hex");
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Put the token into every POST form, with or without an action attribute
|
|
182
|
+
* (one without posts back to the page). GET forms never get it: the token
|
|
183
|
+
* would end up in the URL, and a GET is never CSRF-checked anyway.
|
|
184
|
+
*/
|
|
185
|
+
function injectCsrf(html: string, token: string): string {
|
|
186
|
+
const input = `<input type="hidden" name="_csrf" value="${token}" data-grimoire-csrf>`;
|
|
187
|
+
return html.replace(
|
|
188
|
+
/<form\b([^>]*\bmethod=["']?post["']?[^>]*)>/gi,
|
|
189
|
+
`<form$1>${input}`,
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const csrfCookie = (token: string) => `_csrf=${token}; SameSite=Strict; Path=/`;
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The collected <Head> tags between marker comments, so the client router
|
|
197
|
+
* can find and replace them on navigation.
|
|
198
|
+
*/
|
|
199
|
+
const headBlock = (headHtml: string) =>
|
|
200
|
+
`<!--grimoire-head-->${headHtml}<!--/grimoire-head-->`;
|
|
201
|
+
|
|
202
|
+
/** Wrap page/error HTML in whatever parent layouts loaded successfully. */
|
|
203
|
+
function applyLayoutTree(
|
|
204
|
+
innerHtml: string,
|
|
205
|
+
layoutPairs: LayoutPair[],
|
|
206
|
+
params: Record<string, string>,
|
|
207
|
+
pattern?: string,
|
|
208
|
+
innerId = "grimoire-page",
|
|
209
|
+
): string {
|
|
210
|
+
let bodyHtml = `<div id="${innerId}">${innerHtml}</div>`;
|
|
211
|
+
for (const { mod: layoutMod, data } of [...layoutPairs].reverse()) {
|
|
212
|
+
bodyHtml = String(
|
|
213
|
+
layoutMod.default({
|
|
214
|
+
data: renderable(data),
|
|
215
|
+
children: new SafeHtml(bodyHtml),
|
|
216
|
+
params,
|
|
217
|
+
path: pattern,
|
|
218
|
+
}),
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
return `<div id="grimoire-root">${bodyHtml}</div>`;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Render a +error.tsx page as a full HTML document (doctype, hydration
|
|
226
|
+
* script, and any parent layouts that had already loaded successfully),
|
|
227
|
+
* instead of a bare fragment. No __grimoire_state__ script is emitted —
|
|
228
|
+
* error pages aren't part of the client route table, so hydrate.js
|
|
229
|
+
* simply skips client hydration for them (SSR-only, which is correct
|
|
230
|
+
* since there's no client-side error route to hydrate against).
|
|
231
|
+
*/
|
|
232
|
+
export async function renderErrorPage(
|
|
233
|
+
errorRoutes: RouteFile[],
|
|
234
|
+
pathname: string,
|
|
235
|
+
status: number,
|
|
236
|
+
message: string,
|
|
237
|
+
error: unknown,
|
|
238
|
+
loadModule: ModuleLoader,
|
|
239
|
+
opts: {
|
|
240
|
+
layoutPairs?: LayoutPair[];
|
|
241
|
+
params?: Record<string, string>;
|
|
242
|
+
nonceAttr?: string;
|
|
243
|
+
dev?: boolean;
|
|
244
|
+
} = {},
|
|
245
|
+
): Promise<Response | null> {
|
|
246
|
+
const errorPage = findClosestError(errorRoutes, pathname);
|
|
247
|
+
if (!errorPage) return null;
|
|
248
|
+
const mod = await loadModule(errorPage.filePath);
|
|
249
|
+
|
|
250
|
+
const { layoutPairs = [], params = {}, nonceAttr = "", dev } = opts;
|
|
251
|
+
|
|
252
|
+
// own context so <Head> used by the error page (or wrapping layouts)
|
|
253
|
+
// is collected fresh, independent of whatever the failed page pushed
|
|
254
|
+
return runWithContext(async () => {
|
|
255
|
+
const nonce = nonceAttr.match(/nonce="([^"]+)"/)?.[1];
|
|
256
|
+
initHead(nonce);
|
|
257
|
+
|
|
258
|
+
const errorHtml = String(
|
|
259
|
+
mod.default({ status, message, error, route: pathname }),
|
|
260
|
+
);
|
|
261
|
+
const bodyHtml = applyLayoutTree(errorHtml, layoutPairs, params);
|
|
262
|
+
const headHtml = collectHead();
|
|
263
|
+
const hoistedCss = hoistStylesheets(bodyHtml);
|
|
264
|
+
const styles = scopedStyles(bodyHtml, nonceAttr);
|
|
265
|
+
|
|
266
|
+
const html = `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${styles ? `\n ${styles}` : ""}\n${headBlock(headHtml)}
|
|
267
|
+
</head>
|
|
268
|
+
<body>
|
|
269
|
+
<div id="app">${bodyHtml}</div>
|
|
270
|
+
</body>
|
|
271
|
+
</html>`;
|
|
272
|
+
|
|
273
|
+
return new Response(html, {
|
|
274
|
+
status,
|
|
275
|
+
headers: { "Content-Type": "text/html", Vary: NAVIGATE_HEADER },
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export async function renderRoute(
|
|
281
|
+
matched: MatchedRoute,
|
|
282
|
+
req: Request,
|
|
283
|
+
errorRoutes: RouteFile[] = [],
|
|
284
|
+
loadModule: ModuleLoader = (path) => import(path),
|
|
285
|
+
locals: Record<string, any> = {},
|
|
286
|
+
plugins: GrimoirePlugin[] = [],
|
|
287
|
+
cspNonce?: string,
|
|
288
|
+
dev?: boolean,
|
|
289
|
+
patchedFetch?: typeof fetch,
|
|
290
|
+
/** A form action's fail() on a plain (non-enhanced) POST: the page renders
|
|
291
|
+
* again with the failure as its `form` prop, and with its status. */
|
|
292
|
+
actionFailure?: { status: number; data: unknown },
|
|
293
|
+
): Promise<Response> {
|
|
294
|
+
return runWithContext(async () => {
|
|
295
|
+
const context: LoadContext = {
|
|
296
|
+
request: req,
|
|
297
|
+
params: matched.params,
|
|
298
|
+
url: new URL(req.url),
|
|
299
|
+
locals,
|
|
300
|
+
fetch: patchedFetch ?? globalThis.fetch,
|
|
301
|
+
getClientAddress: () => clientAddressOf(req),
|
|
302
|
+
// no layouts have loaded yet — parent() is empty until the loop runs
|
|
303
|
+
parent: async () => ({}),
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
const timer = createTimer();
|
|
307
|
+
initHead(cspNonce);
|
|
308
|
+
const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
|
|
309
|
+
|
|
310
|
+
// ── layout loading ──────────────────────────────────────────────────────
|
|
311
|
+
const layoutPairs: { layout: RouteFile; mod: any; data: unknown }[] = [];
|
|
312
|
+
const parentData: Record<string, unknown> = {};
|
|
313
|
+
// depends() keys gathered across every server-executed load
|
|
314
|
+
const collectedDeps = new Set<string>();
|
|
315
|
+
// top-level load promises flushed late (deferred streaming)
|
|
316
|
+
const deferred: DeferredEntry[] = [];
|
|
317
|
+
const deferredCounter = { n: 0 };
|
|
318
|
+
const collectDeps = async (run: () => unknown): Promise<unknown> => {
|
|
319
|
+
startCollecting();
|
|
320
|
+
try {
|
|
321
|
+
return await run();
|
|
322
|
+
} finally {
|
|
323
|
+
for (const key of stopCollecting()) collectedDeps.add(key);
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
const route: Route = {
|
|
328
|
+
path: matched.route.path,
|
|
329
|
+
params: matched.params,
|
|
330
|
+
filePath: matched.route.filePath,
|
|
331
|
+
loadPath: matched.pageServer?.filePath,
|
|
332
|
+
layoutPath: matched.layouts.at(-1)?.filePath,
|
|
333
|
+
};
|
|
334
|
+
await runHook(plugins, "onRouteLoad", route, context);
|
|
335
|
+
|
|
336
|
+
// One level per folder with a +layout.tsx, a +layout.server.ts, or
|
|
337
|
+
// both. A server load without a layout component still runs: it's
|
|
338
|
+
// where a folder's guard lives, and skipping it left the folder open.
|
|
339
|
+
const levels = [
|
|
340
|
+
...new Set(
|
|
341
|
+
[...matched.layouts, ...matched.layoutServers].map((l) => l.path),
|
|
342
|
+
),
|
|
343
|
+
].sort((a, b) => a.length - b.length);
|
|
344
|
+
|
|
345
|
+
for (const levelPath of levels) {
|
|
346
|
+
const layout = matched.layouts.find((l) => l.path === levelPath);
|
|
347
|
+
// loads in this layout see everything accumulated so far
|
|
348
|
+
context.parent = async () => ({ ...parentData });
|
|
349
|
+
|
|
350
|
+
const layoutMod = layout ? await loadModule(layout.filePath) : {};
|
|
351
|
+
|
|
352
|
+
if (layoutMod.canMatch) {
|
|
353
|
+
try {
|
|
354
|
+
const result = await layoutMod.canMatch(context);
|
|
355
|
+
if (result === false)
|
|
356
|
+
return new Response("Not Found", { status: 404 });
|
|
357
|
+
if (isRedirectResult(result))
|
|
358
|
+
return new Response(null, {
|
|
359
|
+
status: result.status,
|
|
360
|
+
headers: { Location: result.location },
|
|
361
|
+
});
|
|
362
|
+
} catch (e) {
|
|
363
|
+
if (isRedirectResult(e))
|
|
364
|
+
return new Response(null, {
|
|
365
|
+
status: e.status,
|
|
366
|
+
headers: { Location: e.location },
|
|
367
|
+
});
|
|
368
|
+
if (isErrorResult(e))
|
|
369
|
+
return (
|
|
370
|
+
(await renderErrorPage(
|
|
371
|
+
errorRoutes,
|
|
372
|
+
context.url.pathname,
|
|
373
|
+
e.status,
|
|
374
|
+
e.message,
|
|
375
|
+
e,
|
|
376
|
+
loadModule,
|
|
377
|
+
{ layoutPairs, params: matched.params, nonceAttr, dev },
|
|
378
|
+
)) ?? new Response(e.message, { status: e.status, headers: TEXT })
|
|
379
|
+
);
|
|
380
|
+
throw e;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const layoutServer = matched.layoutServers.find(
|
|
385
|
+
(ls) => ls.path === levelPath,
|
|
386
|
+
);
|
|
387
|
+
let data: unknown;
|
|
388
|
+
if (layoutServer) {
|
|
389
|
+
try {
|
|
390
|
+
const mod = await loadModule(layoutServer.filePath);
|
|
391
|
+
data = await collectDeps(() => mod.load?.(context));
|
|
392
|
+
} catch (e) {
|
|
393
|
+
if (isRedirectResult(e))
|
|
394
|
+
return new Response(null, {
|
|
395
|
+
status: e.status,
|
|
396
|
+
headers: { Location: e.location },
|
|
397
|
+
});
|
|
398
|
+
if (isErrorResult(e))
|
|
399
|
+
return (
|
|
400
|
+
(await renderErrorPage(
|
|
401
|
+
errorRoutes,
|
|
402
|
+
context.url.pathname,
|
|
403
|
+
e.status,
|
|
404
|
+
e.message,
|
|
405
|
+
e,
|
|
406
|
+
loadModule,
|
|
407
|
+
{ layoutPairs, params: matched.params, nonceAttr, dev },
|
|
408
|
+
)) ?? new Response(e.message, { status: e.status, headers: TEXT })
|
|
409
|
+
);
|
|
410
|
+
throw e;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const universalLayoutData = layoutMod.load
|
|
415
|
+
? await collectDeps(() => layoutMod.load(context))
|
|
416
|
+
: undefined;
|
|
417
|
+
|
|
418
|
+
const mergedLayoutData =
|
|
419
|
+
universalLayoutData !== undefined
|
|
420
|
+
? //@ts-expect-error user-provided data is always unknown
|
|
421
|
+
{ ...universalLayoutData, ...data }
|
|
422
|
+
: data;
|
|
423
|
+
|
|
424
|
+
// only components wrap the page; the client indexes layoutData by them
|
|
425
|
+
if (layout)
|
|
426
|
+
layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
|
|
427
|
+
extractDeferred(mergedLayoutData, deferred, deferredCounter);
|
|
428
|
+
if (mergedLayoutData && typeof mergedLayoutData === "object") {
|
|
429
|
+
Object.assign(parentData, mergedLayoutData);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// no page at this address: its layouts are loaded, the 404 goes in them
|
|
434
|
+
if (matched.notFound)
|
|
435
|
+
return (
|
|
436
|
+
(await renderErrorPage(
|
|
437
|
+
errorRoutes,
|
|
438
|
+
context.url.pathname,
|
|
439
|
+
404,
|
|
440
|
+
"Not Found",
|
|
441
|
+
null,
|
|
442
|
+
loadModule,
|
|
443
|
+
{ layoutPairs, params: matched.params, nonceAttr, dev },
|
|
444
|
+
)) ?? new Response("Not Found", { status: 404 })
|
|
445
|
+
);
|
|
446
|
+
|
|
447
|
+
// page loads see every layout's data merged
|
|
448
|
+
context.parent = async () => ({ ...parentData });
|
|
449
|
+
|
|
450
|
+
// ── page server load ────────────────────────────────────────────────────
|
|
451
|
+
let pageData: unknown;
|
|
452
|
+
if (matched.pageServer) {
|
|
453
|
+
try {
|
|
454
|
+
const mod = await loadModule(matched.pageServer.filePath);
|
|
455
|
+
pageData = await collectDeps(() => mod.load?.(context));
|
|
456
|
+
} catch (e) {
|
|
457
|
+
if (isRedirectResult(e))
|
|
458
|
+
return new Response(null, {
|
|
459
|
+
status: e.status,
|
|
460
|
+
headers: { Location: e.location },
|
|
461
|
+
});
|
|
462
|
+
if (isErrorResult(e))
|
|
463
|
+
return (
|
|
464
|
+
(await renderErrorPage(
|
|
465
|
+
errorRoutes,
|
|
466
|
+
context.url.pathname,
|
|
467
|
+
e.status,
|
|
468
|
+
e.message,
|
|
469
|
+
e,
|
|
470
|
+
loadModule,
|
|
471
|
+
{ layoutPairs, params: matched.params, nonceAttr, dev },
|
|
472
|
+
)) ?? new Response(e.message, { status: e.status, headers: TEXT })
|
|
473
|
+
);
|
|
474
|
+
throw e;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// ── page module ─────────────────────────────────────────────────────────
|
|
479
|
+
const pageMod = await loadModule(matched.route.filePath);
|
|
480
|
+
|
|
481
|
+
if (pageMod.canMatch) {
|
|
482
|
+
try {
|
|
483
|
+
const result = await pageMod.canMatch(context);
|
|
484
|
+
if (result === false) return new Response("Not Found", { status: 404 });
|
|
485
|
+
if (isRedirectResult(result))
|
|
486
|
+
return new Response(null, {
|
|
487
|
+
status: result.status,
|
|
488
|
+
headers: { Location: result.location },
|
|
489
|
+
});
|
|
490
|
+
} catch (e) {
|
|
491
|
+
if (isRedirectResult(e))
|
|
492
|
+
return new Response(null, {
|
|
493
|
+
status: e.status,
|
|
494
|
+
headers: { Location: e.location },
|
|
495
|
+
});
|
|
496
|
+
if (isErrorResult(e))
|
|
497
|
+
return (
|
|
498
|
+
(await renderErrorPage(
|
|
499
|
+
errorRoutes,
|
|
500
|
+
context.url.pathname,
|
|
501
|
+
e.status,
|
|
502
|
+
e.message,
|
|
503
|
+
e,
|
|
504
|
+
loadModule,
|
|
505
|
+
{ layoutPairs, params: matched.params, nonceAttr, dev },
|
|
506
|
+
)) ?? new Response(e.message, { status: e.status, headers: TEXT })
|
|
507
|
+
);
|
|
508
|
+
throw e;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
const isNavigate = req.headers.get(NAVIGATE_HEADER) === "1";
|
|
513
|
+
const hasLoading = typeof pageMod.loading === "function";
|
|
514
|
+
|
|
515
|
+
// helper: wrap page html in layout tree
|
|
516
|
+
function applyLayouts(pageHtml: string): string {
|
|
517
|
+
return applyLayoutTree(
|
|
518
|
+
pageHtml,
|
|
519
|
+
layoutPairs,
|
|
520
|
+
matched.params,
|
|
521
|
+
matched.route.path,
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// ── two-pass streaming (loading export present) ─────────────────────────
|
|
526
|
+
if (hasLoading && !isNavigate) {
|
|
527
|
+
const uid = Math.random().toString(36).slice(2);
|
|
528
|
+
const csrfToken = csrfTokenFor(req);
|
|
529
|
+
const loadingHtml = String(pageMod.loading());
|
|
530
|
+
const loadingBody = injectCsrf(
|
|
531
|
+
applyLayouts(`<div id="ab-${uid}">${loadingHtml}</div>`),
|
|
532
|
+
csrfToken,
|
|
533
|
+
);
|
|
534
|
+
// layout stylesheets are in the loading shell — hoist before first flush
|
|
535
|
+
const hoistedCss = hoistStylesheets(loadingBody);
|
|
536
|
+
const shellStyles = scopedStyles(loadingBody, nonceAttr);
|
|
537
|
+
|
|
538
|
+
const stream = new ReadableStream({
|
|
539
|
+
async start(controller) {
|
|
540
|
+
// 1. skeleton + loading shell — browser paints immediately
|
|
541
|
+
controller.enqueue(
|
|
542
|
+
`${buildHtmlSkeleton(nonceAttr, dev)}${preloadLinks(matched.route.path, nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${shellStyles ? `\n ${shellStyles}` : ""}
|
|
543
|
+
</head>
|
|
544
|
+
<body>
|
|
545
|
+
<div id="app">${loadingBody}`,
|
|
546
|
+
);
|
|
547
|
+
|
|
548
|
+
// 2. run universal load while browser renders shell
|
|
549
|
+
const universalData = pageMod.load
|
|
550
|
+
? await collectDeps(() => pageMod.load(context)).catch(
|
|
551
|
+
(e: unknown) => {
|
|
552
|
+
if (isRedirectResult(e)) throw e;
|
|
553
|
+
if (isErrorResult(e)) throw e;
|
|
554
|
+
throw e;
|
|
555
|
+
},
|
|
556
|
+
)
|
|
557
|
+
: undefined;
|
|
558
|
+
|
|
559
|
+
const mergedData =
|
|
560
|
+
universalData !== undefined
|
|
561
|
+
? //@ts-expect-error user-provided data is always unknown
|
|
562
|
+
{ ...universalData, ...pageData }
|
|
563
|
+
: pageData;
|
|
564
|
+
extractDeferred(mergedData, deferred, deferredCounter);
|
|
565
|
+
|
|
566
|
+
// 3. render real page + collect head
|
|
567
|
+
const pageHtml = injectCsrf(
|
|
568
|
+
String(
|
|
569
|
+
await Promise.resolve(
|
|
570
|
+
pageMod.default({
|
|
571
|
+
data: renderable(mergedData),
|
|
572
|
+
params: matched.params,
|
|
573
|
+
form: actionFailure?.data,
|
|
574
|
+
}),
|
|
575
|
+
),
|
|
576
|
+
),
|
|
577
|
+
csrfToken,
|
|
578
|
+
);
|
|
579
|
+
const headHtml = collectHead();
|
|
580
|
+
const stateJson = safeStateJson({
|
|
581
|
+
params: matched.params,
|
|
582
|
+
data: mergedData,
|
|
583
|
+
layoutData: layoutPairs.map((l) => l.data),
|
|
584
|
+
pattern: matched.route.path,
|
|
585
|
+
deps: [...collectedDeps],
|
|
586
|
+
form: actionFailure?.data,
|
|
587
|
+
});
|
|
588
|
+
|
|
589
|
+
// 4. inject late head tags
|
|
590
|
+
if (headHtml) {
|
|
591
|
+
controller.enqueue(
|
|
592
|
+
`<script${nonceAttr}>(function(){var p=new DOMParser().parseFromString(${JSON.stringify(`<head>${headHtml}</head>`).replace(/</g, "\\u003c")},"text/html");for(var e of Array.from(p.head.children)){var c=e.cloneNode(true);c.setAttribute("data-grimoire-head","1");document.head.appendChild(c)}})();</script>`,
|
|
593
|
+
);
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// 5. swap shell with real content
|
|
597
|
+
controller.enqueue(
|
|
598
|
+
`<template id="ab-${uid}-r">${scopedStyles(String(pageHtml), nonceAttr)}${String(pageHtml)}</template>
|
|
599
|
+
<script${nonceAttr}>(function(){var t=document.getElementById("ab-${uid}-r");var target=document.getElementById("ab-${uid}");if(t&&target)target.replaceWith(t.content)})();</script>
|
|
600
|
+
<script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
|
|
601
|
+
</div>
|
|
602
|
+
</body>
|
|
603
|
+
</html>`,
|
|
604
|
+
);
|
|
605
|
+
|
|
606
|
+
// 6. flush deferred values in order as they settle
|
|
607
|
+
for (const d of deferred) {
|
|
608
|
+
try {
|
|
609
|
+
const value = await d.promise;
|
|
610
|
+
controller.enqueue(deferredChunk(d.key, value, false));
|
|
611
|
+
} catch {
|
|
612
|
+
controller.enqueue(deferredChunk(d.key, null, true));
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
controller.close();
|
|
617
|
+
},
|
|
618
|
+
});
|
|
619
|
+
|
|
620
|
+
return new Response(stream, {
|
|
621
|
+
status: actionFailure?.status ?? 200,
|
|
622
|
+
headers: {
|
|
623
|
+
"Content-Type": "text/html",
|
|
624
|
+
"Set-Cookie": csrfCookie(csrfToken),
|
|
625
|
+
Vary: NAVIGATE_HEADER,
|
|
626
|
+
},
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// ── single-pass (no loading export) ────────────────────────────────────
|
|
631
|
+
const universalData = pageMod.load
|
|
632
|
+
? await collectDeps(() => pageMod.load(context)).catch((e) => {
|
|
633
|
+
if (isRedirectResult(e)) throw e;
|
|
634
|
+
if (isErrorResult(e)) throw e;
|
|
635
|
+
throw e;
|
|
636
|
+
})
|
|
637
|
+
: undefined;
|
|
638
|
+
|
|
639
|
+
const mergedData =
|
|
640
|
+
universalData !== undefined
|
|
641
|
+
? //@ts-expect-error user-provided data is always unknown
|
|
642
|
+
{ ...universalData, ...pageData }
|
|
643
|
+
: pageData;
|
|
644
|
+
extractDeferred(mergedData, deferred, deferredCounter);
|
|
645
|
+
|
|
646
|
+
timer.mark("load");
|
|
647
|
+
const pageHtml = await Promise.resolve(
|
|
648
|
+
pageMod.default({
|
|
649
|
+
data: renderable(mergedData),
|
|
650
|
+
params: matched.params,
|
|
651
|
+
form: actionFailure?.data,
|
|
652
|
+
}),
|
|
653
|
+
);
|
|
654
|
+
|
|
655
|
+
// layouts must render before collectHead(): a <Head> call inside a
|
|
656
|
+
// layout component (a common place for site-wide <title>/meta
|
|
657
|
+
// defaults) only registers once the layout itself has run, so
|
|
658
|
+
// collecting too early silently drops it
|
|
659
|
+
let bodyHtml = applyLayouts(String(pageHtml));
|
|
660
|
+
timer.mark("render");
|
|
661
|
+
|
|
662
|
+
const headHtml = collectHead();
|
|
663
|
+
|
|
664
|
+
if (isNavigate) {
|
|
665
|
+
// no stream to flush into — resolve everything before responding
|
|
666
|
+
for (const d of deferred) {
|
|
667
|
+
try {
|
|
668
|
+
(mergedData as Record<string, unknown>)[d.key] = await d.promise;
|
|
669
|
+
} catch {
|
|
670
|
+
(mergedData as Record<string, unknown>)[d.key] = null;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
// Vary is mandatory here: this JSON and the HTML document share one
|
|
674
|
+
// URL and are chosen by a request header, so without it any cache may
|
|
675
|
+
// hand the JSON to a plain document request. That is what surfaced as
|
|
676
|
+
// raw state payloads rendering as the page after a back navigation.
|
|
677
|
+
// Deliberately still cacheable: hover-prefetch exists to warm this
|
|
678
|
+
// entry, and Vary already keeps document requests from matching it.
|
|
679
|
+
timer.mark("deferred");
|
|
680
|
+
return Response.json(
|
|
681
|
+
{
|
|
682
|
+
data: mergedData ?? {},
|
|
683
|
+
layoutData: layoutPairs.map((l) => l.data),
|
|
684
|
+
params: matched.params,
|
|
685
|
+
pattern: matched.route.path,
|
|
686
|
+
head: headHtml,
|
|
687
|
+
deps: [...collectedDeps],
|
|
688
|
+
},
|
|
689
|
+
{ headers: { Vary: NAVIGATE_HEADER, ...timer.headers() } },
|
|
690
|
+
);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// ── single-pass SSR stream ──────────────────────────────────────────────
|
|
694
|
+
const csrfToken = csrfTokenFor(req);
|
|
695
|
+
const stateJson = safeStateJson({
|
|
696
|
+
params: matched.params,
|
|
697
|
+
data: mergedData,
|
|
698
|
+
layoutData: layoutPairs.map((l) => l.data),
|
|
699
|
+
pattern: matched.route.path,
|
|
700
|
+
deps: [...collectedDeps],
|
|
701
|
+
form: actionFailure?.data,
|
|
702
|
+
});
|
|
703
|
+
|
|
704
|
+
bodyHtml = optimizeImages(injectCsrf(bodyHtml, csrfToken));
|
|
705
|
+
|
|
706
|
+
const hoistedCss = hoistStylesheets(bodyHtml);
|
|
707
|
+
const styles = scopedStyles(bodyHtml, nonceAttr);
|
|
708
|
+
|
|
709
|
+
const stream = new ReadableStream({
|
|
710
|
+
async start(controller) {
|
|
711
|
+
controller.enqueue(
|
|
712
|
+
buildHtmlSkeleton(nonceAttr, dev) +
|
|
713
|
+
preloadLinks(matched.route.path, nonceAttr, dev),
|
|
714
|
+
);
|
|
715
|
+
|
|
716
|
+
if (hoistedCss) {
|
|
717
|
+
controller.enqueue(`\n ${hoistedCss}`);
|
|
718
|
+
}
|
|
719
|
+
if (styles) {
|
|
720
|
+
controller.enqueue(`\n ${styles}`);
|
|
721
|
+
}
|
|
722
|
+
controller.enqueue(`\n${headBlock(headHtml)}`);
|
|
723
|
+
|
|
724
|
+
controller.enqueue(`\n</head>
|
|
725
|
+
<body>
|
|
726
|
+
<div id="app">${bodyHtml}</div>
|
|
727
|
+
<script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
|
|
728
|
+
</body>
|
|
729
|
+
</html>`);
|
|
730
|
+
|
|
731
|
+
// flush deferred values in order as they settle
|
|
732
|
+
for (const d of deferred) {
|
|
733
|
+
try {
|
|
734
|
+
const value = await d.promise;
|
|
735
|
+
controller.enqueue(deferredChunk(d.key, value, false));
|
|
736
|
+
} catch {
|
|
737
|
+
controller.enqueue(deferredChunk(d.key, null, true));
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
controller.close();
|
|
742
|
+
},
|
|
743
|
+
});
|
|
744
|
+
|
|
745
|
+
return new Response(stream, {
|
|
746
|
+
status: actionFailure?.status ?? 200,
|
|
747
|
+
headers: {
|
|
748
|
+
"Content-Type": "text/html",
|
|
749
|
+
"Set-Cookie": csrfCookie(csrfToken),
|
|
750
|
+
Vary: NAVIGATE_HEADER,
|
|
751
|
+
...timer.headers(),
|
|
752
|
+
},
|
|
753
|
+
});
|
|
754
|
+
});
|
|
755
|
+
}
|