@modern-js/server 1.2.2-beta.0 → 1.3.2

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.
Files changed (61) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/dist/js/modern/server/dev-server/dev-server.js +7 -3
  3. package/dist/js/node/server/dev-server/dev-server.js +7 -3
  4. package/dist/types/type.d.ts +1 -1
  5. package/jest.config.js +1 -0
  6. package/package.json +10 -10
  7. package/tests/dev.test.ts +7 -2
  8. package/tests/fixtures/pure/tsconfig.json +0 -1
  9. package/tests/server.test.ts +19 -0
  10. package/tests/watcher.test.ts +98 -0
  11. package/dist.zip +0 -0
  12. package/src/constants.ts +0 -26
  13. package/src/dev-tools/babel/register.ts +0 -37
  14. package/src/dev-tools/dev-server-plugin.ts +0 -48
  15. package/src/dev-tools/https/global.d.ts +0 -3
  16. package/src/dev-tools/https/index.ts +0 -12
  17. package/src/dev-tools/launch-editor/index.ts +0 -29
  18. package/src/dev-tools/mock/getMockData.ts +0 -109
  19. package/src/dev-tools/mock/index.ts +0 -63
  20. package/src/dev-tools/socket-server.ts +0 -192
  21. package/src/dev-tools/watcher/dependency-tree.ts +0 -94
  22. package/src/dev-tools/watcher/index.ts +0 -80
  23. package/src/dev-tools/watcher/stats-cache.ts +0 -53
  24. package/src/index.ts +0 -16
  25. package/src/libs/context/context.ts +0 -176
  26. package/src/libs/context/index.ts +0 -7
  27. package/src/libs/hook-api/route.ts +0 -38
  28. package/src/libs/hook-api/template.ts +0 -53
  29. package/src/libs/metrics.ts +0 -15
  30. package/src/libs/proxy.ts +0 -85
  31. package/src/libs/render/cache/__tests__/cache.fun.test.ts +0 -94
  32. package/src/libs/render/cache/__tests__/cache.test.ts +0 -240
  33. package/src/libs/render/cache/__tests__/cacheable.ts +0 -44
  34. package/src/libs/render/cache/__tests__/error-configuration.ts +0 -34
  35. package/src/libs/render/cache/__tests__/matched-cache.ts +0 -88
  36. package/src/libs/render/cache/index.ts +0 -75
  37. package/src/libs/render/cache/page-caches/index.ts +0 -11
  38. package/src/libs/render/cache/page-caches/lru.ts +0 -38
  39. package/src/libs/render/cache/spr.ts +0 -301
  40. package/src/libs/render/cache/type.ts +0 -59
  41. package/src/libs/render/cache/util.ts +0 -97
  42. package/src/libs/render/index.ts +0 -78
  43. package/src/libs/render/modern/browser-list.ts +0 -7
  44. package/src/libs/render/modern/index.ts +0 -41
  45. package/src/libs/render/modern/module.d.ts +0 -4
  46. package/src/libs/render/reader.ts +0 -119
  47. package/src/libs/render/ssr.ts +0 -62
  48. package/src/libs/render/static.ts +0 -52
  49. package/src/libs/render/type.ts +0 -38
  50. package/src/libs/route/index.ts +0 -77
  51. package/src/libs/route/matcher.ts +0 -93
  52. package/src/libs/route/route.ts +0 -32
  53. package/src/libs/serve-file.ts +0 -34
  54. package/src/server/dev-server/dev-server-split.ts +0 -41
  55. package/src/server/dev-server/dev-server.ts +0 -297
  56. package/src/server/dev-server/index.ts +0 -2
  57. package/src/server/index.ts +0 -163
  58. package/src/server/modern-server-split.ts +0 -97
  59. package/src/server/modern-server.ts +0 -636
  60. package/src/type.ts +0 -88
  61. package/src/utils.ts +0 -79
package/CHANGELOG.md CHANGED
@@ -1,5 +1,64 @@
1
1
  # @modern-js/server
2
2
 
3
+ ## 1.3.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 83166714: change .npmignore
8
+ - Updated dependencies [83166714]
9
+ - Updated dependencies [c3de9882]
10
+ - Updated dependencies [33ff48af]
11
+ - @modern-js/core@1.3.2
12
+ - @modern-js/bff-utils@1.2.2
13
+ - @modern-js/hmr-client@1.2.1
14
+ - @modern-js/server-plugin@1.2.1
15
+ - @modern-js/server-utils@1.2.1
16
+ - @modern-js/utils@1.2.2
17
+
18
+ ## 1.3.1
19
+
20
+ ### Patch Changes
21
+
22
+ - e2d3a575: fix extending core config interface
23
+ - 823809c6: fix: hot reload not working on windows
24
+ - e2d3a575: fix extending core config interface
25
+ - Updated dependencies [823809c6]
26
+ - Updated dependencies [4584cc04]
27
+ - Updated dependencies [7c19fd94]
28
+ - @modern-js/bff-utils@1.2.1
29
+ - @modern-js/utils@1.2.1
30
+ - @modern-js/core@1.3.1
31
+
32
+ ## 1.3.0
33
+
34
+ ### Minor Changes
35
+
36
+ - cfe11628: Make Modern.js self bootstraping
37
+
38
+ ### Patch Changes
39
+
40
+ - 146dcd85: modify server framework plugin hook types and hook context
41
+ - c3d46ee4: fix: test config invalid
42
+ - 146dcd85: modify server framework plugin hook types
43
+ - 146dcd85: fix test case in babel compiler
44
+ - 1ebc7ee2: fix: @babel/core version
45
+ - Updated dependencies [2da09c69]
46
+ - Updated dependencies [fc71e36f]
47
+ - Updated dependencies [146dcd85]
48
+ - Updated dependencies [74ce3bb7]
49
+ - Updated dependencies [c3d46ee4]
50
+ - Updated dependencies [cfe11628]
51
+ - Updated dependencies [146dcd85]
52
+ - Updated dependencies [8e7603ee]
53
+ - Updated dependencies [146dcd85]
54
+ - Updated dependencies [1ebc7ee2]
55
+ - @modern-js/utils@1.2.0
56
+ - @modern-js/core@1.3.0
57
+ - @modern-js/server-utils@1.2.0
58
+ - @modern-js/hmr-client@1.2.0
59
+ - @modern-js/bff-utils@1.2.0
60
+ - @modern-js/server-plugin@1.2.0
61
+
3
62
  ## 1.2.1
4
63
 
5
64
  ### Patch Changes
@@ -121,9 +121,13 @@ export class ModernDevServer extends ModernServer {
121
121
  super.close();
122
122
  await this.watcher.close();
123
123
  await new Promise(resolve => {
124
- this.devMiddleware.close(() => {
124
+ if (this.devMiddleware) {
125
+ this.devMiddleware.close(() => {
126
+ resolve();
127
+ });
128
+ } else {
125
129
  resolve();
126
- });
130
+ }
127
131
  });
128
132
  }
129
133
 
@@ -248,7 +252,7 @@ export class ModernDevServer extends ModernServer {
248
252
  watcher.listen(defaultWatchedPaths, {
249
253
  // 初始化的时候不触发 add、addDir 事件
250
254
  ignoreInitial: true,
251
- ignored: /api\/typings\/**/
255
+ ignored: /api\/typings\/.*/
252
256
  }, filepath => {
253
257
  watcher.updateDepTree();
254
258
  watcher.cleanDepCache(filepath);
@@ -150,9 +150,13 @@ class ModernDevServer extends _modernServer.ModernServer {
150
150
  super.close();
151
151
  await this.watcher.close();
152
152
  await new Promise(resolve => {
153
- this.devMiddleware.close(() => {
153
+ if (this.devMiddleware) {
154
+ this.devMiddleware.close(() => {
155
+ resolve();
156
+ });
157
+ } else {
154
158
  resolve();
155
- });
159
+ }
156
160
  });
157
161
  }
158
162
 
@@ -279,7 +283,7 @@ class ModernDevServer extends _modernServer.ModernServer {
279
283
  watcher.listen(defaultWatchedPaths, {
280
284
  // 初始化的时候不触发 add、addDir 事件
281
285
  ignoreInitial: true,
282
- ignored: /api\/typings\/**/
286
+ ignored: /api\/typings\/.*/
283
287
  }, filepath => {
284
288
  watcher.updateDepTree();
285
289
  watcher.cleanDepCache(filepath);
@@ -12,7 +12,7 @@ declare module 'http' {
12
12
  }
13
13
  declare module '@modern-js/core' {
14
14
  interface UserConfig {
15
- bff: {
15
+ bff?: {
16
16
  proxy: Record<string, any>;
17
17
  };
18
18
  }
package/jest.config.js CHANGED
@@ -4,5 +4,6 @@ const sharedConfig = require('@scripts/jest-config');
4
4
  module.exports = {
5
5
  // eslint-disable-next-line node/no-unsupported-features/es-syntax
6
6
  ...sharedConfig,
7
+ testEnvironment: 'node',
7
8
  rootDir: __dirname,
8
9
  };
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "modern",
12
12
  "modern.js"
13
13
  ],
14
- "version": "1.2.2-beta.0",
14
+ "version": "1.3.2",
15
15
  "jsnext:source": "./src/index.ts",
16
16
  "types": "./dist/types/index.d.ts",
17
17
  "main": "./dist/js/node/index.js",
@@ -28,19 +28,19 @@
28
28
  }
29
29
  },
30
30
  "dependencies": {
31
- "@babel/core": "^7.15.0",
31
+ "@babel/core": "7.16.7",
32
32
  "@babel/compat-data": "^7.15.0",
33
33
  "@babel/preset-env": "^7.15.0",
34
34
  "@babel/preset-typescript": "^7.15.0",
35
35
  "@babel/register": "^7.15.3",
36
36
  "@babel/runtime": "^7",
37
- "@modern-js/core": "^1.2.0",
38
- "@modern-js/hmr-client": "^1.1.1",
39
- "@modern-js/server-plugin": "^1.1.4",
40
- "@modern-js/server-utils": "^1.1.2",
41
- "@modern-js/bff-utils": "^1.1.1",
42
- "@modern-js/utils": "^1.1.6",
43
- "axios": "^0.21.4",
37
+ "@modern-js/core": "^1.3.2",
38
+ "@modern-js/hmr-client": "^1.2.1",
39
+ "@modern-js/server-plugin": "^1.2.1",
40
+ "@modern-js/server-utils": "^1.2.1",
41
+ "@modern-js/bff-utils": "^1.2.2",
42
+ "@modern-js/utils": "^1.2.2",
43
+ "axios": "^0.24.0",
44
44
  "babel-plugin-module-resolver": "^4.1.0",
45
45
  "chokidar": "^3.5.2",
46
46
  "compare-versions": "^3.6.0",
@@ -64,7 +64,7 @@
64
64
  },
65
65
  "devDependencies": {
66
66
  "@scripts/build": "0.0.0",
67
- "@modern-js/types": "^1.1.5",
67
+ "@modern-js/types": "^1.2.1",
68
68
  "@types/jest": "^26",
69
69
  "@types/lru-cache": "^5.1.1",
70
70
  "@types/mime-types": "^2.1.0",
package/tests/dev.test.ts CHANGED
@@ -1,11 +1,16 @@
1
1
  import http from 'http';
2
2
  import SocketServer from '../src/dev-tools/socket-server';
3
3
 
4
+ function getRandomPort() {
5
+ return Math.floor(Math.random() * (8000 - 1024)) + 1024;
6
+ }
7
+
4
8
  describe('test dev tools', () => {
5
9
  test('should socket server work correctly', () => {
10
+ const port = getRandomPort();
6
11
  const socketServer: any = new SocketServer({
7
12
  client: {
8
- port: '8080',
13
+ port: port.toString(),
9
14
  overlay: false,
10
15
  logging: 'error',
11
16
  path: '/',
@@ -22,7 +27,7 @@ describe('test dev tools', () => {
22
27
  .createServer((req, res) => {
23
28
  res.end();
24
29
  })
25
- .listen(8080);
30
+ .listen(port);
26
31
 
27
32
  socketServer.prepare(app);
28
33
  expect(socketServer.app).toBe(app);
@@ -5,7 +5,6 @@
5
5
  "jsx": "preserve",
6
6
  "baseUrl": "./",
7
7
  "paths": {
8
- ,
9
8
  "@shared/*": ["./shared/*"]
10
9
  }
11
10
  },
@@ -3,6 +3,7 @@ import { defaultsConfig, NormalizedConfig } from '@modern-js/core';
3
3
  import { ModernServerContext, NextFunction } from '@modern-js/types';
4
4
  import createServer, { Server } from '../src';
5
5
  import { ModernServer } from '../src/server/modern-server';
6
+ import Watcher from '../src/dev-tools/watcher';
6
7
 
7
8
  describe('test server', () => {
8
9
  test('should throw error when ', resolve => {
@@ -99,3 +100,21 @@ describe('test server', () => {
99
100
  });
100
101
  });
101
102
  });
103
+
104
+ describe('dev server', () => {
105
+ const pwd = path.join(__dirname, './fixtures/pure');
106
+ let devServer: Server;
107
+
108
+ test('watch', async () => {
109
+ devServer = await createServer({
110
+ config: defaultsConfig as NormalizedConfig,
111
+ pwd,
112
+ dev: true,
113
+ });
114
+
115
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
116
+ // @ts-expect-error
117
+ expect(devServer.server.watcher).toBeInstanceOf(Watcher);
118
+ await devServer.close();
119
+ });
120
+ });
@@ -0,0 +1,98 @@
1
+ import * as path from 'path';
2
+ import { fs } from '@modern-js/utils';
3
+ import Watcher from '../src/dev-tools/watcher';
4
+
5
+ jest.useRealTimers();
6
+
7
+ describe('watcher', () => {
8
+ let watcher: Watcher;
9
+ jest.setTimeout(25000);
10
+ beforeAll(() => {
11
+ watcher = new Watcher();
12
+ });
13
+
14
+ test('should emit change', done => {
15
+ const pwd = path.join(__dirname, './fixtures/pure');
16
+ const serverDir = path.normalize(path.join(pwd, './tmp-server'));
17
+
18
+ const callback = jest.fn();
19
+ if (fs.pathExistsSync(serverDir)) {
20
+ fs.removeSync(serverDir);
21
+ }
22
+ const writeFiles = () => {
23
+ fs.writeFileSync(
24
+ path.normalize(path.join(serverDir, 'index.js')),
25
+ 'test',
26
+ 'utf8',
27
+ );
28
+ };
29
+
30
+ const clear = () => {
31
+ fs.removeSync(serverDir);
32
+ };
33
+
34
+ fs.mkdirSync(serverDir);
35
+
36
+ watcher.listen(
37
+ [`${serverDir}/**/*`],
38
+ {
39
+ ignoreInitial: true,
40
+ ignored: /api\/typings\/.*/,
41
+ },
42
+ async () => {
43
+ callback();
44
+ expect(callback).toHaveBeenCalledTimes(1);
45
+ await watcher.close();
46
+ clear();
47
+ done();
48
+ },
49
+ );
50
+
51
+ setTimeout(writeFiles, 100);
52
+ });
53
+
54
+ test('should not emit change when typings file changed', done => {
55
+ const pwd = path.join(__dirname, './fixtures/pure');
56
+ const apiDir = path.normalize(path.join(pwd, './api'));
57
+
58
+ const callback = jest.fn();
59
+
60
+ if (fs.pathExistsSync(apiDir)) {
61
+ fs.removeSync(apiDir);
62
+ }
63
+
64
+ const writeFiles = () => {
65
+ fs.writeFileSync(
66
+ path.normalize(path.join(apiDir, 'typings/index.js')),
67
+ 'test',
68
+ 'utf8',
69
+ );
70
+ };
71
+
72
+ const clear = () => {
73
+ fs.removeSync(apiDir);
74
+ };
75
+
76
+ fs.mkdirSync(path.normalize(path.join(apiDir, 'typings')), {
77
+ recursive: true,
78
+ });
79
+
80
+ watcher.listen(
81
+ [`${apiDir}/**/*`],
82
+ {
83
+ ignoreInitial: true,
84
+ ignored: /api\/typings\/.*/,
85
+ },
86
+ callback,
87
+ );
88
+
89
+ setTimeout(async () => {
90
+ expect(callback).toHaveBeenCalledTimes(0);
91
+ await watcher.close();
92
+ clear();
93
+ done();
94
+ }, 1000);
95
+
96
+ setTimeout(writeFiles);
97
+ });
98
+ });
package/dist.zip DELETED
Binary file
package/src/constants.ts DELETED
@@ -1,26 +0,0 @@
1
- export const AGGRED_DIR = {
2
- mock: 'config/mock',
3
- server: 'server',
4
- api: 'api',
5
- shared: 'shared',
6
- lambda: 'lambda',
7
- };
8
-
9
- export enum ApiServerMode {
10
- func = 'function',
11
- frame = 'framework',
12
- }
13
-
14
- export const ERROR_DIGEST = {
15
- INIT: 'Server init error',
16
- ENOTF: 'Page could not be found',
17
- WARMUP: 'SSR warmup failed',
18
- EINTER: 'Internal server error',
19
- ERENDER: 'SSR render failed',
20
- EMICROINJ: 'Get micro-frontend info failed',
21
- };
22
-
23
- export const ERROR_PAGE_TEXT: Record<number, string> = {
24
- 404: 'This page could not be found.',
25
- 500: 'Internal Server Error.',
26
- };
@@ -1,37 +0,0 @@
1
- import path from 'path';
2
- import { resolveBabelConfig } from '@modern-js/server-utils';
3
- import { ModernServerOptions } from '../../type';
4
-
5
- const registerDirs = ['./api', './server', './config/mock', './shared'];
6
-
7
- export const enableRegister = (
8
- projectRoot: string,
9
- config: ModernServerOptions['config'],
10
- ) => {
11
- const TS_CONFIG_FILENAME = `tsconfig.json`;
12
- const tsconfigPath = path.resolve(projectRoot, TS_CONFIG_FILENAME);
13
-
14
- const babelConfig = resolveBabelConfig(projectRoot, config, {
15
- tsconfigPath,
16
- syntax: 'es6+',
17
- type: 'commonjs',
18
- });
19
-
20
- return require('@babel/register')({
21
- ...babelConfig,
22
- only: [
23
- function (filePath: string) {
24
- // TODO: wait params
25
- if (filePath.includes(`node_modules${path.sep}.modern-js`)) {
26
- return true;
27
- }
28
- return registerDirs.some(registerDir =>
29
- filePath.startsWith(path.join(projectRoot, registerDir)),
30
- );
31
- },
32
- ],
33
- extensions: ['.js', '.ts'],
34
- babelrc: false,
35
- root: projectRoot,
36
- });
37
- };
@@ -1,48 +0,0 @@
1
- import Webpack from 'webpack';
2
- import { DevServerOptions } from '../type';
3
-
4
- const { EntryPlugin } = Webpack;
5
- export default class DevServerPlugin {
6
- private readonly options: DevServerOptions;
7
-
8
- constructor(options: DevServerOptions) {
9
- this.options = options;
10
- }
11
-
12
- apply(compiler: Webpack.Compiler) {
13
- const { options } = this;
14
-
15
- const host = `&host=${options.client.host || 'localhost'}`;
16
- const path = `&path=${options.client.path}`;
17
- const port = `&port=${options.client.port}`;
18
-
19
- // Todo @songzhenwei
20
- const clientEntry = `${require.resolve(
21
- '@modern-js/hmr-client',
22
- )}?${host}${path}${port}`;
23
- const hotEntry = require.resolve('webpack/hot/dev-server');
24
- const additionalEntries = [clientEntry, hotEntry];
25
-
26
- // use a hook to add entries if available
27
- for (const additionalEntry of additionalEntries) {
28
- new EntryPlugin(compiler.context, additionalEntry, {
29
- name: undefined,
30
- }).apply(compiler);
31
- }
32
-
33
- // Todo remove, client must inject.
34
- const compilerOptions = compiler.options;
35
- compilerOptions.plugins = compilerOptions.plugins || [];
36
- if (
37
- hotEntry &&
38
- !compilerOptions.plugins.find(
39
- p => p.constructor === Webpack.HotModuleReplacementPlugin,
40
- )
41
- ) {
42
- // apply the HMR plugin, if it didn't exist before.
43
- const plugin = new Webpack.HotModuleReplacementPlugin();
44
-
45
- plugin.apply(compiler);
46
- }
47
- }
48
- }
@@ -1,3 +0,0 @@
1
- declare module 'selfsigned' {
2
- function generate(attributes: any, opt: any): { private: any; cert: any };
3
- }
@@ -1,12 +0,0 @@
1
- import * as devcert from 'devcert';
2
-
3
- export const genHttpsOptions = async (userOptions: any) => {
4
- const httpsOptions = userOptions === true ? {} : userOptions;
5
-
6
- if (!httpsOptions.key || !httpsOptions.cert) {
7
- const selfsign = await devcert.certificateFor(['localhost']);
8
- return selfsign;
9
- }
10
-
11
- return httpsOptions;
12
- };
@@ -1,29 +0,0 @@
1
- import { LAUNCH_EDITOR_ENDPOINT, logger } from '@modern-js/utils';
2
- import { ModernServerContext } from '../../libs/context';
3
- import { NextFunction } from '../../type';
4
-
5
- export const createLaunchEditorHandler =
6
- // eslint-disable-next-line consistent-return
7
- () => (ctx: ModernServerContext, next: NextFunction) => {
8
- if (ctx.url.startsWith(LAUNCH_EDITOR_ENDPOINT)) {
9
- const { filename, line = 1, column = 1 } = ctx.query;
10
- if (!filename) {
11
- ctx.status = 500;
12
- ctx.res.end(
13
- `launch-editor-middleware: required query param "filename" is missing.`,
14
- );
15
- } else {
16
- require('launch-editor')(
17
- `${filename as string}:${line as string}:${column as string}`,
18
- 'code',
19
- (file: string, errorMessage: string) => {
20
- logger.error(`Launch ${file} in editor failed.\n${errorMessage}`);
21
- },
22
- );
23
- ctx.status = 200;
24
- ctx.res.end();
25
- }
26
- } else {
27
- return next();
28
- }
29
- };
@@ -1,109 +0,0 @@
1
- import { IncomingMessage, ServerResponse } from 'http';
2
- import { compatRequire } from '@modern-js/utils';
3
- import { NextFunction } from '../../type';
4
- import { ModernServerContext } from '../../libs/context';
5
-
6
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
7
- const VALID_METHODS = ['get', 'post', 'put', 'delete', 'patch'];
8
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
9
- const BODY_PARSED_METHODS = ['post', 'put', 'delete', 'patch'];
10
-
11
- export type MockConfig = Record<
12
- string,
13
- | {
14
- data: any;
15
- }
16
- | ((
17
- req: IncomingMessage,
18
- res: ServerResponse,
19
- next: NextFunction,
20
- ) => Promise<void>)
21
- >;
22
-
23
- export type MockApi = {
24
- method: string;
25
- path: string;
26
- handler: ReturnType<
27
- typeof createFunctionDataHandler | typeof createStaticDataHandler
28
- >;
29
- };
30
-
31
- const createFunctionDataHandler =
32
- (
33
- method: string,
34
- handler: (
35
- req: IncomingMessage,
36
- res: ServerResponse,
37
- next: NextFunction,
38
- ) => void,
39
- ) =>
40
- async (context: ModernServerContext, next: NextFunction) => {
41
- const { req, res } = context;
42
- return handler(req, res, next);
43
- };
44
-
45
- const createStaticDataHandler =
46
- (method: string, handler: Record<string, any>) =>
47
- (context: ModernServerContext) => {
48
- const { res } = context;
49
- res.setHeader('Content-Type', 'application/json');
50
- res.end(JSON.stringify(handler));
51
- };
52
-
53
- const allowTypes = ['object', 'function'];
54
- const normalizeConfig = (mockConfig: MockConfig) =>
55
- Object.keys(mockConfig).reduce((acc, key) => {
56
- const handler = mockConfig[key];
57
- const type = typeof handler;
58
-
59
- if (!allowTypes.includes(type)) {
60
- throw new Error(
61
- `mock value of ${key} should be object or function, but got ${type}`,
62
- );
63
- }
64
-
65
- const meta = parseKey(key);
66
- if (type === 'object') {
67
- acc.push({
68
- ...meta,
69
- handler: createStaticDataHandler(meta.method, handler),
70
- });
71
- } else {
72
- acc.push({
73
- ...meta,
74
- handler: createFunctionDataHandler(meta.method, handler as any),
75
- });
76
- }
77
-
78
- return acc;
79
- }, [] as MockApi[]);
80
-
81
- const _blank = ' ';
82
- const parseKey = (key: string) => {
83
- // 'Method /pathname' | '/pathname'
84
- const splited = key.split(_blank).filter(Boolean);
85
- if (splited.length > 1) {
86
- const [method, pathname] = splited;
87
- return {
88
- method: method.toLowerCase(),
89
- path: pathname,
90
- };
91
- }
92
-
93
- // default return get method
94
- return {
95
- method: 'get',
96
- path: key,
97
- };
98
- };
99
-
100
- export default (filepath: string) => {
101
- const mockModule = compatRequire(filepath);
102
-
103
- if (!mockModule) {
104
- throw new Error(`Mock file ${filepath} parsed failed!`);
105
- }
106
-
107
- const data = normalizeConfig(mockModule);
108
- return data;
109
- };
@@ -1,63 +0,0 @@
1
- import path from 'path';
2
- import { fs } from '@modern-js/utils';
3
- import { match } from 'path-to-regexp';
4
- import { NextFunction } from '../../type';
5
- import { ModernServerContext } from '../../libs/context';
6
- import { AGGRED_DIR } from '../../constants';
7
- import getMockData, { MockApi } from './getMockData';
8
-
9
- const getMatched = (context: ModernServerContext, mockApiList: MockApi[]) => {
10
- const { path: targetPathname, method: targetMethod } = context;
11
-
12
- const matched = mockApiList.find(mockApi => {
13
- const { method, path: pathname } = mockApi;
14
- if (method.toLowerCase() === targetMethod.toLowerCase()) {
15
- return match(pathname, {
16
- encode: encodeURI,
17
- decode: decodeURIComponent,
18
- })(targetPathname);
19
- }
20
-
21
- return false;
22
- });
23
-
24
- return matched;
25
- };
26
-
27
- export const createMockHandler = ({ pwd }: { pwd: string }) => {
28
- const exts = ['.ts', '.js'];
29
- let filepath = '';
30
-
31
- for (const ext of exts) {
32
- const maybeMatch = path.join(pwd, `${AGGRED_DIR.mock}/index${ext}`);
33
- if (fs.existsSync(maybeMatch)) {
34
- filepath = maybeMatch;
35
- break;
36
- }
37
- }
38
-
39
- if (!filepath) {
40
- return null;
41
- }
42
-
43
- const apiList = getMockData(filepath);
44
- if (!apiList || apiList.length === 0) {
45
- return null;
46
- }
47
-
48
- return async (context: ModernServerContext, next: NextFunction) => {
49
- const { res } = context;
50
- const matched = getMatched(context, apiList);
51
-
52
- if (!matched) {
53
- return next();
54
- }
55
-
56
- if (matched) {
57
- res.setHeader('Access-Control-Allow-Origin', '*');
58
- return matched.handler(context, next);
59
- } else {
60
- return next();
61
- }
62
- };
63
- };