-
-
Notifications
You must be signed in to change notification settings - Fork 10.6k
/
Copy pathsingle-fetch.ts
370 lines (337 loc) · 11.1 KB
/
single-fetch.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
import { encode } from "turbo-stream";
import type { StaticHandler } from "../router/router";
import { isRedirectStatusCode, isResponse } from "../router/router";
import type {
DataStrategyFunctionArgs,
DataStrategyFunction,
} from "../router/utils";
import {
isRouteErrorResponse,
ErrorResponseImpl,
data as routerData,
stripBasename,
} from "../router/utils";
import type {
SingleFetchRedirectResult,
SingleFetchResult,
SingleFetchResults,
} from "../dom/ssr/single-fetch";
import { SingleFetchRedirectSymbol } from "../dom/ssr/single-fetch";
import type { AppLoadContext } from "./data";
import { sanitizeError, sanitizeErrors } from "./errors";
import { ServerMode } from "./mode";
import { getDocumentHeaders } from "./headers";
import type { ServerBuild } from "./build";
export type { SingleFetchResult, SingleFetchResults };
export { SingleFetchRedirectSymbol };
// We can't use a 3xx status or else the `fetch()` would follow the redirect.
// We need to communicate the redirect back as data so we can act on it in the
// client side router. We use a 202 to avoid any automatic caching we might
// get from a 200 since a "temporary" redirect should not be cached. This lets
// the user control cache behavior via Cache-Control
export const SINGLE_FETCH_REDIRECT_STATUS = 202;
export function getSingleFetchDataStrategy({
isActionDataRequest,
loadRouteIds,
}: {
isActionDataRequest?: boolean;
loadRouteIds?: string[];
} = {}): DataStrategyFunction {
return async ({ request, matches }: DataStrategyFunctionArgs) => {
// Don't call loaders on action data requests
if (isActionDataRequest && request.method === "GET") {
return {};
}
// Only run opt-in loaders when fine-grained revalidation is enabled
let matchesToLoad = loadRouteIds
? matches.filter((m) => loadRouteIds.includes(m.route.id))
: matches;
let results = await Promise.all(
matchesToLoad.map((match) => match.resolve())
);
return results.reduce(
(acc, result, i) =>
Object.assign(acc, { [matchesToLoad[i].route.id]: result }),
{}
);
};
}
export async function singleFetchAction(
build: ServerBuild,
serverMode: ServerMode,
staticHandler: StaticHandler,
request: Request,
handlerUrl: URL,
loadContext: AppLoadContext,
handleError: (err: unknown) => void
): Promise<{ result: SingleFetchResult; headers: Headers; status: number }> {
try {
let handlerRequest = new Request(handlerUrl, {
method: request.method,
body: request.body,
headers: request.headers,
signal: request.signal,
...(request.body ? { duplex: "half" } : undefined),
});
let result = await staticHandler.query(handlerRequest, {
requestContext: loadContext,
skipLoaderErrorBubbling: true,
dataStrategy: getSingleFetchDataStrategy({
isActionDataRequest: true,
}),
});
// Unlike `handleDataRequest`, when singleFetch is enabled, query does
// let non-Response return values through
if (isResponse(result)) {
return {
result: getSingleFetchRedirect(
result.status,
result.headers,
build.basename
),
headers: result.headers,
status: SINGLE_FETCH_REDIRECT_STATUS,
};
}
let context = result;
let headers = getDocumentHeaders(build, context);
if (isRedirectStatusCode(context.statusCode) && headers.has("Location")) {
return {
result: getSingleFetchRedirect(
context.statusCode,
headers,
build.basename
),
headers,
status: SINGLE_FETCH_REDIRECT_STATUS,
};
}
// Sanitize errors outside of development environments
if (context.errors) {
Object.values(context.errors).forEach((err) => {
// @ts-expect-error This is "private" from users but intended for internal use
if (!isRouteErrorResponse(err) || err.error) {
handleError(err);
}
});
context.errors = sanitizeErrors(context.errors, serverMode);
}
let singleFetchResult: SingleFetchResult;
if (context.errors) {
singleFetchResult = { error: Object.values(context.errors)[0] };
} else {
singleFetchResult = { data: Object.values(context.actionData || {})[0] };
}
return {
result: singleFetchResult,
headers,
status: context.statusCode,
};
} catch (error) {
handleError(error);
// These should only be internal remix errors, no need to deal with responseStubs
return {
result: { error },
headers: new Headers(),
status: 500,
};
}
}
export async function singleFetchLoaders(
build: ServerBuild,
serverMode: ServerMode,
staticHandler: StaticHandler,
request: Request,
handlerUrl: URL,
loadContext: AppLoadContext,
handleError: (err: unknown) => void
): Promise<{ result: SingleFetchResults; headers: Headers; status: number }> {
try {
let handlerRequest = new Request(handlerUrl, {
headers: request.headers,
signal: request.signal,
});
let loadRouteIds =
new URL(request.url).searchParams.get("_routes")?.split(",") || undefined;
let result = await staticHandler.query(handlerRequest, {
requestContext: loadContext,
skipLoaderErrorBubbling: true,
dataStrategy: getSingleFetchDataStrategy({
loadRouteIds,
}),
});
if (isResponse(result)) {
return {
result: {
[SingleFetchRedirectSymbol]: getSingleFetchRedirect(
result.status,
result.headers,
build.basename
),
},
headers: result.headers,
status: SINGLE_FETCH_REDIRECT_STATUS,
};
}
let context = result;
let headers = getDocumentHeaders(build, context);
if (isRedirectStatusCode(context.statusCode) && headers.has("Location")) {
return {
result: {
[SingleFetchRedirectSymbol]: getSingleFetchRedirect(
context.statusCode,
headers,
build.basename
),
},
headers,
status: SINGLE_FETCH_REDIRECT_STATUS,
};
}
// Sanitize errors outside of development environments
if (context.errors) {
Object.values(context.errors).forEach((err) => {
// @ts-expect-error This is "private" from users but intended for internal use
if (!isRouteErrorResponse(err) || err.error) {
handleError(err);
}
});
context.errors = sanitizeErrors(context.errors, serverMode);
}
// Aggregate results based on the matches we intended to load since we get
// `null` values back in `context.loaderData` for routes we didn't load
let results: SingleFetchResults = {};
let loadedMatches = loadRouteIds
? context.matches.filter(
(m) => m.route.loader && loadRouteIds!.includes(m.route.id)
)
: context.matches;
loadedMatches.forEach((m) => {
let { id } = m.route;
if (context.errors && context.errors.hasOwnProperty(id)) {
results[id] = { error: context.errors[id] };
} else if (context.loaderData.hasOwnProperty(id)) {
results[id] = { data: context.loaderData[id] };
}
});
return {
result: results,
headers,
status: context.statusCode,
};
} catch (error: unknown) {
handleError(error);
// These should only be internal remix errors, no need to deal with responseStubs
return {
result: { root: { error } },
headers: new Headers(),
status: 500,
};
}
}
export function getSingleFetchRedirect(
status: number,
headers: Headers,
basename: string | undefined
): SingleFetchRedirectResult {
let redirect = headers.get("Location")!;
if (basename) {
redirect = stripBasename(redirect, basename) || redirect;
}
return {
redirect,
status,
revalidate:
// Technically X-Remix-Revalidate isn't needed here - that was an implementation
// detail of ?_data requests as our way to tell the front end to revalidate when
// we didn't have a response body to include that information in.
// With single fetch, we tell the front end via this revalidate boolean field.
// However, we're respecting it for now because it may be something folks have
// used in their own responses
// TODO(v3): Consider removing or making this official public API
headers.has("X-Remix-Revalidate") || headers.has("Set-Cookie"),
reload: headers.has("X-Remix-Reload-Document"),
replace: headers.has("X-Remix-Replace"),
};
}
export type Serializable =
| undefined
| null
| boolean
| string
| symbol
| number
| Array<Serializable>
| { [key: PropertyKey]: Serializable }
| bigint
| Date
| URL
| RegExp
| Error
| Map<Serializable, Serializable>
| Set<Serializable>
| Promise<Serializable>;
export function data(value: Serializable, init?: number | ResponseInit) {
return routerData(value, init);
}
// Note: If you change this function please change the corresponding
// decodeViaTurboStream function in server-runtime
export function encodeViaTurboStream(
data: any,
requestSignal: AbortSignal,
streamTimeout: number | undefined,
serverMode: ServerMode
) {
let controller = new AbortController();
// How long are we willing to wait for all of the promises in `data` to resolve
// before timing out? We default this to 50ms shorter than the default value
// of 5000ms we had in `ABORT_DELAY` in Remix v2 that folks may still be using
// in RR v7 so that once we reject we have time to flush the rejections down
// through React's rendering stream before we call `abort()` on that. If the
// user provides their own it's up to them to decouple the aborting of the
// stream from the aborting of React's `renderToPipeableStream`
let timeoutId = setTimeout(
() => controller.abort(new Error("Server Timeout")),
typeof streamTimeout === "number" ? streamTimeout : 4950
);
requestSignal.addEventListener("abort", () => clearTimeout(timeoutId));
return encode(data, {
signal: controller.signal,
plugins: [
(value) => {
// Even though we sanitized errors on context.errors prior to responding,
// we still need to handle this for any deferred data that rejects with an
// Error - as those will not be sanitized yet
if (value instanceof Error) {
let { name, message, stack } =
serverMode === ServerMode.Production
? sanitizeError(value, serverMode)
: value;
return ["SanitizedError", name, message, stack];
}
if (value instanceof ErrorResponseImpl) {
let { data, status, statusText } = value;
return ["ErrorResponse", data, status, statusText];
}
if (
value &&
typeof value === "object" &&
SingleFetchRedirectSymbol in value
) {
return ["SingleFetchRedirect", value[SingleFetchRedirectSymbol]];
}
},
],
postPlugins: [
(value) => {
if (!value) return;
if (typeof value !== "object") return;
return [
"SingleFetchClassInstance",
Object.fromEntries(Object.entries(value)),
];
},
() => ["SingleFetchFallback"],
],
});
}