@aomex/web 0.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 geekact
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,306 @@
1
+ import { Chain, PureChain, PureMiddlewareToken, Next, Middleware, OpenAPI, Validator, TValidatorOptional, ValidatorTransformFn, TransformedValidator, ValidateResult, ValidatorOptions, GetValidatorType } from '@aomex/core';
2
+ import { NonReadonly } from '@aomex/helper';
3
+ import { IncomingMessage, ServerResponse, Server, RequestListener } from 'node:http';
4
+ import EventEmitter from 'node:events';
5
+ import { HttpError } from 'http-errors';
6
+ import { IParseOptions } from 'qs';
7
+ import { Stream } from 'node:stream';
8
+ import contentDisposition from 'content-disposition';
9
+ import { Accepts } from 'accepts';
10
+ import { File as File$1 } from 'formidable';
11
+
12
+ declare module '@aomex/core' {
13
+ interface ChainPlatform {
14
+ readonly web: WebChain;
15
+ }
16
+ }
17
+ type WebMiddlewareToken<P extends object = object> = WebMiddleware<P> | WebChain<P> | PureMiddlewareToken<P>;
18
+ declare class WebChain<Props extends object = object> extends Chain<Props> {
19
+ protected _web_chain_: 'web-chain';
20
+ mount: {
21
+ <P extends object>(middleware: WebChain | PureChain | WebMiddlewareToken<P> | null): WebChain<Props & P>;
22
+ };
23
+ }
24
+
25
+ type StringArrayHeaderKeys = 'set-cookie';
26
+ type StringHeaderKeys = ExtraStringHeaderKeys | OfficialStringHeaderKeys;
27
+ type HeaderKeys = StringHeaderKeys | StringArrayHeaderKeys;
28
+ type ExtraStringHeaderKeys = 'x-forwarded-for' | 'x-forwarded-proto' | 'x-forwarded-host' | 'x-real-ip' | 'access-control-request-private-network' | 'access-control-allow-private-network';
29
+ type OfficialStringHeaderKeys = 'accept' | 'accept-language' | 'accept-patch' | 'accept-ranges' | 'access-control-allow-credentials' | 'access-control-allow-headers' | 'access-control-allow-methods' | 'access-control-allow-origin' | 'access-control-expose-headers' | 'access-control-max-age' | 'access-control-request-headers' | 'access-control-request-method' | 'age' | 'allow' | 'alt-svc' | 'authorization' | 'cache-control' | 'connection' | 'content-disposition' | 'content-encoding' | 'content-language' | 'content-length' | 'content-location' | 'content-range' | 'content-type' | 'cookie' | 'date' | 'etag' | 'expect' | 'expires' | 'forwarded' | 'from' | 'host' | 'if-match' | 'if-modified-since' | 'if-none-match' | 'if-unmodified-since' | 'last-modified' | 'location' | 'origin' | 'pragma' | 'proxy-authenticate' | 'proxy-authorization' | 'public-key-pins' | 'range' | 'referer' | 'retry-after' | 'sec-websocket-accept' | 'sec-websocket-extensions' | 'sec-websocket-key' | 'sec-websocket-protocol' | 'sec-websocket-version' | 'strict-transport-security' | 'tk' | 'trailer' | 'transfer-encoding' | 'upgrade' | 'user-agent' | 'vary' | 'via' | 'warning' | 'www-authenticate';
30
+
31
+ declare class WebRequest extends IncomingMessage {
32
+ app: WebApp;
33
+ res: WebResponse;
34
+ ctx: WebContext;
35
+ readonly method: string;
36
+ readonly url: string;
37
+ params: Record<string, unknown>;
38
+ protected _query?: any;
39
+ protected _body?: any;
40
+ protected _accept?: Accepts;
41
+ get path(): string;
42
+ get querystring(): string;
43
+ get query(): Record<string, unknown>;
44
+ get body(): Promise<unknown>;
45
+ get contentType(): string;
46
+ findContentType(type: string, ...types: string[]): string | null;
47
+ get accept(): Accepts;
48
+ }
49
+ declare module 'node:http' {
50
+ type ExtraHeaders = {
51
+ [K in ExtraStringHeaderKeys]?: string;
52
+ };
53
+ interface IncomingHttpHeaders extends ExtraHeaders {
54
+ }
55
+ }
56
+
57
+ type Body = string | object | Stream | Buffer | null;
58
+ declare class WebResponse<Request extends WebRequest = WebRequest> extends ServerResponse<Request> {
59
+ app: WebApp;
60
+ ctx: WebContext;
61
+ protected _body: Body;
62
+ protected _explicitBody: boolean;
63
+ constructor(req: Request);
64
+ readonly setHeader: {
65
+ <T extends WebResponse>(name: StringHeaderKeys, value: number | string): T;
66
+ <T extends WebResponse>(name: StringArrayHeaderKeys, value: readonly string[]): T;
67
+ <T extends WebResponse>(name: string, value: number | string | readonly string[]): T;
68
+ };
69
+ readonly getHeader: {
70
+ (name: StringHeaderKeys): string | undefined;
71
+ (name: StringArrayHeaderKeys): string[] | undefined;
72
+ (name: string): string | string[] | undefined;
73
+ };
74
+ readonly hasHeader: {
75
+ (name: HeaderKeys): boolean;
76
+ (name: string): boolean;
77
+ };
78
+ readonly removeHeader: {
79
+ (name: HeaderKeys): void;
80
+ (name: string): void;
81
+ };
82
+ /**
83
+ * 批量设置头部数据
84
+ */
85
+ setHeaders(headers: {
86
+ [K: string]: string | number | readonly string[];
87
+ } & {
88
+ [K in StringHeaderKeys]?: string | number;
89
+ } & {
90
+ [K in StringArrayHeaderKeys]?: readonly string[];
91
+ }): void;
92
+ redirect(url: string): void;
93
+ redirect(statusCode: 300 | 301 | 302 | 303 | 305 | 307 | 308, url: string): void;
94
+ download(filePath: string, options?: contentDisposition.Options): void;
95
+ get contentLength(): number;
96
+ set contentLength(length: number);
97
+ get contentType(): string;
98
+ set contentType(typeOrFilenameOrExt: string);
99
+ get body(): Body;
100
+ set body(val: Body);
101
+ flush(): void;
102
+ onError(error?: Error | HttpError | null): void;
103
+ findContentType(type: string, ...types: string[]): string | null;
104
+ }
105
+
106
+ interface WebAppOption {
107
+ globalChain?: WebChain;
108
+ queryParser?: IParseOptions;
109
+ errorFormatter?: (msg: string, statusCode: number, helper: {
110
+ err: HttpError;
111
+ ctx: WebContext;
112
+ }) => Body;
113
+ }
114
+ declare class WebApp extends EventEmitter {
115
+ readonly options: WebAppOption;
116
+ constructor(options?: WebAppOption);
117
+ protected readonly middlewareList: WebMiddlewareToken[];
118
+ listen: Server['listen'];
119
+ callback(): RequestListener<any, any>;
120
+ log(err: HttpError): void;
121
+ on(eventName: 'error', listener: (err: HttpError, ctx: WebContext) => void): this;
122
+ mount(middleware: WebMiddlewareToken): void;
123
+ }
124
+
125
+ declare class WebContext {
126
+ readonly app: WebApp;
127
+ readonly request: WebRequest;
128
+ readonly response: WebResponse;
129
+ constructor(app: WebApp, request: WebRequest, response: WebResponse);
130
+ send(statusCode: number, body?: Body): this;
131
+ send(body: Body): this;
132
+ /**
133
+ * ```typescript
134
+ * ctx.throw(403)
135
+ * ctx.throw('name required', 400)
136
+ * ctx.throw(400, 'name required')
137
+ * ctx.throw('something exploded')
138
+ * ctx.throw(new Error('invalid'), 400);
139
+ * ctx.throw(400, new Error('invalid'));
140
+ * ```
141
+ * @link https://github.com/jshttp/http-errors
142
+ * @throws {HttpError}
143
+ * @see createHttpError.HttpError
144
+ *
145
+ */
146
+ throw(statusCode: number, message?: string | Error, properties?: {}): never;
147
+ throw(message: string | Error, statusCode?: number, properties?: {}): never;
148
+ throw(arg: any, ...properties: Array<number | string | {}>): never;
149
+ }
150
+
151
+ declare module '@aomex/core' {
152
+ interface MiddlewarePlatform {
153
+ readonly web: <Props extends object = object>(fn: (ctx: NonReadonly<Props> & WebContext, next: Next) => any) => WebMiddleware<Props>;
154
+ }
155
+ }
156
+ interface WebMiddlewareToDocument {
157
+ document: OpenAPI.Document;
158
+ pathItem?: OpenAPI.PathItemObject;
159
+ pathItemInMethod?: OpenAPI.OperationObject;
160
+ }
161
+ declare class WebMiddleware<Props extends object = object> extends Middleware<Props> {
162
+ protected _web_middleware_: 'web-middleware';
163
+ toDocument(options: WebMiddlewareToDocument): void;
164
+ }
165
+
166
+ declare module '@aomex/core' {
167
+ interface Rule {
168
+ file(): FileValidator;
169
+ }
170
+ }
171
+ type FileSizeUnit = 'B' | 'b' | 'KB' | 'kb' | 'MB' | 'mb' | 'GB' | 'gb' | 'TB' | 'tb';
172
+ interface FileOptions<T> extends ValidatorOptions<T> {
173
+ maxSize?: number;
174
+ mimeTypes?: string[];
175
+ }
176
+ interface File extends File$1 {
177
+ hash: 'string';
178
+ hashAlgorithm: 'md5';
179
+ }
180
+ declare class FileValidator<T = File> extends Validator<T> {
181
+ protected config: FileOptions<T>;
182
+ optional: () => FileValidator<T | TValidatorOptional>;
183
+ transform: <T1>(fn: ValidatorTransformFn<T, T1>) => TransformedValidator<T1>;
184
+ /**
185
+ * @param {String} unit 默认单位:`B`,即字节
186
+ */
187
+ maxSize(amount: number, unit?: FileSizeUnit): this;
188
+ /**
189
+ * 限制文件的`mime-type`。无论传入标准的格式还是普通的后缀,最终都会转换成标准的mime-types
190
+ * ```typescript
191
+ * file.mimeTypes('.html', '.js', 'image/*', 'text/plain');
192
+ * ```
193
+ */
194
+ mimeTypes(mineOrExt: string, ...others: string[]): this;
195
+ mimeTypes(mineOrExt: string[]): this;
196
+ protected isEmpty(value: any): boolean;
197
+ protected validateValue(file: File, key: string, superKeys: string[]): ValidateResult<File>;
198
+ protected toDocument(): OpenAPI.SchemaObject;
199
+ }
200
+
201
+ declare const getContentType: (type: string) => string | false;
202
+
203
+ declare class WebBodyMiddleware<Props extends {
204
+ [key: string]: Validator;
205
+ }> extends WebMiddleware<{
206
+ readonly body: {
207
+ [K in keyof Props]: GetValidatorType<Props[K]>;
208
+ };
209
+ }> {
210
+ protected readonly props: Props;
211
+ constructor(props: Props);
212
+ toDocument(options: WebMiddlewareToDocument): void;
213
+ }
214
+ /**
215
+ * 对请求时的body数据做验证。验证通过后可通过`ctx.body`获得结果
216
+ *
217
+ * ```typescript
218
+ * export const router = new Router();
219
+ *
220
+ * router.post('/users', {
221
+ * mount: [
222
+ * body({
223
+ * name: rule.string(),
224
+ * age: rule.int().optional(),
225
+ * }),
226
+ * ],
227
+ * action: async (ctx) => {
228
+ * console.log(ctx.body);
229
+ * },
230
+ * });
231
+ * ```
232
+ */
233
+ declare const body: <T extends {
234
+ [key: string]: P;
235
+ }, P extends Validator<unknown>>(fields: T) => WebBodyMiddleware<T>;
236
+
237
+ declare class WebQueryMiddleware<Props extends {
238
+ [key: string]: Validator;
239
+ }> extends WebMiddleware<{
240
+ readonly query: {
241
+ [K in keyof Props]: GetValidatorType<Props[K]>;
242
+ };
243
+ }> {
244
+ protected readonly props: Props;
245
+ constructor(props: Props);
246
+ toDocument(options: WebMiddlewareToDocument): void;
247
+ }
248
+ /**
249
+ * 对url上的查询字符串做验证。验证通过后可通过`ctx.query`获得结果
250
+ *
251
+ * ```typescript
252
+ * export const router = new Router();
253
+ *
254
+ * // https://example.com/users?search=lili&page=1
255
+ * router.get('/users', {
256
+ * mount: [
257
+ * query({
258
+ * search: rule.string().optional(),
259
+ * page: rule.int().min(1).default(1),
260
+ * pageSize: rule.int().min(5).default(10),
261
+ * }),
262
+ * ],
263
+ * action: async (ctx) => {
264
+ * console.log(ctx.query);
265
+ * },
266
+ * });
267
+ * ```
268
+ */
269
+ declare const query: <T extends {
270
+ [key: string]: P;
271
+ }, P extends Validator<unknown>>(fields: T) => WebQueryMiddleware<T>;
272
+
273
+ declare class WebParamMiddleware<Props extends {
274
+ [key: string]: Validator;
275
+ }> extends WebMiddleware<{
276
+ readonly params: {
277
+ [K in keyof Props]: GetValidatorType<Props[K]>;
278
+ };
279
+ }> {
280
+ protected readonly props: Props;
281
+ constructor(props: Props);
282
+ toDocument(options: WebMiddlewareToDocument): void;
283
+ }
284
+ /**
285
+ * 验证路径参数。验证通过后可通过`ctx.params`获得结果
286
+ *
287
+ * ```typescript
288
+ * export const router = new Router();
289
+ *
290
+ * router.put('/users/:id', {
291
+ * mount: [
292
+ * params({
293
+ * id: rule.int().max(1000),
294
+ * }),
295
+ * ],
296
+ * action: async (ctx) => {
297
+ * console.log(ctx.params);
298
+ * },
299
+ * });
300
+ * ```
301
+ */
302
+ declare const params: <T extends {
303
+ [key: string]: P;
304
+ }, P extends Validator<unknown>>(fields: T) => WebParamMiddleware<T>;
305
+
306
+ export { Body, ExtraStringHeaderKeys, File, FileOptions, FileSizeUnit, FileValidator, HeaderKeys, OfficialStringHeaderKeys, StringArrayHeaderKeys, StringHeaderKeys, WebApp, WebAppOption, WebBodyMiddleware, WebChain, WebContext, WebMiddleware, WebMiddlewareToDocument, WebMiddlewareToken, WebParamMiddleware, WebQueryMiddleware, WebRequest, WebResponse, body, getContentType, params, query };
package/dist/index.js ADDED
@@ -0,0 +1,555 @@
1
+ // src/override/middleware.ts
2
+ import assert from "node:assert";
3
+ import { Middleware } from "@aomex/core";
4
+ var WebMiddleware = class extends Middleware {
5
+ toDocument(options) {
6
+ assert(options);
7
+ }
8
+ };
9
+ Middleware.register("web", WebMiddleware);
10
+
11
+ // src/override/chain.ts
12
+ import { Chain } from "@aomex/core";
13
+ var WebChain = class extends Chain {
14
+ };
15
+ Chain.register("web", WebChain);
16
+
17
+ // src/override/file-validator.ts
18
+ import { PersistentFile } from "formidable";
19
+ import mimeTypes from "mime-types";
20
+ import {
21
+ Validator,
22
+ magistrate,
23
+ Rule
24
+ } from "@aomex/core";
25
+ var FileValidator = class extends Validator {
26
+ /**
27
+ * @param {String} unit 默认单位:`B`,即字节
28
+ */
29
+ maxSize(amount, unit = "B") {
30
+ let scale;
31
+ switch (unit.toUpperCase()) {
32
+ case "B":
33
+ scale = 1;
34
+ break;
35
+ case "KB":
36
+ scale = 1024;
37
+ break;
38
+ case "MB":
39
+ scale = 1048576;
40
+ break;
41
+ case "GB":
42
+ scale = 1048576 * 1024;
43
+ break;
44
+ case "TB":
45
+ scale = 1048576 * 1048576;
46
+ }
47
+ this.config.maxSize = amount * scale;
48
+ return this;
49
+ }
50
+ mimeTypes(mineOrExt, ...others) {
51
+ this.config.mimeTypes = [
52
+ ...new Set(
53
+ [].concat(mineOrExt).concat(others).map(mimeTypes.contentType).filter(Boolean)
54
+ )
55
+ ];
56
+ return this;
57
+ }
58
+ isEmpty(value) {
59
+ return super.isEmpty(value) || Array.isArray(value) && !value.length;
60
+ }
61
+ validateValue(file, key, superKeys) {
62
+ const { maxSize, mimeTypes: mimeTypes3 } = this.config;
63
+ if (Array.isArray(file)) {
64
+ return magistrate.fail(
65
+ "use array validator for multiple files",
66
+ key,
67
+ superKeys
68
+ );
69
+ }
70
+ if (!(file instanceof PersistentFile)) {
71
+ return magistrate.fail("must be file", key, superKeys);
72
+ }
73
+ if (maxSize !== void 0 && file.size > maxSize) {
74
+ return magistrate.fail("file size is too large", key, superKeys);
75
+ }
76
+ if (mimeTypes3 && (!file.mimetype || !mimeTypes3.includes(file.mimetype))) {
77
+ return magistrate.fail("file not match mime-types", key, superKeys);
78
+ }
79
+ return magistrate.ok(file);
80
+ }
81
+ toDocument() {
82
+ return {
83
+ type: "string",
84
+ format: "binary"
85
+ };
86
+ }
87
+ };
88
+ Rule.register("file", FileValidator);
89
+
90
+ // src/app/context.ts
91
+ import assert2 from "node:assert";
92
+ import createHttpError from "http-errors";
93
+ var WebContext = class {
94
+ constructor(app, request, response) {
95
+ this.app = app;
96
+ this.request = request;
97
+ this.response = response;
98
+ request.app = response.app = app;
99
+ request.res = response;
100
+ request.ctx = response.ctx = this;
101
+ }
102
+ send(statusOrBody, body2) {
103
+ if (typeof statusOrBody === "number") {
104
+ assert2(
105
+ statusOrBody >= 100 && statusOrBody <= 999,
106
+ `invalid status code: ${statusOrBody}`
107
+ );
108
+ this.response.statusCode = statusOrBody;
109
+ } else {
110
+ body2 = statusOrBody;
111
+ }
112
+ if (body2 !== void 0) {
113
+ this.response.body = body2;
114
+ }
115
+ return this;
116
+ }
117
+ throw(arg, ...args) {
118
+ throw createHttpError(arg, ...args);
119
+ }
120
+ };
121
+
122
+ // src/app/app.ts
123
+ import { createServer } from "node:http";
124
+ import EventEmitter from "node:events";
125
+ import { EOL } from "node:os";
126
+ import { compose } from "@aomex/core";
127
+ import { color } from "@aomex/helper";
128
+
129
+ // src/app/request.ts
130
+ import { IncomingMessage } from "node:http";
131
+ import parseurl from "parseurl";
132
+ import qs from "qs";
133
+ import coBody from "co-body";
134
+ import formidable from "formidable";
135
+ import accepts from "accepts";
136
+ import typeIs from "type-is";
137
+ import contentType from "content-type";
138
+ var WebRequest = class extends IncomingMessage {
139
+ app;
140
+ res;
141
+ ctx;
142
+ params = {};
143
+ _query;
144
+ _body;
145
+ _accept;
146
+ get path() {
147
+ return parseurl(this).pathname;
148
+ }
149
+ get querystring() {
150
+ return parseurl(this).query;
151
+ }
152
+ get query() {
153
+ return this._query ||= qs.parse(this.querystring, {
154
+ comma: true,
155
+ ...this.app.options.queryParser
156
+ });
157
+ }
158
+ get body() {
159
+ if (this._body)
160
+ return Promise.resolve(this._body);
161
+ if (this.findContentType("multipart/*") !== null) {
162
+ const form = formidable({
163
+ hashAlgorithm: "md5",
164
+ keepExtensions: true,
165
+ maxFileSize: 1e3 * 1024 * 1024,
166
+ allowEmptyFiles: true
167
+ });
168
+ return this._body = new Promise((resolve, reject) => {
169
+ form.parse(this, (err, fields, files) => {
170
+ if (err)
171
+ return reject(err);
172
+ resolve({
173
+ ...fields,
174
+ ...files
175
+ });
176
+ });
177
+ });
178
+ }
179
+ return this._body = coBody(this, {
180
+ returnRawBody: false
181
+ });
182
+ }
183
+ get contentType() {
184
+ try {
185
+ return contentType.parse(this).type;
186
+ } catch {
187
+ return "";
188
+ }
189
+ }
190
+ findContentType(type, ...types) {
191
+ const result = typeIs(this, type, ...types);
192
+ return result === false ? null : result;
193
+ }
194
+ get accept() {
195
+ return this._accept || (this._accept = accepts(this));
196
+ }
197
+ };
198
+
199
+ // src/app/response.ts
200
+ import { ServerResponse } from "node:http";
201
+ import stream, { Stream } from "node:stream";
202
+ import statuses from "statuses";
203
+ import escapeHtml from "escape-html";
204
+ import encodeUrl from "encodeurl";
205
+ import destroy from "destroy";
206
+ import contentDisposition from "content-disposition";
207
+ import createHttpError2, { isHttpError } from "http-errors";
208
+ import { extname } from "node:path";
209
+ import { createReadStream } from "node:fs";
210
+
211
+ // src/util/get-content-type.ts
212
+ import mimeTypes2 from "mime-types";
213
+ import LRU from "lru-cache";
214
+ var cache = new LRU({
215
+ max: 100
216
+ });
217
+ var getContentType = (type) => {
218
+ let mimeType = cache.get(type);
219
+ if (!mimeType) {
220
+ mimeType = mimeTypes2.contentType(type);
221
+ cache.set(type, mimeType);
222
+ }
223
+ return mimeType;
224
+ };
225
+
226
+ // src/app/response.ts
227
+ import typeIs2 from "type-is";
228
+ var WebResponse = class extends ServerResponse {
229
+ app;
230
+ ctx;
231
+ _body = null;
232
+ _explicitBody = false;
233
+ constructor(req) {
234
+ super(req);
235
+ }
236
+ /**
237
+ * 批量设置头部数据
238
+ */
239
+ setHeaders(headers) {
240
+ for (const [key, value] of Object.entries(headers)) {
241
+ value !== void 0 && this.setHeader(key, value);
242
+ }
243
+ }
244
+ redirect(status, url) {
245
+ url = typeof url === "string" ? url : status.toString();
246
+ this.statusCode = typeof status === "string" ? 302 : status;
247
+ this.setHeader("location", encodeUrl(url));
248
+ if (this.req.accept.types("html")) {
249
+ url = escapeHtml(url);
250
+ this.contentType = "html";
251
+ this.body = `Redirecting to <a href="${url}">${url}</a>.`;
252
+ } else {
253
+ this.contentType = "text";
254
+ this.body = `Redirecting to ${url}.`;
255
+ }
256
+ }
257
+ download(filePath, options = {}) {
258
+ this.contentType = extname(filePath);
259
+ this.setHeader(
260
+ "content-disposition",
261
+ contentDisposition(filePath, options)
262
+ );
263
+ this.body = createReadStream(filePath);
264
+ }
265
+ get contentLength() {
266
+ const body2 = this._body;
267
+ if (statuses.empty[this.statusCode])
268
+ return 0;
269
+ if (body2 === null && !this.findContentType("json"))
270
+ return 0;
271
+ if (body2 instanceof Stream)
272
+ return -1;
273
+ if (typeof body2 === "string")
274
+ return Buffer.byteLength(body2);
275
+ if (Buffer.isBuffer(body2))
276
+ return body2.length;
277
+ return Buffer.byteLength(JSON.stringify(body2));
278
+ }
279
+ set contentLength(length) {
280
+ if (length >= 0 && !this.headersSent && !this.hasHeader("transfer-encoding")) {
281
+ this.setHeader("content-length", length);
282
+ }
283
+ }
284
+ get contentType() {
285
+ let type = this.getHeader("content-type");
286
+ type &&= type.split(";", 1)[0];
287
+ return type || "";
288
+ }
289
+ set contentType(typeOrFilenameOrExt) {
290
+ const mimeType = getContentType(typeOrFilenameOrExt);
291
+ if (mimeType === false) {
292
+ throw new Error(
293
+ `Fail to parse content type from literal "${typeOrFilenameOrExt}"`
294
+ );
295
+ }
296
+ if (!this.headersSent) {
297
+ this.setHeader("content-type", mimeType);
298
+ }
299
+ }
300
+ get body() {
301
+ return this._body;
302
+ }
303
+ set body(val) {
304
+ this._body = val;
305
+ this._explicitBody = true;
306
+ }
307
+ flush() {
308
+ if (!this.writable || this.headersSent)
309
+ return;
310
+ const { body: body2, req } = this;
311
+ const missContentType = !this.hasHeader("content-type");
312
+ const ok = (chunk2) => {
313
+ if (req.method === "HEAD") {
314
+ this.end();
315
+ } else {
316
+ this.end(chunk2);
317
+ }
318
+ };
319
+ if (statuses.empty[this.statusCode]) {
320
+ this.removeHeader("content-type");
321
+ this.removeHeader("content-length");
322
+ this.removeHeader("transfer-encoding");
323
+ return ok();
324
+ }
325
+ if (body2 === null && (missContentType || !this.findContentType("json"))) {
326
+ missContentType && (this.contentType = "text");
327
+ if (this._explicitBody) {
328
+ this.contentLength = 0;
329
+ return ok();
330
+ }
331
+ const msg = req.httpVersionMajor >= 2 ? String(this.statusCode) : this.statusMessage || String(this.statusCode);
332
+ this.contentLength = Buffer.byteLength(msg);
333
+ return ok(msg);
334
+ }
335
+ if (Buffer.isBuffer(body2)) {
336
+ missContentType && (this.contentType = "bin");
337
+ this.contentLength = body2.length;
338
+ return ok(body2);
339
+ }
340
+ if (typeof body2 === "string") {
341
+ missContentType && (this.contentType = /^\s*</.test(body2) ? "html" : "text");
342
+ this.contentLength = Buffer.byteLength(body2);
343
+ return ok(body2);
344
+ }
345
+ if (body2 instanceof Stream) {
346
+ if (req.method === "HEAD")
347
+ return;
348
+ missContentType && (this.contentType = "bin");
349
+ stream.finished(this, () => {
350
+ destroy(body2);
351
+ });
352
+ body2.once("error", this.onError).pipe(this);
353
+ return;
354
+ }
355
+ const chunk = JSON.stringify(body2);
356
+ missContentType && (this.contentType = "json");
357
+ this.contentLength = Buffer.byteLength(chunk);
358
+ return ok(chunk);
359
+ }
360
+ onError(error) {
361
+ if (error == null)
362
+ return;
363
+ let err;
364
+ if (!isHttpError(error)) {
365
+ err = createHttpError2(error);
366
+ } else {
367
+ err = error;
368
+ }
369
+ this.getHeaderNames().forEach(this.removeHeader.bind(this));
370
+ err.headers && this.setHeaders(err.headers);
371
+ const code = err.status || err.statusCode;
372
+ if (err["code"] === "ENOENT") {
373
+ this.statusCode = 404;
374
+ } else if (typeof code !== "number" || !statuses.message[code]) {
375
+ this.statusCode = 500;
376
+ } else {
377
+ this.statusCode = code;
378
+ }
379
+ this.app.emit("error", err, this.ctx);
380
+ const msg = err.expose ? err.message : statuses.message[this.statusCode];
381
+ const formatter = this.app.options.errorFormatter;
382
+ this.body = formatter ? formatter(msg, this.statusCode, { err, ctx: this.ctx }) : msg;
383
+ this.flush();
384
+ }
385
+ findContentType(type, ...types) {
386
+ const result = typeIs2.is(this.contentType, type, ...types);
387
+ return result === false ? null : result;
388
+ }
389
+ };
390
+
391
+ // src/app/app.ts
392
+ var WebApp = class extends EventEmitter {
393
+ constructor(options = {}) {
394
+ super();
395
+ this.options = options;
396
+ }
397
+ middlewareList = [];
398
+ listen = (...args) => {
399
+ const server = createServer(
400
+ {
401
+ IncomingMessage: WebRequest,
402
+ ServerResponse: WebResponse
403
+ },
404
+ this.callback()
405
+ );
406
+ return server.listen(...args);
407
+ };
408
+ callback() {
409
+ const fn = compose(this.middlewareList);
410
+ if (!this.listenerCount("error")) {
411
+ this.on("error", this.log);
412
+ }
413
+ return (req, res) => {
414
+ res.statusCode = 404;
415
+ const ctx = new WebContext(this, req, res);
416
+ return fn(ctx).then(res.flush.bind(res)).catch(res.onError.bind(res));
417
+ };
418
+ }
419
+ log(err) {
420
+ if ((err.status || err.statusCode) === 404 || err.expose)
421
+ return;
422
+ const msgs = (err.stack || err.toString()).split(EOL, 2);
423
+ console.error(
424
+ ["", color.bgRed(msgs.shift()), msgs.join(EOL), ""].join(EOL)
425
+ );
426
+ }
427
+ on(eventName, listener) {
428
+ return super.on(eventName, listener);
429
+ }
430
+ mount(middleware) {
431
+ this.middlewareList.push(middleware);
432
+ }
433
+ };
434
+
435
+ // src/middleware/body.ts
436
+ import {
437
+ validate,
438
+ Validator as Validator2,
439
+ rule,
440
+ ValidatorError
441
+ } from "@aomex/core";
442
+ var WebBodyMiddleware = class extends WebMiddleware {
443
+ constructor(props) {
444
+ super(async (ctx, next) => {
445
+ try {
446
+ ctx.body = await validate(ctx.request.body, props, {
447
+ throwIfError: true
448
+ });
449
+ return next();
450
+ } catch (e) {
451
+ ctx.throw(e instanceof ValidatorError ? 400 : 500, e);
452
+ }
453
+ });
454
+ this.props = props;
455
+ }
456
+ toDocument(options) {
457
+ const collector = options.pathItemInMethod;
458
+ collector.requestBody = {
459
+ content: {
460
+ "*/*": {
461
+ schema: Validator2.toDocument(rule.object(this.props)).schema
462
+ }
463
+ },
464
+ required: Object.values(this.props).some(
465
+ (validator) => Validator2.toDocument(validator).required
466
+ )
467
+ };
468
+ }
469
+ };
470
+ var body = (fields) => new WebBodyMiddleware(fields);
471
+
472
+ // src/middleware/query.ts
473
+ import {
474
+ validate as validate2,
475
+ Validator as Validator3,
476
+ ValidatorError as ValidatorError2
477
+ } from "@aomex/core";
478
+ var WebQueryMiddleware = class extends WebMiddleware {
479
+ constructor(props) {
480
+ super(async (ctx, next) => {
481
+ try {
482
+ ctx.query = await validate2(ctx.request.query, props, {
483
+ throwIfError: true
484
+ });
485
+ return next();
486
+ } catch (e) {
487
+ ctx.throw(e instanceof ValidatorError2 ? 400 : 500, e);
488
+ }
489
+ });
490
+ this.props = props;
491
+ }
492
+ toDocument(options) {
493
+ const collector = options.pathItemInMethod;
494
+ collector.parameters ||= [];
495
+ Object.entries(this.props).forEach(([name, validator]) => {
496
+ collector.parameters.push({
497
+ name,
498
+ in: "query",
499
+ ...Validator3.toDocument(validator)
500
+ });
501
+ });
502
+ }
503
+ };
504
+ var query = (fields) => new WebQueryMiddleware(fields);
505
+
506
+ // src/middleware/params.ts
507
+ import {
508
+ validate as validate3,
509
+ Validator as Validator4,
510
+ ValidatorError as ValidatorError3
511
+ } from "@aomex/core";
512
+ var WebParamMiddleware = class extends WebMiddleware {
513
+ constructor(props) {
514
+ super(async (ctx, next) => {
515
+ try {
516
+ ctx.params = await validate3(ctx.request.params, props, {
517
+ throwIfError: true
518
+ });
519
+ return next();
520
+ } catch (e) {
521
+ ctx.throw(e instanceof ValidatorError3 ? 400 : 500, e);
522
+ }
523
+ });
524
+ this.props = props;
525
+ }
526
+ toDocument(options) {
527
+ const collector = options.pathItemInMethod;
528
+ collector.parameters ||= [];
529
+ Object.entries(this.props).forEach(([name, validator]) => {
530
+ collector.parameters.push({
531
+ name,
532
+ in: "path",
533
+ ...Validator4.toDocument(validator)
534
+ });
535
+ });
536
+ }
537
+ };
538
+ var params = (fields) => new WebParamMiddleware(fields);
539
+ export {
540
+ FileValidator,
541
+ WebApp,
542
+ WebBodyMiddleware,
543
+ WebChain,
544
+ WebContext,
545
+ WebMiddleware,
546
+ WebParamMiddleware,
547
+ WebQueryMiddleware,
548
+ WebRequest,
549
+ WebResponse,
550
+ body,
551
+ getContentType,
552
+ params,
553
+ query
554
+ };
555
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/override/middleware.ts","../src/override/chain.ts","../src/override/file-validator.ts","../src/app/context.ts","../src/app/app.ts","../src/app/request.ts","../src/app/response.ts","../src/util/get-content-type.ts","../src/middleware/body.ts","../src/middleware/query.ts","../src/middleware/params.ts"],"sourcesContent":["import assert from 'node:assert';\nimport { Middleware, type Next, type OpenAPI } from '@aomex/core';\nimport type { NonReadonly } from '@aomex/helper';\nimport type { WebContext } from '../app/context';\n\ndeclare module '@aomex/core' {\n export interface MiddlewarePlatform {\n readonly web: <Props extends object = object>(\n fn: (ctx: NonReadonly<Props> & WebContext, next: Next) => any,\n ) => WebMiddleware<Props>;\n }\n}\n\nexport interface WebMiddlewareToDocument {\n document: OpenAPI.Document;\n pathItem?: OpenAPI.PathItemObject;\n pathItemInMethod?: OpenAPI.OperationObject;\n}\n\nexport class WebMiddleware<\n Props extends object = object,\n> extends Middleware<Props> {\n protected declare _web_middleware_: 'web-middleware';\n\n public toDocument(options: WebMiddlewareToDocument) {\n assert(options);\n }\n}\n\nMiddleware.register('web', WebMiddleware);\n","import { Chain, type PureChain, type PureMiddlewareToken } from '@aomex/core';\nimport type { WebMiddleware } from './middleware';\n\ndeclare module '@aomex/core' {\n export interface ChainPlatform {\n readonly web: WebChain;\n }\n}\n\nexport type WebMiddlewareToken<P extends object = object> =\n | WebMiddleware<P>\n | WebChain<P>\n | PureMiddlewareToken<P>;\n\nexport class WebChain<Props extends object = object> extends Chain<Props> {\n protected declare _web_chain_: 'web-chain';\n\n declare mount: {\n <P extends object>(\n middleware: WebChain | PureChain | WebMiddlewareToken<P> | null,\n ): WebChain<Props & P>;\n };\n}\n\nChain.register('web', WebChain);\n","import { PersistentFile, File as InternalFile } from 'formidable';\nimport mimeTypes from 'mime-types';\nimport {\n ValidatorOptions,\n Validator,\n TValidatorOptional,\n ValidatorTransformFn,\n TransformedValidator,\n ValidateResult,\n magistrate,\n OpenAPI,\n Rule,\n} from '@aomex/core';\n\ndeclare module '@aomex/core' {\n export interface Rule {\n file(): FileValidator;\n }\n}\n\nexport type FileSizeUnit =\n | 'B'\n | 'b'\n | 'KB'\n | 'kb'\n | 'MB'\n | 'mb'\n | 'GB'\n | 'gb'\n | 'TB'\n | 'tb';\n\nexport interface FileOptions<T> extends ValidatorOptions<T> {\n maxSize?: number;\n mimeTypes?: string[];\n}\n\nexport interface File extends InternalFile {\n hash: 'string';\n hashAlgorithm: 'md5';\n}\n\nexport class FileValidator<T = File> extends Validator<T> {\n protected declare config: FileOptions<T>;\n\n public declare optional: () => FileValidator<T | TValidatorOptional>;\n\n public declare transform: <T1>(\n fn: ValidatorTransformFn<T, T1>,\n ) => TransformedValidator<T1>;\n\n /**\n * @param {String} unit 默认单位:`B`,即字节\n */\n public maxSize(amount: number, unit: FileSizeUnit = 'B'): this {\n let scale;\n switch (unit.toUpperCase() as `${Uppercase<FileSizeUnit>}`) {\n case 'B':\n scale = 1;\n break;\n case 'KB':\n scale = 1024;\n break;\n case 'MB':\n scale = 1048576;\n break;\n case 'GB':\n scale = 1048576 * 1024;\n break;\n case 'TB':\n scale = 1048576 * 1048576;\n }\n this.config.maxSize = amount * scale;\n return this;\n }\n\n /**\n * 限制文件的`mime-type`。无论传入标准的格式还是普通的后缀,最终都会转换成标准的mime-types\n * ```typescript\n * file.mimeTypes('.html', '.js', 'image/*', 'text/plain');\n * ```\n */\n public mimeTypes(mineOrExt: string, ...others: string[]): this;\n public mimeTypes(mineOrExt: string[]): this;\n public mimeTypes(mineOrExt: string[] | string, ...others: string[]): this {\n this.config.mimeTypes = <string[]>[\n ...new Set(\n ([] as string[])\n .concat(mineOrExt)\n .concat(others)\n .map(mimeTypes.contentType)\n .filter(Boolean),\n ),\n ];\n return this;\n }\n\n protected override isEmpty(value: any): boolean {\n return super.isEmpty(value) || (Array.isArray(value) && !value.length);\n }\n\n protected validateValue(\n file: File,\n key: string,\n superKeys: string[],\n ): ValidateResult<File> {\n const { maxSize, mimeTypes } = this.config;\n\n if (Array.isArray(file)) {\n return magistrate.fail(\n 'use array validator for multiple files',\n key,\n superKeys,\n );\n }\n\n if (!(file instanceof PersistentFile)) {\n return magistrate.fail('must be file', key, superKeys);\n }\n\n if (maxSize !== void 0 && file.size > maxSize) {\n return magistrate.fail('file size is too large', key, superKeys);\n }\n\n if (mimeTypes && (!file.mimetype || !mimeTypes.includes(file.mimetype))) {\n return magistrate.fail('file not match mime-types', key, superKeys);\n }\n\n return magistrate.ok(file);\n }\n\n protected override toDocument(): OpenAPI.SchemaObject {\n return {\n type: 'string',\n format: 'binary',\n };\n }\n}\n\nRule.register('file', FileValidator);\n","import assert from 'node:assert';\nimport createHttpError from 'http-errors';\nimport type { WebApp } from './app';\nimport type { WebRequest } from './request';\nimport type { Body, WebResponse } from './response';\n\nexport class WebContext {\n constructor(\n readonly app: WebApp,\n readonly request: WebRequest,\n readonly response: WebResponse,\n ) {\n request.app = response.app = app;\n request.res = response;\n request.ctx = response.ctx = this;\n }\n\n send(statusCode: number, body?: Body): this;\n send(body: Body): this;\n send(statusOrBody: number | Body, body?: Body): this {\n if (typeof statusOrBody === 'number') {\n assert(\n statusOrBody >= 100 && statusOrBody <= 999,\n `invalid status code: ${statusOrBody}`,\n );\n this.response.statusCode = statusOrBody;\n } else {\n body = statusOrBody;\n }\n\n if (body !== void 0) {\n this.response.body = body;\n }\n\n return this;\n }\n\n /**\n * ```typescript\n * ctx.throw(403)\n * ctx.throw('name required', 400)\n * ctx.throw(400, 'name required')\n * ctx.throw('something exploded')\n * ctx.throw(new Error('invalid'), 400);\n * ctx.throw(400, new Error('invalid'));\n * ```\n * @link https://github.com/jshttp/http-errors\n * @throws {HttpError}\n * @see createHttpError.HttpError\n *\n */\n throw(statusCode: number, message?: string | Error, properties?: {}): never;\n throw(message: string | Error, statusCode?: number, properties?: {}): never;\n throw(arg: any, ...properties: Array<number | string | {}>): never;\n throw(arg: any, ...args: any[]): never {\n throw createHttpError(arg, ...args);\n }\n}\n","import { createServer, RequestListener, Server } from 'node:http';\nimport EventEmitter from 'node:events';\nimport { EOL } from 'node:os';\nimport { compose } from '@aomex/core';\nimport { color } from '@aomex/helper';\nimport type { HttpError } from 'http-errors';\nimport type { IParseOptions } from 'qs';\nimport { WebContext } from '../app/context';\nimport type { WebChain, WebMiddlewareToken } from '../override/chain';\nimport { WebRequest } from './request';\nimport { type Body, WebResponse } from './response';\n\nexport interface WebAppOption {\n globalChain?: WebChain;\n queryParser?: IParseOptions;\n errorFormatter?: (\n msg: string,\n statusCode: number,\n helper: { err: HttpError; ctx: WebContext },\n ) => Body;\n}\n\nexport class WebApp extends EventEmitter {\n constructor(readonly options: WebAppOption = {}) {\n super();\n }\n\n protected readonly middlewareList: WebMiddlewareToken[] = [];\n\n public listen: Server['listen'] = (...args: any[]) => {\n const server = createServer(\n {\n IncomingMessage: WebRequest,\n ServerResponse: WebResponse,\n },\n this.callback(),\n );\n return server.listen(...args);\n };\n\n public callback(): RequestListener<any, any> {\n const fn = compose(this.middlewareList);\n\n if (!this.listenerCount('error')) {\n this.on('error', this.log);\n }\n\n return (req: WebRequest, res: WebResponse) => {\n res.statusCode = 404;\n const ctx = new WebContext(this, req, res);\n\n return fn(ctx).then(res.flush.bind(res)).catch(res.onError.bind(res));\n };\n }\n\n public log(err: HttpError) {\n if ((err.status || err.statusCode) === 404 || err.expose) return;\n const msgs = (err.stack || err.toString()).split(EOL, 2);\n console.error(\n ['', color.bgRed(msgs.shift()), msgs.join(EOL), ''].join(EOL),\n );\n }\n\n public override on(\n eventName: 'error',\n listener: (err: HttpError, ctx: WebContext) => void,\n ): this;\n public override on(\n eventName: string | symbol,\n listener: (...args: any[]) => void,\n ): this {\n return super.on(eventName, listener);\n }\n\n public mount(middleware: WebMiddlewareToken): void {\n this.middlewareList.push(middleware);\n }\n}\n","import { IncomingMessage } from 'node:http';\nimport parseurl from 'parseurl';\nimport qs from 'qs';\nimport coBody from 'co-body';\nimport formidable from 'formidable';\nimport accepts, { Accepts } from 'accepts';\nimport typeIs from 'type-is';\nimport contentType from 'content-type';\nimport type { WebApp } from './app';\nimport type { WebContext } from './context';\nimport type { WebResponse } from './response';\nimport type { ExtraStringHeaderKeys } from './header';\n\nexport class WebRequest extends IncomingMessage {\n app!: WebApp;\n res!: WebResponse;\n ctx!: WebContext;\n\n declare readonly method: string;\n declare readonly url: string;\n\n public params: Record<string, unknown> = {};\n protected _query?: any;\n protected _body?: any;\n protected _accept?: Accepts;\n\n get path(): string {\n return parseurl(this)!.pathname!;\n }\n\n get querystring(): string {\n return parseurl(this)!.query as string;\n }\n\n public get query(): Record<string, unknown> {\n return (this._query ||= qs.parse(this.querystring, {\n comma: true,\n ...this.app.options.queryParser,\n }));\n }\n\n public get body(): Promise<unknown> {\n if (this._body) return Promise.resolve(this._body);\n\n if (this.findContentType('multipart/*') !== null) {\n const form = formidable({\n hashAlgorithm: 'md5',\n keepExtensions: true,\n maxFileSize: 1000 * 1024 * 1024,\n allowEmptyFiles: true,\n });\n\n return (this._body = new Promise((resolve, reject) => {\n form.parse(this, (err, fields, files) => {\n if (err) return reject(err);\n\n resolve({\n ...fields,\n ...files,\n });\n });\n }));\n }\n\n return (this._body = coBody(this, {\n returnRawBody: false,\n }));\n }\n\n get contentType(): string {\n try {\n return contentType.parse(this).type;\n } catch {\n return '';\n }\n }\n\n public findContentType(type: string, ...types: string[]): string | null {\n const result = typeIs(this, type, ...types);\n return result === false ? null : result;\n }\n\n get accept(): Accepts {\n return this._accept || (this._accept = accepts(this));\n }\n}\n\ndeclare module 'node:http' {\n type ExtraHeaders = {\n [K in ExtraStringHeaderKeys]?: string;\n };\n\n interface IncomingHttpHeaders extends ExtraHeaders {}\n}\n","import { ServerResponse } from 'node:http';\nimport stream, { Stream } from 'node:stream';\nimport statuses from 'statuses';\nimport escapeHtml from 'escape-html';\nimport encodeUrl from 'encodeurl';\nimport destroy from 'destroy';\nimport contentDisposition from 'content-disposition';\nimport createHttpError, { type HttpError, isHttpError } from 'http-errors';\nimport type { WebApp } from './app';\nimport type { WebContext } from './context';\nimport type {\n StringHeaderKeys,\n StringArrayHeaderKeys,\n HeaderKeys,\n} from './header';\nimport type { WebRequest } from '../app/request';\nimport { extname } from 'node:path';\nimport { createReadStream } from 'node:fs';\nimport { getContentType } from '../util/get-content-type';\nimport typeIs from 'type-is';\n\nexport type Body = string | object | Stream | Buffer | null;\n\nexport class WebResponse<\n Request extends WebRequest = WebRequest,\n> extends ServerResponse<Request> {\n app!: WebApp;\n ctx!: WebContext;\n protected _body: Body = null;\n protected _explicitBody: boolean = false;\n\n constructor(req: Request) {\n super(req);\n }\n\n declare readonly setHeader: {\n <T extends WebResponse>(name: StringHeaderKeys, value: number | string): T;\n <T extends WebResponse>(\n name: StringArrayHeaderKeys,\n value: readonly string[],\n ): T;\n <T extends WebResponse>(\n name: string,\n value: number | string | readonly string[],\n ): T;\n };\n\n declare readonly getHeader: {\n (name: StringHeaderKeys): string | undefined;\n (name: StringArrayHeaderKeys): string[] | undefined;\n (name: string): string | string[] | undefined;\n };\n\n declare readonly hasHeader: {\n (name: HeaderKeys): boolean;\n (name: string): boolean;\n };\n\n declare readonly removeHeader: {\n (name: HeaderKeys): void;\n (name: string): void;\n };\n\n /**\n * 批量设置头部数据\n */\n setHeaders(\n headers: {\n [K: string]: string | number | readonly string[];\n } & { [K in StringHeaderKeys]?: string | number } & {\n [K in StringArrayHeaderKeys]?: readonly string[];\n },\n ): void {\n for (const [key, value] of Object.entries(headers)) {\n value !== undefined && this.setHeader(key, value);\n }\n }\n\n redirect(url: string): void;\n redirect(\n statusCode: 300 | 301 | 302 | 303 | 305 | 307 | 308,\n url: string,\n ): void;\n redirect(status: number | string, url?: string): void {\n url = typeof url === 'string' ? url : status.toString();\n this.statusCode = typeof status === 'string' ? 302 : status;\n this.setHeader('location', encodeUrl(url));\n\n if (this.req.accept.types('html')) {\n url = escapeHtml(url);\n this.contentType = 'html';\n this.body = `Redirecting to <a href=\"${url}\">${url}</a>.`;\n } else {\n this.contentType = 'text';\n this.body = `Redirecting to ${url}.`;\n }\n }\n\n public download(\n filePath: string,\n options: contentDisposition.Options = {},\n ): void {\n this.contentType = extname(filePath);\n this.setHeader(\n 'content-disposition',\n contentDisposition(filePath, options),\n );\n this.body = createReadStream(filePath);\n }\n\n get contentLength(): number {\n const body = this._body;\n\n if (statuses.empty[this.statusCode]) return 0;\n if (body === null && !this.findContentType('json')) return 0;\n if (body instanceof Stream) return -1;\n if (typeof body === 'string') return Buffer.byteLength(body);\n if (Buffer.isBuffer(body)) return body.length;\n return Buffer.byteLength(JSON.stringify(body));\n }\n\n set contentLength(length: number) {\n if (\n length >= 0 &&\n !this.headersSent &&\n !this.hasHeader('transfer-encoding')\n ) {\n this.setHeader('content-length', length);\n }\n }\n\n get contentType(): string {\n let type = this.getHeader('content-type');\n type &&= type.split(';', 1)[0];\n return type || '';\n }\n\n set contentType(typeOrFilenameOrExt: string) {\n const mimeType = getContentType(typeOrFilenameOrExt);\n if (mimeType === false) {\n throw new Error(\n `Fail to parse content type from literal \"${typeOrFilenameOrExt}\"`,\n );\n }\n\n if (!this.headersSent) {\n this.setHeader('content-type', mimeType);\n }\n }\n\n get body(): Body {\n return this._body;\n }\n\n set body(val: Body) {\n this._body = val;\n this._explicitBody = true;\n }\n\n flush() {\n if (!this.writable || this.headersSent) return;\n\n const { body, req } = this;\n const missContentType = !this.hasHeader('content-type');\n\n const ok = (chunk?: any) => {\n if (req.method === 'HEAD') {\n this.end();\n } else {\n this.end(chunk);\n }\n };\n\n if (statuses.empty[this.statusCode]) {\n this.removeHeader('content-type');\n this.removeHeader('content-length');\n this.removeHeader('transfer-encoding');\n return ok();\n }\n\n if (body === null && (missContentType || !this.findContentType('json'))) {\n missContentType && (this.contentType = 'text');\n\n if (this._explicitBody) {\n this.contentLength = 0;\n return ok();\n }\n\n const msg =\n req.httpVersionMajor >= 2\n ? String(this.statusCode)\n : this.statusMessage || String(this.statusCode);\n this.contentLength = Buffer.byteLength(msg);\n return ok(msg);\n }\n\n if (Buffer.isBuffer(body)) {\n missContentType && (this.contentType = 'bin');\n this.contentLength = body.length;\n return ok(body);\n }\n\n if (typeof body === 'string') {\n missContentType &&\n (this.contentType = /^\\s*</.test(body) ? 'html' : 'text');\n this.contentLength = Buffer.byteLength(body);\n return ok(body);\n }\n\n if (body instanceof Stream) {\n if (req.method === 'HEAD') return;\n missContentType && (this.contentType = 'bin');\n stream.finished(this, () => {\n destroy(body);\n });\n body.once('error', this.onError).pipe(this);\n return;\n }\n\n const chunk = JSON.stringify(body);\n missContentType && (this.contentType = 'json');\n this.contentLength = Buffer.byteLength(chunk);\n return ok(chunk);\n }\n\n onError(error?: Error | HttpError | null) {\n if (error == null) return;\n\n let err: HttpError;\n if (!isHttpError(error)) {\n err = createHttpError(error);\n } else {\n err = error;\n }\n\n this.getHeaderNames().forEach(this.removeHeader.bind(this));\n err.headers && this.setHeaders(err.headers);\n\n const code = err.status || err.statusCode;\n if (err['code'] === 'ENOENT') {\n this.statusCode = 404;\n } else if (typeof code !== 'number' || !statuses.message[code]) {\n this.statusCode = 500;\n } else {\n this.statusCode = code;\n }\n\n this.app.emit('error', err, this.ctx);\n\n const msg = err.expose ? err.message : statuses.message[this.statusCode]!;\n const formatter = this.app.options.errorFormatter;\n this.body = formatter\n ? formatter(msg, this.statusCode, { err: err, ctx: this.ctx })\n : msg;\n this.flush();\n }\n\n public findContentType(type: string, ...types: string[]): string | null {\n const result = typeIs.is(this.contentType, type, ...types);\n return result === false ? null : result;\n }\n}\n","import mimeTypes from 'mime-types';\nimport LRU from 'lru-cache';\n\nconst cache = new LRU<string, string | false>({\n max: 100,\n});\n\nexport const getContentType = (type: string): string | false => {\n let mimeType: string | false | undefined = cache.get(type);\n\n if (!mimeType) {\n mimeType = mimeTypes.contentType(type);\n cache.set(type, mimeType);\n }\n\n return mimeType;\n};\n","import {\n validate,\n Validator,\n GetValidatorType,\n rule,\n ValidatorError,\n} from '@aomex/core';\nimport { WebMiddleware, WebMiddlewareToDocument } from '../override';\n\nexport class WebBodyMiddleware<\n Props extends { [key: string]: Validator },\n> extends WebMiddleware<{\n readonly body: { [K in keyof Props]: GetValidatorType<Props[K]> };\n}> {\n constructor(protected readonly props: Props) {\n super(async (ctx, next) => {\n try {\n ctx.body = await validate(ctx.request.body, props, {\n throwIfError: true,\n });\n return next();\n } catch (e) {\n ctx.throw(e instanceof ValidatorError ? 400 : 500, e);\n }\n });\n }\n\n public override toDocument(options: WebMiddlewareToDocument): void {\n const collector = options.pathItemInMethod!;\n collector.requestBody = {\n content: {\n '*/*': {\n schema: Validator.toDocument(rule.object(this.props)).schema,\n },\n },\n required: Object.values(this.props).some(\n (validator) => Validator.toDocument(validator).required,\n ),\n };\n }\n}\n\n/**\n * 对请求时的body数据做验证。验证通过后可通过`ctx.body`获得结果\n *\n * ```typescript\n * export const router = new Router();\n *\n * router.post('/users', {\n * mount: [\n * body({\n * name: rule.string(),\n * age: rule.int().optional(),\n * }),\n * ],\n * action: async (ctx) => {\n * console.log(ctx.body);\n * },\n * });\n * ```\n */\nexport const body = <T extends { [key: string]: P }, P extends Validator>(\n fields: T,\n) => new WebBodyMiddleware<T>(fields);\n","import {\n validate,\n Validator,\n GetValidatorType,\n ValidatorError,\n} from '@aomex/core';\nimport { WebMiddleware, WebMiddlewareToDocument } from '../override';\n\nexport class WebQueryMiddleware<\n Props extends { [key: string]: Validator },\n> extends WebMiddleware<{\n readonly query: { [K in keyof Props]: GetValidatorType<Props[K]> };\n}> {\n constructor(protected readonly props: Props) {\n super(async (ctx, next) => {\n try {\n ctx.query = await validate(ctx.request.query, props, {\n throwIfError: true,\n });\n return next();\n } catch (e) {\n ctx.throw(e instanceof ValidatorError ? 400 : 500, e);\n }\n });\n }\n\n public override toDocument(options: WebMiddlewareToDocument): void {\n const collector = options.pathItemInMethod!;\n collector.parameters ||= [];\n Object.entries(this.props).forEach(([name, validator]) => {\n collector.parameters!.push({\n name,\n in: 'query',\n ...Validator.toDocument(validator),\n });\n });\n }\n}\n\n/**\n * 对url上的查询字符串做验证。验证通过后可通过`ctx.query`获得结果\n *\n * ```typescript\n * export const router = new Router();\n *\n * // https://example.com/users?search=lili&page=1\n * router.get('/users', {\n * mount: [\n * query({\n * search: rule.string().optional(),\n * page: rule.int().min(1).default(1),\n * pageSize: rule.int().min(5).default(10),\n * }),\n * ],\n * action: async (ctx) => {\n * console.log(ctx.query);\n * },\n * });\n * ```\n */\nexport const query = <T extends { [key: string]: P }, P extends Validator>(\n fields: T,\n) => new WebQueryMiddleware<T>(fields);\n","import {\n validate,\n Validator,\n GetValidatorType,\n ValidatorError,\n} from '@aomex/core';\nimport { WebMiddleware, WebMiddlewareToDocument } from '../override';\n\nexport class WebParamMiddleware<\n Props extends { [key: string]: Validator },\n> extends WebMiddleware<{\n readonly params: { [K in keyof Props]: GetValidatorType<Props[K]> };\n}> {\n constructor(protected readonly props: Props) {\n super(async (ctx, next) => {\n try {\n ctx.params = await validate(ctx.request.params, props, {\n throwIfError: true,\n });\n return next();\n } catch (e) {\n ctx.throw(e instanceof ValidatorError ? 400 : 500, e);\n }\n });\n }\n\n public override toDocument(options: WebMiddlewareToDocument): void {\n const collector = options.pathItemInMethod!;\n collector.parameters ||= [];\n Object.entries(this.props).forEach(([name, validator]) => {\n collector.parameters!.push({\n name,\n in: 'path',\n ...Validator.toDocument(validator),\n });\n });\n }\n}\n\n/**\n * 验证路径参数。验证通过后可通过`ctx.params`获得结果\n *\n * ```typescript\n * export const router = new Router();\n *\n * router.put('/users/:id', {\n * mount: [\n * params({\n * id: rule.int().max(1000),\n * }),\n * ],\n * action: async (ctx) => {\n * console.log(ctx.params);\n * },\n * });\n * ```\n */\nexport const params = <T extends { [key: string]: P }, P extends Validator>(\n fields: T,\n) => new WebParamMiddleware<T>(fields);\n"],"mappings":";AAAA,OAAO,YAAY;AACnB,SAAS,kBAA2C;AAkB7C,IAA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EAW/B;AAAA,EAEgB,WAAW,SAAwC;AACjE,UAAM,YAAY,QAAQ;AAC1B,cAAU,eAAe,CAAC;AAC1B,WAAO,QAAQ,KAAK,KAAK,EAAE,QAAQ,CAAC,CAAC,MAAM,SAAS,MAAM;AACxD,gBAAU,WAAY,KAAK;AAAA,QACzB;AAAA,QACA,IAAI;AAAA,QACJ,GAAGC,WAAU,WAAW,SAAS;AAAA,MACnC,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACF;AAuBO,IAAM,QAAQ,CACnB,WACG,IAAI,mBAAsB,MAAM;;;AC9DrC;AAAA,EACE,YAAAC;AAAA,EACA,aAAAC;AAAA,EAEA,kBAAAC;AAAA,OACK;AAGA,IAAM,qBAAN,cAEG,cAEP;AAAA,EACD,YAA+B,OAAc;AAC3C,UAAM,OAAO,KAAK,SAAS;AACzB,UAAI;AACF,YAAI,SAAS,MAAMC,UAAS,IAAI,QAAQ,QAAQ,OAAO;AAAA,UACrD,cAAc;AAAA,QAChB,CAAC;AACD,eAAO,KAAK;AAAA,MACd,SAAS,GAAP;AACA,YAAI,MAAM,aAAaC,kBAAiB,MAAM,KAAK,CAAC;AAAA,MACtD;AAAA,IACF,CAAC;AAV4B;AAAA,EAW/B;AAAA,EAEgB,WAAW,SAAwC;AACjE,UAAM,YAAY,QAAQ;AAC1B,cAAU,eAAe,CAAC;AAC1B,WAAO,QAAQ,KAAK,KAAK,EAAE,QAAQ,CAAC,CAAC,MAAM,SAAS,MAAM;AACxD,gBAAU,WAAY,KAAK;AAAA,QACzB;AAAA,QACA,IAAI;AAAA,QACJ,GAAGC,WAAU,WAAW,SAAS;AAAA,MACnC,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACF;AAoBO,IAAM,SAAS,CACpB,WACG,IAAI,mBAAsB,MAAM;","names":["mimeTypes","assert","body","createHttpError","mimeTypes","typeIs","body","chunk","createHttpError","Validator","Validator","validate","Validator","ValidatorError","validate","ValidatorError","Validator","validate","Validator","ValidatorError","validate","ValidatorError","Validator"]}
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@aomex/web",
3
+ "version": "0.0.0",
4
+ "description": "",
5
+ "type": "module",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js"
11
+ },
12
+ "./package.json": "./package.json"
13
+ },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "LICENSE",
20
+ "package.json",
21
+ "README.md",
22
+ "CHANGELOG.md"
23
+ ],
24
+ "keywords": [],
25
+ "author": "geekact",
26
+ "license": "MIT",
27
+ "peerDependencies": {
28
+ "@aomex/core": "^0.0.0"
29
+ },
30
+ "dependencies": {
31
+ "@aomex/helper": "^0.0.0",
32
+ "@types/content-disposition": "^0.5.5",
33
+ "@types/qs": "^6.9.7",
34
+ "accepts": "^1.3.8",
35
+ "co-body": "^6.1.0",
36
+ "content-disposition": "^0.5.4",
37
+ "content-type": "^1.0.5",
38
+ "destroy": "^1.2.0",
39
+ "encodeurl": "^1.0.2",
40
+ "escape-html": "^1.0.3",
41
+ "formidable": "^3.2.5",
42
+ "http-errors": "^2.0.0",
43
+ "lru-cache": "^7.14.1",
44
+ "mime-types": "^2.1.35",
45
+ "parseurl": "^1.3.3",
46
+ "qs": "^6.11.0",
47
+ "statuses": "^2.0.1",
48
+ "type-is": "^1.6.18"
49
+ },
50
+ "devDependencies": {
51
+ "@types/accepts": "^1.3.5",
52
+ "@types/co-body": "^6.1.0",
53
+ "@types/content-type": "^1.1.5",
54
+ "@types/destroy": "^1.0.0",
55
+ "@types/encodeurl": "^1.0.0",
56
+ "@types/escape-html": "^1.0.2",
57
+ "@types/formidable": "^2.0.5",
58
+ "@types/http-errors": "^2.0.1",
59
+ "@types/mime-types": "^2.1.1",
60
+ "@types/parseurl": "^1.3.1",
61
+ "@types/statuses": "^2.0.1",
62
+ "@types/type-is": "^1.6.3",
63
+ "@aomex/core": "^0.0.0"
64
+ },
65
+ "scripts": {}
66
+ }