@midwayjs/upload 3.16.0 → 3.17.0-beta.1

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.
@@ -1,8 +1,9 @@
1
- import { MidwayApplicationManager } from '@midwayjs/core';
1
+ import { ILogger, MidwayApplicationManager } from '@midwayjs/core';
2
2
  import { UploadOptions } from './interface';
3
3
  export declare class UploadConfiguration {
4
4
  applicationManager: MidwayApplicationManager;
5
5
  uploadConfig: UploadOptions;
6
+ logger: ILogger;
6
7
  onReady(): Promise<void>;
7
8
  onStop(): Promise<void>;
8
9
  }
@@ -20,7 +20,9 @@ let UploadConfiguration = class UploadConfiguration {
20
20
  if (tmpdir) {
21
21
  await (0, utils_1.ensureDir)(tmpdir);
22
22
  if (cleanTimeout) {
23
- (0, utils_1.autoRemoveUploadTmpFile)(tmpdir, cleanTimeout);
23
+ (0, utils_1.autoRemoveUploadTmpFile)(tmpdir, cleanTimeout).catch(err => {
24
+ this.logger.error(err);
25
+ });
24
26
  }
25
27
  }
26
28
  this.applicationManager
@@ -41,6 +43,10 @@ __decorate([
41
43
  (0, core_1.Config)('upload'),
42
44
  __metadata("design:type", Object)
43
45
  ], UploadConfiguration.prototype, "uploadConfig", void 0);
46
+ __decorate([
47
+ (0, core_1.Logger)('coreLogger'),
48
+ __metadata("design:type", Object)
49
+ ], UploadConfiguration.prototype, "logger", void 0);
44
50
  UploadConfiguration = __decorate([
45
51
  (0, core_1.Configuration)({
46
52
  namespace: 'upload',
@@ -1,5 +1,5 @@
1
1
  /// <reference types="node" />
2
- import { IMiddleware, ILogger, IgnoreMatcher } from '@midwayjs/core';
2
+ import { IMiddleware, ILogger, IgnoreMatcher, IMidwayApplication } from '@midwayjs/core';
3
3
  import { UploadOptions } from '.';
4
4
  export declare class UploadMiddleware implements IMiddleware<any, any> {
5
5
  uploadConfig: UploadOptions;
@@ -17,16 +17,15 @@ export declare class UploadMiddleware implements IMiddleware<any, any> {
17
17
  match: IgnoreMatcher<any>[];
18
18
  ignore: IgnoreMatcher<any>[];
19
19
  init(): Promise<void>;
20
- resolve(app: any): (req: any, res: any, next: any) => Promise<any>;
21
- execUpload(ctx: any, req: any, res: any, next: any, isExpress: any): Promise<any>;
22
- getUploadBoundary(request: any): false | string;
23
- isReadableStream(req: any, isExpress: any): boolean;
20
+ resolve(app: IMidwayApplication): (ctxOrReq: any, resOrNext: any, next: any) => Promise<any>;
21
+ static getName(): string;
24
22
  checkAndGetExt(filename: any, whiteListMap?: Map<string, string>): string | boolean;
25
23
  checkFileType(ext: string, data: Buffer, uploadFileMimeTypeMap?: Map<string, string[]>): Promise<{
26
24
  passed: boolean;
27
25
  mime?: string;
28
26
  current?: string;
29
27
  }>;
30
- static getName(): string;
28
+ isReadableStream(req: any, isExpress: any): boolean;
29
+ getUploadBoundary(request: any): false | string;
31
30
  }
32
31
  //# sourceMappingURL=middleware.d.ts.map
@@ -16,9 +16,9 @@ const fs_1 = require("fs");
16
16
  const stream_1 = require("stream");
17
17
  const _1 = require(".");
18
18
  const parse_1 = require("./parse");
19
- const getRawBody = require("raw-body");
20
19
  const file_type_1 = require("file-type");
21
20
  const utils_1 = require("./utils");
21
+ const busboy = require("busboy");
22
22
  const { unlink, writeFile } = fs_1.promises;
23
23
  let UploadMiddleware = class UploadMiddleware {
24
24
  constructor() {
@@ -40,8 +40,6 @@ let UploadMiddleware = class UploadMiddleware {
40
40
  else {
41
41
  this.ignore = [].concat(this.uploadConfig.ignore || []);
42
42
  }
43
- }
44
- resolve(app) {
45
43
  if (this.uploadConfig.whitelist &&
46
44
  Array.isArray(this.uploadConfig.whitelist)) {
47
45
  for (const whiteExt of this.uploadConfig.whitelist) {
@@ -54,164 +52,205 @@ let UploadMiddleware = class UploadMiddleware {
54
52
  this.uploadFileMimeTypeMap.set(ext, mime);
55
53
  }
56
54
  }
57
- if (app.getFrameworkType() === core_1.MidwayFrameworkType.WEB_EXPRESS) {
58
- return async (req, res, next) => {
59
- return this.execUpload(req, req, res, next, true);
60
- };
61
- }
62
- else {
63
- return async (ctx, next) => {
64
- var _a;
65
- const req = ((_a = ctx.request) === null || _a === void 0 ? void 0 : _a.req) || ctx.request;
66
- return this.execUpload(ctx, req, ctx, next, false);
67
- };
68
- }
69
55
  }
70
- async execUpload(ctx, req, res, next, isExpress) {
71
- var _a;
72
- const { mode, tmpdir, fileSize } = this.uploadConfig;
73
- const boundary = this.getUploadBoundary(req);
74
- if (!boundary) {
75
- return next();
76
- }
77
- ctx.fields = {};
78
- ctx.files = [];
79
- ctx.cleanupRequestFiles = async () => {
80
- var _a;
81
- if (!((_a = ctx.files) === null || _a === void 0 ? void 0 : _a.length)) {
82
- return [];
56
+ resolve(app) {
57
+ const isExpress = app.getNamespace() === 'express';
58
+ return async (ctxOrReq, resOrNext, next) => {
59
+ var _a, _b;
60
+ const req = ((_a = ctxOrReq.request) === null || _a === void 0 ? void 0 : _a.req) || ctxOrReq.request || ctxOrReq;
61
+ const boundary = this.getUploadBoundary(req);
62
+ if (!boundary) {
63
+ return next();
83
64
  }
84
- return Promise.all(ctx.files.map(async (fileInfo) => {
85
- if (typeof fileInfo.data !== 'string') {
86
- return false;
87
- }
88
- try {
89
- await unlink(fileInfo.data);
90
- return true;
65
+ // let res = resOrNext;
66
+ if (!isExpress) {
67
+ next = resOrNext;
68
+ // res = ctxOrReq.res;
69
+ }
70
+ const { mode, tmpdir } = this.uploadConfig;
71
+ // create new map include custom white list
72
+ const currentContextWhiteListMap = new Map([
73
+ ...this.uploadWhiteListMap.entries(),
74
+ ]);
75
+ if (typeof this.uploadConfig.whitelist === 'function') {
76
+ const whiteListArray = this.uploadConfig.whitelist.call(this, ctxOrReq);
77
+ whiteListArray.forEach(ext => currentContextWhiteListMap.set(ext, ext));
78
+ }
79
+ // create new map include custom mime type white list
80
+ const currentContextMimeTypeWhiteListMap = new Map([
81
+ ...this.uploadFileMimeTypeMap.entries(),
82
+ ]);
83
+ if (typeof this.uploadConfig.mimeTypeWhiteList === 'function') {
84
+ const mimeTypeWhiteList = this.uploadConfig.mimeTypeWhiteList.call(this, ctxOrReq);
85
+ for (const ext in mimeTypeWhiteList) {
86
+ const mime = [].concat(mimeTypeWhiteList[ext]);
87
+ currentContextMimeTypeWhiteListMap.set(ext, mime);
91
88
  }
92
- catch (_a) {
93
- return false;
89
+ }
90
+ ctxOrReq.cleanupRequestFiles = async () => {
91
+ var _a;
92
+ if (!((_a = ctxOrReq.files) === null || _a === void 0 ? void 0 : _a.length)) {
93
+ return [];
94
94
  }
95
- }));
96
- };
97
- // create new map include custom white list
98
- const currentContextWhiteListMap = new Map([
99
- ...this.uploadWhiteListMap.entries(),
100
- ]);
101
- if (typeof this.uploadConfig.whitelist === 'function') {
102
- const whiteListArray = this.uploadConfig.whitelist.call(this, ctx);
103
- whiteListArray.forEach(ext => currentContextWhiteListMap.set(ext, ext));
104
- }
105
- // create new map include custom mime type white list
106
- const currentContextMimeTypeWhiteListMap = new Map([
107
- ...this.uploadFileMimeTypeMap.entries(),
108
- ]);
109
- if (typeof this.uploadConfig.mimeTypeWhiteList === 'function') {
110
- const mimeTypeWhiteList = this.uploadConfig.mimeTypeWhiteList.call(this, ctx);
111
- for (const ext in mimeTypeWhiteList) {
112
- const mime = [].concat(mimeTypeWhiteList[ext]);
113
- currentContextMimeTypeWhiteListMap.set(ext, mime);
95
+ return Promise.all(ctxOrReq.files.map(async (fileInfo) => {
96
+ if (typeof fileInfo.data !== 'string') {
97
+ return false;
98
+ }
99
+ try {
100
+ await unlink(fileInfo.data);
101
+ return true;
102
+ }
103
+ catch (_a) {
104
+ return false;
105
+ }
106
+ }));
107
+ };
108
+ if (this.isReadableStream(req, isExpress)) {
109
+ let isStreamResolve = false;
110
+ const { files = [], fields = [] } = await new Promise((resolveP, reject) => {
111
+ const bb = busboy({ headers: req.headers });
112
+ const fields = [];
113
+ const files = [];
114
+ let fileModeCount = 0;
115
+ bb.on('file', async (name, file, info) => {
116
+ const { filename, encoding, mimeType } = info;
117
+ const ext = this.checkAndGetExt(filename, currentContextWhiteListMap);
118
+ if (!ext) {
119
+ reject(new _1.MultipartInvalidFilenameError(filename));
120
+ }
121
+ if (mode === 'stream') {
122
+ if (isStreamResolve) {
123
+ // will be skip
124
+ file.resume();
125
+ return;
126
+ }
127
+ files.push(new Promise(resolve => {
128
+ resolve({
129
+ filename,
130
+ mimeType,
131
+ encoding,
132
+ data: file,
133
+ });
134
+ }));
135
+ isStreamResolve = true;
136
+ return resolveP({
137
+ fields: await Promise.all(fields),
138
+ files: await Promise.all(files),
139
+ });
140
+ }
141
+ else {
142
+ fileModeCount++;
143
+ // file mode
144
+ const requireId = `upload_${Date.now()}.${Math.random()}`;
145
+ // read stream pipe to temp file
146
+ const tempFile = (0, path_1.resolve)(tmpdir, `${requireId}${ext}`);
147
+ // get buffer from stream, and check file type
148
+ file.once('data', async (chunk) => {
149
+ const { passed, mime, current } = await this.checkFileType(ext, chunk, currentContextMimeTypeWhiteListMap);
150
+ if (!passed) {
151
+ file.pause();
152
+ reject(new _1.MultipartInvalidFileTypeError(filename, current, mime));
153
+ }
154
+ });
155
+ const writeStream = file.pipe((0, fs_1.createWriteStream)(tempFile));
156
+ file.on('end', () => {
157
+ fileModeCount--;
158
+ });
159
+ writeStream.on('error', reject);
160
+ writeStream.on('finish', async () => {
161
+ files.push(new Promise(resolve => {
162
+ resolve({
163
+ filename,
164
+ mimeType,
165
+ encoding,
166
+ data: tempFile,
167
+ });
168
+ }));
169
+ if (fileModeCount === 0) {
170
+ return resolveP({
171
+ fields: await Promise.all(fields),
172
+ files: await Promise.all(files),
173
+ });
174
+ }
175
+ });
176
+ }
177
+ });
178
+ bb.on('field', (name, value, info) => {
179
+ fields.push(new Promise(resolve => {
180
+ resolve({
181
+ name,
182
+ value,
183
+ });
184
+ }));
185
+ });
186
+ req.pipe(bb);
187
+ });
188
+ ctxOrReq.files = files;
189
+ ctxOrReq.fields = fields.reduce((accumulator, current) => {
190
+ accumulator[current.name] = current.value;
191
+ return accumulator;
192
+ }, {});
193
+ Object.defineProperty(ctxOrReq, 'file', {
194
+ get() {
195
+ return ctxOrReq.files[0];
196
+ },
197
+ set(v) {
198
+ ctxOrReq.files = [v];
199
+ },
200
+ });
114
201
  }
115
- }
116
- let body;
117
- if (this.isReadableStream(req, isExpress)) {
118
- if (mode === 'stream') {
119
- const { fields, fileInfo } = await (0, parse_1.parseFromReadableStream)(req, boundary);
120
- const ext = this.checkAndGetExt(fileInfo.filename, currentContextWhiteListMap);
121
- if (!ext) {
122
- throw new _1.MultipartInvalidFilenameError(fileInfo.filename);
202
+ else {
203
+ let body;
204
+ if (((_b = req === null || req === void 0 ? void 0 : req.originEvent) === null || _b === void 0 ? void 0 : _b.body) &&
205
+ (typeof req.originEvent.body === 'string' ||
206
+ Buffer.isBuffer(req.originEvent.body))) {
207
+ body = req.originEvent.body;
123
208
  }
124
209
  else {
125
- fileInfo[_1.EXT_KEY] = ext;
126
- ctx.fields = fields;
127
- ctx.files = [fileInfo];
210
+ body = req.body;
211
+ }
212
+ const data = await (0, parse_1.parseMultipart)(body, boundary, this.uploadConfig);
213
+ if (!data) {
128
214
  return next();
129
215
  }
216
+ ctxOrReq.fields = data.fields;
217
+ const requireId = `upload_${Date.now()}.${Math.random()}`;
218
+ const files = data.files;
219
+ for (const fileInfo of files) {
220
+ const ext = this.checkAndGetExt(fileInfo.filename, currentContextWhiteListMap);
221
+ if (!ext) {
222
+ throw new _1.MultipartInvalidFilenameError(fileInfo.filename);
223
+ }
224
+ const { passed, mime, current } = await this.checkFileType(ext, fileInfo.data, currentContextMimeTypeWhiteListMap);
225
+ if (!passed) {
226
+ throw new _1.MultipartInvalidFileTypeError(fileInfo.filename, current, mime);
227
+ }
228
+ fileInfo[_1.EXT_KEY] = ext;
229
+ }
230
+ ctxOrReq.files = await Promise.all(files.map(async (file, index) => {
231
+ const { data } = file;
232
+ if (mode === 'file') {
233
+ const ext = file[_1.EXT_KEY];
234
+ const tmpFileName = (0, path_1.resolve)(tmpdir, `${requireId}.${index}${ext}`);
235
+ await writeFile(tmpFileName, data, 'binary');
236
+ file.data = tmpFileName;
237
+ }
238
+ else if (mode === 'stream') {
239
+ file.data = new stream_1.Readable({
240
+ read() {
241
+ this.push(data);
242
+ this.push(null);
243
+ },
244
+ });
245
+ }
246
+ return file;
247
+ }));
130
248
  }
131
- body = await getRawBody(req, {
132
- limit: fileSize,
133
- });
134
- }
135
- else if (((_a = req === null || req === void 0 ? void 0 : req.originEvent) === null || _a === void 0 ? void 0 : _a.body) &&
136
- (typeof req.originEvent.body === 'string' ||
137
- Buffer.isBuffer(req.originEvent.body))) {
138
- body = req.originEvent.body;
139
- }
140
- else {
141
- body = req.body;
142
- }
143
- const data = await (0, parse_1.parseMultipart)(body, boundary, this.uploadConfig);
144
- if (!data) {
145
- return next();
146
- }
147
- ctx.fields = data.fields;
148
- const requireId = `upload_${Date.now()}.${Math.random()}`;
149
- const files = data.files;
150
- for (const fileInfo of files) {
151
- const ext = this.checkAndGetExt(fileInfo.filename, currentContextWhiteListMap);
152
- if (!ext) {
153
- throw new _1.MultipartInvalidFilenameError(fileInfo.filename);
154
- }
155
- const { passed, mime, current } = await this.checkFileType(ext, fileInfo.data, currentContextMimeTypeWhiteListMap);
156
- if (!passed) {
157
- throw new _1.MultipartInvalidFileTypeError(fileInfo.filename, current, mime);
158
- }
159
- fileInfo[_1.EXT_KEY] = ext;
160
- }
161
- ctx.files = await Promise.all(files.map(async (file, index) => {
162
- const { data } = file;
163
- if (mode === 'file') {
164
- const ext = file[_1.EXT_KEY];
165
- const tmpFileName = (0, path_1.resolve)(tmpdir, `${requireId}.${index}${ext}`);
166
- await writeFile(tmpFileName, data, 'binary');
167
- file.data = tmpFileName;
168
- }
169
- else if (mode === 'stream') {
170
- file.data = new stream_1.Readable({
171
- read() {
172
- this.push(data);
173
- this.push(null);
174
- },
175
- });
176
- }
177
- return file;
178
- }));
179
- return next();
180
- }
181
- getUploadBoundary(request) {
182
- var _a;
183
- const method = (request.method || request.httpMethod || '').toUpperCase();
184
- if (method !== 'POST' &&
185
- method !== 'PUT' &&
186
- method !== 'DELETE' &&
187
- method !== 'PATCH') {
188
- return false;
189
- }
190
- if (!((_a = request.headers) === null || _a === void 0 ? void 0 : _a['content-type'])) {
191
- return false;
192
- }
193
- const contentType = request.headers['content-type'];
194
- if (!contentType.startsWith('multipart/form-data;')) {
195
- return false;
196
- }
197
- const boundaryMatch = /boundary=(.*)(;|\s|$)/.exec(contentType);
198
- if (!(boundaryMatch === null || boundaryMatch === void 0 ? void 0 : boundaryMatch[1])) {
199
- return false;
200
- }
201
- return boundaryMatch[1];
249
+ await next();
250
+ };
202
251
  }
203
- isReadableStream(req, isExpress) {
204
- // ref: https://github.com/rvagg/isstream/blob/master/isstream.js#L10
205
- if (req instanceof stream_1.Stream &&
206
- typeof req._read === 'function' &&
207
- typeof req._readableState === 'object' &&
208
- (!req.body || isExpress)) {
209
- return true;
210
- }
211
- if (req.pipe && req.on && !req.body) {
212
- return true;
213
- }
214
- return false;
252
+ static getName() {
253
+ return 'upload';
215
254
  }
216
255
  // check extensions
217
256
  checkAndGetExt(filename, whiteListMap = this.uploadWhiteListMap) {
@@ -253,8 +292,40 @@ let UploadMiddleware = class UploadMiddleware {
253
292
  current: typeInfo.mime,
254
293
  };
255
294
  }
256
- static getName() {
257
- return 'upload';
295
+ isReadableStream(req, isExpress) {
296
+ // ref: https://github.com/rvagg/isstream/blob/master/isstream.js#L10
297
+ if (req instanceof stream_1.Stream &&
298
+ typeof req._read === 'function' &&
299
+ typeof req._readableState === 'object' &&
300
+ (!req.body || isExpress)) {
301
+ return true;
302
+ }
303
+ if (req.pipe && req.on && !req.body) {
304
+ return true;
305
+ }
306
+ return false;
307
+ }
308
+ getUploadBoundary(request) {
309
+ var _a;
310
+ const method = (request.method || request.httpMethod || '').toUpperCase();
311
+ if (method !== 'POST' &&
312
+ method !== 'PUT' &&
313
+ method !== 'DELETE' &&
314
+ method !== 'PATCH') {
315
+ return false;
316
+ }
317
+ if (!((_a = request.headers) === null || _a === void 0 ? void 0 : _a['content-type'])) {
318
+ return false;
319
+ }
320
+ const contentType = request.headers['content-type'];
321
+ if (!contentType.startsWith('multipart/form-data;')) {
322
+ return false;
323
+ }
324
+ const boundaryMatch = /boundary=(.*)(;|\s|$)/.exec(contentType);
325
+ if (!(boundaryMatch === null || boundaryMatch === void 0 ? void 0 : boundaryMatch[1])) {
326
+ return false;
327
+ }
328
+ return boundaryMatch[1];
258
329
  }
259
330
  };
260
331
  __decorate([
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@midwayjs/upload",
3
- "version": "3.16.0",
3
+ "version": "3.17.0-beta.1",
4
4
  "description": "Midway Component for upload",
5
5
  "main": "dist/index.js",
6
6
  "typings": "index.d.ts",
7
7
  "scripts": {
8
8
  "build": "tsc",
9
- "test": "node --require=ts-node/register ../../node_modules/.bin/jest --runInBand",
9
+ "test": "node --require=ts-node/register ../../node_modules/.bin/jest test/express.test.ts --runInBand",
10
10
  "cov": "node --require=ts-node/register ../../node_modules/.bin/jest --runInBand --coverage --forceExit",
11
11
  "ci": "npm run test"
12
12
  },
@@ -23,15 +23,15 @@
23
23
  "license": "MIT",
24
24
  "dependencies": {
25
25
  "file-type": "16.5.4",
26
- "raw-body": "2.5.2"
26
+ "busboy": "1.6.0"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@midwayjs/core": "^3.16.0",
30
30
  "@midwayjs/express": "^3.16.0",
31
31
  "@midwayjs/faas": "^3.16.0",
32
- "@midwayjs/koa": "^3.16.0",
32
+ "@midwayjs/koa": "^3.16.1",
33
33
  "@midwayjs/mock": "^3.16.0",
34
- "@midwayjs/web": "^3.16.0"
35
- },
36
- "gitHead": "7e75fe1bdc9a6df2956f9c22e704063aaa022d76"
34
+ "@midwayjs/web": "^3.16.0",
35
+ "@types/busboy": "1.5.4"
36
+ }
37
37
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2013 - Now midwayjs
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.