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