-
Notifications
You must be signed in to change notification settings - Fork 335
Expand file tree
/
Copy pathresponse.ts
More file actions
270 lines (239 loc) · 7.75 KB
/
Copy pathresponse.ts
File metadata and controls
270 lines (239 loc) · 7.75 KB
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
import { FastResponse } from "srvx";
import { HTTPError } from "./error.ts";
import { isJSONSerializable } from "./utils/internal/object.ts";
import type { H3Config } from "./types/h3.ts";
import { kEventRes, kEventResHeaders, kEventResErrHeaders, type H3Event } from "./event.ts";
export const kNotFound: symbol = /* @__PURE__ */ Symbol.for("h3.notFound");
export const kHandled: symbol = /* @__PURE__ */ Symbol.for("h3.handled");
export function toResponse(
val: unknown,
event: H3Event,
config: H3Config = {},
): Response | Promise<Response> {
if (typeof (val as PromiseLike<unknown>)?.then === "function") {
return (val as Promise<unknown>).then(
(resolvedVal) => toResponse(resolvedVal, event, config),
(r) => toResponse(typeof r === "number" ? new HTTPError({ status: r }) : r, event, config),
) as Promise<Response>;
}
const response = prepareResponse(val, event, config);
if (typeof (response as PromiseLike<Response>)?.then === "function") {
return toResponse(response, event, config);
}
const { onResponse } = config;
return onResponse
? Promise.resolve(onResponse(response as Response, event)).then(() => response)
: response;
}
export class HTTPResponse {
#headers?: Headers;
#init?: Pick<ResponseInit, "status" | "statusText" | "headers"> | undefined;
body?: BodyInit | null;
constructor(
body: BodyInit | null,
init?: Pick<ResponseInit, "status" | "statusText" | "headers">,
) {
this.body = body;
this.#init = init;
}
get status(): number {
return this.#init?.status || 200;
}
get statusText(): string {
return this.#init?.statusText || "OK";
}
get headers(): Headers {
return (this.#headers ||= new Headers(this.#init?.headers));
}
}
function prepareResponse(
val: unknown,
event: H3Event,
config: H3Config,
nested?: boolean,
): Response | Promise<Response> {
if (val === kHandled) {
return new FastResponse(null);
}
if (val === kNotFound) {
val = new HTTPError({
status: 404,
message: `Cannot find any route matching [${event.req.method}] ${event.url}`,
});
}
if (val && val instanceof Error) {
const isHTTPError = HTTPError.isError(val);
const error = isHTTPError ? (val as HTTPError) : new HTTPError(val);
if (!isHTTPError) {
// @ts-expect-error unhandled is readonly for public interface
error.unhandled = true;
if (val?.stack) {
error.stack = val.stack;
}
}
if (error.unhandled && !config.silent) {
console.error(error);
}
const { onError } = config;
const errHeaders: Headers | undefined = (event as any)[kEventRes]?.[kEventResErrHeaders];
return onError && !nested
? Promise.resolve(onError(error, event))
.catch((error) => error)
.then((newVal) => prepareResponse(newVal ?? val, event, config, true))
: errorResponse(error, config.debug, errHeaders);
}
// Only set if event.res.headers is accessed
const preparedRes:
| undefined
| { status?: number; statusText?: string; [kEventResHeaders]?: Headers } = (event as any)[
kEventRes
];
const preparedHeaders = preparedRes?.[kEventResHeaders];
(event as any)[kEventRes] = undefined; // Clear prepared response to avoid duplication
if (!(val instanceof Response)) {
const res = prepareResponseBody(val, event, config);
const status = res.status || preparedRes?.status;
return new FastResponse(nullBody(event.req.method, status) ? null : res.body, {
status,
statusText: res.statusText || preparedRes?.statusText,
headers:
res.headers && preparedHeaders
? mergeHeaders(res.headers, preparedHeaders)
: res.headers || preparedHeaders,
});
}
// Avoid merging if no prepared headers are provided or we are rendering an Error
if (!preparedHeaders || nested || !val.ok) {
return val; // Fast path: no headers to merge
}
try {
mergeHeaders(val.headers, preparedHeaders, val.headers);
return val;
} catch {
// Headers are immutable
return new FastResponse(nullBody(event.req.method, val.status) ? null : val.body, {
status: val.status,
statusText: val.statusText,
headers: mergeHeaders(val.headers, preparedHeaders),
}) as Response;
}
}
function mergeHeaders(base: HeadersInit, overrides: Headers, target = new Headers(base)): Headers {
for (const [name, value] of overrides) {
if (name === "set-cookie") {
target.append(name, value);
} else {
target.set(name, value);
}
}
return target;
}
const frozen =
(name: string) =>
(...args: any[]) => {
throw new Error(`Headers are frozen (${name} ${args.join(", ")})`);
};
class FrozenHeaders extends Headers {
override set = frozen("set");
override append = frozen("append");
override delete = frozen("delete");
}
const emptyHeaders = /* @__PURE__ */ new FrozenHeaders({
"content-length": "0",
});
const jsonHeaders = /* @__PURE__ */ new FrozenHeaders({
"content-type": "application/json;charset=UTF-8",
});
function prepareResponseBody(
val: unknown,
event: H3Event,
config: H3Config,
): Partial<HTTPResponse> {
// Empty Content
if (val === null || val === undefined) {
return { body: "", headers: emptyHeaders };
}
const valType = typeof val;
// Text
if (valType === "string") {
// Default header is text/plain we don't set it for performance reasons
// new Response("").headers.get('content-type') === "text/plain;charset=UTF-8"
return { body: val as string };
}
// Buffer (should be before JSON)
if (val instanceof Uint8Array) {
event.res.headers.set("content-length", val.byteLength.toString());
if (!event.res.headers.has("content-type")) {
event.res.headers.set("content-type", "application/octet-stream");
}
return { body: val as BufferSource };
}
// Partial Response
if (val instanceof HTTPResponse || val?.constructor?.name === "HTTPResponse") {
return val;
}
// JSON
if (isJSONSerializable(val, valType)) {
return {
body: JSON.stringify(val, undefined, config.debug ? 2 : undefined),
headers: jsonHeaders,
};
}
// BigInt
if (valType === "bigint") {
return { body: val.toString(), headers: jsonHeaders };
}
// Blob
if (val instanceof Blob) {
const headers = new Headers({
"content-type": val.type,
"content-length": val.size.toString(),
});
// File
let filename = (val as File).name;
if (filename) {
filename = encodeURIComponent(filename);
// Omit the disposition type ("inline" or "attachment") and let the client (browser) decide.
headers.set("content-disposition", `filename="${filename}"; filename*=UTF-8''${filename}`);
}
return { body: val.stream(), headers };
}
// Symbol or Function
if (valType === "symbol") {
return { body: val.toString() };
}
if (valType === "function") {
return { body: `${(val as () => unknown).name}()` };
}
return { body: val as BodyInit };
}
function nullBody(method: string, status: number | undefined): boolean | 0 | undefined {
// prettier-ignore
return (method === "HEAD" ||
status === 100 || status === 101 || status === 102 ||
status === 204 || status === 205 || status === 304
)
}
function errorResponse(error: HTTPError, debug?: boolean, errHeaders?: Headers): Response {
let headers: Headers = error.headers
? mergeHeaders(jsonHeaders, error.headers)
: new Headers(jsonHeaders);
if (errHeaders) {
headers = mergeHeaders(headers, errHeaders);
}
return new FastResponse(
JSON.stringify(
{
...error.toJSON(),
stack: debug && error.stack ? error.stack.split("\n").map((l) => l.trim()) : undefined,
},
undefined,
debug ? 2 : undefined,
),
{
status: error.status,
statusText: error.statusText,
headers,
},
);
}