-
Notifications
You must be signed in to change notification settings - Fork 235
/
response.ts
405 lines (371 loc) · 12.5 KB
/
response.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
// Copyright 2018-2024 the oak authors. All rights reserved. MIT license.
/**
* Contains the {@linkcode Response} abstraction used by oak.
*
* Most end users would not need to directly access this module.
*
* @module
*/
import { contentType, isRedirectStatus, Status, STATUS_TEXT } from "./deps.ts";
import { DomResponse } from "./http_server_native_request.ts";
import type { Request } from "./request.ts";
import { isAsyncIterable, isFsFile, isHtml } from "./utils/type_guards.ts";
import { BODY_TYPES } from "./utils/consts.ts";
import { encodeUrl } from "./utils/encode_url.ts";
import {
readableStreamFromAsyncIterable,
Uint8ArrayTransformStream,
} from "./utils/streams.ts";
/** The various types of bodies supported when setting the value of `.body`
* on a {@linkcode Response} */
export type ResponseBody =
| string
| number
| bigint
| boolean
| symbol
| object
| undefined
| null;
/** A function that when invoked returns or resolves to a
* {@linkcode ResponseBody}. */
export type ResponseBodyFunction = () => ResponseBody | Promise<ResponseBody>;
/** A symbol that indicates to `response.redirect()` to attempt to redirect
* back to the request referrer. For example:
*
* ```ts
* import { Application, REDIRECT_BACK } from "jsr:@oak/oak/";
*
* const app = new Application();
*
* app.use((ctx) => {
* if (ctx.request.url.pathName === "/back") {
* ctx.response.redirect(REDIRECT_BACK, "/");
* }
* });
*
* await app.listen({ port: 80 });
* ```
*/
export const REDIRECT_BACK = Symbol("redirect backwards");
async function convertBodyToBodyInit(
body: ResponseBody | ResponseBodyFunction,
type?: string,
jsonBodyReplacer?: (key: string, value: unknown) => unknown,
): Promise<[globalThis.BodyInit | undefined, string | undefined]> {
let result: globalThis.BodyInit | undefined;
if (BODY_TYPES.includes(typeof body)) {
result = String(body);
type = type ?? (isHtml(result) ? "html" : "text/plain");
} else if (isFsFile(body)) {
result = body.readable;
} else if (
ArrayBuffer.isView(body) || body instanceof ArrayBuffer ||
body instanceof Blob || body instanceof URLSearchParams
) {
// deno-lint-ignore no-explicit-any
result = body as any;
} else if (body instanceof ReadableStream) {
result = body.pipeThrough(new Uint8ArrayTransformStream());
} else if (body instanceof FormData) {
result = body;
type = undefined;
} else if (isAsyncIterable(body)) {
result = readableStreamFromAsyncIterable(body);
} else if (body && typeof body === "object") {
result = JSON.stringify(body, jsonBodyReplacer);
type = type ?? "json";
} else if (typeof body === "function") {
const result = body.call(null);
return convertBodyToBodyInit(await result, type, jsonBodyReplacer);
} else if (body) {
throw new TypeError("Response body was set but could not be converted.");
}
return [result, type];
}
/** An interface to control what response will be sent when the middleware
* finishes processing the request.
*
* The response is usually accessed via the context's `.response` property.
*
* ### Example
*
* ```ts
* import { Application, Status } from "jsr:@oak/oak/";
*
* const app = new Application();
*
* app.use((ctx) => {
* ctx.response.body = { hello: "oak" };
* ctx.response.type = "json";
* ctx.response.status = Status.OK;
* });
* ```
*/
export class Response {
#body?: ResponseBody | ResponseBodyFunction;
#bodySet = false;
#domResponse?: globalThis.Response;
#headers = new Headers();
#jsonBodyReplacer?: (key: string, value: unknown) => unknown;
#request: Request;
#resources: { close(): void }[] = [];
#status?: Status;
#type?: string;
#writable = true;
async #getBodyInit(): Promise<globalThis.BodyInit | undefined> {
const [body, type] = await convertBodyToBodyInit(
this.body,
this.type,
this.#jsonBodyReplacer,
);
this.type = type;
return body;
}
#setContentType(): void {
if (this.type) {
const contentTypeString = contentType(this.type);
if (contentTypeString && !this.headers.has("Content-Type")) {
this.headers.append("Content-Type", contentTypeString);
}
}
}
/** The body of the response. The body will be automatically processed when
* the response is being sent and converted to a `Uint8Array` or a
* `Deno.Reader`.
*
* Automatic conversion to a `Deno.Reader` occurs for async iterables. */
get body(): ResponseBody | ResponseBodyFunction {
return this.#body;
}
/** The body of the response. The body will be automatically processed when
* the response is being sent and converted to a `Uint8Array` or a
* `Deno.Reader`.
*
* Automatic conversion to a `Deno.Reader` occurs for async iterables. */
set body(value: ResponseBody | ResponseBodyFunction) {
if (!this.#writable) {
throw new Error("The response is not writable.");
}
this.#bodySet = true;
this.#body = value;
}
/** Headers that will be returned in the response. */
get headers(): Headers {
return this.#headers;
}
/** Headers that will be returned in the response. */
set headers(value: Headers) {
if (!this.#writable) {
throw new Error("The response is not writable.");
}
this.#headers = value;
}
/** The HTTP status of the response. If this has not been explicitly set,
* reading the value will return what would be the value of status if the
* response were sent at this point in processing the middleware. If the body
* has been set, the status will be `200 OK`. If a value for the body has
* not been set yet, the status will be `404 Not Found`. */
get status(): Status {
if (this.#status) {
return this.#status;
}
return this.body != null
? Status.OK
: this.#bodySet
? Status.NoContent
: Status.NotFound;
}
/** The HTTP status of the response. If this has not been explicitly set,
* reading the value will return what would be the value of status if the
* response were sent at this point in processing the middleware. If the body
* has been set, the status will be `200 OK`. If a value for the body has
* not been set yet, the status will be `404 Not Found`. */
set status(value: Status) {
if (!this.#writable) {
throw new Error("The response is not writable.");
}
this.#status = value;
}
/** The media type, or extension of the response. Setting this value will
* ensure an appropriate `Content-Type` header is added to the response. */
get type(): string | undefined {
return this.#type;
}
/** The media type, or extension of the response. Setting this value will
* ensure an appropriate `Content-Type` header is added to the response. */
set type(value: string | undefined) {
if (!this.#writable) {
throw new Error("The response is not writable.");
}
this.#type = value;
}
/** A read-only property which determines if the response is writable or not.
* Once the response has been processed, this value is set to `false`. */
get writable(): boolean {
return this.#writable;
}
constructor(
request: Request,
jsonBodyReplacer?: (key: string, value: unknown) => unknown,
) {
this.#request = request;
this.#jsonBodyReplacer = jsonBodyReplacer;
}
/** Add a resource to the list of resources that will be closed when the
* request is destroyed. */
addResource(resource: { close(): void }): void {
this.#resources.push(resource);
}
/** Release any resources that are being tracked by the response.
*
* @param closeResources close any resource IDs registered with the response
*/
destroy(closeResources = true): void {
this.#writable = false;
this.#body = undefined;
this.#domResponse = undefined;
if (closeResources) {
for (const resource of this.#resources) {
try {
resource.close();
} catch {
// we don't care about errors here
}
}
}
}
/** Sets the response to redirect to the supplied `url`.
*
* If the `.status` is not currently a redirect status, the status will be set
* to `302 Found`.
*
* The body will be set to a message indicating the redirection is occurring.
*/
redirect(url: string | URL): void;
/** Sets the response to redirect back to the referrer if available, with an
* optional `alt` URL if there is no referrer header on the request. If there
* is no referrer header, nor an `alt` parameter, the redirect is set to `/`.
*
* If the `.status` is not currently a redirect status, the status will be set
* to `302 Found`.
*
* The body will be set to a message indicating the redirection is occurring.
*/
redirect(url: typeof REDIRECT_BACK, alt?: string | URL): void;
redirect(
url: string | URL | typeof REDIRECT_BACK,
alt: string | URL = "/",
): void {
if (url === REDIRECT_BACK) {
url = this.#request.headers.get("Referer") ?? String(alt);
} else if (typeof url === "object") {
url = String(url);
}
this.headers.set("Location", encodeUrl(url));
if (!this.status || !isRedirectStatus(this.status)) {
this.status = Status.Found;
}
if (this.#request.accepts("html")) {
url = encodeURI(url);
this.type = "text/html; charset=UTF-8";
this.body = `Redirecting to <a href="${url}">${url}</a>.`;
return;
}
this.type = "text/plain; charset=UTF-8";
this.body = `Redirecting to ${url}.`;
}
async toDomResponse(): Promise<globalThis.Response> {
if (this.#domResponse) {
return this.#domResponse;
}
const bodyInit = await this.#getBodyInit();
this.#setContentType();
const { headers } = this;
// If there is no body and no content type and no set length, then set the
// content length to 0
if (
!(
bodyInit ||
headers.has("Content-Type") ||
headers.has("Content-Length")
)
) {
headers.append("Content-Length", "0");
}
this.#writable = false;
const status = this.status;
const responseInit: ResponseInit = {
headers,
status,
statusText: STATUS_TEXT[status],
};
return this.#domResponse = new DomResponse(bodyInit, responseInit);
}
/** Instead of responding based on the values of the response, explicitly set
* the response with a Fetch API `Response`.
*
* If the response is already finalized, this will throw. You can check
* the `.writable` property to determine the state if you are unsure.
*
* > [!NOTE]
* > This will ignore/override values set in the response like the body,
* > headers and status, meaning things like cookie management and automatic
* > body typing will be ignored.
*/
with(response: globalThis.Response): void;
/** Instead of responding based on the values of the response, explicitly set
* the response by providing the initialization to create a Fetch API
* `Response`.
*
* If the response is already finalized, this will throw. You can check
* the `.writable` property to determine the state if you are unsure.
*
* > [!NOTE]
* > This will ignore/override values set in the response like the body,
* > headers and status, meaning things like cookie management and automatic
* > body typing will be ignored.
*/
with(body?: BodyInit | null, init?: ResponseInit): void;
with(
responseOrBody?: globalThis.Response | BodyInit | null,
init?: ResponseInit,
): void {
if (this.#domResponse || !this.#writable) {
throw new Error("A response has already been finalized.");
}
this.#writable = false;
this.#domResponse = responseOrBody instanceof DomResponse
? responseOrBody
: new DomResponse(responseOrBody, init);
}
[Symbol.for("Deno.customInspect")](
inspect: (value: unknown) => string,
): string {
const { body, headers, status, type, writable } = this;
return `${this.constructor.name} ${
inspect({ body, headers, status, type, writable })
}`;
}
[Symbol.for("nodejs.util.inspect.custom")](
depth: number,
// deno-lint-ignore no-explicit-any
options: any,
inspect: (value: unknown, options?: unknown) => string,
// deno-lint-ignore no-explicit-any
): any {
if (depth < 0) {
return options.stylize(`[${this.constructor.name}]`, "special");
}
const newOptions = Object.assign({}, options, {
depth: options.depth === null ? null : options.depth - 1,
});
const { body, headers, status, type, writable } = this;
return `${options.stylize(this.constructor.name, "special")} ${
inspect(
{ body, headers, status, type, writable },
newOptions,
)
}`;
}
}