@eggjs/koa 3.0.1 → 3.1.0-beta.3

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/request.ts DELETED
@@ -1,670 +0,0 @@
1
- import net, { type Socket } from 'node:net';
2
- import { format as stringify } from 'node:url';
3
- import qs, { type ParsedUrlQuery } from 'node:querystring';
4
- import util from 'node:util';
5
- import type { IncomingMessage, ServerResponse } from 'node:http';
6
-
7
- import accepts, { type Accepts } from 'accepts';
8
- import contentType from 'content-type';
9
- import parse from 'parseurl';
10
- import typeis from 'type-is';
11
- import fresh from 'fresh';
12
-
13
- import type { Application } from './application.ts';
14
- import type { Context } from './context.ts';
15
- import type { Response } from './response.ts';
16
-
17
- export interface RequestSocket extends Socket {
18
- encrypted: boolean;
19
- }
20
-
21
- export class Request {
22
- [key: symbol]: unknown;
23
- app: Application;
24
- req: IncomingMessage;
25
- res: ServerResponse;
26
- ctx: Context;
27
- response: Response;
28
- originalUrl: string;
29
-
30
- constructor(
31
- app: Application,
32
- ctx: Context,
33
- req: IncomingMessage,
34
- res: ServerResponse
35
- ) {
36
- this.app = app;
37
- this.req = req;
38
- this.res = res;
39
- this.ctx = ctx;
40
- this.originalUrl = req.url ?? '/';
41
- }
42
-
43
- /**
44
- * Return request header.
45
- */
46
-
47
- get header() {
48
- return this.req.headers;
49
- }
50
-
51
- /**
52
- * Set request header.
53
- */
54
-
55
- set header(val) {
56
- this.req.headers = val;
57
- }
58
-
59
- /**
60
- * Return request header, alias as request.header
61
- */
62
-
63
- get headers() {
64
- return this.req.headers;
65
- }
66
-
67
- /**
68
- * Set request header, alias as request.header
69
- */
70
-
71
- set headers(val) {
72
- this.req.headers = val;
73
- }
74
-
75
- /**
76
- * Get request URL.
77
- */
78
-
79
- get url() {
80
- return this.req.url ?? '/';
81
- }
82
-
83
- /**
84
- * Set request URL.
85
- */
86
-
87
- set url(val) {
88
- this.req.url = val;
89
- }
90
-
91
- /**
92
- * Get origin of URL.
93
- */
94
-
95
- get origin() {
96
- return `${this.protocol}://${this.host}`;
97
- }
98
-
99
- /**
100
- * Get full request URL.
101
- */
102
-
103
- get href() {
104
- // support: `GET http://example.com/foo`
105
- if (/^https?:\/\//i.test(this.originalUrl)) {
106
- return this.originalUrl;
107
- }
108
- return this.origin + this.originalUrl;
109
- }
110
-
111
- /**
112
- * Get request method.
113
- */
114
-
115
- get method() {
116
- return this.req.method ?? 'GET';
117
- }
118
-
119
- /**
120
- * Set request method.
121
- */
122
- set method(val: string) {
123
- this.req.method = val;
124
- }
125
-
126
- /**
127
- * Get request pathname.
128
- */
129
- get path() {
130
- return parse(this.req)?.pathname ?? '';
131
- }
132
-
133
- /**
134
- * Set pathname, retaining the query string when present.
135
- */
136
- set path(pathname: string) {
137
- const url = parse(this.req);
138
- if (!url) return;
139
- if (url.pathname === pathname) return;
140
-
141
- url.pathname = pathname;
142
- url.path = null;
143
-
144
- this.url = stringify(url);
145
- }
146
-
147
- protected _parsedUrlQueryCache: Record<string, ParsedUrlQuery> | undefined;
148
-
149
- /**
150
- * Get parsed query string.
151
- */
152
- get query(): ParsedUrlQuery {
153
- const str = this.querystring;
154
- if (!this._parsedUrlQueryCache) {
155
- this._parsedUrlQueryCache = {};
156
- }
157
- let parsedUrlQuery = this._parsedUrlQueryCache[str];
158
- if (!parsedUrlQuery) {
159
- parsedUrlQuery = qs.parse(str);
160
- this._parsedUrlQueryCache[str] = parsedUrlQuery;
161
- }
162
- return parsedUrlQuery;
163
- }
164
-
165
- /**
166
- * Set query string as an object.
167
- */
168
- set query(obj: ParsedUrlQuery) {
169
- this.querystring = qs.stringify(obj);
170
- }
171
-
172
- /**
173
- * Get query string.
174
- */
175
- get querystring() {
176
- if (!this.req) return '';
177
- return (parse(this.req)?.query as string) ?? '';
178
- }
179
-
180
- /**
181
- * Set query string.
182
- */
183
- set querystring(str: string) {
184
- const url = parse(this.req);
185
- if (!url) return;
186
- if (url.search === `?${str}`) return;
187
-
188
- url.search = str;
189
- url.path = null;
190
- this.url = stringify(url);
191
- }
192
-
193
- /**
194
- * Get the search string. Same as the query string
195
- * except it includes the leading ?.
196
- */
197
- get search() {
198
- const querystring = this.querystring;
199
- if (!querystring) return '';
200
- return `?${querystring}`;
201
- }
202
-
203
- /**
204
- * Set the search string. Same as
205
- * request.querystring= but included for ubiquity.
206
- */
207
- set search(str: string) {
208
- this.querystring = str;
209
- }
210
-
211
- /**
212
- * Parse the "Host" header field host
213
- * and support X-Forwarded-Host when a
214
- * proxy is enabled.
215
- * return `hostname:port` format
216
- */
217
- get host() {
218
- const proxy = this.app.proxy;
219
- let host = proxy ? this.get<string>('X-Forwarded-Host') : '';
220
- if (host) {
221
- host = splitCommaSeparatedValues(host, 1)[0];
222
- }
223
- if (!host) {
224
- if (this.req.httpVersionMajor >= 2) {
225
- host = this.get(':authority');
226
- }
227
- if (!host) {
228
- host = this.get('Host');
229
- }
230
- }
231
- return host;
232
- }
233
-
234
- /**
235
- * Parse the "Host" header field hostname
236
- * and support X-Forwarded-Host when a
237
- * proxy is enabled.
238
- */
239
- get hostname() {
240
- const host = this.host;
241
- if (!host) {
242
- return '';
243
- }
244
- if (host[0] === '[') {
245
- return this.URL.hostname || ''; // IPv6
246
- }
247
- return host.split(':', 1)[0];
248
- }
249
-
250
- protected _memoizedURL: URL | undefined;
251
-
252
- /**
253
- * Get WHATWG parsed URL.
254
- * Lazily memoized.
255
- */
256
- get URL() {
257
- if (!this._memoizedURL) {
258
- const originalUrl = this.originalUrl || ''; // avoid undefined in template string
259
- try {
260
- this._memoizedURL = new URL(`${this.origin}${originalUrl}`);
261
- } catch {
262
- this._memoizedURL = Object.create(null);
263
- }
264
- }
265
- return this._memoizedURL as URL;
266
- }
267
-
268
- /**
269
- * Check if the request is fresh, aka
270
- * Last-Modified and/or the ETag
271
- * still match.
272
- */
273
- get fresh() {
274
- const method = this.method;
275
- const status = this.response.status;
276
-
277
- // GET or HEAD for weak freshness validation only
278
- if (method !== 'GET' && method !== 'HEAD') {
279
- return false;
280
- }
281
-
282
- // 2xx or 304 as per rfc2616 14.26
283
- if ((status >= 200 && status < 300) || status === 304) {
284
- return fresh(this.header, this.response.header);
285
- }
286
-
287
- return false;
288
- }
289
-
290
- /**
291
- * Check if the request is stale, aka
292
- * "Last-Modified" and / or the "ETag" for the
293
- * resource has changed.
294
- */
295
- get stale() {
296
- return !this.fresh;
297
- }
298
-
299
- /**
300
- * Check if the request is idempotent.
301
- */
302
- get idempotent() {
303
- const methods = ['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS', 'TRACE'];
304
- return methods.includes(this.method);
305
- }
306
-
307
- /**
308
- * Return the request socket.
309
- */
310
- get socket() {
311
- return this.req.socket as RequestSocket;
312
- }
313
-
314
- /**
315
- * Get the charset when present or undefined.
316
- */
317
- get charset() {
318
- try {
319
- const { parameters } = contentType.parse(this.req);
320
- return parameters.charset || '';
321
- } catch {
322
- return '';
323
- }
324
- }
325
-
326
- /**
327
- * Return parsed Content-Length when present.
328
- */
329
- get length() {
330
- const len = this.get<string>('Content-Length');
331
- if (len === '') {
332
- return;
333
- }
334
- return Number.parseInt(len);
335
- }
336
-
337
- /**
338
- * Return the protocol string "http" or "https"
339
- * when requested with TLS. When the proxy setting
340
- * is enabled the "X-Forwarded-Proto" header
341
- * field will be trusted. If you're running behind
342
- * a reverse proxy that supplies https for you this
343
- * may be enabled.
344
- */
345
- get protocol() {
346
- if (this.socket.encrypted) {
347
- return 'https';
348
- }
349
- if (!this.app.proxy) {
350
- return 'http';
351
- }
352
- let proto = this.get<string>('X-Forwarded-Proto');
353
- if (proto) {
354
- proto = splitCommaSeparatedValues(proto, 1)[0];
355
- }
356
- return proto || 'http';
357
- }
358
-
359
- /**
360
- * Shorthand for:
361
- *
362
- * this.protocol == 'https'
363
- */
364
- get secure() {
365
- return this.protocol === 'https';
366
- }
367
-
368
- /**
369
- * When `app.proxy` is `true`, parse
370
- * the "X-Forwarded-For" ip address list.
371
- *
372
- * For example if the value was "client, proxy1, proxy2"
373
- * you would receive the array `["client", "proxy1", "proxy2"]`
374
- * where "proxy2" is the furthest down-stream.
375
- */
376
- get ips() {
377
- const proxy = this.app.proxy;
378
- const val = this.get<string>(this.app.proxyIpHeader);
379
- let ips = proxy && val ? splitCommaSeparatedValues(val) : [];
380
- if (this.app.maxIpsCount > 0) {
381
- ips = ips.slice(-this.app.maxIpsCount);
382
- }
383
- return ips;
384
- }
385
-
386
- protected _ip: string;
387
- /**
388
- * Return request's remote address
389
- * When `app.proxy` is `true`, parse
390
- * the "X-Forwarded-For" ip address list and return the first one
391
- */
392
- get ip() {
393
- if (!this._ip) {
394
- this._ip = this.ips[0] || this.socket.remoteAddress || '';
395
- }
396
- return this._ip;
397
- }
398
-
399
- set ip(ip: string) {
400
- this._ip = ip;
401
- }
402
-
403
- /**
404
- * Return subdomains as an array.
405
- *
406
- * Subdomains are the dot-separated parts of the host before the main domain
407
- * of the app. By default, the domain of the app is assumed to be the last two
408
- * parts of the host. This can be changed by setting `app.subdomainOffset`.
409
- *
410
- * For example, if the domain is "tobi.ferrets.example.com":
411
- * If `app.subdomainOffset` is not set, this.subdomains is
412
- * `["ferrets", "tobi"]`.
413
- * If `app.subdomainOffset` is 3, this.subdomains is `["tobi"]`.
414
- */
415
- get subdomains() {
416
- const offset = this.app.subdomainOffset;
417
- const hostname = this.hostname;
418
- if (net.isIP(hostname)) return [];
419
- return hostname.split('.').reverse().slice(offset);
420
- }
421
-
422
- protected _accept: Accepts;
423
- /**
424
- * Get accept object.
425
- * Lazily memoized.
426
- */
427
- get accept() {
428
- return this._accept || (this._accept = accepts(this.req));
429
- }
430
-
431
- /**
432
- * Set accept object.
433
- */
434
- set accept(obj: Accepts) {
435
- this._accept = obj;
436
- }
437
-
438
- /**
439
- * Check if the given `type(s)` is acceptable, returning
440
- * the best match when true, otherwise `false`, in which
441
- * case you should respond with 406 "Not Acceptable".
442
- *
443
- * The `type` value may be a single mime type string
444
- * such as "application/json", the extension name
445
- * such as "json" or an array `["json", "html", "text/plain"]`. When a list
446
- * or array is given the _best_ match, if any is returned.
447
- *
448
- * Examples:
449
- *
450
- * // Accept: text/html
451
- * this.accepts('html');
452
- * // => "html"
453
- *
454
- * // Accept: text/*, application/json
455
- * this.accepts('html');
456
- * // => "html"
457
- * this.accepts('text/html');
458
- * // => "text/html"
459
- * this.accepts('json', 'text');
460
- * // => "json"
461
- * this.accepts('application/json');
462
- * // => "application/json"
463
- *
464
- * // Accept: text/*, application/json
465
- * this.accepts('image/png');
466
- * this.accepts('png');
467
- * // => false
468
- *
469
- * // Accept: text/*;q=.5, application/json
470
- * this.accepts(['html', 'json']);
471
- * this.accepts('html', 'json');
472
- * // => "json"
473
- */
474
- accepts(args: string[]): string | string[] | false;
475
- accepts(...args: string[]): string | string[] | false;
476
- accepts(
477
- args?: string | string[],
478
- ...others: string[]
479
- ): string | string[] | false {
480
- return this.accept.types(args as string, ...others);
481
- }
482
-
483
- /**
484
- * Return accepted encodings or best fit based on `encodings`.
485
- *
486
- * Given `Accept-Encoding: gzip, deflate`
487
- * an array sorted by quality is returned:
488
- *
489
- * ['gzip', 'deflate']
490
- */
491
- acceptsEncodings(): string[];
492
- acceptsEncodings(encodings: string[]): string | false;
493
- acceptsEncodings(...encodings: string[]): string | false;
494
- acceptsEncodings(
495
- encodings?: string | string[],
496
- ...others: string[]
497
- ): string[] | string | false {
498
- if (!encodings) {
499
- return this.accept.encodings();
500
- }
501
- if (Array.isArray(encodings)) {
502
- encodings = [...encodings, ...others];
503
- } else {
504
- encodings = [encodings, ...others];
505
- }
506
- return this.accept.encodings(...encodings);
507
- }
508
-
509
- /**
510
- * Return accepted charsets or best fit based on `charsets`.
511
- *
512
- * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
513
- * an array sorted by quality is returned:
514
- *
515
- * ['utf-8', 'utf-7', 'iso-8859-1']
516
- */
517
- acceptsCharsets(): string[];
518
- acceptsCharsets(charsets: string[]): string | false;
519
- acceptsCharsets(...charsets: string[]): string | false;
520
- acceptsCharsets(
521
- charsets?: string | string[],
522
- ...others: string[]
523
- ): string[] | string | false {
524
- if (!charsets) {
525
- return this.accept.charsets();
526
- }
527
- if (Array.isArray(charsets)) {
528
- charsets = [...charsets, ...others];
529
- } else {
530
- charsets = [charsets, ...others];
531
- }
532
- return this.accept.charsets(...charsets);
533
- }
534
-
535
- /**
536
- * Return accepted languages or best fit based on `langs`.
537
- *
538
- * Given `Accept-Language: en;q=0.8, es, pt`
539
- * an array sorted by quality is returned:
540
- *
541
- * ['es', 'pt', 'en']
542
- */
543
- acceptsLanguages(): string[];
544
- acceptsLanguages(languages: string[]): string | false;
545
- acceptsLanguages(...languages: string[]): string | false;
546
- acceptsLanguages(
547
- languages?: string | string[],
548
- ...others: string[]
549
- ): string | string[] | false {
550
- if (!languages) {
551
- return this.accept.languages();
552
- }
553
- if (Array.isArray(languages)) {
554
- languages = [...languages, ...others];
555
- } else {
556
- languages = [languages, ...others];
557
- }
558
- return this.accept.languages(...languages);
559
- }
560
-
561
- /**
562
- * Check if the incoming request contains the "Content-Type"
563
- * header field and if it contains any of the given mime `type`s.
564
- * If there is no request body, `null` is returned.
565
- * If there is no content type, `false` is returned.
566
- * Otherwise, it returns the first `type` that matches.
567
- *
568
- * Examples:
569
- *
570
- * // With Content-Type: text/html; charset=utf-8
571
- * this.is('html'); // => 'html'
572
- * this.is('text/html'); // => 'text/html'
573
- * this.is('text/*', 'application/json'); // => 'text/html'
574
- *
575
- * // When Content-Type is application/json
576
- * this.is('json', 'urlencoded'); // => 'json'
577
- * this.is('application/json'); // => 'application/json'
578
- * this.is('html', 'application/*'); // => 'application/json'
579
- *
580
- * this.is('html'); // => false
581
- */
582
- is(type?: string | string[], ...types: string[]): string | false | null {
583
- let testTypes: string[] = [];
584
- if (type) {
585
- testTypes = Array.isArray(type) ? type : [type];
586
- }
587
- return typeis(this.req, [...testTypes, ...types]);
588
- }
589
-
590
- /**
591
- * Return the request mime type void of
592
- * parameters such as "charset".
593
- */
594
- get type() {
595
- const type = this.get<string>('Content-Type');
596
- if (!type) return '';
597
- return type.split(';')[0];
598
- }
599
-
600
- /**
601
- * Return request header.
602
- *
603
- * The `Referrer` header field is special-cased,
604
- * both `Referrer` and `Referer` are interchangeable.
605
- *
606
- * Examples:
607
- *
608
- * this.get('Content-Type');
609
- * // => "text/plain"
610
- *
611
- * this.get('content-type');
612
- * // => "text/plain"
613
- *
614
- * this.get('Something');
615
- * // => ''
616
- */
617
- get<T = string | string[]>(field: string): T {
618
- const req = this.req;
619
- switch ((field = field.toLowerCase())) {
620
- case 'referer':
621
- case 'referrer': {
622
- return (req.headers.referrer || req.headers.referer || '') as T;
623
- }
624
- default: {
625
- return (req.headers[field] || '') as T;
626
- }
627
- }
628
- }
629
-
630
- /**
631
- * Inspect implementation.
632
- */
633
- inspect() {
634
- if (!this.req) return;
635
- return this.toJSON();
636
- }
637
-
638
- /**
639
- * Custom inspection implementation for newer Node.js versions.
640
- */
641
- [util.inspect.custom]() {
642
- return this.inspect();
643
- }
644
-
645
- /**
646
- * Return JSON representation.
647
- */
648
- toJSON() {
649
- return {
650
- method: this.method,
651
- url: this.url,
652
- header: this.header,
653
- };
654
- }
655
- }
656
-
657
- /**
658
- * Split a comma-separated value string into an array of values, with an optional limit.
659
- * All the values are trimmed of whitespace and filtered out empty values.
660
- *
661
- * @param {string} value - The comma-separated value string to split.
662
- * @param {number} [limit] - The maximum number of values to return.
663
- * @returns {string[]} An array of values from the comma-separated string.
664
- */
665
- function splitCommaSeparatedValues(value: string, limit?: number): string[] {
666
- return value
667
- .split(',', limit)
668
- .map(v => v.trim())
669
- .filter(v => v.length > 0);
670
- }