utils.js
9.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getConflictPaths = exports.matchMock = exports.normalizeConfig = exports.cleanRequireCache = exports.getMockConfig = exports.getMockData = void 0;
function _react() {
const data = _interopRequireDefault(require("react"));
_react = function _react() {
return data;
};
return data;
}
function _bodyParser() {
const data = _interopRequireDefault(require("@umijs/deps/compiled/body-parser"));
_bodyParser = function _bodyParser() {
return data;
};
return data;
}
function _multer() {
const data = _interopRequireDefault(require("@umijs/deps/compiled/multer"));
_multer = function _multer() {
return data;
};
return data;
}
function _pathToRegexp() {
const data = _interopRequireDefault(require("@umijs/deps/compiled/path-to-regexp"));
_pathToRegexp = function _pathToRegexp() {
return data;
};
return data;
}
function _utils() {
const data = require("@umijs/utils");
_utils = function _utils() {
return data;
};
return data;
}
function _assert() {
const data = _interopRequireDefault(require("assert"));
_assert = function _assert() {
return data;
};
return data;
}
function _fs() {
const data = require("fs");
_fs = function _fs() {
return data;
};
return data;
}
function _path() {
const data = require("path");
_path = function _path() {
return data;
};
return data;
}
var _htmlUtils = require("../../../commands/htmlUtils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const VALID_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
const BODY_PARSED_METHODS = ['post', 'put', 'patch', 'delete'];
const debug = (0, _utils().createDebug)('umi:preset-build-in:mock:utils');
/**
* mock/*
* .umirc.mock.js
* .umirc.mock.ts
* src/** or pages/**
*
* @param param
*/
const getMockData = ({
cwd,
ignore = [],
registerBabel = () => {}
}) => {
const mockPaths = [...(_utils().glob.sync('mock/**/*.[jt]s', {
cwd,
ignore
}) || []), ...(_utils().glob.sync('**/_mock.[jt]s', {
cwd,
ignore
}) || []), '.umirc.mock.js', '.umirc.mock.ts'].map(path => (0, _path().join)(cwd, path)).filter(path => path && (0, _fs().existsSync)(path)).map(path => (0, _utils().winPath)(path));
debug(`load mock data including files ${JSON.stringify(mockPaths)}`); // register babel
registerBabel(mockPaths); // get mock data
const mockData = normalizeConfig(getMockConfig(mockPaths));
const mockWatcherPaths = [...(mockPaths || []), (0, _path().join)(cwd, 'mock')].filter(path => path && (0, _fs().existsSync)(path)).map(path => (0, _utils().winPath)(path));
return {
mockData,
mockPaths,
mockWatcherPaths
};
};
exports.getMockData = getMockData;
const getMockConfig = files => {
return files.reduce((memo, mockFile) => {
try {
const m = require(mockFile); // eslint-disable-line
memo = _objectSpread(_objectSpread({}, memo), m.default || m);
return memo;
} catch (e) {
throw new Error(e.stack);
}
}, {});
};
exports.getMockConfig = getMockConfig;
const cleanRequireCache = paths => {
Object.keys(require.cache).forEach(file => {
if (paths.some(path => {
return (0, _utils().winPath)(file).indexOf(path) > -1;
})) {
delete require.cache[file];
}
});
};
exports.cleanRequireCache = cleanRequireCache;
function parseKey(key) {
let method = 'get';
let path = key;
if (/\s+/.test(key)) {
const splited = key.split(/\s+/);
method = splited[0].toLowerCase();
path = splited[1]; // eslint-disable-line
}
(0, _assert().default)(VALID_METHODS.includes(method), `Invalid method ${method} for path ${path}, please check your mock files.`);
return {
method,
path
};
}
function createHandler(method, path, handler) {
return function (req, res, next) {
if (BODY_PARSED_METHODS.includes(method)) {
_bodyParser().default.json({
limit: '5mb',
strict: false
})(req, res, () => {
_bodyParser().default.urlencoded({
limit: '5mb',
extended: true
})(req, res, () => {
sendData();
});
});
} else {
sendData();
}
function sendData() {
if (typeof handler === 'function') {
(0, _multer().default)().any()(req, res, () => {
handler(req, res, next);
});
} else {
res.json(handler);
}
}
};
}
const normalizeConfig = config => {
return Object.keys(config).reduce((memo, key) => {
const handler = config[key];
const type = typeof handler;
(0, _assert().default)(type === 'function' || type === 'object', `mock value of ${key} should be function or object, but got ${type}`);
const _parseKey = parseKey(key),
method = _parseKey.method,
path = _parseKey.path;
const keys = [];
const re = (0, _pathToRegexp().default)(path, keys);
memo.push({
method,
path,
re,
keys,
handler: createHandler(method, path, handler)
});
return memo;
}, []);
};
exports.normalizeConfig = normalizeConfig;
function decodeParam(val) {
if (typeof val !== 'string' || val.length === 0) {
return val;
}
try {
return decodeURIComponent(val);
} catch (err) {
if (err instanceof URIError) {
err.message = `Failed to decode param ' ${val} '`; // @ts-ignore
err.status = 400; // @ts-ignore
err.statusCode = 400;
}
throw err;
}
}
const matchMock = (req, mockData) => {
const targetPath = req.path,
method = req.method;
const targetMethod = method.toLowerCase();
var _iterator = _createForOfIteratorHelper(mockData),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
const mock = _step.value;
const method = mock.method,
re = mock.re,
keys = mock.keys;
if (method === targetMethod) {
const match = re.exec(targetPath);
if (match) {
const params = {};
for (let i = 1; i < match.length; i += 1) {
const key = keys[i - 1];
const prop = key.name;
const val = decodeParam(match[i]); // @ts-ignore
if (val !== undefined || !hasOwnProdperty.call(params, prop)) {
params[prop] = val;
}
}
req.params = params;
return mock;
}
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return undefined;
};
/**
* check if mock path conflict with router path
* @param param0
*/
exports.matchMock = matchMock;
const getConflictPaths = ({
mockData,
routes
}) => {
const conflictPaths = [];
(0, _htmlUtils.getFlatRoutes)({
routes
}).forEach(route => {
const path = route.path,
redirect = route.redirect;
if (path && !path.startsWith(':') && !redirect) {
const req = {
path: !path.startsWith('/') ? `/${path}` : path,
method: 'get'
};
const matched = matchMock(req, mockData);
if (matched) {
conflictPaths.push({
path: matched.path
});
}
}
});
return conflictPaths;
};
exports.getConflictPaths = getConflictPaths;