@modern-js/prod-server 2.9.1-alpha.0 → 2.11.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 (139) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/dist/cjs/libs/hook-api/index.js +7 -26
  3. package/dist/cjs/libs/render/index.js +2 -1
  4. package/dist/cjs/libs/render/ssr.js +7 -5
  5. package/dist/{js/node/libs/metrics.js → cjs/libs/render/utils.js} +25 -12
  6. package/dist/cjs/server/index.js +1 -1
  7. package/dist/cjs/server/modernServer.js +75 -80
  8. package/dist/esm/libs/hook-api/index.js +9 -37
  9. package/dist/esm/libs/render/index.js +2 -1
  10. package/dist/esm/libs/render/ssr.js +6 -4
  11. package/dist/esm/libs/render/utils.js +12 -0
  12. package/dist/esm/server/index.js +2 -2
  13. package/dist/esm/server/modernServer.js +108 -103
  14. package/dist/esm-node/libs/hook-api/index.js +7 -26
  15. package/dist/esm-node/libs/render/index.js +2 -1
  16. package/dist/esm-node/libs/render/ssr.js +7 -7
  17. package/dist/esm-node/libs/render/utils.js +23 -0
  18. package/dist/esm-node/server/index.js +1 -1
  19. package/dist/esm-node/server/modernServer.js +75 -80
  20. package/dist/types/libs/context/context.d.ts +1 -1
  21. package/dist/types/libs/render/utils.d.ts +5 -0
  22. package/dist/types/server/index.d.ts +2 -1
  23. package/dist/types/server/modernServer.d.ts +4 -4
  24. package/dist/types/type.d.ts +1 -1
  25. package/dist/types/utils.d.ts +1 -1
  26. package/package.json +9 -7
  27. package/dist/js/modern/constants.js +0 -35
  28. package/dist/js/modern/index.js +0 -18
  29. package/dist/js/modern/libs/context/context.js +0 -160
  30. package/dist/js/modern/libs/context/index.js +0 -6
  31. package/dist/js/modern/libs/hook-api/index.js +0 -134
  32. package/dist/js/modern/libs/hook-api/route.js +0 -20
  33. package/dist/js/modern/libs/hook-api/template.js +0 -73
  34. package/dist/js/modern/libs/loadConfig.js +0 -62
  35. package/dist/js/modern/libs/logger.js +0 -111
  36. package/dist/js/modern/libs/metrics.js +0 -11
  37. package/dist/js/modern/libs/proxy.js +0 -92
  38. package/dist/js/modern/libs/render/cache/__tests__/cache.fun.test.js +0 -114
  39. package/dist/js/modern/libs/render/cache/__tests__/cache.test.js +0 -254
  40. package/dist/js/modern/libs/render/cache/__tests__/cacheable.js +0 -47
  41. package/dist/js/modern/libs/render/cache/__tests__/error-configuration.js +0 -37
  42. package/dist/js/modern/libs/render/cache/__tests__/matched-cache.js +0 -91
  43. package/dist/js/modern/libs/render/cache/index.js +0 -115
  44. package/dist/js/modern/libs/render/cache/page-caches/index.js +0 -32
  45. package/dist/js/modern/libs/render/cache/page-caches/lru.js +0 -29
  46. package/dist/js/modern/libs/render/cache/spr.js +0 -248
  47. package/dist/js/modern/libs/render/cache/type.js +0 -0
  48. package/dist/js/modern/libs/render/cache/util.js +0 -102
  49. package/dist/js/modern/libs/render/index.js +0 -86
  50. package/dist/js/modern/libs/render/measure.js +0 -68
  51. package/dist/js/modern/libs/render/reader.js +0 -107
  52. package/dist/js/modern/libs/render/ssr.js +0 -100
  53. package/dist/js/modern/libs/render/static.js +0 -60
  54. package/dist/js/modern/libs/render/type.js +0 -9
  55. package/dist/js/modern/libs/route/index.js +0 -54
  56. package/dist/js/modern/libs/route/matcher.js +0 -87
  57. package/dist/js/modern/libs/route/route.js +0 -16
  58. package/dist/js/modern/libs/serve-file.js +0 -67
  59. package/dist/js/modern/server/index.js +0 -208
  60. package/dist/js/modern/server/modern-server-split.js +0 -74
  61. package/dist/js/modern/server/modern-server.js +0 -554
  62. package/dist/js/modern/type.js +0 -0
  63. package/dist/js/modern/utils.js +0 -136
  64. package/dist/js/modern/worker-server.js +0 -89
  65. package/dist/js/node/constants.js +0 -62
  66. package/dist/js/node/index.js +0 -44
  67. package/dist/js/node/libs/context/context.js +0 -189
  68. package/dist/js/node/libs/context/index.js +0 -30
  69. package/dist/js/node/libs/hook-api/index.js +0 -164
  70. package/dist/js/node/libs/hook-api/route.js +0 -43
  71. package/dist/js/node/libs/hook-api/template.js +0 -97
  72. package/dist/js/node/libs/loadConfig.js +0 -91
  73. package/dist/js/node/libs/logger.js +0 -133
  74. package/dist/js/node/libs/proxy.js +0 -114
  75. package/dist/js/node/libs/render/cache/__tests__/cache.fun.test.js +0 -115
  76. package/dist/js/node/libs/render/cache/__tests__/cache.test.js +0 -245
  77. package/dist/js/node/libs/render/cache/__tests__/cacheable.js +0 -70
  78. package/dist/js/node/libs/render/cache/__tests__/error-configuration.js +0 -60
  79. package/dist/js/node/libs/render/cache/__tests__/matched-cache.js +0 -114
  80. package/dist/js/node/libs/render/cache/index.js +0 -134
  81. package/dist/js/node/libs/render/cache/page-caches/index.js +0 -55
  82. package/dist/js/node/libs/render/cache/page-caches/lru.js +0 -58
  83. package/dist/js/node/libs/render/cache/spr.js +0 -270
  84. package/dist/js/node/libs/render/cache/type.js +0 -15
  85. package/dist/js/node/libs/render/cache/util.js +0 -138
  86. package/dist/js/node/libs/render/index.js +0 -115
  87. package/dist/js/node/libs/render/measure.js +0 -90
  88. package/dist/js/node/libs/render/reader.js +0 -140
  89. package/dist/js/node/libs/render/ssr.js +0 -123
  90. package/dist/js/node/libs/render/static.js +0 -89
  91. package/dist/js/node/libs/render/type.js +0 -32
  92. package/dist/js/node/libs/route/index.js +0 -78
  93. package/dist/js/node/libs/route/matcher.js +0 -106
  94. package/dist/js/node/libs/route/route.js +0 -39
  95. package/dist/js/node/libs/serve-file.js +0 -97
  96. package/dist/js/node/server/index.js +0 -219
  97. package/dist/js/node/server/modern-server-split.js +0 -97
  98. package/dist/js/node/server/modern-server.js +0 -559
  99. package/dist/js/node/type.js +0 -15
  100. package/dist/js/node/utils.js +0 -166
  101. package/dist/js/node/worker-server.js +0 -113
  102. package/dist/js/treeshaking/constants.js +0 -29
  103. package/dist/js/treeshaking/index.js +0 -13
  104. package/dist/js/treeshaking/libs/context/context.js +0 -274
  105. package/dist/js/treeshaking/libs/context/index.js +0 -5
  106. package/dist/js/treeshaking/libs/hook-api/index.js +0 -281
  107. package/dist/js/treeshaking/libs/hook-api/route.js +0 -68
  108. package/dist/js/treeshaking/libs/hook-api/template.js +0 -127
  109. package/dist/js/treeshaking/libs/loadConfig.js +0 -82
  110. package/dist/js/treeshaking/libs/logger.js +0 -205
  111. package/dist/js/treeshaking/libs/metrics.js +0 -6
  112. package/dist/js/treeshaking/libs/proxy.js +0 -244
  113. package/dist/js/treeshaking/libs/render/cache/__tests__/cache.fun.test.js +0 -291
  114. package/dist/js/treeshaking/libs/render/cache/__tests__/cache.test.js +0 -781
  115. package/dist/js/treeshaking/libs/render/cache/__tests__/cacheable.js +0 -67
  116. package/dist/js/treeshaking/libs/render/cache/__tests__/error-configuration.js +0 -45
  117. package/dist/js/treeshaking/libs/render/cache/__tests__/matched-cache.js +0 -147
  118. package/dist/js/treeshaking/libs/render/cache/index.js +0 -346
  119. package/dist/js/treeshaking/libs/render/cache/page-caches/index.js +0 -154
  120. package/dist/js/treeshaking/libs/render/cache/page-caches/lru.js +0 -84
  121. package/dist/js/treeshaking/libs/render/cache/spr.js +0 -492
  122. package/dist/js/treeshaking/libs/render/cache/type.js +0 -1
  123. package/dist/js/treeshaking/libs/render/cache/util.js +0 -280
  124. package/dist/js/treeshaking/libs/render/index.js +0 -234
  125. package/dist/js/treeshaking/libs/render/measure.js +0 -146
  126. package/dist/js/treeshaking/libs/render/reader.js +0 -339
  127. package/dist/js/treeshaking/libs/render/ssr.js +0 -223
  128. package/dist/js/treeshaking/libs/render/static.js +0 -216
  129. package/dist/js/treeshaking/libs/render/type.js +0 -7
  130. package/dist/js/treeshaking/libs/route/index.js +0 -130
  131. package/dist/js/treeshaking/libs/route/matcher.js +0 -143
  132. package/dist/js/treeshaking/libs/route/route.js +0 -40
  133. package/dist/js/treeshaking/libs/serve-file.js +0 -184
  134. package/dist/js/treeshaking/server/index.js +0 -505
  135. package/dist/js/treeshaking/server/modern-server-split.js +0 -360
  136. package/dist/js/treeshaking/server/modern-server.js +0 -1089
  137. package/dist/js/treeshaking/type.js +0 -1
  138. package/dist/js/treeshaking/utils.js +0 -147
  139. package/dist/js/treeshaking/worker-server.js +0 -233
@@ -1,248 +0,0 @@
1
- var __async = (__this, __arguments, generator) => {
2
- return new Promise((resolve, reject) => {
3
- var fulfilled = (value) => {
4
- try {
5
- step(generator.next(value));
6
- } catch (e) {
7
- reject(e);
8
- }
9
- };
10
- var rejected = (value) => {
11
- try {
12
- step(generator.throw(value));
13
- } catch (e) {
14
- reject(e);
15
- }
16
- };
17
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
- step((generator = generator.apply(__this, __arguments)).next());
19
- });
20
- };
21
- import crypto from "crypto";
22
- import LRUCache from "lru-cache";
23
- import { mime } from "@modern-js/utils";
24
- import {
25
- cacheAddition,
26
- connectFactor,
27
- fname,
28
- maybeSync,
29
- namespaceHash,
30
- valueFactory,
31
- withCoalescedInvoke
32
- } from "./util";
33
- import { createPageCaches } from "./page-caches";
34
- const MAX_CACHE_EACH_REQ = Number(process.env.ROUTE_CACHE_LIMIT) || 10;
35
- const MAX_SIZE_EACH_CLUSTER = Number(process.env.CLUSTER_CACHE_LIMIT) || 100;
36
- const BASE_LEVEL = 0;
37
- const QUERY_LEVEL = 1;
38
- const HEADER_LEVEL = 2;
39
- const QUERY_HEADER_LEVEL = 3;
40
- class CacheManager {
41
- constructor(cacheOptions) {
42
- this.find = (() => {
43
- {
44
- const _this = this;
45
- return {
46
- [fname(BASE_LEVEL)](context, cacheKey) {
47
- return _this.md5(cacheKey);
48
- },
49
- [fname(QUERY_LEVEL)](context, cacheKey, data) {
50
- const queryFactor = _this.queryFactor(context, data);
51
- if (!queryFactor) {
52
- return null;
53
- }
54
- return _this.md5(connectFactor(cacheKey, queryFactor));
55
- },
56
- [fname(HEADER_LEVEL)](context, cacheKey, data) {
57
- const headerFactor = _this.headerFactor(context, data);
58
- if (!headerFactor) {
59
- return null;
60
- }
61
- return _this.md5(connectFactor(cacheKey, headerFactor));
62
- },
63
- [fname(QUERY_HEADER_LEVEL)](context, cacheKey, data) {
64
- const queryFactor = _this.queryFactor(context, data);
65
- const headerFactor = _this.headerFactor(context, data);
66
- if (!queryFactor || !headerFactor) {
67
- return null;
68
- }
69
- return _this.md5(connectFactor(cacheKey, headerFactor, queryFactor));
70
- }
71
- };
72
- }
73
- })();
74
- this.cacheOptions = cacheOptions;
75
- this.cache = new LRUCache({
76
- max: Math.min(MAX_SIZE_EACH_CLUSTER, 600) * 1024 * 1024,
77
- length(n) {
78
- const len = n.caches.keys().reduce((total, cur) => {
79
- var _a;
80
- return total + (((_a = n.caches.peek(cur)) == null ? void 0 : _a.size) || 0);
81
- }, 1);
82
- return len;
83
- }
84
- });
85
- }
86
- md5(content) {
87
- const md5 = crypto.createHash("md5");
88
- return md5.update(content).digest("hex");
89
- }
90
- generateRequestKey(context) {
91
- const { pathname, entry } = context;
92
- return this.md5(`${pathname}_${entry}`);
93
- }
94
- replaceValue(value, matcher) {
95
- let final = value;
96
- Object.keys(matcher).some((replacer) => {
97
- const reg = new RegExp(matcher[replacer]);
98
- if (reg.test(value)) {
99
- final = replacer;
100
- return true;
101
- }
102
- return false;
103
- });
104
- return final;
105
- }
106
- factor(keys, obj, matches = {}) {
107
- keys.sort();
108
- const getValue = valueFactory(obj);
109
- const factorAry = keys.reduce((ary, key) => {
110
- let value = getValue(key) || "";
111
- const matcher = matches[key];
112
- if (matcher) {
113
- value = this.replaceValue(value, matcher);
114
- }
115
- return ary.concat([key, value]);
116
- }, []);
117
- return factorAry.join(",");
118
- }
119
- queryFactor(context, data) {
120
- var _a, _b;
121
- const queryKeys = (_a = data.includes) == null ? void 0 : _a.query;
122
- const queryMatches = (_b = data.matches) == null ? void 0 : _b.query;
123
- if (!queryKeys || queryKeys.length === 0) {
124
- return null;
125
- }
126
- const requestQuery = context.query;
127
- const queryFactor = this.factor(queryKeys, requestQuery, queryMatches);
128
- return queryFactor;
129
- }
130
- headerFactor(context, data) {
131
- var _a, _b;
132
- const headerKeys = (_a = data.includes) == null ? void 0 : _a.header;
133
- const headerMatches = (_b = data.matches) == null ? void 0 : _b.header;
134
- if (!headerKeys || headerKeys.length === 0) {
135
- return null;
136
- }
137
- const requestHeader = context.headers;
138
- const headerFactor = this.factor(headerKeys, requestHeader, headerMatches);
139
- return headerFactor;
140
- }
141
- best(context, cacheKey, data) {
142
- return __async(this, null, function* () {
143
- const { level } = data;
144
- const cacheHash = this.find[fname(level)](context, cacheKey, data);
145
- if (!cacheHash) {
146
- return null;
147
- }
148
- return data.caches.get(cacheHash);
149
- });
150
- }
151
- createCacheContent(config, caches) {
152
- return {
153
- level: config.level,
154
- interval: config.interval,
155
- includes: config.includes || null,
156
- limit: config.staleLimit,
157
- matches: config.matches || null,
158
- caches
159
- };
160
- }
161
- get(context) {
162
- return __async(this, null, function* () {
163
- const cacheKey = this.generateRequestKey(context);
164
- const data = this.cache.get(cacheKey);
165
- if (!data) {
166
- return null;
167
- }
168
- const dest = yield this.best(context, cacheKey, data);
169
- if (!dest) {
170
- return null;
171
- }
172
- const { expireTime, limitTime, html, cacheHash } = dest;
173
- const isStale = Date.now() - expireTime > 0;
174
- const isGarbage = limitTime ? Date.now() - limitTime > 0 : false;
175
- return {
176
- content: html || "",
177
- contentType: mime.contentType("html"),
178
- isStale,
179
- isGarbage,
180
- hash: cacheHash
181
- };
182
- });
183
- }
184
- set(context, html, cacheConfig, sync = false) {
185
- return __async(this, null, function* () {
186
- if (!cacheConfig) {
187
- return false;
188
- }
189
- const cacheKey = this.generateRequestKey(context);
190
- let data = this.cache.get(cacheKey);
191
- if (!data) {
192
- const caches = yield createPageCaches(MAX_CACHE_EACH_REQ);
193
- data = this.createCacheContent(cacheConfig, caches);
194
- }
195
- const cacheHash = this.find[fname(cacheConfig.level)](
196
- context,
197
- cacheKey,
198
- data
199
- );
200
- if (!cacheHash) {
201
- return false;
202
- }
203
- const cacheSyncOrAsync = () => __async(this, null, function* () {
204
- const next = data;
205
- const limit = cacheConfig.staleLimit;
206
- const storeHTML = cacheAddition(html, cacheHash);
207
- const size = storeHTML.length;
208
- yield next.caches.set(cacheHash, {
209
- expireTime: Date.now() + cacheConfig.interval * 1e3,
210
- limitTime: typeof limit === "number" ? Date.now() + limit * 1e3 : null,
211
- cacheHash,
212
- html: storeHTML,
213
- size
214
- });
215
- this.cache.set(cacheKey, next);
216
- return true;
217
- });
218
- const doCache = withCoalescedInvoke(cacheSyncOrAsync).bind(
219
- null,
220
- namespaceHash("stream", cacheHash),
221
- []
222
- );
223
- return maybeSync(doCache)(sync);
224
- });
225
- }
226
- del(context, cacheHash) {
227
- return __async(this, null, function* () {
228
- const cacheKey = this.generateRequestKey(context);
229
- const data = this.cache.get(cacheKey);
230
- data == null ? void 0 : data.caches.del(cacheHash);
231
- });
232
- }
233
- }
234
- let manager;
235
- function createCache() {
236
- if (manager) {
237
- return manager;
238
- }
239
- manager = new CacheManager({ max: 0 });
240
- return manager;
241
- }
242
- function destroyCache() {
243
- manager = null;
244
- }
245
- export {
246
- createCache,
247
- destroyCache
248
- };
File without changes
@@ -1,102 +0,0 @@
1
- var __async = (__this, __arguments, generator) => {
2
- return new Promise((resolve, reject) => {
3
- var fulfilled = (value) => {
4
- try {
5
- step(generator.next(value));
6
- } catch (e) {
7
- reject(e);
8
- }
9
- };
10
- var rejected = (value) => {
11
- try {
12
- step(generator.throw(value));
13
- } catch (e) {
14
- reject(e);
15
- }
16
- };
17
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
- step((generator = generator.apply(__this, __arguments)).next());
19
- });
20
- };
21
- import url from "url";
22
- function namespaceHash(namespace, hash) {
23
- return `${namespace}/${hash}`;
24
- }
25
- function fname(lv) {
26
- return `f${lv}`;
27
- }
28
- function connectFactor(...args) {
29
- return args.join("-");
30
- }
31
- function valueFactory(obj) {
32
- if (obj instanceof url.URLSearchParams) {
33
- return function(key) {
34
- return obj.get(key);
35
- };
36
- } else {
37
- return function(key) {
38
- const value = obj[key];
39
- if (Array.isArray(value)) {
40
- return value.join(",");
41
- }
42
- return value;
43
- };
44
- }
45
- }
46
- function getTime([s, ns]) {
47
- return Math.floor(s * 1e3 + ns / 1e6);
48
- }
49
- const RE_START_IN_HEAD = /<head>/;
50
- function cacheAddition(html, hash) {
51
- const additionHtml = html.replace(
52
- RE_START_IN_HEAD,
53
- `<head><meta name="x-moden-spr" content="${hash}">`
54
- );
55
- return additionHtml;
56
- }
57
- const globalInvokeCache = /* @__PURE__ */ new Map();
58
- function withCoalescedInvoke(func) {
59
- return function(key, args) {
60
- return __async(this, null, function* () {
61
- const entry = globalInvokeCache.get(key);
62
- if (entry) {
63
- return entry.then((res) => ({
64
- isOrigin: false,
65
- value: res.value
66
- }));
67
- }
68
- function __wrapper() {
69
- return func(...args);
70
- }
71
- const future = __wrapper().then((res) => {
72
- globalInvokeCache.delete(key);
73
- return { isOrigin: true, value: res };
74
- }).catch((err) => {
75
- globalInvokeCache.delete(key);
76
- throw err;
77
- });
78
- globalInvokeCache.set(key, future);
79
- return future;
80
- });
81
- };
82
- }
83
- function maybeSync(fn) {
84
- return (sync) => {
85
- if (sync) {
86
- return fn();
87
- } else {
88
- fn();
89
- return Promise.resolve();
90
- }
91
- };
92
- }
93
- export {
94
- cacheAddition,
95
- connectFactor,
96
- fname,
97
- getTime,
98
- maybeSync,
99
- namespaceHash,
100
- valueFactory,
101
- withCoalescedInvoke
102
- };
@@ -1,86 +0,0 @@
1
- var __async = (__this, __arguments, generator) => {
2
- return new Promise((resolve, reject) => {
3
- var fulfilled = (value) => {
4
- try {
5
- step(generator.next(value));
6
- } catch (e) {
7
- reject(e);
8
- }
9
- };
10
- var rejected = (value) => {
11
- try {
12
- step(generator.throw(value));
13
- } catch (e) {
14
- reject(e);
15
- }
16
- };
17
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
- step((generator = generator.apply(__this, __arguments)).next());
19
- });
20
- };
21
- import path from "path";
22
- import { fs, mime } from "@modern-js/utils";
23
- import { ERROR_DIGEST } from "../../constants";
24
- import { handleDirectory } from "./static";
25
- import { readFile } from "./reader";
26
- import * as ssr from "./ssr";
27
- const createRenderHandler = ({
28
- distDir,
29
- staticGenerate,
30
- forceCSR
31
- }) => function render(_0) {
32
- return __async(this, arguments, function* ({
33
- ctx,
34
- route,
35
- runner
36
- }) {
37
- if (ctx.resHasHandled()) {
38
- return null;
39
- }
40
- const { entryPath, urlPath } = route;
41
- const entry = path.join(distDir, entryPath);
42
- if (!route.isSPA) {
43
- const result = yield handleDirectory(ctx, entry, urlPath);
44
- return result;
45
- }
46
- const templatePath = entry;
47
- if (!fs.existsSync(templatePath)) {
48
- throw new Error(`Could not find template file: ${templatePath}`);
49
- }
50
- const content = yield readFile(templatePath);
51
- if (!content) {
52
- return null;
53
- }
54
- const useCSR = forceCSR && ctx.query.csr;
55
- if (route.isSSR && !useCSR) {
56
- try {
57
- const result = yield ssr.render(
58
- ctx,
59
- {
60
- distDir,
61
- entryName: route.entryName,
62
- urlPath: route.urlPath,
63
- bundle: route.bundle,
64
- template: content.toString(),
65
- staticGenerate
66
- },
67
- runner
68
- );
69
- return result;
70
- } catch (err) {
71
- ctx.error(
72
- ERROR_DIGEST.ERENDER,
73
- err.stack || err.message
74
- );
75
- ctx.res.setHeader("x-modern-ssr-fallback", "1");
76
- }
77
- }
78
- return {
79
- content,
80
- contentType: mime.contentType(path.extname(templatePath))
81
- };
82
- });
83
- };
84
- export {
85
- createRenderHandler
86
- };
@@ -1,68 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- import { headersWithoutCookie } from "../../utils";
21
- const createMetrics = (context, metrics) => {
22
- const { entryName: entry, request } = context;
23
- const { pathname = "" } = request || {};
24
- const emitTimer = (name, cost, tags = {}) => {
25
- metrics.emitTimer(name, cost, __spreadProps(__spreadValues({}, tags), {
26
- pathname,
27
- entry
28
- }));
29
- };
30
- const emitCounter = (name, counter, tags = {}) => {
31
- metrics.emitCounter(name, counter, __spreadProps(__spreadValues({}, tags), {
32
- pathname,
33
- entry
34
- }));
35
- };
36
- return { emitTimer, emitCounter };
37
- };
38
- const createLogger = (serverContext, logger) => {
39
- const request = serverContext.request || {};
40
- const { headers = {}, pathname = "" } = request;
41
- const debug = (message, ...args) => {
42
- logger.debug(`SSR Debug - ${message}, req.url = %s`, ...args, pathname);
43
- };
44
- const info = (message, ...args) => {
45
- logger.info(`SSR Info - ${message}, req.url = %s`, ...args, pathname);
46
- };
47
- const error = (message, e) => {
48
- if (!e) {
49
- e = message;
50
- message = "";
51
- }
52
- logger.error(
53
- `SSR Error - ${message}, error = %s, req.url = %s, req.headers = %o`,
54
- e instanceof Error ? e.stack || e.message : e,
55
- pathname,
56
- headersWithoutCookie(headers)
57
- );
58
- };
59
- return {
60
- error,
61
- info,
62
- debug
63
- };
64
- };
65
- export {
66
- createLogger,
67
- createMetrics
68
- };
@@ -1,107 +0,0 @@
1
- var __async = (__this, __arguments, generator) => {
2
- return new Promise((resolve, reject) => {
3
- var fulfilled = (value) => {
4
- try {
5
- step(generator.next(value));
6
- } catch (e) {
7
- reject(e);
8
- }
9
- };
10
- var rejected = (value) => {
11
- try {
12
- step(generator.throw(value));
13
- } catch (e) {
14
- reject(e);
15
- }
16
- };
17
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
- step((generator = generator.apply(__this, __arguments)).next());
19
- });
20
- };
21
- import { fs } from "@modern-js/utils";
22
- import LRU from "lru-cache";
23
- const Byte = 1;
24
- const KB = 1024 * Byte;
25
- const MB = 1024 * KB;
26
- const getContentLength = (cache) => cache.content.length;
27
- const createCacheItem = (filepath, mtime) => __async(void 0, null, function* () {
28
- const content = yield fs.readFile(filepath);
29
- return {
30
- content,
31
- mtime
32
- };
33
- });
34
- class LruReader {
35
- constructor() {
36
- this.cache = new LRU({
37
- max: 256 * MB,
38
- length: getContentLength,
39
- maxAge: 5 * 60 * 5e3
40
- });
41
- }
42
- init() {
43
- }
44
- close() {
45
- }
46
- read(filepath) {
47
- return __async(this, null, function* () {
48
- if (this.cache.has(filepath)) {
49
- const { content } = this.cache.get(filepath);
50
- return { content };
51
- }
52
- if (!fs.existsSync(filepath)) {
53
- return null;
54
- }
55
- const stat = fs.statSync(filepath);
56
- if (stat.isDirectory()) {
57
- return null;
58
- }
59
- if (stat.size > 20 * MB) {
60
- return null;
61
- }
62
- const item = yield createCacheItem(filepath, stat.mtime);
63
- this.cache.set(filepath, item);
64
- return item;
65
- });
66
- }
67
- update() {
68
- const { cache } = this;
69
- const files = cache.keys();
70
- for (const filepath of files) {
71
- if (!fs.existsSync(filepath)) {
72
- cache.del(filepath);
73
- }
74
- try {
75
- const item = cache.get(filepath);
76
- const stat = fs.statSync(filepath);
77
- const { mtime } = stat;
78
- if (item.mtime < mtime) {
79
- cache.del(filepath);
80
- }
81
- } catch (e) {
82
- cache.del(filepath);
83
- }
84
- }
85
- }
86
- }
87
- const reader = new LruReader();
88
- const readFile = (filepath) => __async(void 0, null, function* () {
89
- const file = yield reader.read(filepath);
90
- return file == null ? void 0 : file.content;
91
- });
92
- const updateFile = () => {
93
- reader.update();
94
- };
95
- const init = () => {
96
- reader.init();
97
- };
98
- const close = () => {
99
- reader.close();
100
- };
101
- export {
102
- LruReader,
103
- close,
104
- init,
105
- readFile,
106
- updateFile
107
- };
@@ -1,100 +0,0 @@
1
- var __async = (__this, __arguments, generator) => {
2
- return new Promise((resolve, reject) => {
3
- var fulfilled = (value) => {
4
- try {
5
- step(generator.next(value));
6
- } catch (e) {
7
- reject(e);
8
- }
9
- };
10
- var rejected = (value) => {
11
- try {
12
- step(generator.throw(value));
13
- } catch (e) {
14
- reject(e);
15
- }
16
- };
17
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
- step((generator = generator.apply(__this, __arguments)).next());
19
- });
20
- };
21
- import path from "path";
22
- import {
23
- fs,
24
- LOADABLE_STATS_FILE,
25
- mime,
26
- ROUTE_MINIFEST_FILE,
27
- SERVER_RENDER_FUNCTION_NAME
28
- } from "@modern-js/utils";
29
- import cookie from "cookie";
30
- import cache from "./cache";
31
- import { createLogger, createMetrics } from "./measure";
32
- const render = (ctx, renderOptions, runner) => __async(void 0, null, function* () {
33
- var _a;
34
- const { urlPath, bundle, distDir, template, entryName, staticGenerate } = renderOptions;
35
- const bundleJS = path.join(distDir, bundle);
36
- const loadableUri = path.join(distDir, LOADABLE_STATS_FILE);
37
- const loadableStats = fs.existsSync(loadableUri) ? require(loadableUri) : "";
38
- const routesManifestUri = path.join(distDir, ROUTE_MINIFEST_FILE);
39
- const routeManifest = fs.existsSync(routesManifestUri) ? require(routesManifestUri) : void 0;
40
- const context = {
41
- request: {
42
- baseUrl: urlPath,
43
- params: ctx.params,
44
- pathname: ctx.path,
45
- host: ctx.host,
46
- query: ctx.query,
47
- url: ctx.href,
48
- cookieMap: cookie.parse(ctx.headers.cookie || ""),
49
- headers: ctx.headers
50
- },
51
- response: {
52
- setHeader: (key, value) => {
53
- return ctx.res.setHeader(key, value);
54
- },
55
- status: (code) => {
56
- ctx.res.statusCode = code;
57
- },
58
- locals: ((_a = ctx.res) == null ? void 0 : _a.locals) || {}
59
- },
60
- redirection: {},
61
- template,
62
- loadableStats,
63
- routeManifest,
64
- entryName,
65
- staticGenerate,
66
- logger: void 0,
67
- metrics: void 0,
68
- req: ctx.req,
69
- res: ctx.res
70
- };
71
- context.logger = createLogger(context, ctx.logger);
72
- context.metrics = createMetrics(context, ctx.metrics);
73
- runner.extendSSRContext(context);
74
- const serverRender = require(bundleJS)[SERVER_RENDER_FUNCTION_NAME];
75
- const content = yield cache(serverRender, ctx)(context);
76
- const { url, status = 302 } = context.redirection;
77
- if (url) {
78
- return {
79
- content: url,
80
- contentType: "",
81
- statusCode: status,
82
- redirect: true
83
- };
84
- }
85
- if (typeof content === "string") {
86
- return {
87
- content,
88
- contentType: mime.contentType("html")
89
- };
90
- } else {
91
- return {
92
- content: "",
93
- contentStream: content,
94
- contentType: mime.contentType("html")
95
- };
96
- }
97
- });
98
- export {
99
- render
100
- };