@aomex/web 0.0.3 → 0.0.4
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/CHANGELOG.md +17 -0
- package/dist/index.d.ts +69 -54
- package/dist/index.js +168 -117
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# @aomex/web
|
|
2
2
|
|
|
3
|
+
## 0.0.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [`121253a`](https://github.com/aomex/aomex/commit/121253a6fc203e427bfd25e82d713bec6ac13b38) Thanks [@geekact](https://github.com/geekact)! - middleware 增加构造函数
|
|
8
|
+
|
|
9
|
+
- [`59dc183`](https://github.com/aomex/aomex/commit/59dc183bcec9b7221c18865563b38cba5d82869b) Thanks [@geekact](https://github.com/geekact)! - 增加 response 中间件
|
|
10
|
+
|
|
11
|
+
- [`8cb74fd`](https://github.com/aomex/aomex/commit/8cb74fdd27626037aa9bc80cb2930e4f0d67f8e6) Thanks [@geekact](https://github.com/geekact)! - middleware 增加 skipIf 方法
|
|
12
|
+
|
|
13
|
+
- [`d834392`](https://github.com/aomex/aomex/commit/d834392b1e0f6333d66d11378d9f4ceb813a58a9) Thanks [@geekact](https://github.com/geekact)! - 导出通用的 skip 函数
|
|
14
|
+
|
|
15
|
+
- [`91feda4`](https://github.com/aomex/aomex/commit/91feda457dfa8bd8dd2c8f38bfaaf4f7f2f7702f) Thanks [@geekact](https://github.com/geekact)! - 重命名 pathItemInMethod 为 methodItem
|
|
16
|
+
|
|
17
|
+
- Updated dependencies []:
|
|
18
|
+
- @aomex/core@0.0.3
|
|
19
|
+
|
|
3
20
|
## 0.0.3
|
|
4
21
|
|
|
5
22
|
### Patch Changes
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Chain, PureChain, PureMiddlewareToken, Next, Middleware, OpenAPI,
|
|
1
|
+
import { Chain, PureChain, PureMiddlewareToken, Validator, GetValidatorType, Next, Middleware, OpenAPI, TValidatorOptional, ValidatorTransformFn, TransformedValidator, ValidateResult, ValidatorOptions } from '@aomex/core';
|
|
2
2
|
import { NonReadonly } from '@aomex/helper';
|
|
3
3
|
import { IncomingMessage, ServerResponse, Server, RequestListener } from 'node:http';
|
|
4
4
|
import EventEmitter from 'node:events';
|
|
@@ -159,58 +159,6 @@ declare class WebContext {
|
|
|
159
159
|
throw(arg: any, ...properties: Array<number | string | {}>): never;
|
|
160
160
|
}
|
|
161
161
|
|
|
162
|
-
declare module '@aomex/core' {
|
|
163
|
-
interface MiddlewarePlatform {
|
|
164
|
-
readonly web: <Props extends object = object>(fn: (ctx: NonReadonly<Props> & WebContext, next: Next) => any) => WebMiddleware<Props>;
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
interface WebMiddlewareToDocument {
|
|
168
|
-
document: OpenAPI.Document;
|
|
169
|
-
pathItem?: OpenAPI.PathItemObject;
|
|
170
|
-
pathItemInMethod?: OpenAPI.OperationObject;
|
|
171
|
-
}
|
|
172
|
-
declare class WebMiddleware<Props extends object = object> extends Middleware<Props> {
|
|
173
|
-
protected _web_middleware_: 'web-middleware';
|
|
174
|
-
toDocument(options: WebMiddlewareToDocument): void;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
declare module '@aomex/core' {
|
|
178
|
-
interface Rule {
|
|
179
|
-
file(): FileValidator;
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
type FileSizeUnit = 'B' | 'b' | 'KB' | 'kb' | 'MB' | 'mb' | 'GB' | 'gb' | 'TB' | 'tb';
|
|
183
|
-
interface FileOptions<T> extends ValidatorOptions<T> {
|
|
184
|
-
maxSize?: number;
|
|
185
|
-
mimeTypes?: string[];
|
|
186
|
-
}
|
|
187
|
-
interface File extends File$1 {
|
|
188
|
-
hash: 'string';
|
|
189
|
-
hashAlgorithm: 'md5';
|
|
190
|
-
}
|
|
191
|
-
declare class FileValidator<T = File> extends Validator<T> {
|
|
192
|
-
protected config: FileOptions<T>;
|
|
193
|
-
optional: () => FileValidator<T | TValidatorOptional>;
|
|
194
|
-
transform: <T1>(fn: ValidatorTransformFn<T, T1>) => TransformedValidator<T1>;
|
|
195
|
-
/**
|
|
196
|
-
* @param {String} unit 默认单位:`B`,即字节
|
|
197
|
-
*/
|
|
198
|
-
maxSize(amount: number, unit?: FileSizeUnit): this;
|
|
199
|
-
/**
|
|
200
|
-
* 限制文件的`mime-type`。无论传入标准的格式还是普通的后缀,最终都会转换成标准的mime-types
|
|
201
|
-
* ```typescript
|
|
202
|
-
* file.mimeTypes('.html', '.js', 'image/*', 'text/plain');
|
|
203
|
-
* ```
|
|
204
|
-
*/
|
|
205
|
-
mimeTypes(mineOrExt: string, ...others: string[]): this;
|
|
206
|
-
mimeTypes(mineOrExt: string[]): this;
|
|
207
|
-
protected isEmpty(value: any): boolean;
|
|
208
|
-
protected validateValue(file: File, key: string, superKeys: string[]): ValidateResult<File>;
|
|
209
|
-
protected toDocument(): OpenAPI.SchemaObject;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
declare const getContentType: (type: string) => string | false;
|
|
213
|
-
|
|
214
162
|
declare class WebBodyMiddleware<Props extends {
|
|
215
163
|
[key: string]: Validator;
|
|
216
164
|
}> extends WebMiddleware<{
|
|
@@ -314,4 +262,71 @@ declare const params: <T extends {
|
|
|
314
262
|
[key: string]: P;
|
|
315
263
|
}, P extends Validator<unknown>>(fields: T) => WebParamMiddleware<T>;
|
|
316
264
|
|
|
317
|
-
|
|
265
|
+
interface WebMiddlewareSkipOptions {
|
|
266
|
+
custom?: (ctx: WebContext) => boolean | Promise<boolean>;
|
|
267
|
+
path?: string | RegExp | (string | RegExp)[];
|
|
268
|
+
ext?: string | string[];
|
|
269
|
+
method?: string | string[];
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* 跳过指定web插件或者web插件集合
|
|
273
|
+
* @param token web插件或者web插件集合
|
|
274
|
+
* @param options 跳过条件,不传则代表`总是跳过`
|
|
275
|
+
*/
|
|
276
|
+
declare const skip: <Props extends object = object>(token: WebMiddlewareToken<Props>, options?: WebMiddlewareSkipOptions | NonNullable<WebMiddlewareSkipOptions['custom']>) => WebMiddleware<Props>;
|
|
277
|
+
|
|
278
|
+
declare module '@aomex/core' {
|
|
279
|
+
interface MiddlewarePlatform {
|
|
280
|
+
readonly web: <Props extends object = object>(fn: (ctx: NonReadonly<Props> & WebContext, next: Next) => any) => WebMiddleware<Props>;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
interface WebMiddlewareToDocument {
|
|
284
|
+
document: OpenAPI.Document;
|
|
285
|
+
pathItem?: OpenAPI.PathItemObject;
|
|
286
|
+
methodItem?: OpenAPI.OperationObject;
|
|
287
|
+
}
|
|
288
|
+
declare class WebMiddleware<Props extends object = object> extends Middleware<Props> {
|
|
289
|
+
protected _web_middleware_: 'web-middleware';
|
|
290
|
+
constructor(fn: (ctx: NonReadonly<Props> & WebContext, next: Next) => any);
|
|
291
|
+
skipIf(options: WebMiddlewareSkipOptions | NonNullable<WebMiddlewareSkipOptions['custom']>): WebMiddleware<Props>;
|
|
292
|
+
toDocument(options: WebMiddlewareToDocument): void;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
declare module '@aomex/core' {
|
|
296
|
+
interface Rule {
|
|
297
|
+
file(): FileValidator;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
type FileSizeUnit = 'B' | 'b' | 'KB' | 'kb' | 'MB' | 'mb' | 'GB' | 'gb' | 'TB' | 'tb';
|
|
301
|
+
interface FileOptions<T> extends ValidatorOptions<T> {
|
|
302
|
+
maxSize?: number;
|
|
303
|
+
mimeTypes?: string[];
|
|
304
|
+
}
|
|
305
|
+
interface File extends File$1 {
|
|
306
|
+
hash: 'string';
|
|
307
|
+
hashAlgorithm: 'md5';
|
|
308
|
+
}
|
|
309
|
+
declare class FileValidator<T = File> extends Validator<T> {
|
|
310
|
+
protected config: FileOptions<T>;
|
|
311
|
+
optional: () => FileValidator<T | TValidatorOptional>;
|
|
312
|
+
transform: <T1>(fn: ValidatorTransformFn<T, T1>) => TransformedValidator<T1>;
|
|
313
|
+
/**
|
|
314
|
+
* @param {String} unit 默认单位:`B`,即字节
|
|
315
|
+
*/
|
|
316
|
+
maxSize(amount: number, unit?: FileSizeUnit): this;
|
|
317
|
+
/**
|
|
318
|
+
* 限制文件的`mime-type`。无论传入标准的格式还是普通的后缀,最终都会转换成标准的mime-types
|
|
319
|
+
* ```typescript
|
|
320
|
+
* file.mimeTypes('.html', '.js', 'image/*', 'text/plain');
|
|
321
|
+
* ```
|
|
322
|
+
*/
|
|
323
|
+
mimeTypes(mineOrExt: string, ...others: string[]): this;
|
|
324
|
+
mimeTypes(mineOrExt: string[]): this;
|
|
325
|
+
protected isEmpty(value: any): boolean;
|
|
326
|
+
protected validateValue(file: File, key: string, superKeys: string[]): ValidateResult<File>;
|
|
327
|
+
protected toDocument(): OpenAPI.SchemaObject;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
declare const getContentType: (type: string) => string | false;
|
|
331
|
+
|
|
332
|
+
export { Body, ExtraStringHeaderKeys, File, FileOptions, FileSizeUnit, FileValidator, HeaderKeys, OfficialStringHeaderKeys, StringArrayHeaderKeys, StringHeaderKeys, WebApp, WebAppOption, WebBodyMiddleware, WebChain, WebContext, WebMiddleware, WebMiddlewareSkipOptions, WebMiddlewareToDocument, WebMiddlewareToken, WebParamMiddleware, WebQueryMiddleware, WebRequest, WebResponse, body, getContentType, params, query, skip };
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,167 @@
|
|
|
1
1
|
// src/override/middleware.ts
|
|
2
2
|
import assert from "node:assert";
|
|
3
|
-
import { Middleware } from "@aomex/core";
|
|
4
|
-
|
|
3
|
+
import { Middleware as Middleware2 } from "@aomex/core";
|
|
4
|
+
|
|
5
|
+
// src/middleware/body.ts
|
|
6
|
+
import {
|
|
7
|
+
validate,
|
|
8
|
+
Validator,
|
|
9
|
+
rule,
|
|
10
|
+
ValidatorError
|
|
11
|
+
} from "@aomex/core";
|
|
12
|
+
var WebBodyMiddleware = class extends WebMiddleware {
|
|
13
|
+
constructor(props) {
|
|
14
|
+
super(async (ctx, next) => {
|
|
15
|
+
try {
|
|
16
|
+
ctx.body = await validate(ctx.request.body, props, {
|
|
17
|
+
throwIfError: true
|
|
18
|
+
});
|
|
19
|
+
return next();
|
|
20
|
+
} catch (e) {
|
|
21
|
+
ctx.throw(e instanceof ValidatorError ? 400 : 500, e);
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
this.props = props;
|
|
25
|
+
}
|
|
26
|
+
toDocument(options) {
|
|
27
|
+
if (!options.methodItem)
|
|
28
|
+
return;
|
|
29
|
+
options.methodItem.requestBody = {
|
|
30
|
+
content: {
|
|
31
|
+
"*/*": {
|
|
32
|
+
schema: Validator.toDocument(rule.object(this.props)).schema
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
required: Object.values(this.props).some(
|
|
36
|
+
(validator) => Validator.toDocument(validator).required
|
|
37
|
+
)
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
var body = (fields) => new WebBodyMiddleware(fields);
|
|
42
|
+
|
|
43
|
+
// src/middleware/query.ts
|
|
44
|
+
import {
|
|
45
|
+
validate as validate2,
|
|
46
|
+
Validator as Validator2,
|
|
47
|
+
ValidatorError as ValidatorError2
|
|
48
|
+
} from "@aomex/core";
|
|
49
|
+
var WebQueryMiddleware = class extends WebMiddleware {
|
|
50
|
+
constructor(props) {
|
|
51
|
+
super(async (ctx, next) => {
|
|
52
|
+
try {
|
|
53
|
+
ctx.query = await validate2(ctx.request.query, props, {
|
|
54
|
+
throwIfError: true
|
|
55
|
+
});
|
|
56
|
+
return next();
|
|
57
|
+
} catch (e) {
|
|
58
|
+
ctx.throw(e instanceof ValidatorError2 ? 400 : 500, e);
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
this.props = props;
|
|
62
|
+
}
|
|
63
|
+
toDocument(options) {
|
|
64
|
+
const methodItem = options.methodItem;
|
|
65
|
+
if (!methodItem)
|
|
66
|
+
return;
|
|
67
|
+
methodItem.parameters ||= [];
|
|
68
|
+
Object.entries(this.props).forEach(([name, validator]) => {
|
|
69
|
+
methodItem.parameters.push({
|
|
70
|
+
name,
|
|
71
|
+
in: "query",
|
|
72
|
+
...Validator2.toDocument(validator)
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
var query = (fields) => new WebQueryMiddleware(fields);
|
|
78
|
+
|
|
79
|
+
// src/middleware/params.ts
|
|
80
|
+
import {
|
|
81
|
+
validate as validate3,
|
|
82
|
+
Validator as Validator3,
|
|
83
|
+
ValidatorError as ValidatorError3
|
|
84
|
+
} from "@aomex/core";
|
|
85
|
+
var WebParamMiddleware = class extends WebMiddleware {
|
|
86
|
+
constructor(props) {
|
|
87
|
+
super(async (ctx, next) => {
|
|
88
|
+
try {
|
|
89
|
+
ctx.params = await validate3(ctx.request.params, props, {
|
|
90
|
+
throwIfError: true
|
|
91
|
+
});
|
|
92
|
+
return next();
|
|
93
|
+
} catch (e) {
|
|
94
|
+
ctx.throw(e instanceof ValidatorError3 ? 400 : 500, e);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
this.props = props;
|
|
98
|
+
}
|
|
99
|
+
toDocument(options) {
|
|
100
|
+
const methodItem = options.methodItem;
|
|
101
|
+
if (!methodItem)
|
|
102
|
+
return;
|
|
103
|
+
methodItem.parameters ||= [];
|
|
104
|
+
Object.entries(this.props).forEach(([name, validator]) => {
|
|
105
|
+
methodItem.parameters.push({
|
|
106
|
+
name,
|
|
107
|
+
in: "path",
|
|
108
|
+
...Validator3.toDocument(validator)
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
var params = (fields) => new WebParamMiddleware(fields);
|
|
114
|
+
|
|
115
|
+
// src/middleware/skip.ts
|
|
116
|
+
import { extname } from "node:path";
|
|
117
|
+
import { compose, Middleware, middleware } from "@aomex/core";
|
|
118
|
+
import { toArray } from "@aomex/helper";
|
|
119
|
+
var skip = (token, options) => {
|
|
120
|
+
if (!options)
|
|
121
|
+
return middleware.web((_, next) => next());
|
|
122
|
+
const opts = typeof options === "function" ? { custom: options } : options;
|
|
123
|
+
const originFn = token instanceof Middleware ? token.fn : compose(toArray(token));
|
|
124
|
+
return middleware.web(async (ctx, next) => {
|
|
125
|
+
const skipped = await shouldSkip(ctx, opts);
|
|
126
|
+
return skipped ? next() : originFn(ctx, next);
|
|
127
|
+
});
|
|
128
|
+
};
|
|
129
|
+
var shouldSkip = async (ctx, options) => {
|
|
130
|
+
if (await options.custom?.(ctx))
|
|
131
|
+
return true;
|
|
132
|
+
if (options.path) {
|
|
133
|
+
const { path: pathname } = ctx.request;
|
|
134
|
+
return toArray(options.path).some(
|
|
135
|
+
(path) => typeof path === "string" ? path === pathname : path.exec(pathname) !== null
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
if (options.ext) {
|
|
139
|
+
const currentExt = extname(ctx.request.path);
|
|
140
|
+
if (currentExt === "")
|
|
141
|
+
return false;
|
|
142
|
+
return toArray(options.ext).some((ext) => {
|
|
143
|
+
return currentExt === (ext.startsWith(".") ? ext : `.${ext}`);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
if (options.method) {
|
|
147
|
+
return toArray(options.method).includes(ctx.request.method);
|
|
148
|
+
}
|
|
149
|
+
return false;
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// src/override/middleware.ts
|
|
153
|
+
var WebMiddleware = class extends Middleware2 {
|
|
154
|
+
constructor(fn) {
|
|
155
|
+
super(fn);
|
|
156
|
+
}
|
|
157
|
+
skipIf(options) {
|
|
158
|
+
return skip(this, options);
|
|
159
|
+
}
|
|
5
160
|
toDocument(options) {
|
|
6
161
|
assert(options);
|
|
7
162
|
}
|
|
8
163
|
};
|
|
9
|
-
|
|
164
|
+
Middleware2.register("web", WebMiddleware);
|
|
10
165
|
|
|
11
166
|
// src/override/chain.ts
|
|
12
167
|
import { Chain } from "@aomex/core";
|
|
@@ -18,11 +173,11 @@ Chain.register("web", WebChain);
|
|
|
18
173
|
import { PersistentFile } from "formidable";
|
|
19
174
|
import mimeTypes from "mime-types";
|
|
20
175
|
import {
|
|
21
|
-
Validator,
|
|
176
|
+
Validator as Validator4,
|
|
22
177
|
magistrate,
|
|
23
178
|
Rule
|
|
24
179
|
} from "@aomex/core";
|
|
25
|
-
var FileValidator = class extends
|
|
180
|
+
var FileValidator = class extends Validator4 {
|
|
26
181
|
/**
|
|
27
182
|
* @param {String} unit 默认单位:`B`,即字节
|
|
28
183
|
*/
|
|
@@ -123,7 +278,7 @@ var WebContext = class {
|
|
|
123
278
|
import { createServer } from "node:http";
|
|
124
279
|
import EventEmitter from "node:events";
|
|
125
280
|
import { EOL } from "node:os";
|
|
126
|
-
import { Chain as Chain2, compose } from "@aomex/core";
|
|
281
|
+
import { Chain as Chain2, compose as compose2 } from "@aomex/core";
|
|
127
282
|
import { color } from "@aomex/helper";
|
|
128
283
|
|
|
129
284
|
// src/app/request.ts
|
|
@@ -221,7 +376,7 @@ import encodeUrl from "encodeurl";
|
|
|
221
376
|
import destroy from "destroy";
|
|
222
377
|
import contentDisposition from "content-disposition";
|
|
223
378
|
import createHttpError2, { isHttpError } from "http-errors";
|
|
224
|
-
import { extname } from "node:path";
|
|
379
|
+
import { extname as extname2 } from "node:path";
|
|
225
380
|
import { createReadStream } from "node:fs";
|
|
226
381
|
|
|
227
382
|
// src/util/get-content-type.ts
|
|
@@ -279,7 +434,7 @@ var WebResponse = class extends ServerResponse {
|
|
|
279
434
|
}
|
|
280
435
|
}
|
|
281
436
|
download(filePath, options = {}) {
|
|
282
|
-
this.contentType =
|
|
437
|
+
this.contentType = extname2(filePath);
|
|
283
438
|
this.setHeader(
|
|
284
439
|
"content-disposition",
|
|
285
440
|
contentDisposition(filePath, options)
|
|
@@ -449,7 +604,7 @@ var WebApp = class extends EventEmitter {
|
|
|
449
604
|
return server.listen(...args);
|
|
450
605
|
};
|
|
451
606
|
callback() {
|
|
452
|
-
const fn =
|
|
607
|
+
const fn = compose2(this.middlewareList);
|
|
453
608
|
if (!this.listenerCount("error")) {
|
|
454
609
|
this.on("error", this.log);
|
|
455
610
|
}
|
|
@@ -468,115 +623,10 @@ var WebApp = class extends EventEmitter {
|
|
|
468
623
|
on(eventName, listener) {
|
|
469
624
|
return super.on(eventName, listener);
|
|
470
625
|
}
|
|
471
|
-
mount(
|
|
472
|
-
this.middlewareList.push(
|
|
473
|
-
}
|
|
474
|
-
};
|
|
475
|
-
|
|
476
|
-
// src/middleware/body.ts
|
|
477
|
-
import {
|
|
478
|
-
validate,
|
|
479
|
-
Validator as Validator2,
|
|
480
|
-
rule,
|
|
481
|
-
ValidatorError
|
|
482
|
-
} from "@aomex/core";
|
|
483
|
-
var WebBodyMiddleware = class extends WebMiddleware {
|
|
484
|
-
constructor(props) {
|
|
485
|
-
super(async (ctx, next) => {
|
|
486
|
-
try {
|
|
487
|
-
ctx.body = await validate(ctx.request.body, props, {
|
|
488
|
-
throwIfError: true
|
|
489
|
-
});
|
|
490
|
-
return next();
|
|
491
|
-
} catch (e) {
|
|
492
|
-
ctx.throw(e instanceof ValidatorError ? 400 : 500, e);
|
|
493
|
-
}
|
|
494
|
-
});
|
|
495
|
-
this.props = props;
|
|
496
|
-
}
|
|
497
|
-
toDocument(options) {
|
|
498
|
-
const collector = options.pathItemInMethod;
|
|
499
|
-
collector.requestBody = {
|
|
500
|
-
content: {
|
|
501
|
-
"*/*": {
|
|
502
|
-
schema: Validator2.toDocument(rule.object(this.props)).schema
|
|
503
|
-
}
|
|
504
|
-
},
|
|
505
|
-
required: Object.values(this.props).some(
|
|
506
|
-
(validator) => Validator2.toDocument(validator).required
|
|
507
|
-
)
|
|
508
|
-
};
|
|
509
|
-
}
|
|
510
|
-
};
|
|
511
|
-
var body = (fields) => new WebBodyMiddleware(fields);
|
|
512
|
-
|
|
513
|
-
// src/middleware/query.ts
|
|
514
|
-
import {
|
|
515
|
-
validate as validate2,
|
|
516
|
-
Validator as Validator3,
|
|
517
|
-
ValidatorError as ValidatorError2
|
|
518
|
-
} from "@aomex/core";
|
|
519
|
-
var WebQueryMiddleware = class extends WebMiddleware {
|
|
520
|
-
constructor(props) {
|
|
521
|
-
super(async (ctx, next) => {
|
|
522
|
-
try {
|
|
523
|
-
ctx.query = await validate2(ctx.request.query, props, {
|
|
524
|
-
throwIfError: true
|
|
525
|
-
});
|
|
526
|
-
return next();
|
|
527
|
-
} catch (e) {
|
|
528
|
-
ctx.throw(e instanceof ValidatorError2 ? 400 : 500, e);
|
|
529
|
-
}
|
|
530
|
-
});
|
|
531
|
-
this.props = props;
|
|
532
|
-
}
|
|
533
|
-
toDocument(options) {
|
|
534
|
-
const collector = options.pathItemInMethod;
|
|
535
|
-
collector.parameters ||= [];
|
|
536
|
-
Object.entries(this.props).forEach(([name, validator]) => {
|
|
537
|
-
collector.parameters.push({
|
|
538
|
-
name,
|
|
539
|
-
in: "query",
|
|
540
|
-
...Validator3.toDocument(validator)
|
|
541
|
-
});
|
|
542
|
-
});
|
|
543
|
-
}
|
|
544
|
-
};
|
|
545
|
-
var query = (fields) => new WebQueryMiddleware(fields);
|
|
546
|
-
|
|
547
|
-
// src/middleware/params.ts
|
|
548
|
-
import {
|
|
549
|
-
validate as validate3,
|
|
550
|
-
Validator as Validator4,
|
|
551
|
-
ValidatorError as ValidatorError3
|
|
552
|
-
} from "@aomex/core";
|
|
553
|
-
var WebParamMiddleware = class extends WebMiddleware {
|
|
554
|
-
constructor(props) {
|
|
555
|
-
super(async (ctx, next) => {
|
|
556
|
-
try {
|
|
557
|
-
ctx.params = await validate3(ctx.request.params, props, {
|
|
558
|
-
throwIfError: true
|
|
559
|
-
});
|
|
560
|
-
return next();
|
|
561
|
-
} catch (e) {
|
|
562
|
-
ctx.throw(e instanceof ValidatorError3 ? 400 : 500, e);
|
|
563
|
-
}
|
|
564
|
-
});
|
|
565
|
-
this.props = props;
|
|
566
|
-
}
|
|
567
|
-
toDocument(options) {
|
|
568
|
-
const collector = options.pathItemInMethod;
|
|
569
|
-
collector.parameters ||= [];
|
|
570
|
-
Object.entries(this.props).forEach(([name, validator]) => {
|
|
571
|
-
collector.parameters.push({
|
|
572
|
-
name,
|
|
573
|
-
in: "path",
|
|
574
|
-
...Validator4.toDocument(validator)
|
|
575
|
-
});
|
|
576
|
-
});
|
|
626
|
+
mount(middleware2) {
|
|
627
|
+
this.middlewareList.push(middleware2);
|
|
577
628
|
}
|
|
578
629
|
};
|
|
579
|
-
var params = (fields) => new WebParamMiddleware(fields);
|
|
580
630
|
|
|
581
631
|
// src/index.ts
|
|
582
632
|
import { HttpError } from "http-errors";
|
|
@@ -595,6 +645,7 @@ export {
|
|
|
595
645
|
body,
|
|
596
646
|
getContentType,
|
|
597
647
|
params,
|
|
598
|
-
query
|
|
648
|
+
query,
|
|
649
|
+
skip
|
|
599
650
|
};
|
|
600
651
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +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","../src/index.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 { Chain, 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 public readonly globalChainPoint?: string;\n protected readonly middlewareList: WebMiddlewareToken[];\n\n constructor(readonly options: WebAppOption = {}) {\n super();\n if (options.globalChain) {\n this.globalChainPoint = Chain.createPoint(options.globalChain);\n this.middlewareList = [options.globalChain];\n } else {\n this.middlewareList = [];\n }\n }\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 return fn(new WebContext(this, req, res))\n .then(res.flush.bind(res))\n .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 requestIP from 'request-ip';\nimport fresh from 'fresh';\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 get ip(): string {\n return requestIP.getClientIp(this) || '';\n }\n\n get fresh(): boolean {\n const method = this.method;\n const status = this.res.statusCode;\n\n if (method !== 'GET' && method !== 'HEAD') return false;\n if (status < 200) return false;\n if (status > 299 && status !== 304) return false;\n\n return fresh(this.headers, this.res.getHeaders());\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';\nimport vary from 'vary';\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 protected _explicitStatus = false;\n\n constructor(req: Request) {\n super(req);\n super.statusCode = 404;\n }\n\n /** @ts-expect-error */\n override set statusCode(code: number) {\n this._explicitStatus = true;\n super.statusCode = code;\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 if (!this._explicitStatus) {\n this.statusCode = 200;\n }\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 (!this._explicitStatus) {\n this.statusCode = 200;\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 public vary(field: HeaderKeys | HeaderKeys[]): void;\n public vary(field: string | string[]): void;\n public vary(field: HeaderKeys | HeaderKeys[] | string | string[]): void {\n return vary(this, field);\n }\n\n public varyAppend(header: HeaderKeys, field: string | string[]): string;\n public varyAppend(header: string, field: string | string[]): string;\n public varyAppend(\n header: HeaderKeys | string,\n field: string | string[],\n ): string {\n return vary.append(header, field);\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","export * from './override';\nexport * from './app';\nexport * from './util';\nexport * from './middleware';\nexport { HttpError } from 'http-errors';\n"],"mappings":";AAAA,OAAO,YAAY;AACnB,SAAS,kBAA2C;AAkB7C,IAAM,gBAAN,cAEG,WAAkB;AAAA,EAGnB,WAAW,SAAkC;AAClD,WAAO,OAAO;AAAA,EAChB;AACF;AAEA,WAAW,SAAS,OAAO,aAAa;;;AC7BxC,SAAS,aAAuD;AAczD,IAAM,WAAN,cAAsD,MAAa;AAQ1E;AAEA,MAAM,SAAS,OAAO,QAAQ;;;ACxB9B,SAAS,sBAA4C;AACrD,OAAO,eAAe;AACtB;AAAA,EAEE;AAAA,EAKA;AAAA,EAEA;AAAA,OACK;AA8BA,IAAM,gBAAN,cAAsC,UAAa;AAAA;AAAA;AAAA;AAAA,EAYjD,QAAQ,QAAgB,OAAqB,KAAW;AAC7D,QAAI;AACJ,YAAQ,KAAK,YAAY,GAAmC;AAAA,MAC1D,KAAK;AACH,gBAAQ;AACR;AAAA,MACF,KAAK;AACH,gBAAQ;AACR;AAAA,MACF,KAAK;AACH,gBAAQ;AACR;AAAA,MACF,KAAK;AACH,gBAAQ,UAAU;AAClB;AAAA,MACF,KAAK;AACH,gBAAQ,UAAU;AAAA,IACtB;AACA,SAAK,OAAO,UAAU,SAAS;AAC/B,WAAO;AAAA,EACT;AAAA,EAUO,UAAU,cAAiC,QAAwB;AACxE,SAAK,OAAO,YAAsB;AAAA,MAChC,GAAG,IAAI;AAAA,QACJ,CAAC,EACC,OAAO,SAAS,EAChB,OAAO,MAAM,EACb,IAAI,UAAU,WAAW,EACzB,OAAO,OAAO;AAAA,MACnB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA,EAEmB,QAAQ,OAAqB;AAC9C,WAAO,MAAM,QAAQ,KAAK,KAAM,MAAM,QAAQ,KAAK,KA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C;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;;;ACvDrC,SAAS,iBAAiB;","names":["mimeTypes","assert","body","Chain","createHttpError","mimeTypes","typeIs","body","chunk","createHttpError","Chain","Validator","Validator","validate","Validator","ValidatorError","validate","ValidatorError","Validator","validate","Validator","ValidatorError","validate","ValidatorError","Validator"]}
|
|
1
|
+
{"version":3,"sources":["../src/override/middleware.ts","../src/middleware/body.ts","../src/middleware/query.ts","../src/middleware/params.ts","../src/middleware/skip.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/index.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';\nimport { skip, type WebMiddlewareSkipOptions } from '../middleware';\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 methodItem?: 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 constructor(fn: (ctx: NonReadonly<Props> & WebContext, next: Next) => any) {\n super(fn);\n }\n\n public skipIf(\n options:\n | WebMiddlewareSkipOptions\n | NonNullable<WebMiddlewareSkipOptions['custom']>,\n ): WebMiddleware<Props> {\n return skip(this, options);\n }\n\n public toDocument(options: WebMiddlewareToDocument) {\n assert(options);\n }\n}\n\nMiddleware.register('web', WebMiddleware);\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 as Error);\n }\n });\n }\n\n public override toDocument(options: WebMiddlewareToDocument): void {\n if (!options.methodItem) return;\n\n options.methodItem.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 as Error);\n }\n });\n }\n\n public override toDocument(options: WebMiddlewareToDocument): void {\n const methodItem = options.methodItem;\n if (!methodItem) return;\n methodItem.parameters ||= [];\n Object.entries(this.props).forEach(([name, validator]) => {\n methodItem.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 as Error);\n }\n });\n }\n\n public override toDocument(options: WebMiddlewareToDocument): void {\n const methodItem = options.methodItem;\n if (!methodItem) return;\n methodItem.parameters ||= [];\n Object.entries(this.props).forEach(([name, validator]) => {\n methodItem.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","import { extname } from 'node:path';\nimport { compose, Middleware, middleware, MiddlewareFn } from '@aomex/core';\nimport { toArray } from '@aomex/helper';\nimport type { WebContext } from '../app';\nimport type { WebMiddleware, WebMiddlewareToken } from '../override';\n\nexport interface WebMiddlewareSkipOptions {\n custom?: (ctx: WebContext) => boolean | Promise<boolean>;\n path?: string | RegExp | (string | RegExp)[];\n ext?: string | string[];\n method?: string | string[];\n}\n\n/**\n * 跳过指定web插件或者web插件集合\n * @param token web插件或者web插件集合\n * @param options 跳过条件,不传则代表`总是跳过`\n */\nexport const skip = <Props extends object = object>(\n token: WebMiddlewareToken<Props>,\n options?:\n | WebMiddlewareSkipOptions\n | NonNullable<WebMiddlewareSkipOptions['custom']>,\n): WebMiddleware<Props> => {\n if (!options) return middleware.web((_, next) => next());\n\n const opts = typeof options === 'function' ? { custom: options } : options;\n const originFn: MiddlewareFn<Props> =\n token instanceof Middleware ? token.fn : compose(toArray(token));\n return middleware.web<Props>(async (ctx, next) => {\n const skipped = await shouldSkip(ctx, opts);\n return skipped ? next() : originFn(ctx, next);\n });\n};\n\nconst shouldSkip = async (\n ctx: WebContext,\n options: WebMiddlewareSkipOptions,\n): Promise<boolean> => {\n if (await options.custom?.(ctx)) return true;\n\n if (options.path) {\n const { path: pathname } = ctx.request;\n return toArray(options.path).some((path) =>\n typeof path === 'string'\n ? path === pathname\n : path.exec(pathname) !== null,\n );\n }\n\n if (options.ext) {\n const currentExt = extname(ctx.request.path);\n if (currentExt === '') return false;\n return toArray(options.ext).some((ext) => {\n return currentExt === (ext.startsWith('.') ? ext : `.${ext}`);\n });\n }\n\n if (options.method) {\n return toArray(options.method).includes(ctx.request.method);\n }\n\n return false;\n};\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 { Chain, 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 public readonly globalChainPoint?: string;\n protected readonly middlewareList: WebMiddlewareToken[];\n\n constructor(readonly options: WebAppOption = {}) {\n super();\n if (options.globalChain) {\n this.globalChainPoint = Chain.createPoint(options.globalChain);\n this.middlewareList = [options.globalChain];\n } else {\n this.middlewareList = [];\n }\n }\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 return fn(new WebContext(this, req, res))\n .then(res.flush.bind(res))\n .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 requestIP from 'request-ip';\nimport fresh from 'fresh';\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 get ip(): string {\n return requestIP.getClientIp(this) || '';\n }\n\n get fresh(): boolean {\n const method = this.method;\n const status = this.res.statusCode;\n\n if (method !== 'GET' && method !== 'HEAD') return false;\n if (status < 200) return false;\n if (status > 299 && status !== 304) return false;\n\n return fresh(this.headers, this.res.getHeaders());\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';\nimport vary from 'vary';\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 protected _explicitStatus = false;\n\n constructor(req: Request) {\n super(req);\n super.statusCode = 404;\n }\n\n /** @ts-expect-error */\n override set statusCode(code: number) {\n this._explicitStatus = true;\n super.statusCode = code;\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 if (!this._explicitStatus) {\n this.statusCode = 200;\n }\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 (!this._explicitStatus) {\n this.statusCode = 200;\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 public vary(field: HeaderKeys | HeaderKeys[]): void;\n public vary(field: string | string[]): void;\n public vary(field: HeaderKeys | HeaderKeys[] | string | string[]): void {\n return vary(this, field);\n }\n\n public varyAppend(header: HeaderKeys, field: string | string[]): string;\n public varyAppend(header: string, field: string | string[]): string;\n public varyAppend(\n header: HeaderKeys | string,\n field: string | string[],\n ): string {\n return vary.append(header, field);\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","export * from './override';\nexport * from './app';\nexport * from './util';\nexport * from './middleware';\nexport { HttpError } from 'http-errors';\n"],"mappings":";AAAA,OAAO,YAAY;AACnB,SAAS,cAAAA,mBAA2C;;;ACDpD;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AAGA,IAAM,oBAAN,cAEG,cAEP;AAAA,EACD,YAA+B,OAAc;AAC3C,UAAM,OAAO,KAAK,SAAS;AACzB,UAAI;AACF,YAAI,OAAO,MAAM,SAAS,IAAI,QAAQ,MAAM,OAAO;AAAA,UACjD,cAAc;AAAA,QAChB,CAAC;AACD,eAAO,KAAK;AAAA,MACd,SAAS,GAAP;AACA,YAAI,MAAM,aAAa,iBAAiB,MAAM,KAAK,CAAU;AAAA,MAC/D;AAAA,IACF,CAAC;AAV4B;AAAA,EAW/B;AAAA,EAEgB,WAAW,SAAwC;AACjE,QAAI,CAAC,QAAQ;AAAY;AAEzB,YAAQ,WAAW,cAAc;AAAA,MAC/B,SAAS;AAAA,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AAgB;AACzB,SAAK,IAAI,UAAU,IAAI,gBAAgB,OAAO,IAAI;AAAQ;AAC1D,UAAM,QAAQ,IAAI,SAAS,IAAI,SAAS,GAAG,MAAM,KAAK,CAAC;AACvD,YAAQ;AAAA,MACN,CAAC,IAAI,MAAM,MAAM,KAAK,MAAM,CAAC,GAAG,KAAK,KAAK,GAAG,GAAG,EAAE,EAAE,KAAK,GAAG;AAAA,IAC9D;AAAA,EACF;AAAA,EAMgB,GACd,WACA,UACM;AACN,WAAO,MAAM,GAAG,WAAW,QAAQ;AAAA,EACrC;AAAA,EAEO,MAAMC,aAAsC;AACjD,SAAK,eAAe,KAAKA,WAAU;AAAA,EACrC;AACF;;;AI/EA,SAAS,iBAAiB;","names":["Middleware","validate","Validator","ValidatorError","validate","ValidatorError","Validator","validate","Validator","ValidatorError","validate","ValidatorError","Validator","Middleware","Validator","mimeTypes","assert","body","Chain","compose","createHttpError","extname","mimeTypes","typeIs","extname","body","chunk","createHttpError","Chain","compose","middleware"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aomex/web",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.4",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"homepage": "https://aomex.js.org",
|
|
27
27
|
"license": "MIT",
|
|
28
28
|
"peerDependencies": {
|
|
29
|
-
"@aomex/core": "^0.0.
|
|
29
|
+
"@aomex/core": "^0.0.3"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
32
|
"@aomex/helper": "^0.0.1",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
"vary": "^1.1.2"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
|
-
"@aomex/core": "^0.0.
|
|
55
|
+
"@aomex/core": "^0.0.3",
|
|
56
56
|
"@types/accepts": "^1.3.5",
|
|
57
57
|
"@types/co-body": "^6.1.0",
|
|
58
58
|
"@types/content-type": "^1.1.5",
|