@eggjs/koa 3.1.0-beta.2 → 3.1.0-beta.20

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/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@eggjs/koa",
3
- "version": "3.1.0-beta.2",
3
+ "version": "3.1.0-beta.20",
4
4
  "engines": {
5
- "node": ">= 20.19.0"
5
+ "node": ">=22.18.0"
6
6
  },
7
7
  "publishConfig": {
8
8
  "access": "public"
@@ -24,6 +24,7 @@
24
24
  "url": "git://github.com/eggjs/egg.git",
25
25
  "directory": "packages/koa"
26
26
  },
27
+ "homepage": "https://github.com/eggjs/egg/tree/next/packages/koa",
27
28
  "keywords": [
28
29
  "web",
29
30
  "app",
@@ -42,7 +43,7 @@
42
43
  "content-type": "^1.0.5",
43
44
  "cookies": "^0.9.1",
44
45
  "destroy": "^1.0.4",
45
- "encodeurl": "^1.0.2",
46
+ "encodeurl": "^2.0.0",
46
47
  "escape-html": "^1.0.3",
47
48
  "fresh": "~0.5.2",
48
49
  "gals": "1",
@@ -52,7 +53,7 @@
52
53
  "on-finished": "^2.4.1",
53
54
  "parseurl": "^1.3.3",
54
55
  "statuses": "^2.0.1",
55
- "type-is": "^1.6.18",
56
+ "type-is": "^2.0.0",
56
57
  "vary": "^1.1.2"
57
58
  },
58
59
  "devDependencies": {
@@ -65,20 +66,20 @@
65
66
  "@types/fresh": "^0.5.2",
66
67
  "@types/http-errors": "^2.0.4",
67
68
  "@types/koa-compose": "^3.2.8",
68
- "@types/node": "24",
69
69
  "@types/on-finished": "^2.3.4",
70
70
  "@types/parseurl": "^1.3.3",
71
71
  "@types/statuses": "^2.0.5",
72
- "@types/supertest": "^6.0.2",
73
72
  "@types/type-is": "^1.6.6",
74
73
  "@types/vary": "^1.1.3",
75
74
  "mm": "^4.0.2",
76
- "supertest": "^3.1.0",
77
- "tsdown": "^0.14.2",
78
- "typescript": "5"
75
+ "tsdown": "^0.15.4",
76
+ "typescript": "^5.9.3",
77
+ "@eggjs/supertest": "9.0.0-beta.20"
79
78
  },
80
79
  "scripts": {
81
80
  "build": "tsdown",
81
+ "typecheck": "tsc --noEmit",
82
+ "lint": "oxlint --type-aware",
82
83
  "test": "vitest run"
83
84
  }
84
85
  }
@@ -1,131 +0,0 @@
1
- import { Response } from "./response.js";
2
- import { Request } from "./request.js";
3
- import { AnyProto, CustomError } from "./types.js";
4
- import { Context } from "./context.js";
5
- import util from "node:util";
6
- import Emitter from "node:events";
7
- import http, { IncomingMessage, ServerResponse } from "node:http";
8
- import * as http_errors0 from "http-errors";
9
- import { AsyncLocalStorage } from "node:async_hooks";
10
-
11
- //#region src/application.d.ts
12
- type ProtoImplClass<T = object> = new (...args: any[]) => T;
13
- type Next = () => Promise<void>;
14
- type _MiddlewareFunc<T> = (ctx: T, next: Next) => Promise<void> | void;
15
- type MiddlewareFunc<T extends Context = Context> = _MiddlewareFunc<T> & {
16
- _name?: string;
17
- };
18
- /**
19
- * Expose `Application` class.
20
- * Inherits from `Emitter.prototype`.
21
- */
22
- declare class Application extends Emitter {
23
- [key: symbol]: unknown;
24
- /**
25
- * Make HttpError available to consumers of the library so that consumers don't
26
- * have a direct dependency upon `http-errors`
27
- */
28
- static HttpError: http_errors0.HttpErrorConstructor<number>;
29
- protected _proxy: boolean;
30
- protected _env: string;
31
- subdomainOffset: number;
32
- proxyIpHeader: string;
33
- maxIpsCount: number;
34
- protected _keys?: string[];
35
- middleware: MiddlewareFunc<Context>[];
36
- ctxStorage: AsyncLocalStorage<Context>;
37
- silent: boolean;
38
- ContextClass: ProtoImplClass<Context>;
39
- context: AnyProto;
40
- RequestClass: ProtoImplClass<Request>;
41
- request: AnyProto;
42
- ResponseClass: ProtoImplClass<Response>;
43
- response: AnyProto;
44
- /**
45
- * Initialize a new `Application`.
46
- *
47
- * @param {object} [options] Application options
48
- * @param {string} [options.env] Environment, default is `development`
49
- * @param {string[]} [options.keys] Signed cookie keys
50
- * @param {boolean} [options.proxy] Trust proxy headers
51
- * @param {number} [options.subdomainOffset] Subdomain offset
52
- * @param {string} [options.proxyIpHeader] Proxy IP header, defaults to X-Forwarded-For
53
- * @param {number} [options.maxIpsCount] Max IPs read from proxy IP header, default to 0 (means infinity)
54
- */
55
- constructor(options?: {
56
- proxy?: boolean;
57
- subdomainOffset?: number;
58
- proxyIpHeader?: string;
59
- maxIpsCount?: number;
60
- env?: string;
61
- keys?: string[];
62
- });
63
- get keys(): string[] | undefined;
64
- set keys(value: string[] | undefined);
65
- get env(): string;
66
- set env(value: string);
67
- get proxy(): boolean;
68
- set proxy(value: boolean);
69
- /**
70
- * Shorthand for:
71
- *
72
- * http.createServer(app.callback()).listen(...)
73
- */
74
- listen(...args: any[]): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
75
- /**
76
- * Return JSON representation.
77
- * We only bother showing settings.
78
- */
79
- toJSON(): {
80
- subdomainOffset: number;
81
- proxy: boolean;
82
- env: string;
83
- };
84
- /**
85
- * Inspect implementation.
86
- */
87
- inspect(): {
88
- subdomainOffset: number;
89
- proxy: boolean;
90
- env: string;
91
- };
92
- [util.inspect.custom](): {
93
- subdomainOffset: number;
94
- proxy: boolean;
95
- env: string;
96
- };
97
- /**
98
- * Use the given middleware `fn`.
99
- */
100
- use<T extends Context = Context>(fn: MiddlewareFunc<T>): this;
101
- /**
102
- * Return a request handler callback
103
- * for node's native http server.
104
- */
105
- callback(): (req: IncomingMessage, res: ServerResponse) => Promise<void | http.ServerResponse<http.IncomingMessage>>;
106
- /**
107
- * return current context from async local storage
108
- */
109
- get currentContext(): Context | undefined;
110
- /**
111
- * Handle request in callback.
112
- * @private
113
- */
114
- protected handleRequest(ctx: Context, fnMiddleware: (ctx: Context) => Promise<void>): Promise<void | http.ServerResponse<http.IncomingMessage>>;
115
- /**
116
- * Initialize a new context.
117
- * @private
118
- */
119
- createContext(req: IncomingMessage, res: ServerResponse): Context;
120
- /**
121
- * Default error handler.
122
- * @private
123
- */
124
- protected onerror(err: CustomError): void;
125
- /**
126
- * Response helper.
127
- */
128
- protected _respond(ctx: Context): http.ServerResponse<http.IncomingMessage> | undefined;
129
- }
130
- //#endregion
131
- export { Application, MiddlewareFunc, Next, ProtoImplClass };
@@ -1,233 +0,0 @@
1
- import { Context } from "./context.js";
2
- import { Request } from "./request.js";
3
- import { Response } from "./response.js";
4
- import util, { debuglog } from "node:util";
5
- import Emitter from "node:events";
6
- import Stream from "node:stream";
7
- import http from "node:http";
8
- import { getAsyncLocalStorage } from "gals";
9
- import { isGeneratorFunction } from "is-type-of";
10
- import onFinished from "on-finished";
11
- import statuses from "statuses";
12
- import compose from "koa-compose";
13
- import { HttpError } from "http-errors";
14
-
15
- //#region src/application.ts
16
- const debug = debuglog("egg/koa/application");
17
- /**
18
- * Expose `Application` class.
19
- * Inherits from `Emitter.prototype`.
20
- */
21
- var Application = class extends Emitter {
22
- /**
23
- * Make HttpError available to consumers of the library so that consumers don't
24
- * have a direct dependency upon `http-errors`
25
- */
26
- static HttpError = HttpError;
27
- _proxy;
28
- _env;
29
- subdomainOffset;
30
- proxyIpHeader;
31
- maxIpsCount;
32
- _keys;
33
- middleware;
34
- ctxStorage;
35
- silent;
36
- ContextClass;
37
- context;
38
- RequestClass;
39
- request;
40
- ResponseClass;
41
- response;
42
- /**
43
- * Initialize a new `Application`.
44
- *
45
- * @param {object} [options] Application options
46
- * @param {string} [options.env] Environment, default is `development`
47
- * @param {string[]} [options.keys] Signed cookie keys
48
- * @param {boolean} [options.proxy] Trust proxy headers
49
- * @param {number} [options.subdomainOffset] Subdomain offset
50
- * @param {string} [options.proxyIpHeader] Proxy IP header, defaults to X-Forwarded-For
51
- * @param {number} [options.maxIpsCount] Max IPs read from proxy IP header, default to 0 (means infinity)
52
- */
53
- constructor(options) {
54
- super();
55
- options = options || {};
56
- this._proxy = options.proxy || false;
57
- this.subdomainOffset = options.subdomainOffset || 2;
58
- this.proxyIpHeader = options.proxyIpHeader || "X-Forwarded-For";
59
- this.maxIpsCount = options.maxIpsCount || 0;
60
- this._env = options.env || process.env.NODE_ENV || "development";
61
- if (options.keys) this._keys = options.keys;
62
- this.middleware = [];
63
- this.ctxStorage = getAsyncLocalStorage();
64
- this.silent = false;
65
- this.ContextClass = class ApplicationContext extends Context {};
66
- this.context = this.ContextClass.prototype;
67
- this.RequestClass = class ApplicationRequest extends Request {};
68
- this.request = this.RequestClass.prototype;
69
- this.ResponseClass = class ApplicationResponse extends Response {};
70
- this.response = this.ResponseClass.prototype;
71
- }
72
- get keys() {
73
- return this._keys;
74
- }
75
- set keys(value) {
76
- this._keys = value;
77
- }
78
- get env() {
79
- return this._env;
80
- }
81
- set env(value) {
82
- this._env = value;
83
- }
84
- get proxy() {
85
- return this._proxy;
86
- }
87
- set proxy(value) {
88
- this._proxy = value;
89
- }
90
- /**
91
- * Shorthand for:
92
- *
93
- * http.createServer(app.callback()).listen(...)
94
- */
95
- listen(...args) {
96
- debug("listen with args: %o", args);
97
- return http.createServer(this.callback()).listen(...args);
98
- }
99
- /**
100
- * Return JSON representation.
101
- * We only bother showing settings.
102
- */
103
- toJSON() {
104
- return {
105
- subdomainOffset: this.subdomainOffset,
106
- proxy: this.proxy,
107
- env: this.env
108
- };
109
- }
110
- /**
111
- * Inspect implementation.
112
- */
113
- inspect() {
114
- return this.toJSON();
115
- }
116
- [util.inspect.custom]() {
117
- return this.inspect();
118
- }
119
- /**
120
- * Use the given middleware `fn`.
121
- */
122
- use(fn) {
123
- if (typeof fn !== "function") throw new TypeError("middleware must be a function!");
124
- const name = fn._name || fn.name || "-";
125
- if (isGeneratorFunction(fn)) throw new TypeError(`Support for generators was removed, middleware: ${name}. See the documentation for examples of how to convert old middleware https://github.com/koajs/koa/blob/master/docs/migration.md`);
126
- debug("use %o #%d", name, this.middleware.length);
127
- this.middleware.push(fn);
128
- return this;
129
- }
130
- /**
131
- * Return a request handler callback
132
- * for node's native http server.
133
- */
134
- callback() {
135
- const fn = compose(this.middleware);
136
- if (!this.listenerCount("error")) this.on("error", this.onerror.bind(this));
137
- const handleRequest = (req, res) => {
138
- const ctx = this.createContext(req, res);
139
- return this.ctxStorage.run(ctx, async () => {
140
- return await this.handleRequest(ctx, fn);
141
- });
142
- };
143
- return handleRequest;
144
- }
145
- /**
146
- * return current context from async local storage
147
- */
148
- get currentContext() {
149
- return this.ctxStorage.getStore();
150
- }
151
- /**
152
- * Handle request in callback.
153
- * @private
154
- */
155
- async handleRequest(ctx, fnMiddleware) {
156
- this.emit("request", ctx);
157
- const res = ctx.res;
158
- res.statusCode = 404;
159
- const onerror = (err) => ctx.onerror(err);
160
- onFinished(res, (err) => {
161
- if (err) onerror(err);
162
- this.emit("response", ctx);
163
- });
164
- try {
165
- await fnMiddleware(ctx);
166
- return this._respond(ctx);
167
- } catch (err) {
168
- return onerror(err);
169
- }
170
- }
171
- /**
172
- * Initialize a new context.
173
- * @private
174
- */
175
- createContext(req, res) {
176
- return new this.ContextClass(this, req, res);
177
- }
178
- /**
179
- * Default error handler.
180
- * @private
181
- */
182
- onerror(err) {
183
- if (!(err instanceof Error || Object.prototype.toString.call(err) === "[object Error]")) throw new TypeError(util.format("non-error thrown: %j", err));
184
- if (err.status === 404 || err.expose) return;
185
- if (this.silent) return;
186
- const msg = err.stack || err.toString();
187
- console.error(`\n${msg.replaceAll(/^/gm, " ")}\n`);
188
- }
189
- /**
190
- * Response helper.
191
- */
192
- _respond(ctx) {
193
- if (ctx.respond === false) return;
194
- if (!ctx.writable) return;
195
- const res = ctx.res;
196
- let body = ctx.body;
197
- const code = ctx.status;
198
- if (statuses.empty[code]) {
199
- ctx.body = null;
200
- return res.end();
201
- }
202
- if (ctx.method === "HEAD") {
203
- if (!res.headersSent && !ctx.response.has("Content-Length")) {
204
- const { length } = ctx.response;
205
- if (Number.isInteger(length)) ctx.length = length;
206
- }
207
- return res.end();
208
- }
209
- if (body === null || body === void 0) {
210
- if (ctx.response._explicitNullBody) {
211
- ctx.response.remove("Content-Type");
212
- ctx.response.remove("Transfer-Encoding");
213
- return res.end();
214
- }
215
- if (ctx.req.httpVersionMajor >= 2) body = String(code);
216
- else body = ctx.message || String(code);
217
- if (!res.headersSent) {
218
- ctx.type = "text";
219
- ctx.length = Buffer.byteLength(body);
220
- }
221
- return res.end(body);
222
- }
223
- if (Buffer.isBuffer(body)) return res.end(body);
224
- if (typeof body === "string") return res.end(body);
225
- if (body instanceof Stream) return body.pipe(res);
226
- body = JSON.stringify(body);
227
- if (!res.headersSent) ctx.length = Buffer.byteLength(body);
228
- res.end(body);
229
- }
230
- };
231
-
232
- //#endregion
233
- export { Application };
package/dist/context.d.ts DELETED
@@ -1,230 +0,0 @@
1
- import { Response } from "./response.js";
2
- import { Request, RequestSocket } from "./request.js";
3
- import { AnyProto, CustomError } from "./types.js";
4
- import { Application } from "./application.js";
5
- import util from "node:util";
6
- import { IncomingMessage, ServerResponse } from "node:http";
7
- import Cookies from "cookies";
8
- import { ParsedUrlQuery } from "node:querystring";
9
- import { Accepts } from "accepts";
10
- import * as http11 from "http";
11
-
12
- //#region src/context.d.ts
13
- declare class Context {
14
- #private;
15
- [key: symbol | string]: unknown;
16
- app: Application;
17
- req: IncomingMessage;
18
- res: ServerResponse;
19
- request: Request & AnyProto;
20
- response: Response & AnyProto;
21
- originalUrl: string;
22
- respond?: boolean;
23
- constructor(app: Application, req: IncomingMessage, res: ServerResponse);
24
- /**
25
- * util.inspect() implementation, which
26
- * just returns the JSON output.
27
- */
28
- inspect(): {
29
- request: {
30
- method: string;
31
- url: string;
32
- header: http11.IncomingHttpHeaders;
33
- };
34
- response: {
35
- status: number;
36
- message: string;
37
- header: http11.OutgoingHttpHeaders;
38
- };
39
- app: {
40
- subdomainOffset: number;
41
- proxy: boolean;
42
- env: string;
43
- };
44
- originalUrl: string;
45
- req: string;
46
- res: string;
47
- socket: string;
48
- };
49
- /**
50
- * Custom inspection implementation for newer Node.js versions.
51
- */
52
- [util.inspect.custom](): {
53
- request: {
54
- method: string;
55
- url: string;
56
- header: http11.IncomingHttpHeaders;
57
- };
58
- response: {
59
- status: number;
60
- message: string;
61
- header: http11.OutgoingHttpHeaders;
62
- };
63
- app: {
64
- subdomainOffset: number;
65
- proxy: boolean;
66
- env: string;
67
- };
68
- originalUrl: string;
69
- req: string;
70
- res: string;
71
- socket: string;
72
- };
73
- /**
74
- * Return JSON representation.
75
- *
76
- * Here we explicitly invoke .toJSON() on each
77
- * object, as iteration will otherwise fail due
78
- * to the getters and cause utilities such as
79
- * clone() to fail.
80
- */
81
- toJSON(): {
82
- request: {
83
- method: string;
84
- url: string;
85
- header: http11.IncomingHttpHeaders;
86
- };
87
- response: {
88
- status: number;
89
- message: string;
90
- header: http11.OutgoingHttpHeaders;
91
- };
92
- app: {
93
- subdomainOffset: number;
94
- proxy: boolean;
95
- env: string;
96
- };
97
- originalUrl: string;
98
- req: string;
99
- res: string;
100
- socket: string;
101
- };
102
- /**
103
- * Similar to .throw(), adds assertion.
104
- *
105
- * ```ts
106
- * this.assert(this.user, 401, 'Please login!');
107
- * ```
108
- */
109
- assert(value: unknown, status?: number, errorProps?: Record<string, unknown>): void;
110
- assert(value: unknown, status?: number, errorMessage?: string, errorProps?: Record<string, unknown>): void;
111
- /**
112
- * Throw an error with `status` (default 500) and
113
- * `msg`. Note that these are user-level
114
- * errors, and the message may be exposed to the client.
115
- *
116
- * this.throw(403)
117
- * this.throw(400, 'name required')
118
- * this.throw('something exploded')
119
- * this.throw(new Error('invalid'))
120
- * this.throw(400, new Error('invalid'))
121
- * this.throw(400, new Error('invalid'), { foo: 'bar' })
122
- * this.throw(new Error('invalid'), { foo: 'bar' })
123
- *
124
- * See: https://github.com/jshttp/http-errors
125
- *
126
- * Note: `status` should only be passed as the first parameter.
127
- *
128
- * @param {String|Number|Error} status error, msg or status
129
- * @param {String|Number|Error|Object} [error] error, msg, status or errorProps
130
- * @param {Object} [errorProps] error object properties
131
- */
132
- throw(status: number): void;
133
- throw(status: number, errorProps: object): void;
134
- throw(status: number, errorMessage: string): void;
135
- throw(status: number, errorMessage: string, errorProps: object): void;
136
- throw(status: number, error: Error): void;
137
- throw(status: number, error: Error, errorProps: object): void;
138
- throw(errorMessage: string): void;
139
- throw(errorMessage: string, errorProps: object): void;
140
- throw(errorMessage: string, status: number): void;
141
- throw(errorMessage: string, status: number, errorProps: object): void;
142
- throw(error: Error): void;
143
- throw(error: Error, errorProps: object): void;
144
- throw(error: Error, status: number): void;
145
- throw(error: Error, status: number, errorProps: object): void;
146
- /**
147
- * Default error handling.
148
- * @private
149
- */
150
- onerror(err: CustomError): void;
151
- protected _cookies: Cookies | undefined;
152
- get cookies(): Cookies;
153
- set cookies(cookies: Cookies);
154
- get state(): Record<string, any>;
155
- /**
156
- * Request delegation.
157
- */
158
- acceptsLanguages(): string[];
159
- acceptsLanguages(languages: string[]): string | false;
160
- acceptsLanguages(...languages: string[]): string | false;
161
- acceptsEncodings(): string[];
162
- acceptsEncodings(encodings: string[]): string | false;
163
- acceptsEncodings(...encodings: string[]): string | false;
164
- acceptsCharsets(): string[];
165
- acceptsCharsets(charsets: string[]): string | false;
166
- acceptsCharsets(...charsets: string[]): string | false;
167
- accepts(args: string[]): string | string[] | false;
168
- accepts(...args: string[]): string | string[] | false;
169
- get<T = string | string[]>(field: string): T;
170
- is(type?: string | string[], ...types: string[]): string | false | null;
171
- get querystring(): string;
172
- set querystring(str: string);
173
- get idempotent(): boolean;
174
- get socket(): RequestSocket;
175
- get search(): string;
176
- set search(str: string);
177
- get method(): string;
178
- set method(method: string);
179
- get query(): ParsedUrlQuery;
180
- set query(obj: ParsedUrlQuery);
181
- get path(): string;
182
- set path(path: string);
183
- get url(): string;
184
- set url(url: string);
185
- get accept(): Accepts;
186
- set accept(accept: Accepts);
187
- get origin(): string;
188
- get href(): string;
189
- get subdomains(): string[];
190
- get protocol(): string;
191
- get host(): string;
192
- get hostname(): string;
193
- get URL(): URL;
194
- get header(): http11.IncomingHttpHeaders;
195
- get headers(): http11.IncomingHttpHeaders;
196
- get secure(): boolean;
197
- get stale(): boolean;
198
- get fresh(): boolean;
199
- get ips(): string[];
200
- get ip(): string;
201
- /**
202
- * Response delegation.
203
- */
204
- attachment(...args: Parameters<Response['attachment']>): void;
205
- redirect(...args: Parameters<Response['redirect']>): void;
206
- remove(...args: Parameters<Response['remove']>): void;
207
- vary(...args: Parameters<Response['vary']>): void;
208
- has(...args: Parameters<Response['has']>): boolean;
209
- set(...args: Parameters<Response['set']>): void;
210
- append(...args: Parameters<Response['append']>): void;
211
- flushHeaders(...args: Parameters<Response['flushHeaders']>): void;
212
- get status(): number;
213
- set status(status: number);
214
- get message(): string;
215
- set message(msg: string);
216
- get body(): any;
217
- set body(val: any);
218
- get length(): number | undefined;
219
- set length(n: number | string | undefined);
220
- get type(): string;
221
- set type(type: string | null | undefined);
222
- get lastModified(): string | Date | undefined;
223
- set lastModified(val: string | Date | undefined);
224
- get etag(): string;
225
- set etag(val: string);
226
- get headerSent(): boolean;
227
- get writable(): boolean;
228
- }
229
- //#endregion
230
- export { Context };