@dr.pogodin/react-utils 1.46.2 → 1.47.0-alpha.1

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 (237) hide show
  1. package/babel.config.js +1 -0
  2. package/babel.libweb.config.js +16 -0
  3. package/bin/build.js +16 -10
  4. package/bin/setup.js +11 -8
  5. package/build/development/client/getInj.js.map +1 -1
  6. package/build/development/client/index.js.map +1 -1
  7. package/build/development/client/init.js.map +1 -1
  8. package/build/development/index.js +7 -1
  9. package/build/development/index.js.map +1 -1
  10. package/build/development/server/Cache.js.map +1 -1
  11. package/build/development/server/index.js +13 -8
  12. package/build/development/server/index.js.map +1 -1
  13. package/build/development/server/renderer.js +15 -8
  14. package/build/development/server/renderer.js.map +1 -1
  15. package/build/development/server/server.js +7 -5
  16. package/build/development/server/server.js.map +1 -1
  17. package/build/development/shared/components/Button/index.js +6 -6
  18. package/build/development/shared/components/Button/index.js.map +1 -1
  19. package/build/development/shared/components/Checkbox/index.js +8 -8
  20. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  21. package/build/development/shared/components/GenericLink/index.js +5 -1
  22. package/build/development/shared/components/GenericLink/index.js.map +1 -1
  23. package/build/development/shared/components/Input/index.js +10 -9
  24. package/build/development/shared/components/Input/index.js.map +1 -1
  25. package/build/development/shared/components/Link.js.map +1 -1
  26. package/build/development/shared/components/Modal/index.js +8 -6
  27. package/build/development/shared/components/Modal/index.js.map +1 -1
  28. package/build/development/shared/components/NavLink.js.map +1 -1
  29. package/build/development/shared/components/PageLayout/index.js +6 -6
  30. package/build/development/shared/components/PageLayout/index.js.map +1 -1
  31. package/build/development/shared/components/TextArea/index.js +13 -9
  32. package/build/development/shared/components/TextArea/index.js.map +1 -1
  33. package/build/development/shared/components/Throbber/index.js +6 -6
  34. package/build/development/shared/components/Throbber/index.js.map +1 -1
  35. package/build/development/shared/components/WithTooltip/Tooltip.js +1 -0
  36. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  37. package/build/development/shared/components/WithTooltip/index.js +7 -7
  38. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  39. package/build/development/shared/components/YouTubeVideo/index.js +9 -9
  40. package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
  41. package/build/development/shared/components/index.js.map +1 -1
  42. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  43. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  44. package/build/development/shared/components/selectors/CustomDropdown/index.js +11 -11
  45. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  46. package/build/development/shared/components/selectors/NativeDropdown/index.js +12 -12
  47. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  48. package/build/development/shared/components/selectors/Switch/index.js +7 -7
  49. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  50. package/build/development/shared/utils/config.js.map +1 -1
  51. package/build/development/shared/utils/globalState.js.map +1 -1
  52. package/build/development/shared/utils/index.js.map +1 -1
  53. package/build/development/shared/utils/jest/E2eSsrEnv.js +14 -10
  54. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  55. package/build/development/shared/utils/splitComponent.js +1 -0
  56. package/build/development/shared/utils/splitComponent.js.map +1 -1
  57. package/build/development/shared/utils/time.js.map +1 -1
  58. package/build/production/client/getInj.js.map +1 -1
  59. package/build/production/client/index.js.map +1 -1
  60. package/build/production/client/init.js.map +1 -1
  61. package/build/production/index.js +4 -1
  62. package/build/production/index.js.map +1 -1
  63. package/build/production/server/Cache.js.map +1 -1
  64. package/build/production/server/index.js +5 -5
  65. package/build/production/server/index.js.map +1 -1
  66. package/build/production/server/renderer.js +7 -7
  67. package/build/production/server/renderer.js.map +1 -1
  68. package/build/production/server/server.js +4 -4
  69. package/build/production/server/server.js.map +1 -1
  70. package/build/production/shared/components/Button/index.js +1 -1
  71. package/build/production/shared/components/Button/index.js.map +1 -1
  72. package/build/production/shared/components/Checkbox/index.js +1 -1
  73. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  74. package/build/production/shared/components/GenericLink/index.js +2 -2
  75. package/build/production/shared/components/GenericLink/index.js.map +1 -1
  76. package/build/production/shared/components/Input/index.js +1 -1
  77. package/build/production/shared/components/Input/index.js.map +1 -1
  78. package/build/production/shared/components/Link.js.map +1 -1
  79. package/build/production/shared/components/Modal/index.js +1 -1
  80. package/build/production/shared/components/Modal/index.js.map +1 -1
  81. package/build/production/shared/components/NavLink.js.map +1 -1
  82. package/build/production/shared/components/PageLayout/index.js +1 -1
  83. package/build/production/shared/components/PageLayout/index.js.map +1 -1
  84. package/build/production/shared/components/TextArea/index.js +1 -1
  85. package/build/production/shared/components/TextArea/index.js.map +1 -1
  86. package/build/production/shared/components/Throbber/index.js +1 -1
  87. package/build/production/shared/components/Throbber/index.js.map +1 -1
  88. package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
  89. package/build/production/shared/components/WithTooltip/index.js +1 -1
  90. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  91. package/build/production/shared/components/YouTubeVideo/index.js +1 -1
  92. package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
  93. package/build/production/shared/components/index.js.map +1 -1
  94. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  95. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  96. package/build/production/shared/components/selectors/CustomDropdown/index.js +1 -1
  97. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  98. package/build/production/shared/components/selectors/NativeDropdown/index.js +1 -1
  99. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  100. package/build/production/shared/components/selectors/Switch/index.js +1 -1
  101. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  102. package/build/production/shared/utils/config.js.map +1 -1
  103. package/build/production/shared/utils/globalState.js.map +1 -1
  104. package/build/production/shared/utils/index.js.map +1 -1
  105. package/build/production/shared/utils/jest/E2eSsrEnv.js +8 -7
  106. package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  107. package/build/production/shared/utils/splitComponent.js.map +1 -1
  108. package/build/production/shared/utils/time.js.map +1 -1
  109. package/build/web/client/getInj.js +54 -0
  110. package/build/web/client/getInj.js.map +1 -0
  111. package/build/web/client/index.js +38 -0
  112. package/build/web/client/index.js.map +1 -0
  113. package/build/web/client/init.js +49 -0
  114. package/build/web/client/init.js.map +1 -0
  115. package/build/web/index.js +25 -0
  116. package/build/web/index.js.map +1 -0
  117. package/build/web/server/Cache.js +54 -0
  118. package/build/web/server/Cache.js.map +1 -0
  119. package/build/web/server/index.js +211 -0
  120. package/build/web/server/index.js.map +1 -0
  121. package/build/web/server/renderer.js +516 -0
  122. package/build/web/server/renderer.js.map +1 -0
  123. package/build/web/server/server.js +231 -0
  124. package/build/web/server/server.js.map +1 -0
  125. package/build/web/server/utils/errors.js +103 -0
  126. package/build/web/server/utils/errors.js.map +1 -0
  127. package/build/web/server/utils/index.js +4 -0
  128. package/build/web/server/utils/index.js.map +1 -0
  129. package/build/web/shared/components/Button/index.js +90 -0
  130. package/build/web/shared/components/Button/index.js.map +1 -0
  131. package/build/web/shared/components/Button/style.scss +54 -0
  132. package/build/web/shared/components/Checkbox/index.js +35 -0
  133. package/build/web/shared/components/Checkbox/index.js.map +1 -0
  134. package/build/web/shared/components/Checkbox/theme.scss +63 -0
  135. package/build/web/shared/components/GenericLink/index.js +107 -0
  136. package/build/web/shared/components/GenericLink/index.js.map +1 -0
  137. package/build/web/shared/components/GenericLink/style.scss +3 -0
  138. package/build/web/shared/components/Input/index.js +71 -0
  139. package/build/web/shared/components/Input/index.js.map +1 -0
  140. package/build/web/shared/components/Input/theme.scss +52 -0
  141. package/build/web/shared/components/Link.js +20 -0
  142. package/build/web/shared/components/Link.js.map +1 -0
  143. package/build/web/shared/components/Modal/base-theme.scss +38 -0
  144. package/build/web/shared/components/Modal/index.js +128 -0
  145. package/build/web/shared/components/Modal/index.js.map +1 -0
  146. package/build/web/shared/components/Modal/styles.scss +3 -0
  147. package/build/web/shared/components/NavLink.js +13 -0
  148. package/build/web/shared/components/NavLink.js.map +1 -0
  149. package/build/web/shared/components/PageLayout/base-theme.scss +30 -0
  150. package/build/web/shared/components/PageLayout/index.js +38 -0
  151. package/build/web/shared/components/PageLayout/index.js.map +1 -0
  152. package/build/web/shared/components/TextArea/index.js +106 -0
  153. package/build/web/shared/components/TextArea/index.js.map +1 -0
  154. package/build/web/shared/components/TextArea/style.scss +68 -0
  155. package/build/web/shared/components/Throbber/index.js +26 -0
  156. package/build/web/shared/components/Throbber/index.js.map +1 -0
  157. package/build/web/shared/components/Throbber/theme.scss +26 -0
  158. package/build/web/shared/components/WithTooltip/Tooltip.js +226 -0
  159. package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -0
  160. package/build/web/shared/components/WithTooltip/default-theme.scss +36 -0
  161. package/build/web/shared/components/WithTooltip/index.js +117 -0
  162. package/build/web/shared/components/WithTooltip/index.js.map +1 -0
  163. package/build/web/shared/components/YouTubeVideo/base.scss +15 -0
  164. package/build/web/shared/components/YouTubeVideo/index.js +56 -0
  165. package/build/web/shared/components/YouTubeVideo/index.js.map +1 -0
  166. package/build/web/shared/components/YouTubeVideo/throbber.scss +11 -0
  167. package/build/web/shared/components/index.js +18 -0
  168. package/build/web/shared/components/index.js.map +1 -0
  169. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +79 -0
  170. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -0
  171. package/build/web/shared/components/selectors/CustomDropdown/Options/style.scss +6 -0
  172. package/build/web/shared/components/selectors/CustomDropdown/index.js +120 -0
  173. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -0
  174. package/build/web/shared/components/selectors/CustomDropdown/theme.scss +118 -0
  175. package/build/web/shared/components/selectors/NativeDropdown/index.js +82 -0
  176. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -0
  177. package/build/web/shared/components/selectors/NativeDropdown/theme.scss +81 -0
  178. package/build/web/shared/components/selectors/Switch/index.js +49 -0
  179. package/build/web/shared/components/selectors/Switch/index.js.map +1 -0
  180. package/build/web/shared/components/selectors/Switch/theme.scss +39 -0
  181. package/build/web/shared/components/selectors/common.js +12 -0
  182. package/build/web/shared/components/selectors/common.js.map +1 -0
  183. package/build/web/shared/components/selectors/index.js +4 -0
  184. package/build/web/shared/components/selectors/index.js.map +1 -0
  185. package/build/web/shared/utils/config.js +21 -0
  186. package/build/web/shared/utils/config.js.map +1 -0
  187. package/build/web/shared/utils/globalState.js +15 -0
  188. package/build/web/shared/utils/globalState.js.map +1 -0
  189. package/build/web/shared/utils/index.js +13 -0
  190. package/build/web/shared/utils/index.js.map +1 -0
  191. package/build/web/shared/utils/isomorphy/buildInfo.js +44 -0
  192. package/build/web/shared/utils/isomorphy/buildInfo.js.map +1 -0
  193. package/build/web/shared/utils/isomorphy/environment-check.js +17 -0
  194. package/build/web/shared/utils/isomorphy/environment-check.js.map +1 -0
  195. package/build/web/shared/utils/isomorphy/index.js +36 -0
  196. package/build/web/shared/utils/isomorphy/index.js.map +1 -0
  197. package/build/web/shared/utils/jest/E2eSsrEnv.js +230 -0
  198. package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -0
  199. package/build/web/shared/utils/jest/global.js +4 -0
  200. package/build/web/shared/utils/jest/global.js.map +1 -0
  201. package/build/web/shared/utils/jest/index.js +165 -0
  202. package/build/web/shared/utils/jest/index.js.map +1 -0
  203. package/build/web/shared/utils/splitComponent.js +221 -0
  204. package/build/web/shared/utils/splitComponent.js.map +1 -0
  205. package/build/web/shared/utils/time.js +85 -0
  206. package/build/web/shared/utils/time.js.map +1 -0
  207. package/build/web/shared/utils/webpack.js +61 -0
  208. package/build/web/shared/utils/webpack.js.map +1 -0
  209. package/build/web/styles/_global/reset.css +52 -0
  210. package/build/web/styles/_mixins/fonts.scss +40 -0
  211. package/build/web/styles/_mixins/media.scss +150 -0
  212. package/build/web/styles/_mixins/typography.scss +83 -0
  213. package/build/web/styles/global.scss +11 -0
  214. package/build/web/styles/mixins.scss +6 -0
  215. package/config/babel/node-ssr.js +5 -2
  216. package/config/webpack/app-base.js +10 -7
  217. package/config/webpack/app-development.js +3 -2
  218. package/package.json +16 -27
  219. package/src/index.ts +7 -1
  220. package/src/server/index.ts +6 -8
  221. package/src/server/renderer.tsx +7 -9
  222. package/src/server/server.ts +3 -5
  223. package/src/shared/components/Modal/base-theme.scss +1 -1
  224. package/src/shared/components/PageLayout/base-theme.scss +1 -1
  225. package/src/shared/utils/jest/E2eSsrEnv.ts +8 -1
  226. package/build/development/__chunk_groups__.json +0 -6
  227. package/build/development/style.css +0 -909
  228. package/build/development/web.bundle.js +0 -752
  229. package/build/production/__chunk_groups__.json +0 -6
  230. package/build/production/style.css +0 -2
  231. package/build/production/style.css.map +0 -1
  232. package/build/production/web.bundle.js +0 -3
  233. package/build/production/web.bundle.js.LICENSE.txt +0 -9
  234. package/build/production/web.bundle.js.map +0 -1
  235. package/dev-styles.js +0 -1
  236. package/null.js +0 -1
  237. package/prod-styles.js +0 -1
@@ -0,0 +1,516 @@
1
+ /**
2
+ * ExpressJS middleware for server-side rendering of a ReactJS app.
3
+ */
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { Writable } from 'node:stream';
8
+ import { brotliCompress, brotliDecompress } from 'node:zlib';
9
+ import winston from 'winston';
10
+ import { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';
11
+ import { timer } from '@dr.pogodin/js-utils';
12
+ import clone from 'lodash/clone';
13
+ import cloneDeep from 'lodash/cloneDeep';
14
+ import defaults from 'lodash/defaults';
15
+ import get from 'lodash/get';
16
+ import isString from 'lodash/isString';
17
+ import mapValues from 'lodash/mapValues';
18
+ import omit from 'lodash/omit';
19
+ import config from 'config';
20
+ import forge from 'node-forge';
21
+ import { prerenderToNodeStream } from 'react-dom/static';
22
+ import { HelmetProvider } from '@dr.pogodin/react-helmet';
23
+ import { StaticRouter } from 'react-router';
24
+ import serializeJs from 'serialize-javascript';
25
+ import { setBuildInfo } from "../shared/utils/isomorphy/buildInfo";
26
+ import Cache from "./Cache";
27
+ import { jsx as _jsx } from "react/jsx-runtime";
28
+ const sanitizedConfig = omit(config, 'SECRET');
29
+
30
+ // Note: These type definitions for logger are copied from Winston logger,
31
+ // then simplified to make it easier to fit an alternative logger into this
32
+ // interface.
33
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
34
+
35
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
36
+
37
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
38
+
39
+ export let SCRIPT_LOCATIONS = /*#__PURE__*/function (SCRIPT_LOCATIONS) {
40
+ SCRIPT_LOCATIONS["BODY_OPEN"] = "BODY_OPEN";
41
+ SCRIPT_LOCATIONS["DEFAULT"] = "DEFAULT";
42
+ SCRIPT_LOCATIONS["HEAD_OPEN"] = "HEAD_OPEN";
43
+ return SCRIPT_LOCATIONS;
44
+ }({});
45
+ export class ServerSsrContext extends SsrContext {
46
+ chunks = [];
47
+ status = 200;
48
+ constructor(req, chunkGroups, initialState) {
49
+ super(cloneDeep(initialState) ?? {});
50
+ this.chunkGroups = chunkGroups;
51
+ this.req = req;
52
+ }
53
+ }
54
+ /**
55
+ * Reads build-time information about the app. This information is generated
56
+ * by our standard Webpack config for apps, and it is written into
57
+ * ".build-info" file in the context folder specified in Webpack config.
58
+ * At the moment, that file contains build timestamp and a random 32-bit key,
59
+ * suitable for cryptographical use.
60
+ * @param context Webpack context path used during the build.
61
+ * @return Resolves to the build-time information.
62
+ */
63
+ function getBuildInfo(context) {
64
+ const url = path.resolve(context, '.build-info');
65
+ return JSON.parse(fs.readFileSync(url, 'utf8'));
66
+ }
67
+
68
+ /**
69
+ * Attempts to read from disk the named chunk groups mapping generated
70
+ * by Webpack during the compilation.
71
+ * It will not work for development builds, where these stats should be captured
72
+ * via compilator callback.
73
+ * @param buildDir
74
+ * @return
75
+ */
76
+ function readChunkGroupsJson(buildDir) {
77
+ const url = path.resolve(buildDir, '__chunk_groups__.json');
78
+ let res;
79
+ try {
80
+ res = JSON.parse(fs.readFileSync(url, 'utf8'));
81
+ } catch {
82
+ // TODO: Should we message the error here somehow?
83
+ res = null;
84
+ }
85
+ return res;
86
+ }
87
+
88
+ /**
89
+ * Prepares a new Cipher for data encryption.
90
+ * @param key Encryption key (32-bit random key is expected, see
91
+ * node-forge documentation, in case of doubts).
92
+ * @return Resolves to the object with two fields:
93
+ * 1. cipher - a new Cipher, ready for encryption;
94
+ * 2. iv - initial vector used by the cipher.
95
+ */
96
+ async function prepareCipher(key) {
97
+ return new Promise((resolve, reject) => {
98
+ forge.random.getBytes(32, (err, iv) => {
99
+ if (err) reject(err);else {
100
+ const cipher = forge.cipher.createCipher('AES-CBC', key);
101
+ cipher.start({
102
+ iv
103
+ });
104
+ resolve({
105
+ cipher,
106
+ iv
107
+ });
108
+ }
109
+ });
110
+ });
111
+ }
112
+
113
+ /**
114
+ * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses
115
+ * are acceptable to the caller.
116
+ * @param req
117
+ */
118
+ export function isBrotliAcceptable(req) {
119
+ const acceptable = req.get('accept-encoding');
120
+ if (acceptable) {
121
+ const ops = acceptable.split(',');
122
+ for (const op of ops) {
123
+ const [type, priority] = op.trim().split(';q=');
124
+ if ((type === '*' || type === 'br') && (!priority || parseFloat(priority) > 0)) {
125
+ return true;
126
+ }
127
+ }
128
+ }
129
+ return false;
130
+ }
131
+
132
+ /**
133
+ * Given an array of extra script strings / objects, it returns an object with
134
+ * arrays of scripts to inject in different HTML template locations. During
135
+ * the script groupping it also filters out any empty scripts.
136
+ * @param {({
137
+ * code: string;
138
+ * location: string;
139
+ * }|string)[]} [scripts=[]]
140
+ * @return {{
141
+ * BODY_OPEN: string[];
142
+ * DEFAULT: string[];
143
+ * HEAD_OPEN: string[];
144
+ * }}
145
+ */
146
+ function groupExtraScripts(scripts = []) {
147
+ const res = {
148
+ [SCRIPT_LOCATIONS.BODY_OPEN]: '',
149
+ [SCRIPT_LOCATIONS.DEFAULT]: '',
150
+ [SCRIPT_LOCATIONS.HEAD_OPEN]: ''
151
+ };
152
+ for (const script of scripts) {
153
+ if (isString(script)) {
154
+ if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;
155
+ } else if (script.code) {
156
+ if (script.location in res) res[script.location] += script.code;else throw Error(`Invalid location "${script.location}"`);
157
+ }
158
+ }
159
+ return res;
160
+ }
161
+
162
+ /**
163
+ * Creates a new default (Winston) logger.
164
+ * @param {object} [options={}]
165
+ * @param {string} [options.defaultLogLevel='info']
166
+ * @return {object}
167
+ */
168
+ export function newDefaultLogger({
169
+ defaultLogLevel = 'info'
170
+ } = {}) {
171
+ const {
172
+ format,
173
+ transports
174
+ } = winston;
175
+ return winston.createLogger({
176
+ format: format.combine(format.splat(), format.timestamp(), format.colorize(), format.printf(({
177
+ level,
178
+ message,
179
+ timestamp,
180
+ stack,
181
+ ...rest
182
+ }) => {
183
+ let res = `${level}\t(at ${timestamp}):\t${message}`;
184
+ if (Object.keys(rest).length) {
185
+ res += `\n${JSON.stringify(rest, null, 2)}`;
186
+ }
187
+ if (stack) res += `\n${stack}`;
188
+ return res;
189
+ })),
190
+ level: defaultLogLevel,
191
+ transports: [new transports.Console()]
192
+ });
193
+ }
194
+ /**
195
+ * Creates the middleware.
196
+ * @param webpackConfig
197
+ * @param options Additional options:
198
+ * @param [options.Application] The root ReactJS component of
199
+ * the app to use for the server-side rendering. When not provided
200
+ * the server-side rendering is disabled.
201
+ * @param [options.buildInfo] "Build info" object to use. If provided,
202
+ * it will be used, instead of trying to load from the filesystem the one
203
+ * generated by the Webpack build. It is intended for test environments,
204
+ * where passing this stuff via file system is no bueno.
205
+ * @param [options.favicon] `true` will include favicon
206
+ * link into the rendered HTML templates.
207
+ * @param [options.noCsp] `true` means that no
208
+ * Content-Security-Policy (CSP) is used by server, thus the renderer
209
+ * may cut a few corners.
210
+ * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.
211
+ * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,
212
+ * defaults to 1 second.
213
+ * @param [options.staticCacheSize=1.e7] The maximum
214
+ * static cache size in bytes. Defaults to ~10 MB.
215
+ * @param [options.staticCacheController] When given, it activates,
216
+ * and controls the static caching of generated HTML markup. When this function
217
+ * is provided, on each incoming request it is triggered with the request
218
+ * passed in as the argument. To attempt to serve the response from the cache
219
+ * it should return the object with the following fields:
220
+ * - `key: string` – the cache key for the response;
221
+ * - `maxage?: number` – the maximum age of cached result in ms.
222
+ * If undefined - infinite age is assumed.
223
+ * @return Created middleware.
224
+ */
225
+ export default function factory(webpackConfig, options) {
226
+ const ops = defaults(clone(options), {
227
+ beforeRender: async () => Promise.resolve({}),
228
+ maxSsrRounds: 10,
229
+ ssrTimeout: 1000,
230
+ staticCacheSize: 1.e7
231
+ });
232
+
233
+ // Note: in normal use the default logger is created and set in the root
234
+ // server function, and this initialization is for testing uses, where
235
+ // renderer is imported directly.
236
+ ops.logger ??= newDefaultLogger({
237
+ defaultLogLevel: ops.defaultLoggerLogLevel
238
+ });
239
+ const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context);
240
+ setBuildInfo(buildInfo);
241
+
242
+ // publicPath from webpack.output has a trailing slash at the end.
243
+ const {
244
+ publicPath,
245
+ path: outputPath
246
+ } = webpackConfig.output;
247
+ const manifestLink = fs.existsSync(`${outputPath}/manifest.json`) ? `<link rel="manifest" href="${publicPath}manifest.json">` : '';
248
+
249
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
250
+
251
+ const cache = ops.staticCacheController ? new Cache(ops.staticCacheSize) : null;
252
+ const CHUNK_GROUPS = readChunkGroupsJson(outputPath);
253
+
254
+ // TODO: Look at it later.
255
+ // eslint-disable-next-line complexity
256
+ return async (req, res, next) => {
257
+ try {
258
+ // Ensures any caches always revalidate HTML markup before reuse.
259
+ res.set('Cache-Control', 'no-cache');
260
+ res.cookie('csrfToken', req.csrfToken());
261
+ let cacheRef;
262
+ if (cache) {
263
+ cacheRef = ops.staticCacheController(req);
264
+ if (cacheRef) {
265
+ const data = cache.get(cacheRef);
266
+ if (data !== null) {
267
+ const {
268
+ buffer,
269
+ status
270
+ } = data;
271
+ if (ops.noCsp && isBrotliAcceptable(req)) {
272
+ res.set('Content-Type', 'text/html');
273
+ res.set('Content-Encoding', 'br');
274
+ if (status !== 200) res.status(status);
275
+ res.send(buffer);
276
+ } else {
277
+ await new Promise((done, failed) => {
278
+ brotliDecompress(buffer, (error, html) => {
279
+ if (error) failed(error);else {
280
+ let h = html.toString();
281
+ if (!ops.noCsp) {
282
+ // TODO: Starting from Node v15 we'll be able to use string's
283
+ // .replaceAll() method instead relying on reg. expression for
284
+ // global matching.
285
+ const regex = new RegExp(buffer.nonce, 'g');
286
+
287
+ // TODO: It should be implemented more careful.
288
+ h = h.replace(regex, req.nonce);
289
+ }
290
+ if (status !== 200) res.status(status);
291
+ res.send(h);
292
+ done();
293
+ }
294
+ });
295
+ });
296
+ }
297
+ return;
298
+ }
299
+ }
300
+ }
301
+ const brr = ops.beforeRender(req, sanitizedConfig);
302
+ const [{
303
+ configToInject,
304
+ extraScripts,
305
+ initialState
306
+ }, {
307
+ cipher,
308
+ iv
309
+ }] = await Promise.all([
310
+ // NOTE: Written this way to avoid triggering the "await-thenable"
311
+ // ESLint rule.
312
+ brr instanceof Promise ? brr : Promise.resolve(brr), prepareCipher(buildInfo.key)]);
313
+ let helmet;
314
+
315
+ // Gets the mapping between code chunk names and their asset files.
316
+ // These data come from the Webpack compilation, either from the stats
317
+ // attached to the request (in dev mode), or from a file output during
318
+ // the build (in prod mode).
319
+ let chunkGroups;
320
+ const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');
321
+ if (webpackStats) {
322
+ chunkGroups = mapValues(webpackStats.toJson({
323
+ all: false,
324
+ chunkGroups: true
325
+ }).namedChunkGroups, item => item.assets?.map(({
326
+ name
327
+ }) => name) ?? []);
328
+ } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;else chunkGroups = {};
329
+
330
+ /* Optional server-side rendering. */
331
+ const App = ops.Application;
332
+ let appHtmlMarkup = '';
333
+ const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);
334
+ let stream;
335
+ if (App) {
336
+ const ssrStart = Date.now();
337
+
338
+ // TODO: Somehow, without it TS does not realise that
339
+ // App has been checked to exist.
340
+ const App2 = App;
341
+ const renderPass = async () => new Promise((resolveArg, rejectArg) => {
342
+ ssrContext.chunks = [];
343
+
344
+ // NOTE: JS does not have problems if resolve() and reject() methods
345
+ // of a Promise are called multiple times, with different arguments;
346
+ // it only respects the first call, and ignores subsequent ones.
347
+ // We, however, really want to assert that here, to safeguard against
348
+ // any future problems due to unexpected internal changes in React,
349
+ // if any.
350
+ let error;
351
+ const resolve = arg => {
352
+ if (error !== undefined) throw Error('Internal error');
353
+ error = null;
354
+ resolveArg(arg);
355
+ };
356
+ const reject = arg => {
357
+ if (error !== undefined && error !== arg) {
358
+ throw Error('Internal error');
359
+ }
360
+ error = arg;
361
+ rejectArg(arg);
362
+ };
363
+
364
+ // TODO: prerenderToNodeStream has (abort) "signal" option,
365
+ // and we should wire it up to the SSR timeout below.
366
+ const helmetContext = {};
367
+ void prerenderToNodeStream(/*#__PURE__*/_jsx(GlobalStateProvider, {
368
+ initialState: ssrContext.state,
369
+ ssrContext: ssrContext,
370
+ children: /*#__PURE__*/_jsx(StaticRouter, {
371
+ location: req.url,
372
+ children: /*#__PURE__*/_jsx(HelmetProvider, {
373
+ context: helmetContext,
374
+ children: /*#__PURE__*/_jsx(App2, {})
375
+ })
376
+ })
377
+ }), {
378
+ onError: reject
379
+ }).then(result => {
380
+ ({
381
+ helmet
382
+ } = helmetContext);
383
+ resolve(result.prelude);
384
+ }).catch(reject);
385
+ });
386
+ let ssrRound = 0;
387
+ let bailed = false;
388
+ for (; ssrRound < ops.maxSsrRounds; ++ssrRound) {
389
+ stream = await renderPass();
390
+ if (!ssrContext.dirty) break;
391
+ const timeout = ops.ssrTimeout + ssrStart - Date.now();
392
+ bailed = timeout <= 0 || !(await Promise.race([Promise.allSettled(ssrContext.pending), timer(timeout).then(() => false)]));
393
+ if (bailed) break;
394
+ }
395
+ let logMsg;
396
+ if (ssrContext.dirty) {
397
+ // NOTE: In the case of incomplete SSR one more round is necessary
398
+ // to ensure the correct hydration when some pending promises have
399
+ // resolved and placed their data into the initial global state.
400
+ stream = await renderPass();
401
+ logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)` : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;
402
+ } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;
403
+ ops.logger.log(ssrContext.dirty ? 'warn' : 'info', logMsg);
404
+ if (ssrContext.redirectTo) {
405
+ res.redirect(ssrContext.status, ssrContext.redirectTo);
406
+ return;
407
+ }
408
+ await new Promise(ready => {
409
+ stream.pipe(new Writable({
410
+ destroy: ready,
411
+ write: (chunk, _, done) => {
412
+ appHtmlMarkup += chunk.toString();
413
+ done();
414
+ }
415
+ }));
416
+ });
417
+ }
418
+
419
+ /* Encrypts data to be injected into HTML.
420
+ * Keep in mind, that this encryption is no way secure: as the JS bundle
421
+ * contains decryption key and is able to decode it at the client side.
422
+ * Hovewer, for a number of reasons, encryption of injected data is still
423
+ * better than injection of a plain text. */
424
+ const payload = serializeJs({
425
+ CHUNK_GROUPS: chunkGroups,
426
+ CONFIG: configToInject ?? sanitizedConfig,
427
+ ISTATE: ssrContext.state
428
+ }, {
429
+ ignoreFunction: true,
430
+ unsafe: true
431
+ });
432
+ cipher.update(forge.util.createBuffer(payload, 'utf8'));
433
+ cipher.finish();
434
+ const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);
435
+ const chunkSet = new Set();
436
+
437
+ // TODO: "main" chunk has to be added explicitly,
438
+ // because unlike all other chunks they are not managed by <CodeSplit>
439
+ // component, thus they are not added to the ssrContext.chunks
440
+ // automatically. Actually, names of these entry chunks should be
441
+ // read from Wepback config, as the end user may customize them,
442
+ // remove or add other entry points, but it requires additional
443
+ // efforts to figure out how to automatically order them right,
444
+ // thus for now this handles the default config.
445
+ ['main', ...ssrContext.chunks].forEach(chunk => {
446
+ const assets = chunkGroups[chunk];
447
+ if (assets) assets.forEach(asset => chunkSet.add(asset));
448
+ });
449
+ let styleChunkString = '';
450
+ let scriptChunkString = '';
451
+ chunkSet.forEach(chunk => {
452
+ if (chunk.endsWith('.css')) {
453
+ styleChunkString += `<link href="${publicPath}${chunk}" rel="stylesheet">`;
454
+ } else if (chunk.endsWith('.js')
455
+ // In dev mode HMR adds JS updates into asset arrays,
456
+ // and they (updates) should be ignored.
457
+ && !chunk.endsWith('.hot-update.js')) {
458
+ scriptChunkString += `<script src="${publicPath}${chunk}" type="application/javascript"></script>`;
459
+ }
460
+ });
461
+ const grouppedExtraScripts = groupExtraScripts(extraScripts);
462
+ const faviconLink = ops.favicon ? '<link rel="shortcut icon" href="/favicon.ico">' : '';
463
+ const html = `<!DOCTYPE html>
464
+ <html lang="en">
465
+ <head>
466
+ ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}
467
+ ${helmet?.title.toString() ?? ''}
468
+ ${helmet?.meta.toString() ?? ''}
469
+ <meta name="theme-color" content="#FFFFFF">
470
+ ${manifestLink}
471
+ ${helmet?.link.toString() ?? ''}${styleChunkString}
472
+ ${faviconLink}
473
+ <meta charset="utf-8">
474
+ <meta
475
+ content="width=device-width,initial-scale=1.0"
476
+ name="viewport"
477
+ >
478
+ <meta itemprop="drpruinj" content="${INJ}">
479
+ </head>
480
+ <body>
481
+ ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}
482
+ <div id="react-view">${appHtmlMarkup}</div>
483
+ ${scriptChunkString}
484
+ ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}
485
+ </body>
486
+ </html>`;
487
+ const status = ssrContext.status || 200;
488
+ if (status !== 200) res.status(status);
489
+ if (cacheRef && status < 500) {
490
+ // Note: waiting for the caching to complete is not strictly necessary,
491
+ // but it greately simplifies testing, and error reporting.
492
+ await new Promise((done, failed) => {
493
+ brotliCompress(html, (error, buffer) => {
494
+ if (error) failed(error);else {
495
+ const b = buffer;
496
+ b.nonce = req.nonce;
497
+ cache.add({
498
+ buffer: b,
499
+ status
500
+ }, cacheRef.key, buffer.length);
501
+ done();
502
+ }
503
+ });
504
+ });
505
+ }
506
+
507
+ // Note: as caching code above may throw in some cases, sending response
508
+ // before it completes will likely hide the error, making it difficult
509
+ // to debug. Thus, at least for now, lets send response after it.
510
+ res.send(html);
511
+ } catch (error) {
512
+ next(error);
513
+ }
514
+ };
515
+ }
516
+ //# sourceMappingURL=renderer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"renderer.js","names":["fs","path","Writable","brotliCompress","brotliDecompress","winston","GlobalStateProvider","SsrContext","timer","clone","cloneDeep","defaults","get","isString","mapValues","omit","config","forge","prerenderToNodeStream","HelmetProvider","StaticRouter","serializeJs","setBuildInfo","Cache","jsx","_jsx","sanitizedConfig","SCRIPT_LOCATIONS","ServerSsrContext","chunks","status","constructor","req","chunkGroups","initialState","getBuildInfo","context","url","resolve","JSON","parse","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","Promise","reject","random","getBytes","err","iv","cipher","createCipher","start","isBrotliAcceptable","acceptable","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","all","helmet","webpackStats","locals","toJson","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","helmetContext","state","children","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","logMsg","log","redirectTo","redirect","ready","pipe","destroy","write","chunk","_","payload","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport type { Request, RequestHandler } from 'express';\nimport type { ComponentType } from 'react';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\n\nimport clone from 'lodash/clone';\nimport cloneDeep from 'lodash/cloneDeep';\nimport defaults from 'lodash/defaults';\nimport get from 'lodash/get';\nimport isString from 'lodash/isString';\nimport mapValues from 'lodash/mapValues';\nimport omit from 'lodash/omit';\n\nimport config from 'config';\nimport forge from 'node-forge';\n\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { type HelmetDataContext, HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (level: string, message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LeveledLogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nexport class ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n redirectTo?: string;\n\n req: Request;\n\n status: number = 200;\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) ?? ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8')) as BuildInfoT;\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8')) as Record<string, string[]>;\n } catch {\n // TODO: Should we message the error here somehow?\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nasync function prepareCipher(key: string): Promise<{\n cipher: forge.cipher.BlockCipher;\n iv: string;\n}> {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param req\n */\nexport function isBrotliAcceptable(req: Request): boolean {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (const op of ops) {\n const [type, priority] = op.trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<string | ScriptT> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (const script of scripts) {\n if (isString(script)) {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (script.location in res) res[script.location] += script.code;\n else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}): winston.Logger {\n const { format, transports } = winston;\n return winston.createLogger({\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\n transports: [new transports.Console()],\n });\n}\n\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: unknown;\n};\n\nexport type BeforeRenderT = (\n req: Request,\n config: ConfigT,\n) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n staticCacheSize?: number;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults(clone(options), {\n beforeRender: async () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context!);\n setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath as string}manifest.json\">` : '';\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface BufferWithNonce extends ArrayBuffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n // TODO: Look at it later.\n // eslint-disable-next-line complexity\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n\n // TODO: It should be implemented more careful.\n h = h.replace(regex, (req as unknown as {\n nonce: string;\n }).nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const brr = ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT);\n\n const [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n // NOTE: Written this way to avoid triggering the \"await-thenable\"\n // ESLint rule.\n brr instanceof Promise ? brr : Promise.resolve(brr),\n\n prepareCipher(buildInfo.key),\n ]);\n\n let helmet: HelmetDataContext['helmet'];\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats') as Stats | undefined;\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name)\n ?? [],\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: NodeJS.ReadableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n rejectArg(arg as Error);\n };\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n const helmetContext = {} as HelmetDataContext;\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\n const timeout = ops.ssrTimeout! + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject ?? sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath as string}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath as string}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon\n ? '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet?.title.toString() ?? ''}\n ${helmet?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmet?.link.toString() ?? ''}${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n const b = buffer as unknown as BufferWithNonce;\n b.nonce = (req as unknown as {\n nonce: string;\n }).nonce;\n cache!.add({ buffer: b, status }, cacheRef.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,OAAOA,EAAE,MAAM,SAAS;AACxB,OAAOC,IAAI,MAAM,WAAW;AAC5B,SAASC,QAAQ,QAAQ,aAAa;AACtC,SAASC,cAAc,EAAEC,gBAAgB,Q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