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

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