@modern-js/prod-server 2.48.6 → 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 (174) hide show
  1. package/README.md +20 -16
  2. package/dist/cjs/{libs/route/route.js → error.js} +16 -17
  3. package/dist/cjs/index.js +18 -24
  4. package/dist/cjs/init.js +71 -0
  5. package/dist/cjs/{type.js → types.js} +2 -2
  6. package/dist/esm/error.js +15 -0
  7. package/dist/esm/index.js +53 -19
  8. package/dist/esm/init.js +73 -0
  9. package/dist/esm-node/error.js +14 -0
  10. package/dist/esm-node/index.js +16 -17
  11. package/dist/esm-node/init.js +47 -0
  12. package/dist/types/error.d.ts +6 -0
  13. package/dist/types/index.d.ts +8 -11
  14. package/dist/types/init.d.ts +4 -0
  15. package/dist/types/types.d.ts +14 -0
  16. package/package.json +23 -64
  17. package/dist/cjs/constants.js +0 -72
  18. package/dist/cjs/libs/context/context.js +0 -236
  19. package/dist/cjs/libs/context/index.js +0 -31
  20. package/dist/cjs/libs/hook-api/afterRenderForStream.js +0 -34
  21. package/dist/cjs/libs/hook-api/base.js +0 -96
  22. package/dist/cjs/libs/hook-api/index.js +0 -85
  23. package/dist/cjs/libs/hook-api/index.worker.js +0 -116
  24. package/dist/cjs/libs/hook-api/route.js +0 -44
  25. package/dist/cjs/libs/hook-api/template.js +0 -72
  26. package/dist/cjs/libs/hook-api/templateForStream.js +0 -52
  27. package/dist/cjs/libs/loadConfig.js +0 -70
  28. package/dist/cjs/libs/metrics.js +0 -33
  29. package/dist/cjs/libs/preload/flushServerHeader.js +0 -49
  30. package/dist/cjs/libs/preload/index.js +0 -24
  31. package/dist/cjs/libs/preload/parseLinks.js +0 -124
  32. package/dist/cjs/libs/preload/shouldFlushServerHeader.js +0 -52
  33. package/dist/cjs/libs/preload/transformLinks2String.js +0 -150
  34. package/dist/cjs/libs/proxy.js +0 -99
  35. package/dist/cjs/libs/render/index.js +0 -109
  36. package/dist/cjs/libs/render/measure.js +0 -74
  37. package/dist/cjs/libs/render/ssr.js +0 -130
  38. package/dist/cjs/libs/render/ssrCache/cacheMod.js +0 -51
  39. package/dist/cjs/libs/render/ssrCache/index.js +0 -90
  40. package/dist/cjs/libs/render/ssrCache/manager.js +0 -120
  41. package/dist/cjs/libs/render/static.js +0 -72
  42. package/dist/cjs/libs/render/type.js +0 -33
  43. package/dist/cjs/libs/render/utils.js +0 -41
  44. package/dist/cjs/libs/reporter.js +0 -39
  45. package/dist/cjs/libs/route/index.js +0 -83
  46. package/dist/cjs/libs/route/matcher.js +0 -113
  47. package/dist/cjs/libs/serveFile.js +0 -84
  48. package/dist/cjs/libs/serverTiming.js +0 -41
  49. package/dist/cjs/renderHtml.js +0 -65
  50. package/dist/cjs/server/index.js +0 -223
  51. package/dist/cjs/server/modernServer.js +0 -522
  52. package/dist/cjs/server/modernServerSplit.js +0 -67
  53. package/dist/cjs/utils.js +0 -164
  54. package/dist/cjs/workerServer.js +0 -260
  55. package/dist/esm/constants.js +0 -43
  56. package/dist/esm/libs/context/context.js +0 -260
  57. package/dist/esm/libs/context/index.js +0 -8
  58. package/dist/esm/libs/hook-api/afterRenderForStream.js +0 -33
  59. package/dist/esm/libs/hook-api/base.js +0 -73
  60. package/dist/esm/libs/hook-api/index.js +0 -55
  61. package/dist/esm/libs/hook-api/index.worker.js +0 -99
  62. package/dist/esm/libs/hook-api/route.js +0 -26
  63. package/dist/esm/libs/hook-api/template.js +0 -56
  64. package/dist/esm/libs/hook-api/templateForStream.js +0 -35
  65. package/dist/esm/libs/loadConfig.js +0 -36
  66. package/dist/esm/libs/metrics.js +0 -9
  67. package/dist/esm/libs/preload/flushServerHeader.js +0 -50
  68. package/dist/esm/libs/preload/index.js +0 -2
  69. package/dist/esm/libs/preload/parseLinks.js +0 -172
  70. package/dist/esm/libs/preload/shouldFlushServerHeader.js +0 -27
  71. package/dist/esm/libs/preload/transformLinks2String.js +0 -140
  72. package/dist/esm/libs/proxy.js +0 -160
  73. package/dist/esm/libs/render/index.js +0 -175
  74. package/dist/esm/libs/render/measure.js +0 -69
  75. package/dist/esm/libs/render/ssr.js +0 -133
  76. package/dist/esm/libs/render/ssrCache/cacheMod.js +0 -25
  77. package/dist/esm/libs/render/ssrCache/index.js +0 -170
  78. package/dist/esm/libs/render/ssrCache/manager.js +0 -178
  79. package/dist/esm/libs/render/static.js +0 -100
  80. package/dist/esm/libs/render/type.js +0 -9
  81. package/dist/esm/libs/render/utils.js +0 -16
  82. package/dist/esm/libs/reporter.js +0 -15
  83. package/dist/esm/libs/route/index.js +0 -82
  84. package/dist/esm/libs/route/matcher.js +0 -92
  85. package/dist/esm/libs/route/route.js +0 -17
  86. package/dist/esm/libs/serveFile.js +0 -68
  87. package/dist/esm/libs/serverTiming.js +0 -22
  88. package/dist/esm/renderHtml.js +0 -133
  89. package/dist/esm/server/index.js +0 -350
  90. package/dist/esm/server/modernServer.js +0 -884
  91. package/dist/esm/server/modernServerSplit.js +0 -113
  92. package/dist/esm/utils.js +0 -103
  93. package/dist/esm/workerServer.js +0 -352
  94. package/dist/esm-node/constants.js +0 -43
  95. package/dist/esm-node/libs/context/context.js +0 -202
  96. package/dist/esm-node/libs/context/index.js +0 -6
  97. package/dist/esm-node/libs/hook-api/afterRenderForStream.js +0 -10
  98. package/dist/esm-node/libs/hook-api/base.js +0 -61
  99. package/dist/esm-node/libs/hook-api/index.js +0 -57
  100. package/dist/esm-node/libs/hook-api/index.worker.js +0 -89
  101. package/dist/esm-node/libs/hook-api/route.js +0 -20
  102. package/dist/esm-node/libs/hook-api/template.js +0 -47
  103. package/dist/esm-node/libs/hook-api/templateForStream.js +0 -28
  104. package/dist/esm-node/libs/loadConfig.js +0 -34
  105. package/dist/esm-node/libs/metrics.js +0 -9
  106. package/dist/esm-node/libs/preload/flushServerHeader.js +0 -25
  107. package/dist/esm-node/libs/preload/index.js +0 -2
  108. package/dist/esm-node/libs/preload/parseLinks.js +0 -90
  109. package/dist/esm-node/libs/preload/shouldFlushServerHeader.js +0 -27
  110. package/dist/esm-node/libs/preload/transformLinks2String.js +0 -126
  111. package/dist/esm-node/libs/proxy.js +0 -74
  112. package/dist/esm-node/libs/render/index.js +0 -75
  113. package/dist/esm-node/libs/render/measure.js +0 -49
  114. package/dist/esm-node/libs/render/ssr.js +0 -96
  115. package/dist/esm-node/libs/render/ssrCache/cacheMod.js +0 -17
  116. package/dist/esm-node/libs/render/ssrCache/index.js +0 -66
  117. package/dist/esm-node/libs/render/ssrCache/manager.js +0 -96
  118. package/dist/esm-node/libs/render/static.js +0 -38
  119. package/dist/esm-node/libs/render/type.js +0 -9
  120. package/dist/esm-node/libs/render/utils.js +0 -16
  121. package/dist/esm-node/libs/reporter.js +0 -15
  122. package/dist/esm-node/libs/route/index.js +0 -58
  123. package/dist/esm-node/libs/route/matcher.js +0 -89
  124. package/dist/esm-node/libs/route/route.js +0 -16
  125. package/dist/esm-node/libs/serveFile.js +0 -49
  126. package/dist/esm-node/libs/serverTiming.js +0 -17
  127. package/dist/esm-node/renderHtml.js +0 -73
  128. package/dist/esm-node/server/index.js +0 -189
  129. package/dist/esm-node/server/modernServer.js +0 -488
  130. package/dist/esm-node/server/modernServerSplit.js +0 -43
  131. package/dist/esm-node/utils.js +0 -132
  132. package/dist/esm-node/workerServer.js +0 -235
  133. package/dist/types/constants.d.ts +0 -30
  134. package/dist/types/libs/context/context.d.ts +0 -62
  135. package/dist/types/libs/context/index.d.ts +0 -7
  136. package/dist/types/libs/hook-api/afterRenderForStream.d.ts +0 -4
  137. package/dist/types/libs/hook-api/base.d.ts +0 -53
  138. package/dist/types/libs/hook-api/index.d.ts +0 -6
  139. package/dist/types/libs/hook-api/index.worker.d.ts +0 -19
  140. package/dist/types/libs/hook-api/route.d.ts +0 -9
  141. package/dist/types/libs/hook-api/template.d.ts +0 -22
  142. package/dist/types/libs/hook-api/templateForStream.d.ts +0 -8
  143. package/dist/types/libs/loadConfig.d.ts +0 -13
  144. package/dist/types/libs/metrics.d.ts +0 -3
  145. package/dist/types/libs/preload/flushServerHeader.d.ts +0 -14
  146. package/dist/types/libs/preload/index.d.ts +0 -2
  147. package/dist/types/libs/preload/parseLinks.d.ts +0 -13
  148. package/dist/types/libs/preload/shouldFlushServerHeader.d.ts +0 -3
  149. package/dist/types/libs/preload/transformLinks2String.d.ts +0 -3
  150. package/dist/types/libs/proxy.d.ts +0 -13
  151. package/dist/types/libs/render/index.d.ts +0 -21
  152. package/dist/types/libs/render/measure.d.ts +0 -10
  153. package/dist/types/libs/render/ssr.d.ts +0 -12
  154. package/dist/types/libs/render/ssrCache/cacheMod.d.ts +0 -8
  155. package/dist/types/libs/render/ssrCache/index.d.ts +0 -6
  156. package/dist/types/libs/render/ssrCache/manager.d.ts +0 -20
  157. package/dist/types/libs/render/static.d.ts +0 -3
  158. package/dist/types/libs/render/type.d.ts +0 -36
  159. package/dist/types/libs/render/utils.d.ts +0 -5
  160. package/dist/types/libs/reporter.d.ts +0 -2
  161. package/dist/types/libs/route/index.d.ts +0 -15
  162. package/dist/types/libs/route/matcher.d.ts +0 -15
  163. package/dist/types/libs/route/route.d.ts +0 -14
  164. package/dist/types/libs/serveFile.d.ts +0 -9
  165. package/dist/types/libs/serverTiming.d.ts +0 -13
  166. package/dist/types/renderHtml.d.ts +0 -23
  167. package/dist/types/server/index.d.ts +0 -55
  168. package/dist/types/server/modernServer.d.ts +0 -71
  169. package/dist/types/server/modernServerSplit.d.ts +0 -2
  170. package/dist/types/type.d.ts +0 -78
  171. package/dist/types/utils.d.ts +0 -24
  172. package/dist/types/workerServer.d.ts +0 -59
  173. /package/dist/esm/{type.js → types.js} +0 -0
  174. /package/dist/esm-node/{type.js → types.js} +0 -0
@@ -1,488 +0,0 @@
1
- import { createServer } from "http";
2
- import path from "path";
3
- import { fs, isProd, isPromise, isWebOnly, mime, ROUTE_SPEC_FILE } from "@modern-js/utils";
4
- import { time } from "@modern-js/runtime-utils/time";
5
- import { RouteMatchManager } from "../libs/route";
6
- import { createRenderHandler } from "../libs/render";
7
- import { createStaticFileHandler, faviconFallbackHandler } from "../libs/serveFile";
8
- import { createErrorDocument, createMiddlewareCollecter, getStaticReg, mergeExtension, noop, debug, isRedirect } from "../utils";
9
- import { createProxyHandler } from "../libs/proxy";
10
- import { createContext } from "../libs/context";
11
- import { AGGRED_DIR, ERROR_DIGEST, ERROR_PAGE_TEXT, RUN_MODE, ServerReportTimings } from "../constants";
12
- import { createAfterMatchContext, createAfterRenderContext, createMiddlewareContext } from "../libs/hook-api";
13
- import { cacheMod } from "../libs/render/ssrCache/cacheMod";
14
- const SERVER_DIR = "./server";
15
- class ModernServer {
16
- // server prepare
17
- async onInit(runner, app) {
18
- var _conf_bff, _this_conf_output;
19
- this.runner = runner;
20
- const { distDir, conf } = this;
21
- debug("final server conf", this.conf);
22
- if ((_conf_bff = conf.bff) === null || _conf_bff === void 0 ? void 0 : _conf_bff.proxy) {
23
- const { handlers, handleUpgrade } = createProxyHandler(conf.bff.proxy);
24
- app && handleUpgrade(app);
25
- handlers.forEach((handler) => {
26
- this.addHandler(handler);
27
- });
28
- }
29
- const usageRoutes = this.filterRoutes(this.getRoutes());
30
- this.router.reset(usageRoutes);
31
- this.warmupSSRBundle();
32
- cacheMod.loadServerCacheMod(isProd() ? distDir : this.pwd);
33
- await this.prepareFrameHandler();
34
- await this.prepareLoaderHandler(usageRoutes, distDir);
35
- this.routeRenderHandler = this.getRenderHandler();
36
- await this.setupBeforeProdMiddleware();
37
- this.addHandler(this.setupStaticMiddleware((_this_conf_output = this.conf.output) === null || _this_conf_output === void 0 ? void 0 : _this_conf_output.assetPrefix));
38
- this.addHandler(faviconFallbackHandler);
39
- this.addHandler(this.routeHandler.bind(this));
40
- this.compose();
41
- }
42
- getRenderHandler() {
43
- var _this_conf_server, _conf_security;
44
- const { distDir, staticGenerate, conf, metaName } = this;
45
- const ssrConfig = (_this_conf_server = this.conf.server) === null || _this_conf_server === void 0 ? void 0 : _this_conf_server.ssr;
46
- const forceCSR = typeof ssrConfig === "object" ? ssrConfig.forceCSR : false;
47
- return createRenderHandler({
48
- distDir,
49
- staticGenerate,
50
- forceCSR,
51
- conf: this.conf,
52
- nonce: (_conf_security = conf.security) === null || _conf_security === void 0 ? void 0 : _conf_security.nonce,
53
- metaName
54
- });
55
- }
56
- // server ready
57
- onRepack(_) {
58
- }
59
- // exposed requestHandler
60
- getRequestHandler() {
61
- return this.requestHandler.bind(this);
62
- }
63
- async render(req, res, url) {
64
- req.logger = req.logger || this.logger;
65
- req.metrics = req.metrics || this.metrics;
66
- const context = createContext(req, res, {
67
- metaName: this.metaName
68
- });
69
- const matched = this.router.match(url || context.path);
70
- if (!matched) {
71
- return null;
72
- }
73
- res.statusCode = 200;
74
- const route = matched.generate(context.url);
75
- const result = await this.handleWeb(context, route);
76
- if (!result) {
77
- return null;
78
- }
79
- if (result.contentStream) {
80
- return result.contentStream;
81
- }
82
- return result.content.toString();
83
- }
84
- async createHTTPServer(handler) {
85
- return createServer(handler);
86
- }
87
- /* —————————————————————— function will be overwrite —————————————————————— */
88
- async onServerChange({ filepath }) {
89
- const { pwd } = this;
90
- const { api, server } = AGGRED_DIR;
91
- const apiPath = path.normalize(path.join(pwd, api));
92
- const serverPath = path.normalize(path.join(pwd, server));
93
- const onlyApi = filepath.startsWith(apiPath);
94
- const onlyWeb = filepath.startsWith(serverPath);
95
- await this.prepareFrameHandler({
96
- onlyWeb,
97
- onlyApi
98
- });
99
- }
100
- // get routes info
101
- getRoutes() {
102
- if (this.presetRoutes) {
103
- return this.presetRoutes;
104
- }
105
- const file = path.join(this.distDir, ROUTE_SPEC_FILE);
106
- if (fs.existsSync(file)) {
107
- const content = fs.readJSONSync(file);
108
- return content.routes;
109
- }
110
- return [];
111
- }
112
- // add promisify request handler to server
113
- // handler should do not do more things after invoke next
114
- addHandler(handler) {
115
- this.handlers.push(handler);
116
- }
117
- // return 404 page
118
- render404(context) {
119
- context.error(ERROR_DIGEST.ENOTF, "404 Not Found");
120
- this.renderErrorPage(context, 404);
121
- }
122
- async prepareLoaderHandler(specs, distDir) {
123
- const { runner } = this;
124
- const handler = await runner.prepareLoaderHandler({
125
- serverRoutes: specs,
126
- distDir
127
- }, {
128
- onLast: () => null
129
- });
130
- this.loaderHandler = handler;
131
- }
132
- // gather frame extension and get framework handler
133
- async prepareFrameHandler(options) {
134
- const { workDir, runner } = this;
135
- const { onlyApi, onlyWeb } = options || {};
136
- const { getMiddlewares, ...collector } = createMiddlewareCollecter();
137
- await runner.gather(collector);
138
- const { api: pluginAPIExt, web: pluginWebExt } = getMiddlewares();
139
- const serverDir = path.join(workDir, SERVER_DIR);
140
- if (await fs.pathExists(path.join(serverDir)) && !onlyApi) {
141
- const webExtension = mergeExtension(pluginWebExt);
142
- this.frameWebHandler = await this.prepareWebHandler(webExtension);
143
- }
144
- if (!onlyWeb) {
145
- const apiExtension = mergeExtension(pluginAPIExt);
146
- this.frameAPIHandler = await this.prepareAPIHandler(apiExtension);
147
- }
148
- }
149
- async prepareWebHandler(extension) {
150
- const { workDir, runner } = this;
151
- const handler = await runner.prepareWebServer({
152
- pwd: workDir,
153
- config: extension
154
- }, {
155
- onLast: () => null
156
- });
157
- return handler;
158
- }
159
- async prepareAPIHandler(extension) {
160
- const { workDir, runner, conf } = this;
161
- const { bff } = conf;
162
- const prefix = (bff === null || bff === void 0 ? void 0 : bff.prefix) || "/api";
163
- const webOnly = await isWebOnly();
164
- if (webOnly && process.env.NODE_ENV === "development") {
165
- return (req, res) => {
166
- res.setHeader("Content-Type", "text/plain");
167
- res.end(JSON.stringify(""));
168
- };
169
- }
170
- return runner.prepareApiServer({
171
- pwd: workDir,
172
- config: extension,
173
- prefix: Array.isArray(prefix) ? prefix[0] : prefix,
174
- httpMethodDecider: bff === null || bff === void 0 ? void 0 : bff.httpMethodDecider,
175
- render: this.render.bind(this)
176
- }, {
177
- onLast: () => null
178
- });
179
- }
180
- filterRoutes(routes) {
181
- return routes;
182
- }
183
- async setupBeforeProdMiddleware() {
184
- const { conf, runner } = this;
185
- const preMiddleware = await runner.beforeProdServer(conf);
186
- preMiddleware.flat().forEach((mid) => {
187
- this.addHandler(mid);
188
- });
189
- }
190
- setupStaticMiddleware(prefix) {
191
- const staticPathRegExp = getStaticReg(this.conf.output, this.conf.html, prefix);
192
- return createStaticFileHandler([
193
- {
194
- path: staticPathRegExp,
195
- target: this.distDir
196
- }
197
- ], prefix);
198
- }
199
- async handleAPI(context) {
200
- const { req, res } = context;
201
- if (!this.frameAPIHandler) {
202
- throw new Error("can not found api handler");
203
- }
204
- await this.frameAPIHandler(req, res);
205
- }
206
- async handleWeb(context, route) {
207
- const { res } = context;
208
- if (this.loaderHandler) {
209
- await this.loaderHandler(context);
210
- if (this.isSend(res)) {
211
- return null;
212
- }
213
- }
214
- context.setParams(route.params);
215
- context.setServerData("router", {
216
- baseUrl: route.urlPath,
217
- params: route.params
218
- });
219
- if (route.responseHeaders) {
220
- Object.keys(route.responseHeaders).forEach((key) => {
221
- const value = route.responseHeaders[key];
222
- if (value) {
223
- context.res.setHeader(key, value);
224
- }
225
- });
226
- }
227
- const renderResult = await this.routeRenderHandler({
228
- ctx: context,
229
- route,
230
- runner: this.runner
231
- });
232
- if (!renderResult) {
233
- this.render404(context);
234
- return null;
235
- }
236
- if (renderResult.redirect) {
237
- this.redirect(res, renderResult.content, renderResult.statusCode);
238
- return null;
239
- }
240
- if (this.isSend(res)) {
241
- return null;
242
- }
243
- res.set("content-type", renderResult.contentType);
244
- return renderResult;
245
- }
246
- async proxy() {
247
- return null;
248
- }
249
- // warmup ssr function
250
- warmupSSRBundle() {
251
- const { distDir } = this;
252
- const bundles = this.router.getBundles();
253
- bundles.forEach((bundle) => {
254
- const filepath = path.join(distDir, bundle);
255
- if (fs.existsSync(filepath)) {
256
- require(filepath);
257
- }
258
- });
259
- }
260
- createContext(req, res, options = {}) {
261
- return createContext(req, res, options);
262
- }
263
- /* —————————————————————— private function —————————————————————— */
264
- // handler route.json, include api / csr / ssr
265
- async routeHandler(context) {
266
- const { res, reporter } = context;
267
- const matched = this.router.match(context.path);
268
- if (!matched) {
269
- this.render404(context);
270
- return;
271
- }
272
- await reporter.init({
273
- match: matched
274
- });
275
- const end = time();
276
- res.on("finish", () => {
277
- const cost = end();
278
- reporter.reportTiming(ServerReportTimings.SERVER_HANDLE_REQUEST, cost);
279
- });
280
- let route = matched.generate(context.url);
281
- if (route.isApi) {
282
- await this.handleAPI(context);
283
- return;
284
- }
285
- if (route.entryName && this.runMode === RUN_MODE.FULL) {
286
- const afterMatchContext = createAfterMatchContext(context, route.entryName);
287
- const end2 = time();
288
- await this.runner.afterMatch(afterMatchContext, {
289
- onLast: noop
290
- });
291
- const cost = end2();
292
- cost && reporter.reportTiming(ServerReportTimings.SERVER_HOOK_AFTER_MATCH, cost);
293
- if (this.isSend(res)) {
294
- return;
295
- }
296
- const { current, url, status } = afterMatchContext.router;
297
- if (url) {
298
- this.redirect(res, url, status);
299
- return;
300
- }
301
- if (route.entryName !== current) {
302
- const matched2 = this.router.matchEntry(current);
303
- if (!matched2) {
304
- this.render404(context);
305
- return;
306
- }
307
- route = matched2.generate(context.url);
308
- }
309
- }
310
- if (this.frameWebHandler) {
311
- res.locals = res.locals || {};
312
- const middlewareContext = createMiddlewareContext(context);
313
- const end2 = time();
314
- await this.frameWebHandler(middlewareContext);
315
- const cost = end2();
316
- cost && reporter.reportTiming(ServerReportTimings.SERVER_MIDDLEWARE, cost);
317
- res.locals = {
318
- ...res.locals,
319
- ...middlewareContext.response.locals
320
- };
321
- if (this.isSend(res)) {
322
- return;
323
- }
324
- }
325
- const renderResult = await this.handleWeb(context, route);
326
- if (!renderResult) {
327
- return;
328
- }
329
- const { contentStream: responseStream, headers } = renderResult;
330
- if (headers) {
331
- for (const name in headers) {
332
- const value = headers[name];
333
- res.setHeader(name, value);
334
- }
335
- }
336
- let { content: response } = renderResult;
337
- if (route.entryName && responseStream) {
338
- responseStream.pipe(res);
339
- return;
340
- }
341
- if (route.entryName && this.runMode === RUN_MODE.FULL) {
342
- const afterRenderContext = createAfterRenderContext(context, route, response.toString());
343
- const end2 = time();
344
- await this.runner.afterRender(afterRenderContext, {
345
- onLast: noop
346
- });
347
- const cost = end2();
348
- cost && reporter.reportTiming(ServerReportTimings.SERVER_HOOK_AFTER_RENDER, cost);
349
- if (this.isSend(res)) {
350
- return;
351
- }
352
- response = afterRenderContext.template.get();
353
- }
354
- res.end(response);
355
- }
356
- isSend(res) {
357
- if (res.modernFlushedHeaders) {
358
- if (res.writableFinished) {
359
- return true;
360
- }
361
- } else if (res.headersSent) {
362
- return true;
363
- }
364
- if (res.getHeader("Location") && isRedirect(res.statusCode)) {
365
- res.end();
366
- return true;
367
- }
368
- return false;
369
- }
370
- // compose handlers and create the final handler
371
- compose() {
372
- const { handlers } = this;
373
- if (!Array.isArray(handlers)) {
374
- throw new TypeError("Middleware stack must be an array!");
375
- }
376
- for (const fn of handlers) {
377
- if (typeof fn !== "function") {
378
- throw new TypeError("Middleware must be composed of functions!");
379
- }
380
- }
381
- this._handler = (context, next) => {
382
- let i = 0;
383
- const dispatch = (error) => {
384
- if (error) {
385
- return this.onError(context, error);
386
- }
387
- const handler = handlers[i++];
388
- if (!handler) {
389
- return next();
390
- }
391
- try {
392
- const result = handler(context, dispatch);
393
- if (isPromise(result)) {
394
- return result.catch(onError);
395
- }
396
- } catch (e) {
397
- return onError(e);
398
- }
399
- };
400
- const onError = (err) => {
401
- this.onError(context, err);
402
- };
403
- return dispatch();
404
- };
405
- }
406
- requestHandler(req, res, next = () => {
407
- }) {
408
- res.statusCode = 200;
409
- req.logger = req.logger || this.logger;
410
- req.metrics = req.metrics || this.metrics;
411
- let context;
412
- try {
413
- context = this.createContext(req, res, {
414
- metaName: this.metaName
415
- });
416
- } catch (e) {
417
- this.logger.error(e);
418
- res.statusCode = 500;
419
- res.setHeader("content-type", mime.contentType("html"));
420
- return res.end(createErrorDocument(500, ERROR_PAGE_TEXT[500]));
421
- }
422
- try {
423
- return this._handler(context, next);
424
- } catch (err) {
425
- return this.onError(context, err);
426
- }
427
- }
428
- redirect(res, url, status = 302) {
429
- res.set("Location", url);
430
- res.statusCode = status;
431
- res.end();
432
- }
433
- onError(context, err) {
434
- context.error(ERROR_DIGEST.EINTER, err);
435
- this.renderErrorPage(context, 500);
436
- }
437
- async renderErrorPage(context, status) {
438
- const { res } = context;
439
- context.status = status;
440
- res.set("content-type", mime.contentType("html"));
441
- const statusPage = `/${status}`;
442
- const customErrorPage = `/_error`;
443
- const matched = this.router.match(statusPage) || this.router.match(customErrorPage);
444
- if (matched) {
445
- const route = matched.generate(context.url);
446
- const { entryName } = route;
447
- if (entryName === status.toString() || entryName === "_error") {
448
- try {
449
- const file = await this.routeRenderHandler({
450
- route,
451
- ctx: context,
452
- runner: this.runner
453
- });
454
- if (file) {
455
- context.res.end(file.content);
456
- return;
457
- }
458
- } catch (e) {
459
- }
460
- }
461
- }
462
- const text = ERROR_PAGE_TEXT[status] || ERROR_PAGE_TEXT[500];
463
- context.res.end(createErrorDocument(status, text));
464
- }
465
- constructor({ pwd, config, routes, staticGenerate, logger, metrics, runMode, proxyTarget, appContext }) {
466
- this.handlers = [];
467
- this.loaderHandler = null;
468
- this.frameWebHandler = null;
469
- this.frameAPIHandler = null;
470
- require("ignore-styles");
471
- this.pwd = pwd;
472
- this.distDir = path.resolve(pwd, config.output.path || "dist");
473
- this.workDir = this.distDir;
474
- this.conf = config;
475
- debug("server conf", this.conf);
476
- this.logger = logger;
477
- this.metrics = metrics;
478
- this.router = new RouteMatchManager();
479
- this.presetRoutes = routes;
480
- this.proxyTarget = proxyTarget;
481
- this.staticGenerate = staticGenerate || false;
482
- this.runMode = runMode || RUN_MODE.FULL;
483
- this.metaName = appContext === null || appContext === void 0 ? void 0 : appContext.metaName;
484
- }
485
- }
486
- export {
487
- ModernServer
488
- };
@@ -1,43 +0,0 @@
1
- import { ModernServer } from "./modernServer";
2
- class ModernSSRServer extends ModernServer {
3
- prepareAPIHandler(_) {
4
- return null;
5
- }
6
- async handleAPI(context) {
7
- return this.render404(context);
8
- }
9
- }
10
- class ModernAPIServer extends ModernServer {
11
- prepareWebHandler(_) {
12
- return null;
13
- }
14
- filterRoutes(routes) {
15
- return routes.filter((route) => route.isApi);
16
- }
17
- }
18
- class ModernWebServer extends ModernServer {
19
- async warmupSSRBundle() {
20
- return null;
21
- }
22
- async handleAPI(context) {
23
- return this.render404(context);
24
- }
25
- async handleWeb(context, route) {
26
- route.isSSR = false;
27
- return super.handleWeb(context, route);
28
- }
29
- }
30
- const createProdServer = (options) => {
31
- if (options.apiOnly) {
32
- return new ModernAPIServer(options);
33
- } else if (options.ssrOnly) {
34
- return new ModernSSRServer(options);
35
- } else if (options.webOnly) {
36
- return new ModernWebServer(options);
37
- } else {
38
- return new ModernServer(options);
39
- }
40
- };
41
- export {
42
- createProdServer
43
- };
@@ -1,132 +0,0 @@
1
- import { createDebugger } from "@modern-js/utils";
2
- const debug = createDebugger("prod-server");
3
- const mergeExtension = (users) => {
4
- const output = [];
5
- return {
6
- middleware: output.concat(users)
7
- };
8
- };
9
- const noop = () => {
10
- };
11
- const createErrorDocument = (status, text) => {
12
- const title = `${status}: ${text}`;
13
- return `<!DOCTYPE html>
14
- <html lang="en">
15
- <head>
16
- <meta charset="utf-8">
17
- <meta name="viewport" content="width=device-width">
18
- <title>${title}</title>
19
- <style>
20
- html,body {
21
- margin: 0;
22
- }
23
-
24
- .page-container {
25
- color: #000;
26
- background: #fff;
27
- height: 100vh;
28
- text-align: center;
29
- display: flex;
30
- flex-direction: column;
31
- align-items: center;
32
- justify-content: center;
33
- }
34
- </style>
35
- </head>
36
- <body>
37
- <div class="page-container">
38
- <h1>${status}</h1>
39
- <div>${text}</div>
40
- </body>
41
- </html>
42
- `;
43
- };
44
- const createMiddlewareCollecter = () => {
45
- const webMiddlewares = [];
46
- const apiMiddlewares = [];
47
- const addWebMiddleware = (input) => {
48
- webMiddlewares.push(input);
49
- };
50
- const addAPIMiddleware = (input) => {
51
- apiMiddlewares.push(input);
52
- };
53
- const getMiddlewares = () => ({
54
- web: webMiddlewares,
55
- api: apiMiddlewares
56
- });
57
- return {
58
- getMiddlewares,
59
- addWebMiddleware,
60
- addAPIMiddleware
61
- };
62
- };
63
- const getStaticReg = (output = {}, html = {}, prefix = "/") => {
64
- const { distPath: { css: cssPath, js: jsPath, media: mediaPath } = {} } = output;
65
- const { favicon, faviconByEntries } = html;
66
- const favicons = prepareFavicons(favicon, faviconByEntries);
67
- const staticFiles = [
68
- cssPath,
69
- jsPath,
70
- mediaPath
71
- ].filter((v) => Boolean(v));
72
- const staticReg = [
73
- "static/",
74
- "upload/",
75
- ...staticFiles
76
- ];
77
- const iconReg = [
78
- "favicon.ico",
79
- "icon.png",
80
- ...favicons
81
- ];
82
- const regPrefix = prefix.endsWith("/") ? prefix : `${prefix}/`;
83
- const staticPathRegExp = new RegExp(`^${regPrefix}(${[
84
- ...staticReg,
85
- ...iconReg
86
- ].join("|")})`);
87
- return staticPathRegExp;
88
- };
89
- const prepareFavicons = (favicon, faviconByEntries) => {
90
- const faviconNames = [];
91
- if (favicon) {
92
- faviconNames.push(favicon.substring(favicon.lastIndexOf("/") + 1));
93
- }
94
- if (faviconByEntries) {
95
- Object.keys(faviconByEntries).forEach((f) => {
96
- const curFavicon = faviconByEntries[f];
97
- if (curFavicon) {
98
- faviconNames.push(curFavicon.substring(curFavicon.lastIndexOf("/") + 1));
99
- }
100
- });
101
- }
102
- return faviconNames;
103
- };
104
- const headersWithoutCookie = (headers) => {
105
- if (typeof headers.cookie !== "undefined") {
106
- const safeHeaders = {
107
- ...headers
108
- };
109
- delete safeHeaders.cookie;
110
- return safeHeaders;
111
- }
112
- return headers;
113
- };
114
- const isRedirect = (code) => {
115
- return [
116
- 301,
117
- 302,
118
- 307,
119
- 308
120
- ].includes(code);
121
- };
122
- export {
123
- createErrorDocument,
124
- createMiddlewareCollecter,
125
- debug,
126
- getStaticReg,
127
- headersWithoutCookie,
128
- isRedirect,
129
- mergeExtension,
130
- noop,
131
- prepareFavicons
132
- };