-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathserver.ts
650 lines (568 loc) · 18.1 KB
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
import type { AppLoadContext } from "./data";
import { callRouteAction, callRouteLoader, extractData } from "./data";
import type { AppState } from "./errors";
import type { HandleDataRequestFunction, ServerBuild } from "./build";
import type { EntryContext } from "./entry";
import { createEntryMatches, createEntryRouteModules } from "./entry";
import { serializeError } from "./errors";
import { getDocumentHeaders } from "./headers";
import { ServerMode, isServerMode } from "./mode";
import type { RouteMatch } from "./routeMatching";
import { matchServerRoutes } from "./routeMatching";
import type { ServerRoute } from "./routes";
import { createRoutes } from "./routes";
import { json, isRedirectResponse, isCatchResponse } from "./responses";
import { createServerHandoffString } from "./serverHandoff";
export type RequestHandler = (
request: Request,
loadContext?: AppLoadContext
) => Promise<Response>;
export type CreateRequestHandlerFunction = (
build: ServerBuild,
mode?: string
) => RequestHandler;
export const createRequestHandler: CreateRequestHandlerFunction = (
build,
mode
) => {
let routes = createRoutes(build.routes);
let serverMode = isServerMode(mode) ? mode : ServerMode.Production;
return async function requestHandler(request, loadContext) {
let url = new URL(request.url);
let matches = matchServerRoutes(routes, url.pathname);
let response: Response;
if (url.searchParams.has("_data")) {
response = await handleDataRequest({
request,
loadContext,
matches: matches!,
handleDataRequest: build.entry.module.handleDataRequest,
serverMode,
});
} else if (matches && !matches[matches.length - 1].route.module.default) {
response = await handleResourceRequest({
request,
loadContext,
matches,
serverMode,
});
} else {
response = await handleDocumentRequest({
build,
loadContext,
matches,
request,
routes,
serverMode,
});
}
if (request.method === "HEAD") {
return new Response(null, {
headers: response.headers,
status: response.status,
statusText: response.statusText,
});
}
return response;
};
};
async function handleDataRequest({
handleDataRequest,
loadContext,
matches,
request,
serverMode,
}: {
handleDataRequest?: HandleDataRequestFunction;
loadContext: unknown;
matches: RouteMatch<ServerRoute>[];
request: Request;
serverMode: ServerMode;
}): Promise<Response> {
if (!isValidRequestMethod(request)) {
return errorBoundaryError(
new Error(`Invalid request method "${request.method}"`),
405
);
}
let url = new URL(request.url);
if (!matches) {
return errorBoundaryError(
new Error(`No route matches URL "${url.pathname}"`),
404
);
}
let response: Response;
let match: RouteMatch<ServerRoute>;
try {
if (isActionRequest(request)) {
match = getRequestMatch(url, matches);
response = await callRouteAction({
loadContext,
match,
request: request,
});
} else {
let routeId = url.searchParams.get("_data");
if (!routeId) {
return errorBoundaryError(new Error(`Missing route id in ?_data`), 403);
}
let tempMatch = matches.find((match) => match.route.id === routeId);
if (!tempMatch) {
return errorBoundaryError(
new Error(`Route "${routeId}" does not match URL "${url.pathname}"`),
403
);
}
match = tempMatch;
response = await callRouteLoader({ loadContext, match, request });
}
if (isRedirectResponse(response)) {
// We don't have any way to prevent a fetch request from following
// redirects. So we use the `X-Remix-Redirect` header to indicate the
// next URL, and then "follow" the redirect manually on the client.
let headers = new Headers(response.headers);
headers.set("X-Remix-Redirect", headers.get("Location")!);
headers.delete("Location");
if (response.headers.get("Set-Cookie") !== null) {
headers.set("X-Remix-Revalidate", "yes");
}
return new Response(null, {
status: 204,
headers,
});
}
if (handleDataRequest) {
response = await handleDataRequest(response.clone(), {
context: loadContext,
params: match.params,
request: request.clone(),
});
}
return response;
} catch (error: unknown) {
if (serverMode !== ServerMode.Test) {
console.error(error);
}
if (serverMode === ServerMode.Development) {
return errorBoundaryError(error as Error, 500);
}
return errorBoundaryError(new Error("Unexpected Server Error"), 500);
}
}
async function handleDocumentRequest({
build,
loadContext,
matches,
request,
routes,
serverMode,
}: {
build: ServerBuild;
loadContext: unknown;
matches: RouteMatch<ServerRoute>[] | null;
request: Request;
routes: ServerRoute[];
serverMode?: ServerMode;
}): Promise<Response> {
let url = new URL(request.url);
let appState: AppState = {
trackBoundaries: true,
trackCatchBoundaries: true,
catchBoundaryRouteId: null,
renderBoundaryRouteId: null,
loaderBoundaryRouteId: null,
error: undefined,
catch: undefined,
};
if (!isValidRequestMethod(request)) {
matches = null;
appState.trackCatchBoundaries = false;
appState.catch = {
data: null,
status: 405,
statusText: "Method Not Allowed",
};
} else if (!matches) {
appState.trackCatchBoundaries = false;
appState.catch = {
data: null,
status: 404,
statusText: "Not Found",
};
}
let actionStatus: { status: number; statusText: string } | undefined;
let actionData: Record<string, unknown> | undefined;
let actionMatch: RouteMatch<ServerRoute> | undefined;
let actionResponse: Response | undefined;
if (matches && isActionRequest(request)) {
actionMatch = getRequestMatch(url, matches);
try {
actionResponse = await callRouteAction({
loadContext,
match: actionMatch,
request: request,
});
if (isRedirectResponse(actionResponse)) {
return actionResponse;
}
actionStatus = {
status: actionResponse.status,
statusText: actionResponse.statusText,
};
if (isCatchResponse(actionResponse)) {
appState.catchBoundaryRouteId = getDeepestRouteIdWithBoundary(
matches,
"CatchBoundary"
);
appState.trackCatchBoundaries = false;
appState.catch = {
...actionStatus,
data: await extractData(actionResponse),
};
} else {
actionData = {
[actionMatch.route.id]: await extractData(actionResponse),
};
}
} catch (error: any) {
appState.loaderBoundaryRouteId = getDeepestRouteIdWithBoundary(
matches,
"ErrorBoundary"
);
appState.trackBoundaries = false;
appState.error = await serializeError(error);
if (serverMode !== ServerMode.Test) {
console.error(
`There was an error running the action for route ${actionMatch.route.id}`
);
}
}
}
let routeModules = createEntryRouteModules(build.routes);
let matchesToLoad = matches || [];
if (appState.catch) {
matchesToLoad = getMatchesUpToDeepestBoundary(
// get rid of the action, we don't want to call it's loader either
// because we'll be rendering the catch boundary, if you can get access
// to the loader data in the catch boundary then how the heck is it
// supposed to deal with thrown responses?
matchesToLoad.slice(0, -1),
"CatchBoundary"
);
} else if (appState.error) {
matchesToLoad = getMatchesUpToDeepestBoundary(
// get rid of the action, we don't want to call it's loader either
// because we'll be rendering the error boundary, if you can get access
// to the loader data in the error boundary then how the heck is it
// supposed to deal with errors in the loader, too?
matchesToLoad.slice(0, -1),
"ErrorBoundary"
);
}
let routeLoaderResults = await Promise.allSettled(
matchesToLoad.map((match) =>
match.route.module.loader
? callRouteLoader({
loadContext,
match,
request,
})
: Promise.resolve(undefined)
)
);
// Store the state of the action. We will use this to determine later
// what catch or error boundary should be rendered under cases where
// actions don't throw but loaders do, actions throw and parent loaders
// also throw, etc.
let actionCatch = appState.catch;
let actionError = appState.error;
let actionCatchBoundaryRouteId = appState.catchBoundaryRouteId;
let actionLoaderBoundaryRouteId = appState.loaderBoundaryRouteId;
// Reset the app error and catch state to propagate the loader states
// from the results into the app state.
appState.catch = undefined;
appState.error = undefined;
let headerMatches: RouteMatch<ServerRoute>[] = [];
let routeLoaderResponses: Record<string, Response> = {};
let loaderStatusCodes: number[] = [];
let routeData: Record<string, unknown> = {};
for (let index = 0; index < matchesToLoad.length; index++) {
let match = matchesToLoad[index];
let result = routeLoaderResults[index];
let error = result.status === "rejected" ? result.reason : undefined;
let response = result.status === "fulfilled" ? result.value : undefined;
let isRedirect = response ? isRedirectResponse(response) : false;
let isCatch = response ? isCatchResponse(response) : false;
// If a parent loader has already caught or error'd, bail because
// we don't need any more child data.
if (appState.catch || appState.error) {
break;
}
// If there is a response and it's a redirect, do it unless there
// is an action error or catch state, those action boundary states
// take precedence over loader sates, this means if a loader redirects
// after an action catches or errors we won't follow it, and instead
// render the boundary caused by the action.
if (!actionCatch && !actionError && response && isRedirect) {
return response;
}
// Track the boundary ID's for the loaders
if (match.route.module.CatchBoundary) {
appState.catchBoundaryRouteId = match.route.id;
}
if (match.route.module.ErrorBoundary) {
appState.loaderBoundaryRouteId = match.route.id;
}
if (error) {
loaderStatusCodes.push(500);
appState.trackBoundaries = false;
appState.error = await serializeError(error);
if (serverMode !== ServerMode.Test) {
console.error(
`There was an error running the data loader for route ${match.route.id}`
);
}
break;
} else if (response) {
headerMatches.push(match);
routeLoaderResponses[match.route.id] = response;
loaderStatusCodes.push(response.status);
if (isCatch) {
// If it's a catch response, store it in app state, and bail
appState.trackCatchBoundaries = false;
appState.catch = {
data: await extractData(response),
status: response.status,
statusText: response.statusText,
};
break;
} else {
// Extract and store the loader data
routeData[match.route.id] = await extractData(response);
}
}
}
// If there was not a loader catch or error state triggered reset the
// boundaries as they are probably deeper in the tree if the action
// initially triggered a boundary as that match would not exist in the
// matches to load.
if (!appState.catch) {
appState.catchBoundaryRouteId = actionCatchBoundaryRouteId;
}
if (!appState.error) {
appState.loaderBoundaryRouteId = actionLoaderBoundaryRouteId;
}
// If there was an action error or catch, we will reset the state to the
// initial values, otherwise we will use whatever came out of the loaders.
appState.catch = actionCatch || appState.catch;
appState.error = actionError || appState.error;
let renderableMatches = getRenderableMatches(matches, appState);
if (!renderableMatches) {
renderableMatches = [];
let root = routes[0];
if (root?.module.CatchBoundary) {
appState.catchBoundaryRouteId = "root";
renderableMatches.push({
params: {},
pathname: "",
route: routes[0],
});
}
}
// Handle responses with a non-200 status code. The first loader with a
// non-200 status code determines the status code for the whole response.
let notOkResponse =
actionStatus && actionStatus.status !== 200
? actionStatus.status
: loaderStatusCodes.find((status) => status !== 200);
let responseStatusCode = appState.error
? 500
: typeof notOkResponse === "number"
? notOkResponse
: appState.catch
? appState.catch.status
: 200;
let responseHeaders = getDocumentHeaders(
build,
renderableMatches,
routeLoaderResponses,
actionResponse
);
let entryMatches = createEntryMatches(renderableMatches, build.assets.routes);
let serverHandoff = {
actionData,
appState: appState,
matches: entryMatches,
routeData,
};
let entryContext: EntryContext = {
...serverHandoff,
manifest: build.assets,
routeModules,
serverHandoffString: createServerHandoffString(serverHandoff),
};
let handleDocumentRequest = build.entry.module.default;
try {
return await handleDocumentRequest(
request.clone(),
responseStatusCode,
responseHeaders,
entryContext
);
} catch (error: any) {
responseStatusCode = 500;
// Go again, this time with the componentDidCatch emulation. As it rendered
// last time we mutated `componentDidCatch.routeId` for the last rendered
// route, now we know where to render the error boundary (feels a little
// hacky but that's how hooks work). This tells the emulator to stop
// tracking the `routeId` as we render because we already have an error to
// render.
appState.trackBoundaries = false;
appState.error = await serializeError(error);
entryContext.serverHandoffString = createServerHandoffString(serverHandoff);
try {
return await handleDocumentRequest(
request.clone(),
responseStatusCode,
responseHeaders,
entryContext
);
} catch (error: any) {
if (serverMode !== ServerMode.Test) {
console.error(error);
}
let message = "Unexpected Server Error";
if (serverMode === ServerMode.Development) {
message += `\n\n${String(error)}`;
}
// Good grief folks, get your act together 😂!
return new Response(message, {
status: 500,
headers: {
"Content-Type": "text/plain",
},
});
}
}
}
async function handleResourceRequest({
loadContext,
matches,
request,
serverMode,
}: {
request: Request;
loadContext: unknown;
matches: RouteMatch<ServerRoute>[];
serverMode: ServerMode;
}): Promise<Response> {
let match = matches.slice(-1)[0];
try {
if (isActionRequest(request)) {
return await callRouteAction({ match, loadContext, request });
} else {
return await callRouteLoader({ match, loadContext, request });
}
} catch (error: any) {
if (serverMode !== ServerMode.Test) {
console.error(error);
}
let message = "Unexpected Server Error";
if (serverMode === ServerMode.Development) {
message += `\n\n${String(error)}`;
}
// Good grief folks, get your act together 😂!
return new Response(message, {
status: 500,
headers: {
"Content-Type": "text/plain",
},
});
}
}
const validActionMethods = new Set(["POST", "PUT", "PATCH", "DELETE"]);
function isActionRequest({ method }: Request): boolean {
return validActionMethods.has(method.toUpperCase());
}
const validRequestMethods = new Set(["GET", "HEAD", ...validActionMethods]);
function isValidRequestMethod({ method }: Request): boolean {
return validRequestMethods.has(method.toUpperCase());
}
async function errorBoundaryError(error: Error, status: number) {
return json(await serializeError(error), {
status,
headers: {
"X-Remix-Error": "yes",
},
});
}
function isIndexRequestUrl(url: URL) {
for (let param of url.searchParams.getAll("index")) {
// only use bare `?index` params without a value
// ✅ /foo?index
// ✅ /foo?index&index=123
// ✅ /foo?index=123&index
// ❌ /foo?index=123
if (param === "") {
return true;
}
}
return false;
}
function getRequestMatch(url: URL, matches: RouteMatch<ServerRoute>[]) {
let match = matches.slice(-1)[0];
if (!isIndexRequestUrl(url) && match.route.id.endsWith("/index")) {
return matches.slice(-2)[0];
}
return match;
}
function getDeepestRouteIdWithBoundary(
matches: RouteMatch<ServerRoute>[],
key: "CatchBoundary" | "ErrorBoundary"
) {
let matched = getMatchesUpToDeepestBoundary(matches, key).slice(-1)[0];
return matched ? matched.route.id : null;
}
function getMatchesUpToDeepestBoundary(
matches: RouteMatch<ServerRoute>[],
key: "CatchBoundary" | "ErrorBoundary"
) {
let deepestBoundaryIndex: number = -1;
matches.forEach((match, index) => {
if (match.route.module[key]) {
deepestBoundaryIndex = index;
}
});
if (deepestBoundaryIndex === -1) {
// no route error boundaries, don't need to call any loaders
return [];
}
return matches.slice(0, deepestBoundaryIndex + 1);
}
// This prevents `<Outlet/>` from rendering anything below where the error threw
// TODO: maybe do this in <RemixErrorBoundary + context>
function getRenderableMatches(
matches: RouteMatch<ServerRoute>[] | null,
appState: AppState
) {
if (!matches) {
return null;
}
// no error, no worries
if (!appState.catch && !appState.error) {
return matches;
}
let lastRenderableIndex: number = -1;
matches.forEach((match, index) => {
let id = match.route.id;
if (
appState.renderBoundaryRouteId === id ||
appState.loaderBoundaryRouteId === id ||
appState.catchBoundaryRouteId === id
) {
lastRenderableIndex = index;
}
});
return matches.slice(0, lastRenderableIndex + 1);
}