@eggjs/koa 3.0.0 → 3.1.0-beta.2

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/src/response.ts DELETED
@@ -1,524 +0,0 @@
1
- import assert from 'node:assert';
2
- import { extname } from 'node:path';
3
- import util from 'node:util';
4
- import Stream from 'node:stream';
5
- import type { IncomingMessage, ServerResponse } from 'node:http';
6
-
7
- import contentDisposition, {
8
- type Options as ContentDispositionOptions,
9
- } from 'content-disposition';
10
- import { getType } from 'cache-content-type';
11
- import onFinish from 'on-finished';
12
- import escape from 'escape-html';
13
- import { is as typeis } from 'type-is';
14
- import statuses from 'statuses';
15
- import destroy from 'destroy';
16
- import vary from 'vary';
17
- import encodeUrl from 'encodeurl';
18
-
19
- import type { Application } from './application.ts';
20
- import type { Context } from './context.ts';
21
- import type { Request } from './request.ts';
22
-
23
- export class Response {
24
- [key: symbol]: unknown;
25
- app: Application;
26
- req: IncomingMessage;
27
- res: ServerResponse;
28
- ctx: Context;
29
- request: Request;
30
-
31
- constructor(
32
- app: Application,
33
- ctx: Context,
34
- req: IncomingMessage,
35
- res: ServerResponse
36
- ) {
37
- this.app = app;
38
- this.req = req;
39
- this.res = res;
40
- this.ctx = ctx;
41
- }
42
-
43
- /**
44
- * Return the request socket.
45
- */
46
- get socket() {
47
- return this.res.socket;
48
- }
49
-
50
- /**
51
- * Return response header.
52
- */
53
- get header() {
54
- return this.res.getHeaders() || {};
55
- }
56
-
57
- /**
58
- * Return response header, alias as response.header
59
- */
60
- get headers() {
61
- return this.header;
62
- }
63
-
64
- _explicitStatus: boolean;
65
-
66
- /**
67
- * Get response status code.
68
- */
69
- get status() {
70
- return this.res.statusCode;
71
- }
72
-
73
- /**
74
- * Set response status code.
75
- */
76
- set status(code: number) {
77
- if (this.headerSent) return;
78
- assert.ok(Number.isInteger(code), 'status code must be a number');
79
- assert.ok(code >= 100 && code <= 999, `invalid status code: ${code}`);
80
- this._explicitStatus = true;
81
- this.res.statusCode = code;
82
- if (this.req.httpVersionMajor < 2 && statuses.message[code]) {
83
- this.res.statusMessage = statuses.message[code];
84
- }
85
- if (this.body && statuses.empty[code]) {
86
- this.body = null;
87
- }
88
- }
89
-
90
- /**
91
- * Get response status message
92
- */
93
- get message(): string {
94
- return this.res.statusMessage ?? statuses.message[this.status];
95
- }
96
-
97
- /**
98
- * Set response status message
99
- */
100
- set message(msg: string) {
101
- this.res.statusMessage = msg;
102
- }
103
-
104
- // oxlint-disable-next-line typescript/no-explicit-any
105
- _body: any;
106
- _explicitNullBody: boolean;
107
-
108
- /**
109
- * Get response body.
110
- */
111
- get body() {
112
- return this._body;
113
- }
114
-
115
- /**
116
- * Set response body.
117
- */
118
- set body(
119
- val: string | Buffer | object | Stream | null | undefined | boolean
120
- ) {
121
- const original = this._body;
122
- this._body = val;
123
-
124
- // no content
125
- if (val === null || val === undefined) {
126
- if (!statuses.empty[this.status]) {
127
- this.status = 204;
128
- }
129
- if (val === null) {
130
- this._explicitNullBody = true;
131
- }
132
- this.remove('Content-Type');
133
- this.remove('Content-Length');
134
- this.remove('Transfer-Encoding');
135
- return;
136
- }
137
-
138
- // set the status
139
- if (!this._explicitStatus) this.status = 200;
140
-
141
- // set the content-type only if not yet set
142
- const setType = !this.has('Content-Type');
143
-
144
- // string
145
- if (typeof val === 'string') {
146
- if (setType) this.type = /^\s*?</.test(val) ? 'html' : 'text';
147
- this.length = Buffer.byteLength(val);
148
- return;
149
- }
150
-
151
- // buffer
152
- if (Buffer.isBuffer(val)) {
153
- if (setType) this.type = 'bin';
154
- this.length = val.length;
155
- return;
156
- }
157
-
158
- // stream
159
- if (val instanceof Stream) {
160
- onFinish(this.res, destroy.bind(null, val));
161
- // oxlint-disable-next-line eqeqeq
162
- if (original != val) {
163
- val.once('error', err => this.ctx.onerror(err));
164
- // overwriting
165
- if (original !== null && original !== undefined) {
166
- this.remove('Content-Length');
167
- }
168
- }
169
-
170
- if (setType) {
171
- this.type = 'bin';
172
- }
173
- return;
174
- }
175
-
176
- // json
177
- this.remove('Content-Length');
178
- this.type = 'json';
179
- }
180
-
181
- /**
182
- * Set Content-Length field to `n`.
183
- */
184
- set length(n: number | string | undefined) {
185
- if (n === undefined) return;
186
- if (!this.has('Transfer-Encoding')) {
187
- this.set('Content-Length', n);
188
- }
189
- }
190
-
191
- /**
192
- * Return parsed response Content-Length when present.
193
- *
194
- * When Content-Length is not defined it will return `undefined`.
195
- */
196
- get length(): number | undefined {
197
- if (this.has('Content-Length')) {
198
- return Number.parseInt(this.get('Content-Length')) || 0;
199
- }
200
-
201
- const { body } = this;
202
- if (!body || body instanceof Stream) {
203
- return undefined;
204
- }
205
- if (typeof body === 'string') {
206
- return Buffer.byteLength(body);
207
- }
208
- if (Buffer.isBuffer(body)) {
209
- return body.length;
210
- }
211
- return Buffer.byteLength(JSON.stringify(body));
212
- }
213
-
214
- /**
215
- * Check if a header has been written to the socket.
216
- */
217
- get headerSent() {
218
- return this.res.headersSent;
219
- }
220
-
221
- /**
222
- * Vary on `field`.
223
- */
224
- vary(field: string) {
225
- if (this.headerSent) return;
226
- vary(this.res, field);
227
- }
228
-
229
- _getBackReferrer() {
230
- const referrer = this.ctx.get<string>('Referrer');
231
- if (referrer) {
232
- // referrer is a relative path
233
- if (referrer.startsWith('/')) {
234
- return referrer;
235
- }
236
-
237
- // referrer is an absolute URL, check if it's the same origin
238
- const url = new URL(referrer, this.ctx.href);
239
- if (url.host === this.ctx.host) {
240
- return referrer;
241
- }
242
- }
243
- }
244
-
245
- /**
246
- * Perform a 302 redirect to `url`.
247
- *
248
- * The string "back" is special-cased
249
- * to provide Referrer support, when Referrer
250
- * is not present `alt` or "/" is used.
251
- *
252
- * Examples:
253
- *
254
- * this.redirect('back');
255
- * this.redirect('back', '/index.html');
256
- * this.redirect('/login');
257
- * this.redirect('http://google.com'); // will format to 'http://google.com/'
258
- */
259
- redirect(url: string, alt?: string) {
260
- // location
261
- if (url === 'back') {
262
- url = this._getBackReferrer() || alt || '/';
263
- }
264
- if (url.startsWith('https://') || url.startsWith('http://')) {
265
- // formatting url again avoid security escapes
266
- url = new URL(url).toString();
267
- }
268
- this.set('Location', encodeUrl(url));
269
-
270
- // status
271
- if (!statuses.redirect[this.status]) this.status = 302;
272
-
273
- // html
274
- if (this.ctx.accepts('html')) {
275
- url = escape(url);
276
- this.type = 'text/html; charset=utf-8';
277
- this.body = `Redirecting to ${url}.`;
278
- return;
279
- }
280
-
281
- // text
282
- this.type = 'text/plain; charset=utf-8';
283
- this.body = `Redirecting to ${url}.`;
284
- }
285
-
286
- /**
287
- * Set Content-Disposition header to "attachment" with optional `filename`.
288
- */
289
- attachment(filename?: string, options?: ContentDispositionOptions) {
290
- if (filename) this.type = extname(filename);
291
- this.set('Content-Disposition', contentDisposition(filename, options));
292
- }
293
-
294
- /**
295
- * Set Content-Type response header with `type` through `mime.lookup()`
296
- * when it does not contain a charset.
297
- *
298
- * Examples:
299
- *
300
- * this.type = '.html';
301
- * this.type = 'html';
302
- * this.type = 'json';
303
- * this.type = 'application/json';
304
- * this.type = 'png';
305
- */
306
- set type(type: string | null | undefined) {
307
- if (!type) {
308
- this.remove('Content-Type');
309
- return;
310
- }
311
- const mimeType = getType(type);
312
- if (mimeType) {
313
- this.set('Content-Type', mimeType);
314
- }
315
- }
316
-
317
- /**
318
- * Return the response mime type void of
319
- * parameters such as "charset".
320
- */
321
- get type(): string {
322
- const type = this.get<string>('Content-Type');
323
- if (!type) return '';
324
- return type.split(';', 1)[0];
325
- }
326
-
327
- /**
328
- * Check whether the response is one of the listed types.
329
- * Pretty much the same as `this.request.is()`.
330
- *
331
- * this.response.is('html')
332
- * this.response.is('html', 'json')
333
- */
334
- is(type?: string | string[], ...types: string[]): string | false {
335
- let testTypes: string[] = [];
336
- if (type) {
337
- testTypes = Array.isArray(type) ? type : [type];
338
- }
339
- return typeis(this.type, [...testTypes, ...types]);
340
- }
341
-
342
- /**
343
- * Set the Last-Modified date using a string or a Date.
344
- *
345
- * this.response.lastModified = new Date();
346
- * this.response.lastModified = '2013-09-13';
347
- */
348
- set lastModified(val: string | Date | undefined) {
349
- if (typeof val === 'string') val = new Date(val);
350
- if (val) {
351
- this.set('Last-Modified', val.toUTCString());
352
- }
353
- }
354
-
355
- /**
356
- * Get the Last-Modified date in Date form, if it exists.
357
- */
358
- get lastModified(): Date | undefined {
359
- const date = this.get<string>('last-modified');
360
- if (date) return new Date(date);
361
- }
362
-
363
- /**
364
- * Set the ETag of a response.
365
- * This will normalize the quotes if necessary.
366
- *
367
- * this.response.etag = 'md5-hash-sum';
368
- * this.response.etag = '"md5-hash-sum"';
369
- * this.response.etag = 'W/"123456789"';
370
- */
371
- set etag(val: string) {
372
- if (!/^(W\/)?"/.test(val)) val = `"${val}"`;
373
- this.set('ETag', val);
374
- }
375
-
376
- /**
377
- * Get the ETag of a response.
378
- */
379
- get etag() {
380
- return this.get('ETag');
381
- }
382
-
383
- /**
384
- * Return response header.
385
- *
386
- * Examples:
387
- *
388
- * this.get('Content-Type');
389
- * // => "text/plain"
390
- *
391
- * this.get('content-type');
392
- * // => "text/plain"
393
- */
394
- get<T = string | string[] | number>(field: string): T {
395
- return (this.header[field.toLowerCase()] || '') as T;
396
- }
397
-
398
- /**
399
- * Returns true if the header identified by name is currently set in the outgoing headers.
400
- * The header name matching is case-insensitive.
401
- *
402
- * Examples:
403
- *
404
- * this.has('Content-Type');
405
- * // => true
406
- *
407
- * this.get('content-type');
408
- * // => true
409
- */
410
- has(field: string) {
411
- return this.res.hasHeader(field);
412
- }
413
-
414
- /**
415
- * Set header `field` to `val` or pass
416
- * an object of header fields.
417
- *
418
- * Examples:
419
- *
420
- * this.set('Foo', ['bar', 'baz']);
421
- * this.set('Accept', 'application/json');
422
- * this.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
423
- */
424
- set(
425
- field: string | Record<string, string>,
426
- val?: string | number | unknown[]
427
- ) {
428
- if (this.headerSent) return;
429
- if (typeof field === 'string') {
430
- let value = val as string | string[];
431
- if (Array.isArray(val)) {
432
- value = val.map(v => (typeof v === 'string' ? v : String(v)));
433
- } else if (typeof val !== 'string') {
434
- value = String(val);
435
- }
436
- this.res.setHeader(field, value);
437
- } else {
438
- for (const key in field) {
439
- this.set(key, field[key]);
440
- }
441
- }
442
- }
443
-
444
- /**
445
- * Append additional header `field` with value `val`.
446
- *
447
- * Examples:
448
- *
449
- * ```
450
- * this.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
451
- * this.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
452
- * this.append('Warning', '199 Miscellaneous warning');
453
- */
454
- append(field: string, val: string | string[]) {
455
- const prev = this.get<string | string[]>(field);
456
-
457
- let value = val;
458
- if (prev) {
459
- value = Array.isArray(prev) ? prev.concat(value) : [prev].concat(val);
460
- }
461
-
462
- return this.set(field, value);
463
- }
464
-
465
- /**
466
- * Remove header `field`.
467
- */
468
- remove(field: string) {
469
- if (this.headerSent) return;
470
- this.res.removeHeader(field);
471
- }
472
-
473
- /**
474
- * Checks if the request is writable.
475
- * Tests for the existence of the socket
476
- * as node sometimes does not set it.
477
- */
478
- get writable() {
479
- // can't write any more after response finished
480
- // response.writableEnded is available since Node > 12.9
481
- // https://nodejs.org/api/http.html#http_response_writableended
482
- // response.finished is undocumented feature of previous Node versions
483
- // https://stackoverflow.com/questions/16254385/undocumented-response-finished-in-node-js
484
- if (this.res.writableEnded || this.res.finished) return false;
485
-
486
- const socket = this.res.socket;
487
- // There are already pending outgoing res, but still writable
488
- // https://github.com/nodejs/node/blob/v4.4.7/lib/_http_server.js#L486
489
- if (!socket) return true;
490
- return socket.writable;
491
- }
492
-
493
- /**
494
- * Inspect implementation.
495
- */
496
- inspect() {
497
- if (!this.res) return;
498
- const o = this.toJSON();
499
- Reflect.set(o, 'body', this.body);
500
- return o;
501
- }
502
-
503
- [util.inspect.custom]() {
504
- return this.inspect();
505
- }
506
-
507
- /**
508
- * Return JSON representation.
509
- */
510
- toJSON() {
511
- return {
512
- status: this.status,
513
- message: this.message,
514
- header: this.header,
515
- };
516
- }
517
-
518
- /**
519
- * Flush any set headers and begin the body
520
- */
521
- flushHeaders() {
522
- this.res.flushHeaders();
523
- }
524
- }
package/src/types.ts DELETED
@@ -1,13 +0,0 @@
1
- export type CustomError = Error & {
2
- headers?: Record<string, string>;
3
- status?: number;
4
- statusCode?: number;
5
- code?: string;
6
- expose?: boolean;
7
- headerSent?: boolean;
8
- };
9
-
10
- export interface AnyProto {
11
- // oxlint-disable-next-line typescript/no-explicit-any
12
- [key: string | symbol]: any;
13
- }