@modern-js/bff-core 1.21.5 → 2.0.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.
@@ -14,30 +14,23 @@ export const getPathFromFilename = (baseDir, filename) => {
14
14
  return `:${item.substring(1, item.length - 1)}`;
15
15
  }
16
16
  }
17
-
18
17
  return item;
19
18
  });
20
19
  const name = nameSplit.join('/');
21
20
  const finalName = name.endsWith(INDEX_SUFFIX) ? name.substring(0, name.length - INDEX_SUFFIX.length) : name;
22
21
  return clearRouteName(finalName);
23
22
  };
24
-
25
23
  const clearRouteName = routeName => {
26
24
  let finalRouteName = routeName.trim();
27
-
28
25
  if (!finalRouteName.startsWith('/')) {
29
26
  finalRouteName = `/${finalRouteName}`;
30
27
  }
31
-
32
28
  if (finalRouteName.length > 1 && finalRouteName.endsWith('/')) {
33
29
  finalRouteName = finalRouteName.substring(0, finalRouteName.length - 1);
34
30
  }
35
-
36
31
  return finalRouteName;
37
32
  };
38
-
39
33
  export const isHandler = input => input && typeof input === 'function';
40
-
41
34
  const enableRegister = requireFn => {
42
35
  // esbuild-register 做 unRegister 时,不会删除 register 添加的 require.extensions,导致第二次调用时 require.extensions['.ts'] 是 nodejs 默认 loader
43
36
  // 所以这里根据第一次调用时,require.extensions 有没有,来判断是否需要使用 esbuild-register
@@ -49,12 +42,10 @@ const enableRegister = requireFn => {
49
42
  existTsLoader = Boolean(require.extensions['.ts']);
50
43
  firstCall = false;
51
44
  }
52
-
53
45
  if (!existTsLoader) {
54
46
  const {
55
47
  register
56
48
  } = require('esbuild-register/dist/node');
57
-
58
49
  const {
59
50
  unregister
60
51
  } = register({
@@ -64,36 +55,28 @@ const enableRegister = requireFn => {
64
55
  unregister();
65
56
  return requiredModule;
66
57
  }
67
-
68
58
  const requiredModule = requireFn(modulePath);
69
59
  return requiredModule;
70
60
  };
71
61
  };
72
-
73
62
  const isFunction = input => input && {}.toString.call(input) === '[object Function]';
74
-
75
63
  export const requireHandlerModule = enableRegister(modulePath => {
76
64
  // 测试环境不走缓存,因为缓存的 h andler 文件,会被 mockAPI 函数进行 mock,升级 jest28,setupFilesAfterEnv 能做异步操作的话,可解此问题
77
65
  const originRequire = process.env.NODE_ENV === 'test' ? jest.requireActual : require;
78
66
  const module = originRequire(modulePath);
79
-
80
67
  if (isFunction(module)) {
81
68
  return {
82
69
  default: module
83
70
  };
84
71
  }
85
-
86
72
  return module;
87
73
  });
88
-
89
74
  const routeValue = routePath => {
90
75
  if (routePath.includes(':')) {
91
76
  return 11;
92
77
  }
93
-
94
78
  return 1;
95
79
  };
96
-
97
80
  export const sortRoutes = apiHandlers => {
98
81
  return apiHandlers.sort((handlerA, handlerB) => {
99
82
  return routeValue(handlerA.routeName) - routeValue(handlerB.routeName);
@@ -1,18 +1,13 @@
1
1
  export let OperatorType;
2
-
3
2
  (function (OperatorType) {
4
3
  OperatorType[OperatorType["Trigger"] = 0] = "Trigger";
5
4
  OperatorType[OperatorType["Middleware"] = 1] = "Middleware";
6
5
  })(OperatorType || (OperatorType = {}));
7
-
8
6
  export let TriggerType;
9
-
10
7
  (function (TriggerType) {
11
8
  TriggerType[TriggerType["Http"] = 0] = "Http";
12
9
  })(TriggerType || (TriggerType = {}));
13
-
14
10
  export let HttpMetadata;
15
-
16
11
  (function (HttpMetadata) {
17
12
  HttpMetadata["Method"] = "METHOD";
18
13
  HttpMetadata["Data"] = "DATA";
@@ -21,17 +16,13 @@ export let HttpMetadata;
21
16
  HttpMetadata["Headers"] = "HEADERS";
22
17
  HttpMetadata["Response"] = "RESPONSE";
23
18
  })(HttpMetadata || (HttpMetadata = {}));
24
-
25
19
  export let ResponseMetaType;
26
-
27
20
  (function (ResponseMetaType) {
28
21
  ResponseMetaType[ResponseMetaType["StatusCode"] = 0] = "StatusCode";
29
22
  ResponseMetaType[ResponseMetaType["Redirect"] = 1] = "Redirect";
30
23
  ResponseMetaType[ResponseMetaType["Headers"] = 2] = "Headers";
31
24
  })(ResponseMetaType || (ResponseMetaType = {}));
32
-
33
25
  export let HttpMethod;
34
-
35
26
  (function (HttpMethod) {
36
27
  HttpMethod["Get"] = "GET";
37
28
  HttpMethod["Post"] = "POST";
@@ -43,5 +34,4 @@ export let HttpMethod;
43
34
  HttpMethod["Option"] = "OPTION";
44
35
  HttpMethod["Head"] = "HEAD";
45
36
  })(HttpMethod || (HttpMethod = {}));
46
-
47
37
  export const httpMethods = Object.values(HttpMethod);
@@ -4,7 +4,6 @@ import fs from 'fs';
4
4
  import Module from 'module';
5
5
  export const getRelativeRuntimePath = (appDirectory, serverRuntimePath) => {
6
6
  let relativeRuntimePath = '';
7
-
8
7
  if (os.platform() === 'win32') {
9
8
  // isRelative function in babel-plugin-resolver plugin can't handle windows relative path correctly, see babel-plugin-resolver's utils.
10
9
  relativeRuntimePath = `../${path.relative(appDirectory, serverRuntimePath)}`;
@@ -12,18 +11,14 @@ export const getRelativeRuntimePath = (appDirectory, serverRuntimePath) => {
12
11
  // Look up one level, because the artifacts after build have dist directories
13
12
  relativeRuntimePath = path.join('../', path.relative(appDirectory, serverRuntimePath));
14
13
  }
15
-
16
14
  if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
17
15
  relativeRuntimePath = `./${path.relative(appDirectory, serverRuntimePath)}`;
18
16
  }
19
-
20
17
  return relativeRuntimePath;
21
18
  };
22
-
23
19
  const sortByLongestPrefix = arr => {
24
20
  return arr.concat().sort((a, b) => b.length - a.length);
25
21
  };
26
-
27
22
  export const createMatchPath = paths => {
28
23
  const sortedKeys = sortByLongestPrefix(Object.keys(paths));
29
24
  const sortedPaths = {};
@@ -34,57 +29,45 @@ export const createMatchPath = paths => {
34
29
  const found = Object.keys(sortedPaths).find(key => {
35
30
  return request.startsWith(key);
36
31
  });
37
-
38
32
  if (found) {
39
33
  let foundPaths = sortedPaths[found];
40
-
41
34
  if (!Array.isArray(foundPaths)) {
42
35
  foundPaths = [foundPaths];
43
36
  }
44
-
45
37
  foundPaths = foundPaths.filter(foundPath => path.isAbsolute(foundPath));
46
-
47
38
  for (const p of foundPaths) {
48
39
  const foundPath = request.replace(found, p);
49
-
50
40
  if (fs.existsSync(foundPath)) {
51
41
  return foundPath;
52
42
  }
53
43
  }
54
-
55
44
  return request.replace(found, foundPaths[0]);
56
45
  }
57
-
58
46
  return null;
59
47
  };
60
- }; // every path must be a absolute path;
48
+ };
61
49
 
50
+ // every path must be a absolute path;
62
51
  export const registerPaths = paths => {
63
- const originalResolveFilename = Module._resolveFilename; // eslint-disable-next-line node/no-unsupported-features/node-builtins
64
-
52
+ const originalResolveFilename = Module._resolveFilename;
53
+ // eslint-disable-next-line node/no-unsupported-features/node-builtins
65
54
  const {
66
55
  builtinModules
67
56
  } = Module;
68
57
  const matchPath = createMatchPath(paths);
69
-
70
58
  Module._resolveFilename = function (request, _parent) {
71
59
  const isCoreModule = builtinModules.includes(request);
72
-
73
60
  if (!isCoreModule) {
74
61
  const matched = matchPath(request);
75
-
76
62
  if (matched) {
77
63
  // eslint-disable-next-line prefer-rest-params
78
64
  const modifiedArguments = [matched, ...[].slice.call(arguments, 1)]; // Passes all arguments. Even those that is not specified above.
79
-
80
65
  return originalResolveFilename.apply(this, modifiedArguments);
81
66
  }
82
- } // eslint-disable-next-line prefer-rest-params
83
-
84
-
67
+ }
68
+ // eslint-disable-next-line prefer-rest-params
85
69
  return originalResolveFilename.apply(this, arguments);
86
70
  };
87
-
88
71
  return () => {
89
72
  Module._resolveFilename = originalResolveFilename;
90
73
  };
@@ -1,18 +1,14 @@
1
1
  import * as ah from 'async_hooks';
2
-
3
2
  const createStorage = () => {
4
3
  let storage;
5
-
6
4
  if (typeof ah.AsyncLocalStorage !== 'undefined') {
7
5
  storage = new ah.AsyncLocalStorage();
8
6
  }
9
-
10
7
  const run = (context, cb) => {
11
8
  if (!storage) {
12
9
  throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
13
10
  `);
14
11
  }
15
-
16
12
  return new Promise((resolve, reject) => {
17
13
  storage.run(context, () => {
18
14
  try {
@@ -23,26 +19,20 @@ const createStorage = () => {
23
19
  });
24
20
  });
25
21
  };
26
-
27
22
  const useContext = () => {
28
23
  if (!storage) {
29
24
  throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
30
25
  `);
31
26
  }
32
-
33
27
  const context = storage.getStore();
34
-
35
28
  if (!context) {
36
29
  throw new Error(`Can't call useContext out of scope, it should be placed in the bff function`);
37
30
  }
38
-
39
31
  return context;
40
32
  };
41
-
42
33
  return {
43
34
  run,
44
35
  useContext
45
36
  };
46
37
  };
47
-
48
38
  export { createStorage };
@@ -1,15 +1,14 @@
1
- import util from 'util'; // fork from https://github.com/nodejs/node/blob/master/lib/internal/errors.js
1
+ import util from 'util';
2
2
 
3
+ // fork from https://github.com/nodejs/node/blob/master/lib/internal/errors.js
3
4
  export const getTypeErrorMessage = actual => {
4
5
  let msg = '';
5
-
6
6
  if (actual == null) {
7
7
  msg += `. Received ${actual}`;
8
8
  } else if (typeof actual === 'function' && actual.name) {
9
9
  msg += `. Received function ${actual.name}`;
10
10
  } else if (typeof actual === 'object') {
11
11
  var _actual$constructor;
12
-
13
12
  if ((_actual$constructor = actual.constructor) !== null && _actual$constructor !== void 0 && _actual$constructor.name) {
14
13
  msg += `. Received an instance of ${actual.constructor.name}`;
15
14
  } else {
@@ -22,28 +21,24 @@ export const getTypeErrorMessage = actual => {
22
21
  let inspected = util.inspect(actual, {
23
22
  colors: false
24
23
  });
25
-
26
24
  if (inspected.length > 25) {
27
25
  inspected = `${inspected.slice(0, 25)}...`;
28
26
  }
29
-
30
27
  msg += `. Received type ${typeof actual} (${inspected})`;
31
28
  }
32
-
33
29
  return msg;
34
- }; // eslint-disable-next-line @typescript-eslint/naming-convention
30
+ };
35
31
 
32
+ // eslint-disable-next-line @typescript-eslint/naming-convention
36
33
  export class ERR_INVALID_ARG_TYPE extends Error {
37
34
  constructor(funcName, expectedType, actual) {
38
35
  const message = `[ERR_INVALID_ARG_TYPE]: The '${funcName}' argument must be of type ${expectedType}${getTypeErrorMessage(actual)}`;
39
36
  super(message);
40
37
  }
41
-
42
38
  }
43
39
  export const validateFunction = (maybeFunc, name) => {
44
40
  if (typeof maybeFunc !== 'function') {
45
41
  throw new ERR_INVALID_ARG_TYPE(name, 'function', maybeFunc);
46
42
  }
47
-
48
43
  return true;
49
44
  };
@@ -4,15 +4,10 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.Api = Api;
7
-
8
7
  require("reflect-metadata");
9
-
10
8
  var _koaCompose = _interopRequireDefault(require("koa-compose"));
11
-
12
9
  var _utils = require("./utils");
13
-
14
10
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
-
16
11
  function Api(...args) {
17
12
  const handler = args.pop();
18
13
  (0, _utils.validateFunction)(handler, 'Apihandler');
@@ -21,35 +16,27 @@ function Api(...args) {
21
16
  getMetadata(key) {
22
17
  return Reflect.getMetadata(key, runner);
23
18
  },
24
-
25
19
  setMetadata(key, value) {
26
20
  return Reflect.defineMetadata(key, value, runner);
27
21
  }
28
-
29
22
  };
30
-
31
23
  for (const operator of operators) {
32
24
  if (operator.metadata) {
33
25
  operator.metadata(metadataHelper);
34
26
  }
35
27
  }
36
-
37
28
  const validateHandlers = operators.filter(operator => operator.validate).map(operator => operator.validate);
38
29
  const pipeHandlers = operators.filter(operator => operator.execute).map(operator => operator.execute);
39
-
40
30
  async function runner(inputs) {
41
31
  const executeHelper = {
42
32
  result: null,
43
-
44
33
  get inputs() {
45
34
  return inputs;
46
35
  },
47
-
48
36
  set inputs(val) {
49
37
  // eslint-disable-next-line no-param-reassign
50
38
  inputs = val;
51
39
  }
52
-
53
40
  };
54
41
  const stack = [...validateHandlers, ...pipeHandlers];
55
42
  stack.push(async (helper, next) => {
@@ -60,7 +47,6 @@ function Api(...args) {
60
47
  await (0, _koaCompose.default)(stack)(executeHelper);
61
48
  return executeHelper.result;
62
49
  }
63
-
64
50
  runner[_utils.HANDLER_WITH_META] = true;
65
51
  return runner;
66
52
  }
@@ -4,20 +4,13 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.generateClient = exports.DEFAULT_CLIENT_REQUEST_CREATOR = void 0;
7
-
8
7
  var path = _interopRequireWildcard(require("path"));
9
-
10
8
  var _router = require("../router");
11
-
12
9
  var _result = require("./result");
13
-
14
10
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
15
-
16
11
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
17
-
18
12
  const DEFAULT_CLIENT_REQUEST_CREATOR = '@modern-js/create-request';
19
13
  exports.DEFAULT_CLIENT_REQUEST_CREATOR = DEFAULT_CLIENT_REQUEST_CREATOR;
20
-
21
14
  const generateClient = async ({
22
15
  resourcePath,
23
16
  apiDir,
@@ -34,27 +27,21 @@ const generateClient = async ({
34
27
  } else {
35
28
  // 这里约束传入的 requestCreator 包也必须有两个导出 client 和 server,因为目前的机制 client 和 server 要导出不同的 configure 函数;该 api 不对使用者暴露,后续可优化
36
29
  let resolvedPath = requestCreator;
37
-
38
30
  try {
39
31
  resolvedPath = path.dirname(_requireResolve(requestCreator));
40
- } catch (error) {} // eslint-disable-next-line no-param-reassign
41
-
42
-
32
+ } catch (error) {}
33
+ // eslint-disable-next-line no-param-reassign
43
34
  requestCreator = `${resolvedPath}${target ? `/${target}` : ''}`.replace(/\\/g, '/');
44
35
  }
45
-
46
36
  const apiRouter = new _router.ApiRouter({
47
37
  apiDir,
48
38
  prefix
49
39
  });
50
40
  const handlerInfos = apiRouter.getSingleModuleHandlers(resourcePath);
51
-
52
41
  if (!handlerInfos) {
53
42
  return (0, _result.Err)(`generate client error: Cannot require module ${resourcePath}`);
54
43
  }
55
-
56
44
  let handlersCode = '';
57
-
58
45
  for (const handlerInfo of handlerInfos) {
59
46
  const {
60
47
  name,
@@ -62,20 +49,16 @@ const generateClient = async ({
62
49
  routePath
63
50
  } = handlerInfo;
64
51
  let exportStatement = `const ${name} =`;
65
-
66
52
  if (name.toLowerCase() === 'default') {
67
53
  exportStatement = 'default';
68
54
  }
69
-
70
55
  const upperHttpMethod = httpMethod.toUpperCase();
71
56
  const routeName = routePath;
72
57
  handlersCode += `export ${exportStatement} createRequest('${routeName}', '${upperHttpMethod}', process.env.PORT || ${String(port)}${fetcher ? `, fetch` : ''});
73
58
  `;
74
59
  }
75
-
76
60
  const importCode = `import { createRequest } from '${requestCreator}';
77
61
  ${fetcher ? `import { fetch } from '${fetcher}';\n` : ''}`;
78
62
  return (0, _result.Ok)(`${importCode}\n${handlersCode}`);
79
63
  };
80
-
81
64
  exports.generateClient = generateClient;
@@ -3,9 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
-
7
6
  var _generateClient = require("./generate-client");
8
-
9
7
  Object.keys(_generateClient).forEach(function (key) {
10
8
  if (key === "default" || key === "__esModule") return;
11
9
  if (key in exports && exports[key] === _generateClient[key]) return;
@@ -4,7 +4,6 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.Ok = exports.Err = void 0;
7
-
8
7
  // eslint-disable-next-line @typescript-eslint/no-redeclare
9
8
  const Err = value => {
10
9
  const err = {
@@ -14,11 +13,10 @@ const Err = value => {
14
13
  isOk: false
15
14
  };
16
15
  return err;
17
- }; // eslint-disable-next-line @typescript-eslint/no-redeclare
18
-
16
+ };
19
17
 
18
+ // eslint-disable-next-line @typescript-eslint/no-redeclare
20
19
  exports.Err = Err;
21
-
22
20
  const Ok = value => {
23
21
  const ok = {
24
22
  kind: 'Ok',
@@ -28,5 +26,4 @@ const Ok = value => {
28
26
  };
29
27
  return ok;
30
28
  };
31
-
32
29
  exports.Ok = Ok;
@@ -4,31 +4,20 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.ValidationError = exports.HttpError = void 0;
7
-
8
7
  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; }
9
-
10
8
  class HttpError extends Error {
11
9
  constructor(status, message) {
12
10
  super(message);
13
-
14
11
  _defineProperty(this, "status", void 0);
15
-
16
12
  this.status = status;
17
13
  }
18
-
19
14
  }
20
-
21
15
  exports.HttpError = HttpError;
22
-
23
16
  class ValidationError extends HttpError {
24
17
  constructor(status, message) {
25
18
  super(status, message);
26
-
27
19
  _defineProperty(this, "code", void 0);
28
-
29
20
  this.code = 'VALIDATION_ERROR';
30
21
  }
31
-
32
22
  }
33
-
34
23
  exports.ValidationError = ValidationError;
@@ -61,13 +61,9 @@ Object.defineProperty(exports, "registerPaths", {
61
61
  return _utils.registerPaths;
62
62
  }
63
63
  });
64
-
65
64
  var _api = require("./api");
66
-
67
65
  var _http = require("./errors/http");
68
-
69
66
  var _router = require("./router");
70
-
71
67
  Object.keys(_router).forEach(function (key) {
72
68
  if (key === "default" || key === "__esModule") return;
73
69
  if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
@@ -79,9 +75,7 @@ Object.keys(_router).forEach(function (key) {
79
75
  }
80
76
  });
81
77
  });
82
-
83
78
  var _types = require("./types");
84
-
85
79
  Object.keys(_types).forEach(function (key) {
86
80
  if (key === "default" || key === "__esModule") return;
87
81
  if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
@@ -93,9 +87,7 @@ Object.keys(_types).forEach(function (key) {
93
87
  }
94
88
  });
95
89
  });
96
-
97
90
  var _client = require("./client");
98
-
99
91
  Object.keys(_client).forEach(function (key) {
100
92
  if (key === "default" || key === "__esModule") return;
101
93
  if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
@@ -107,9 +99,7 @@ Object.keys(_client).forEach(function (key) {
107
99
  }
108
100
  });
109
101
  });
110
-
111
102
  var _http2 = require("./operators/http");
112
-
113
103
  Object.keys(_http2).forEach(function (key) {
114
104
  if (key === "default" || key === "__esModule") return;
115
105
  if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
@@ -121,5 +111,4 @@ Object.keys(_http2).forEach(function (key) {
121
111
  }
122
112
  });
123
113
  });
124
-
125
114
  var _utils = require("./utils");