@modern-js/server 2.48.5 → 2.49.0

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 (80) hide show
  1. package/dist/cjs/createDevServer.js +95 -0
  2. package/dist/cjs/{server/index.js → helpers/devOptions.js} +11 -28
  3. package/dist/cjs/helpers/fileReader.js +51 -0
  4. package/dist/cjs/helpers/index.js +107 -0
  5. package/dist/cjs/{server/workerSSRRender.js → helpers/repack.js} +27 -21
  6. package/dist/cjs/helpers/utils.js +29 -0
  7. package/dist/cjs/index.js +3 -13
  8. package/dist/esm/createDevServer.js +99 -0
  9. package/dist/esm/helpers/devOptions.js +10 -0
  10. package/dist/esm/helpers/fileReader.js +45 -0
  11. package/dist/esm/helpers/index.js +119 -0
  12. package/dist/esm/helpers/repack.js +31 -0
  13. package/dist/esm/helpers/utils.js +5 -0
  14. package/dist/esm/index.js +2 -12
  15. package/dist/esm-node/createDevServer.js +61 -0
  16. package/dist/esm-node/helpers/devOptions.js +10 -0
  17. package/dist/esm-node/helpers/fileReader.js +27 -0
  18. package/dist/esm-node/helpers/index.js +69 -0
  19. package/dist/esm-node/helpers/repack.js +27 -0
  20. package/dist/esm-node/helpers/utils.js +5 -0
  21. package/dist/esm-node/index.js +2 -11
  22. package/dist/types/createDevServer.d.ts +6 -0
  23. package/dist/types/{constants.d.ts → helpers/constants.d.ts} +1 -1
  24. package/dist/types/helpers/devOptions.d.ts +4 -0
  25. package/dist/types/helpers/fileReader.d.ts +2 -0
  26. package/dist/types/helpers/index.d.ts +14 -0
  27. package/dist/types/helpers/repack.d.ts +3 -0
  28. package/dist/types/helpers/utils.d.ts +1 -0
  29. package/dist/types/index.d.ts +2 -6
  30. package/dist/types/types.d.ts +4 -11
  31. package/package.json +10 -11
  32. package/dist/cjs/dev-tools/dev-middleware/hmr-client/createSocketUrl.js +0 -61
  33. package/dist/cjs/dev-tools/dev-middleware/hmr-client/index.js +0 -159
  34. package/dist/cjs/dev-tools/dev-middleware/index.js +0 -90
  35. package/dist/cjs/dev-tools/dev-middleware/socketServer.js +0 -173
  36. package/dist/cjs/dev-tools/https/index.js +0 -54
  37. package/dist/cjs/dev-tools/mock/getMockData.js +0 -104
  38. package/dist/cjs/dev-tools/mock/index.js +0 -85
  39. package/dist/cjs/dev-tools/register/index.js +0 -144
  40. package/dist/cjs/server/devServer.js +0 -267
  41. package/dist/cjs/server/devServerOld.js +0 -346
  42. package/dist/esm/dev-tools/dev-middleware/hmr-client/createSocketUrl.js +0 -54
  43. package/dist/esm/dev-tools/dev-middleware/hmr-client/index.js +0 -162
  44. package/dist/esm/dev-tools/dev-middleware/index.js +0 -82
  45. package/dist/esm/dev-tools/dev-middleware/socketServer.js +0 -149
  46. package/dist/esm/dev-tools/https/index.js +0 -74
  47. package/dist/esm/dev-tools/mock/getMockData.js +0 -102
  48. package/dist/esm/dev-tools/mock/index.js +0 -88
  49. package/dist/esm/dev-tools/register/index.js +0 -109
  50. package/dist/esm/server/devServer.js +0 -449
  51. package/dist/esm/server/devServerOld.js +0 -519
  52. package/dist/esm/server/index.js +0 -45
  53. package/dist/esm/server/workerSSRRender.js +0 -43
  54. package/dist/esm-node/dev-tools/dev-middleware/hmr-client/createSocketUrl.js +0 -36
  55. package/dist/esm-node/dev-tools/dev-middleware/hmr-client/index.js +0 -145
  56. package/dist/esm-node/dev-tools/dev-middleware/index.js +0 -60
  57. package/dist/esm-node/dev-tools/dev-middleware/socketServer.js +0 -143
  58. package/dist/esm-node/dev-tools/https/index.js +0 -30
  59. package/dist/esm-node/dev-tools/mock/getMockData.js +0 -80
  60. package/dist/esm-node/dev-tools/mock/index.js +0 -51
  61. package/dist/esm-node/dev-tools/register/index.js +0 -110
  62. package/dist/esm-node/server/devServer.js +0 -233
  63. package/dist/esm-node/server/devServerOld.js +0 -312
  64. package/dist/esm-node/server/index.js +0 -26
  65. package/dist/esm-node/server/workerSSRRender.js +0 -21
  66. package/dist/types/dev-tools/dev-middleware/hmr-client/createSocketUrl.d.ts +0 -7
  67. package/dist/types/dev-tools/dev-middleware/hmr-client/index.d.ts +0 -1
  68. package/dist/types/dev-tools/dev-middleware/index.d.ts +0 -21
  69. package/dist/types/dev-tools/dev-middleware/socketServer.d.ts +0 -25
  70. package/dist/types/dev-tools/https/index.d.ts +0 -7
  71. package/dist/types/dev-tools/mock/getMockData.d.ts +0 -18
  72. package/dist/types/dev-tools/mock/index.d.ts +0 -4
  73. package/dist/types/dev-tools/register/index.d.ts +0 -2
  74. package/dist/types/server/devServer.d.ts +0 -38
  75. package/dist/types/server/devServerOld.d.ts +0 -37
  76. package/dist/types/server/index.d.ts +0 -8
  77. package/dist/types/server/workerSSRRender.d.ts +0 -10
  78. /package/dist/cjs/{constants.js → helpers/constants.js} +0 -0
  79. /package/dist/esm/{constants.js → helpers/constants.js} +0 -0
  80. /package/dist/esm-node/{constants.js → helpers/constants.js} +0 -0
@@ -1,159 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (let key of __getOwnPropNames(from))
11
- if (!__hasOwnProp.call(to, key) && key !== except)
12
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
- }
14
- return to;
15
- };
16
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
- // If the importer is in node compatibility mode or this is not an ESM
18
- // file that has been converted to a CommonJS file using a Babel-
19
- // compatible transform (i.e. "__esModule" has not been set), then set
20
- // "default" to the CommonJS "module.exports" for node compatibility.
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
- mod
23
- ));
24
- var import_strip_ansi = __toESM(require("@modern-js/utils/strip-ansi"));
25
- var import_format_webpack = require("@modern-js/utils/universal/format-webpack");
26
- var import_createSocketUrl = require("./createSocketUrl");
27
- const hadRuntimeError = false;
28
- const socketUrl = (0, import_createSocketUrl.createSocketUrl)(__resourceQuery);
29
- const connection = new WebSocket(socketUrl);
30
- connection.onopen = function() {
31
- if (typeof console !== "undefined" && typeof console.info === "function") {
32
- console.info("[HMR] connected.");
33
- }
34
- };
35
- connection.onclose = function() {
36
- if (typeof console !== "undefined" && typeof console.info === "function") {
37
- console.info("[HMR] disconnected. Refresh the page if necessary.");
38
- }
39
- };
40
- let isFirstCompilation = true;
41
- let mostRecentCompilationHash = null;
42
- let hasCompileErrors = false;
43
- function clearOutdatedErrors() {
44
- if (typeof console !== "undefined" && typeof console.clear === "function") {
45
- if (hasCompileErrors) {
46
- console.clear();
47
- }
48
- }
49
- }
50
- function handleSuccess() {
51
- clearOutdatedErrors();
52
- const isHotUpdate = !isFirstCompilation;
53
- isFirstCompilation = false;
54
- hasCompileErrors = false;
55
- if (isHotUpdate) {
56
- tryApplyUpdates();
57
- }
58
- }
59
- function handleWarnings(warnings) {
60
- clearOutdatedErrors();
61
- const isHotUpdate = !isFirstCompilation;
62
- isFirstCompilation = false;
63
- hasCompileErrors = false;
64
- function printWarnings() {
65
- const formatted = (0, import_format_webpack.formatWebpackMessages)({
66
- warnings,
67
- errors: []
68
- });
69
- if (typeof console !== "undefined" && typeof console.warn === "function") {
70
- for (let i = 0; i < formatted.warnings.length; i++) {
71
- if (i === 5) {
72
- console.warn("There were more warnings in other files.\nYou can find a complete log in the terminal.");
73
- break;
74
- }
75
- console.warn((0, import_strip_ansi.default)(formatted.warnings[i]));
76
- }
77
- }
78
- }
79
- printWarnings();
80
- if (isHotUpdate) {
81
- tryApplyUpdates();
82
- }
83
- }
84
- function handleErrors(errors) {
85
- clearOutdatedErrors();
86
- isFirstCompilation = false;
87
- hasCompileErrors = true;
88
- const formatted = (0, import_format_webpack.formatWebpackMessages)({
89
- errors,
90
- warnings: []
91
- });
92
- if (typeof console !== "undefined" && typeof console.error === "function") {
93
- for (const error of formatted.errors) {
94
- console.error((0, import_strip_ansi.default)(error));
95
- }
96
- }
97
- }
98
- function handleAvailableHash(hash) {
99
- mostRecentCompilationHash = hash;
100
- }
101
- connection.onmessage = function(e) {
102
- const message = JSON.parse(e.data);
103
- switch (message.type) {
104
- case "hash":
105
- handleAvailableHash(message.data);
106
- break;
107
- case "still-ok":
108
- case "ok":
109
- handleSuccess();
110
- break;
111
- case "content-changed":
112
- window.location.reload();
113
- break;
114
- case "warnings":
115
- handleWarnings(message.data);
116
- break;
117
- case "errors":
118
- handleErrors(message.data);
119
- break;
120
- default:
121
- }
122
- };
123
- function isUpdateAvailable() {
124
- return mostRecentCompilationHash !== __webpack_hash__;
125
- }
126
- function canApplyUpdates() {
127
- return module.hot.status() === "idle";
128
- }
129
- function tryApplyUpdates() {
130
- if (!module.hot) {
131
- window.location.reload();
132
- return;
133
- }
134
- if (!isUpdateAvailable() || !canApplyUpdates()) {
135
- return;
136
- }
137
- function handleApplyUpdates(err, updatedModules) {
138
- const wantsForcedReload = err || !updatedModules || hadRuntimeError;
139
- if (wantsForcedReload) {
140
- window.location.reload();
141
- return;
142
- }
143
- if (isUpdateAvailable()) {
144
- tryApplyUpdates();
145
- }
146
- }
147
- const result = module.hot.check(
148
- /* autoApply */
149
- true,
150
- handleApplyUpdates
151
- );
152
- if (result === null || result === void 0 ? void 0 : result.then) {
153
- result.then((updatedModules) => {
154
- handleApplyUpdates(null, updatedModules);
155
- }, (err) => {
156
- handleApplyUpdates(err, null);
157
- });
158
- }
159
- }
@@ -1,90 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var dev_middleware_exports = {};
30
- __export(dev_middleware_exports, {
31
- default: () => DevMiddleware
32
- });
33
- module.exports = __toCommonJS(dev_middleware_exports);
34
- var import_events = require("events");
35
- var import_socketServer = __toESM(require("./socketServer"));
36
- const noop = () => {
37
- };
38
- function getHMRClientPath(client) {
39
- const protocol = (client === null || client === void 0 ? void 0 : client.protocol) ? `&protocol=${client.protocol}` : "";
40
- const host = (client === null || client === void 0 ? void 0 : client.host) ? `&host=${client.host}` : "";
41
- const path = (client === null || client === void 0 ? void 0 : client.path) ? `&path=${client.path}` : "";
42
- const port = (client === null || client === void 0 ? void 0 : client.port) ? `&port=${client.port}` : "";
43
- const clientEntry = `${require.resolve("@modern-js/server/hmr-client")}?${host}${path}${port}${protocol}`;
44
- return clientEntry;
45
- }
46
- class DevMiddleware extends import_events.EventEmitter {
47
- init(app) {
48
- app.on("listening", () => {
49
- this.socketServer.prepare(app);
50
- });
51
- app.on("close", async () => {
52
- var _this_middleware;
53
- (_this_middleware = this.middleware) === null || _this_middleware === void 0 ? void 0 : _this_middleware.close(noop);
54
- this.socketServer.close();
55
- });
56
- }
57
- sockWrite(type, data) {
58
- this.socketServer.sockWrite(type, data);
59
- }
60
- setupDevMiddleware(devMiddleware) {
61
- const { devOptions } = this;
62
- const callbacks = {
63
- onInvalid: () => {
64
- this.socketServer.sockWrite("invalid");
65
- },
66
- onDone: (stats) => {
67
- this.socketServer.updateStats(stats);
68
- this.emit("change", stats);
69
- }
70
- };
71
- const enableHMR = this.devOptions.hot || this.devOptions.liveReload;
72
- const middleware = devMiddleware({
73
- headers: devOptions.headers,
74
- stats: false,
75
- callbacks,
76
- hmrClientPath: enableHMR ? getHMRClientPath(devOptions.client) : void 0,
77
- serverSideRender: true,
78
- ...devOptions.devMiddleware
79
- });
80
- return middleware;
81
- }
82
- constructor({ dev, devMiddleware }) {
83
- super();
84
- this.devOptions = dev;
85
- this.socketServer = new import_socketServer.default(dev);
86
- if (devMiddleware) {
87
- this.middleware = this.setupDevMiddleware(devMiddleware);
88
- }
89
- }
90
- }
@@ -1,173 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var socketServer_exports = {};
30
- __export(socketServer_exports, {
31
- default: () => SocketServer
32
- });
33
- module.exports = __toCommonJS(socketServer_exports);
34
- var import_ws = __toESM(require("ws"));
35
- var import_utils = require("@modern-js/utils");
36
- class SocketServer {
37
- // create socket, install socket handler, bind socket event
38
- prepare(app) {
39
- var _this_options_client;
40
- this.app = app;
41
- this.wsServer = new import_ws.default.Server({
42
- noServer: true,
43
- path: (_this_options_client = this.options.client) === null || _this_options_client === void 0 ? void 0 : _this_options_client.path
44
- });
45
- this.app.on("upgrade", (req, sock, head) => {
46
- if (!this.wsServer.shouldHandle(req)) {
47
- return;
48
- }
49
- this.wsServer.handleUpgrade(req, sock, head, (connection) => {
50
- this.wsServer.emit("connection", connection, req);
51
- });
52
- });
53
- this.wsServer.on("error", (err) => {
54
- import_utils.logger.error(err);
55
- });
56
- this.timer = setInterval(() => {
57
- this.wsServer.clients.forEach((socket) => {
58
- const extWs = socket;
59
- if (!extWs.isAlive) {
60
- extWs.terminate();
61
- } else {
62
- extWs.isAlive = false;
63
- extWs.ping(() => {
64
- });
65
- }
66
- });
67
- }, 3e4);
68
- this.wsServer.on("connection", (socket) => {
69
- this.onConnect(socket);
70
- });
71
- }
72
- updateStats(stats) {
73
- this.stats = stats;
74
- this.sendStats();
75
- }
76
- // write message to each socket
77
- sockWrite(type, data) {
78
- this.sockets.forEach((socket) => {
79
- this.send(socket, JSON.stringify({
80
- type,
81
- data
82
- }));
83
- });
84
- }
85
- singleWrite(socket, type, data) {
86
- this.send(socket, JSON.stringify({
87
- type,
88
- data
89
- }));
90
- }
91
- close() {
92
- this.sockets.forEach((socket) => {
93
- socket.close();
94
- });
95
- if (this.timer) {
96
- clearInterval(this.timer);
97
- this.timer = null;
98
- }
99
- }
100
- onConnect(socket) {
101
- const connection = socket;
102
- connection.isAlive = true;
103
- connection.on("pong", () => {
104
- connection.isAlive = true;
105
- });
106
- if (!connection) {
107
- return;
108
- }
109
- this.sockets.push(connection);
110
- connection.on("close", () => {
111
- const idx = this.sockets.indexOf(connection);
112
- if (idx >= 0) {
113
- this.sockets.splice(idx, 1);
114
- }
115
- });
116
- if (this.options.hot) {
117
- this.singleWrite(connection, "hot");
118
- }
119
- if (this.options.liveReload) {
120
- this.singleWrite(connection, "liveReload");
121
- }
122
- if (this.stats) {
123
- this.sendStats(true);
124
- }
125
- }
126
- // get standard stats
127
- getStats() {
128
- const curStats = this.stats;
129
- if (!curStats) {
130
- return null;
131
- }
132
- const defaultStats = {
133
- all: false,
134
- hash: true,
135
- assets: true,
136
- warnings: true,
137
- errors: true,
138
- errorDetails: false
139
- };
140
- return curStats.toJson(defaultStats);
141
- }
142
- // determine what message should send by stats
143
- sendStats(force = false) {
144
- const stats = this.getStats();
145
- if (!stats) {
146
- return null;
147
- }
148
- const shouldEmit = !force && stats && (!stats.errors || stats.errors.length === 0) && stats.assets && stats.assets.every((asset) => !asset.emitted);
149
- if (shouldEmit) {
150
- return this.sockWrite("still-ok");
151
- }
152
- this.sockWrite("hash", stats.hash);
153
- if (stats.errors && stats.errors.length > 0) {
154
- return this.sockWrite("errors", stats.errors);
155
- } else if (stats.warnings && stats.warnings.length > 0) {
156
- return this.sockWrite("warnings", stats.warnings);
157
- } else {
158
- return this.sockWrite("ok");
159
- }
160
- }
161
- // send message to connecting socket
162
- send(connection, message) {
163
- if (connection.readyState !== 1) {
164
- return;
165
- }
166
- connection.send(message);
167
- }
168
- constructor(options) {
169
- this.sockets = [];
170
- this.timer = null;
171
- this.options = options;
172
- }
173
- }
@@ -1,54 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var https_exports = {};
20
- __export(https_exports, {
21
- genHttpsOptions: () => genHttpsOptions
22
- });
23
- module.exports = __toCommonJS(https_exports);
24
- var import_utils = require("@modern-js/utils");
25
- const genHttpsOptions = async (userOptions, pwd) => {
26
- const httpsOptions = typeof userOptions === "boolean" ? {} : userOptions;
27
- if (!httpsOptions.key || !httpsOptions.cert) {
28
- let devcertPath;
29
- try {
30
- devcertPath = require.resolve("devcert", {
31
- paths: [
32
- pwd,
33
- __dirname
34
- ]
35
- });
36
- } catch (err) {
37
- const packageManager = await (0, import_utils.getPackageManager)(pwd);
38
- const command = import_utils.chalk.yellow.bold(`${packageManager} add devcert@1.2.2 -D`);
39
- import_utils.logger.error(`You have enabled "dev.https" option, but the "devcert" package is not installed.`);
40
- import_utils.logger.error(`Please run ${command} to install manually, otherwise the https can not work.`);
41
- throw new Error('[https] "devcert" is not found.');
42
- }
43
- const devcert = require(devcertPath);
44
- const selfsign = await devcert.certificateFor([
45
- "localhost"
46
- ]);
47
- return selfsign;
48
- }
49
- return httpsOptions;
50
- };
51
- // Annotate the CommonJS export names for ESM import in node:
52
- 0 && (module.exports = {
53
- genHttpsOptions
54
- });
@@ -1,104 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var getMockData_exports = {};
20
- __export(getMockData_exports, {
21
- default: () => getMockData_default,
22
- getMatched: () => getMatched
23
- });
24
- module.exports = __toCommonJS(getMockData_exports);
25
- var import_path_to_regexp = require("path-to-regexp");
26
- const VALID_METHODS = [
27
- "get",
28
- "post",
29
- "put",
30
- "delete",
31
- "patch"
32
- ];
33
- const BODY_PARSED_METHODS = [
34
- "post",
35
- "put",
36
- "delete",
37
- "patch"
38
- ];
39
- const createFunctionDataHandler = (method, handler) => async (context, next) => {
40
- const { req, res } = context;
41
- return handler(req, res, next);
42
- };
43
- const createStaticDataHandler = (method, handler) => (context) => {
44
- const { res } = context;
45
- res.setHeader("Content-Type", "application/json");
46
- res.end(JSON.stringify(handler));
47
- };
48
- const allowTypes = [
49
- "object",
50
- "function"
51
- ];
52
- var getMockData_default = (mockConfig) => Object.keys(mockConfig).reduce((acc, key) => {
53
- const handler = mockConfig[key];
54
- const type = typeof handler;
55
- if (!allowTypes.includes(type)) {
56
- throw new Error(`mock value of ${key} should be object or function, but got ${type}`);
57
- }
58
- const meta = parseKey(key);
59
- if (type === "object") {
60
- acc.push({
61
- ...meta,
62
- handler: createStaticDataHandler(meta.method, handler)
63
- });
64
- } else {
65
- acc.push({
66
- ...meta,
67
- handler: createFunctionDataHandler(meta.method, handler)
68
- });
69
- }
70
- return acc;
71
- }, []);
72
- const _blank = " ";
73
- const parseKey = (key) => {
74
- const splitted = key.split(_blank).filter(Boolean);
75
- if (splitted.length > 1) {
76
- const [method, pathname] = splitted;
77
- return {
78
- method: method.toLowerCase(),
79
- path: pathname
80
- };
81
- }
82
- return {
83
- method: "get",
84
- path: key
85
- };
86
- };
87
- const getMatched = (context, mockApiList) => {
88
- const { path: targetPathname, method: targetMethod } = context;
89
- const matched = mockApiList.find((mockApi) => {
90
- const { method, path: pathname } = mockApi;
91
- if (method.toLowerCase() === targetMethod.toLowerCase()) {
92
- return (0, import_path_to_regexp.match)(pathname, {
93
- encode: encodeURI,
94
- decode: decodeURIComponent
95
- })(targetPathname);
96
- }
97
- return false;
98
- });
99
- return matched;
100
- };
101
- // Annotate the CommonJS export names for ESM import in node:
102
- 0 && (module.exports = {
103
- getMatched
104
- });
@@ -1,85 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var mock_exports = {};
30
- __export(mock_exports, {
31
- createMockHandler: () => createMockHandler
32
- });
33
- module.exports = __toCommonJS(mock_exports);
34
- var import_path = __toESM(require("path"));
35
- var import_utils = require("@modern-js/utils");
36
- var import_prod_server = require("@modern-js/prod-server");
37
- var import_getMockData = __toESM(require("./getMockData"));
38
- const createMockHandler = ({ pwd }) => {
39
- const exts = [
40
- ".ts",
41
- ".js"
42
- ];
43
- let filepath = "";
44
- for (const ext of exts) {
45
- const maybeMatch = import_path.default.join(pwd, `${import_prod_server.AGGRED_DIR.mock}/index${ext}`);
46
- if (import_utils.fs.existsSync(maybeMatch)) {
47
- filepath = maybeMatch;
48
- break;
49
- }
50
- }
51
- if (!filepath) {
52
- return null;
53
- }
54
- const mod = (0, import_utils.compatRequire)(filepath, false);
55
- const { default: mockModule = mod, config } = mod;
56
- if ((config === null || config === void 0 ? void 0 : config.enable) === false) {
57
- return null;
58
- }
59
- if (!mockModule) {
60
- throw new Error(`Mock file ${filepath} parsed failed!`);
61
- }
62
- const apiList = (0, import_getMockData.default)(mockModule);
63
- if (!apiList || apiList.length === 0) {
64
- return null;
65
- }
66
- return async (context, next) => {
67
- if (typeof (config === null || config === void 0 ? void 0 : config.enable) === "function") {
68
- const enableMock = config.enable(context.req, context.res);
69
- if (!enableMock) {
70
- return next();
71
- }
72
- }
73
- const { res } = context;
74
- const matched = (0, import_getMockData.getMatched)(context, apiList);
75
- if (!matched) {
76
- return next();
77
- }
78
- res.setHeader("Access-Control-Allow-Origin", "*");
79
- return matched.handler(context, next);
80
- };
81
- };
82
- // Annotate the CommonJS export names for ESM import in node:
83
- 0 && (module.exports = {
84
- createMockHandler
85
- });