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