@dr.pogodin/react-utils 1.25.5 → 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 (294) hide show
  1. package/babel.config.js +3 -1
  2. package/bin/build.js +25 -5
  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 +168 -42
  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 -24
  14. package/build/development/server/index.js.map +1 -1
  15. package/build/development/server/renderer.js +56 -44
  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 +8 -7
  24. package/build/development/shared/components/Button/index.js.map +1 -1
  25. package/build/development/shared/components/Checkbox/index.js +25 -28
  26. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  27. package/build/development/shared/components/Dropdown/index.js +25 -19
  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 +8 -9
  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 +17 -18
  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 +17 -20
  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 -23
  46. package/build/development/shared/components/Throbber/index.js.map +1 -1
  47. package/build/development/shared/components/WithTooltip/Tooltip.js +20 -24
  48. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  49. package/build/development/shared/components/WithTooltip/index.js +11 -11
  50. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  51. package/build/development/shared/components/YouTubeVideo/index.js +16 -15
  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 +1 -2
  56. package/build/development/shared/utils/config.js.map +1 -1
  57. package/build/development/shared/utils/globalState.js +15 -0
  58. package/build/development/shared/utils/globalState.js.map +1 -0
  59. package/build/development/shared/utils/index.js +13 -11
  60. package/build/development/shared/utils/index.js.map +1 -1
  61. package/build/development/shared/utils/isomorphy/buildInfo.js +7 -3
  62. package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
  63. package/build/development/shared/utils/isomorphy/environment-check.js +2 -4
  64. package/build/development/shared/utils/isomorphy/environment-check.js.map +1 -1
  65. package/build/development/shared/utils/isomorphy/index.js.map +1 -1
  66. package/build/development/shared/utils/jest/E2eSsrEnv.js +35 -28
  67. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  68. package/build/development/shared/utils/jest/global.js +17 -0
  69. package/build/development/shared/utils/jest/global.js.map +1 -0
  70. package/build/development/shared/utils/jest/index.js +18 -11
  71. package/build/development/shared/utils/jest/index.js.map +1 -1
  72. package/build/development/shared/utils/splitComponent.js +25 -34
  73. package/build/development/shared/utils/splitComponent.js.map +1 -1
  74. package/build/development/shared/utils/time.js +16 -13
  75. package/build/development/shared/utils/time.js.map +1 -1
  76. package/build/development/shared/utils/webpack.js +3 -3
  77. package/build/development/shared/utils/webpack.js.map +1 -1
  78. package/build/development/web.bundle.js +92 -82
  79. package/build/production/client/getInj.js +1 -1
  80. package/build/production/client/getInj.js.map +1 -1
  81. package/build/production/client/index.js +4 -4
  82. package/build/production/client/index.js.map +1 -1
  83. package/build/production/client/init.js +3 -1
  84. package/build/production/client/init.js.map +1 -1
  85. package/build/production/index.js +1 -1
  86. package/build/production/index.js.map +1 -1
  87. package/build/production/server/Cache.js +7 -8
  88. package/build/production/server/Cache.js.map +1 -1
  89. package/build/production/server/index.js +5 -4
  90. package/build/production/server/index.js.map +1 -1
  91. package/build/production/server/renderer.js +32 -30
  92. package/build/production/server/renderer.js.map +1 -1
  93. package/build/production/server/server.js +7 -5
  94. package/build/production/server/server.js.map +1 -1
  95. package/build/production/server/utils/errors.js +9 -10
  96. package/build/production/server/utils/errors.js.map +1 -1
  97. package/build/production/server/utils/index.js +1 -1
  98. package/build/production/server/utils/index.js.map +1 -1
  99. package/build/production/shared/components/Button/index.js +4 -4
  100. package/build/production/shared/components/Button/index.js.map +1 -1
  101. package/build/production/shared/components/Checkbox/index.js +12 -12
  102. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  103. package/build/production/shared/components/Dropdown/index.js +11 -11
  104. package/build/production/shared/components/Dropdown/index.js.map +1 -1
  105. package/build/production/shared/components/GenericLink/index.js +25 -20
  106. package/build/production/shared/components/GenericLink/index.js.map +1 -1
  107. package/build/production/shared/components/Input/index.js +7 -7
  108. package/build/production/shared/components/Input/index.js.map +1 -1
  109. package/build/production/shared/components/Link.js +2 -2
  110. package/build/production/shared/components/Link.js.map +1 -1
  111. package/build/production/shared/components/MetaTags.js +10 -10
  112. package/build/production/shared/components/MetaTags.js.map +1 -1
  113. package/build/production/shared/components/Modal/index.js +2 -2
  114. package/build/production/shared/components/Modal/index.js.map +1 -1
  115. package/build/production/shared/components/NavLink.js +1 -1
  116. package/build/production/shared/components/NavLink.js.map +1 -1
  117. package/build/production/shared/components/PageLayout/index.js +2 -2
  118. package/build/production/shared/components/PageLayout/index.js.map +1 -1
  119. package/build/production/shared/components/ScalableRect/index.js +7 -3
  120. package/build/production/shared/components/ScalableRect/index.js.map +1 -1
  121. package/build/production/shared/components/Throbber/index.js +2 -2
  122. package/build/production/shared/components/Throbber/index.js.map +1 -1
  123. package/build/production/shared/components/WithTooltip/Tooltip.js +13 -13
  124. package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
  125. package/build/production/shared/components/WithTooltip/index.js +3 -3
  126. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  127. package/build/production/shared/components/YouTubeVideo/index.js +7 -7
  128. package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
  129. package/build/production/shared/components/index.js +1 -1
  130. package/build/production/shared/components/index.js.map +1 -1
  131. package/build/production/shared/utils/config.js +1 -1
  132. package/build/production/shared/utils/config.js.map +1 -1
  133. package/build/production/shared/utils/globalState.js +3 -0
  134. package/build/production/shared/utils/globalState.js.map +1 -0
  135. package/build/production/shared/utils/index.js +3 -3
  136. package/build/production/shared/utils/index.js.map +1 -1
  137. package/build/production/shared/utils/isomorphy/buildInfo.js +7 -4
  138. package/build/production/shared/utils/isomorphy/buildInfo.js.map +1 -1
  139. package/build/production/shared/utils/isomorphy/environment-check.js +2 -2
  140. package/build/production/shared/utils/isomorphy/environment-check.js.map +1 -1
  141. package/build/production/shared/utils/isomorphy/index.js.map +1 -1
  142. package/build/production/shared/utils/jest/E2eSsrEnv.js +9 -9
  143. package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  144. package/build/production/shared/utils/jest/global.js +2 -0
  145. package/build/production/shared/utils/jest/global.js.map +1 -0
  146. package/build/production/shared/utils/jest/index.js +6 -6
  147. package/build/production/shared/utils/jest/index.js.map +1 -1
  148. package/build/production/shared/utils/splitComponent.js +16 -16
  149. package/build/production/shared/utils/splitComponent.js.map +1 -1
  150. package/build/production/shared/utils/time.js +12 -8
  151. package/build/production/shared/utils/time.js.map +1 -1
  152. package/build/production/shared/utils/webpack.js +3 -3
  153. package/build/production/shared/utils/webpack.js.map +1 -1
  154. package/build/production/web.bundle.js +1 -1
  155. package/build/production/web.bundle.js.map +1 -1
  156. package/build/types-code/client/getInj.d.ts +3 -0
  157. package/build/types-code/client/index.d.ts +11 -0
  158. package/build/types-code/client/init.d.ts +9 -0
  159. package/build/types-code/index.d.ts +10 -0
  160. package/build/types-code/server/Cache.d.ts +37 -0
  161. package/build/types-code/server/index.d.ts +145 -0
  162. package/build/types-code/server/renderer.d.ts +106 -0
  163. package/build/types-code/server/server.d.ts +41 -0
  164. package/build/types-code/server/utils/errors.d.ts +104 -0
  165. package/build/types-code/server/utils/index.d.ts +1 -0
  166. package/build/types-code/shared/components/Button/index.d.ts +27 -0
  167. package/build/types-code/shared/components/Checkbox/index.d.ts +21 -0
  168. package/build/types-code/shared/components/Dropdown/index.d.ts +23 -0
  169. package/build/types-code/shared/components/GenericLink/index.d.ts +61 -0
  170. package/build/types-code/shared/components/Input/index.d.ts +11 -0
  171. package/build/types-code/shared/components/Link.d.ts +12 -0
  172. package/build/types-code/shared/components/MetaTags.d.ts +68 -0
  173. package/build/types-code/shared/components/Modal/index.d.ts +26 -0
  174. package/build/types-code/shared/components/NavLink.d.ts +5 -0
  175. package/build/types-code/shared/components/PageLayout/index.d.ts +16 -0
  176. package/build/types-code/shared/components/ScalableRect/index.d.ts +19 -0
  177. package/build/types-code/shared/components/Throbber/index.d.ts +9 -0
  178. package/build/types-code/shared/components/WithTooltip/Tooltip.d.ts +23 -0
  179. package/build/types-code/shared/components/WithTooltip/index.d.ts +17 -0
  180. package/build/types-code/shared/components/YouTubeVideo/index.d.ts +13 -0
  181. package/build/types-code/shared/components/index.d.ts +16 -0
  182. package/build/types-code/shared/utils/config.d.ts +2 -0
  183. package/build/types-code/shared/utils/globalState.d.ts +20 -0
  184. package/build/types-code/shared/utils/index.d.ts +52 -0
  185. package/build/types-code/shared/utils/isomorphy/buildInfo.d.ts +23 -0
  186. package/build/types-code/shared/utils/isomorphy/environment-check.d.ts +11 -0
  187. package/build/types-code/shared/utils/isomorphy/index.d.ts +20 -0
  188. package/build/types-code/shared/utils/jest/E2eSsrEnv.d.ts +31 -0
  189. package/build/types-code/shared/utils/jest/global.d.ts +12 -0
  190. package/build/types-code/shared/utils/jest/index.d.ts +85 -0
  191. package/build/types-code/shared/utils/splitComponent.d.ts +41 -0
  192. package/build/types-code/shared/utils/time.d.ts +62 -0
  193. package/build/types-code/shared/utils/webpack.d.ts +18 -0
  194. package/build/types-scss/__tests__/js/config/publicPath support/__assets__/style.scss.d.ts +1 -0
  195. package/build/types-scss/__tests__/js/config/stylename-generation/__assets__/MockPackageA/TestComponent/style.scss.d.ts +1 -0
  196. package/build/types-scss/__tests__/js/config/stylename-generation/__assets__/MockPackageB/TestComponent/style.scss.d.ts +1 -0
  197. package/build/types-scss/__tests__/js/config/stylename-generation/__assets__/style.scss.d.ts +1 -0
  198. package/build/types-scss/__tests__/js/shared/components/NavLink/styles.scss.d.ts +1 -0
  199. package/build/types-scss/__tests__/js/shared/utils/splitComponent/__assets__/SampleScene/ComponentA/style.scss.d.ts +1 -0
  200. package/build/types-scss/__tests__/js/shared/utils/splitComponent/__assets__/SampleScene/ComponentB/style.scss.d.ts +1 -0
  201. package/build/types-scss/__tests__/js/shared/utils/splitComponent/__assets__/SampleScene/ComponentC/style.scss.d.ts +1 -0
  202. package/build/types-scss/__tests__/js/shared/utils/splitComponent/__assets__/SampleScene/style.scss.d.ts +1 -0
  203. package/build/types-scss/__tests__/ts/config/publicPath support/__assets__/style.scss.d.ts +1 -0
  204. package/build/types-scss/__tests__/ts/config/stylename-generation/__assets__/MockPackageA/TestComponent/style.scss.d.ts +1 -0
  205. package/build/types-scss/__tests__/ts/config/stylename-generation/__assets__/MockPackageB/TestComponent/style.scss.d.ts +1 -0
  206. package/build/types-scss/__tests__/ts/config/stylename-generation/__assets__/style.scss.d.ts +1 -0
  207. package/build/types-scss/__tests__/ts/shared/components/NavLink/styles.scss.d.ts +1 -0
  208. package/build/types-scss/__tests__/ts/shared/utils/splitComponent/__assets__/SampleScene/ComponentA/style.scss.d.ts +1 -0
  209. package/build/types-scss/__tests__/ts/shared/utils/splitComponent/__assets__/SampleScene/ComponentB/style.scss.d.ts +1 -0
  210. package/build/types-scss/__tests__/ts/shared/utils/splitComponent/__assets__/SampleScene/ComponentC/style.scss.d.ts +1 -0
  211. package/build/types-scss/__tests__/ts/shared/utils/splitComponent/__assets__/SampleScene/style.scss.d.ts +1 -0
  212. package/build/types-scss/src/shared/components/Button/style.scss.d.ts +6 -0
  213. package/build/types-scss/src/shared/components/Checkbox/theme.scss.d.ts +6 -0
  214. package/build/types-scss/src/shared/components/Dropdown/theme.scss.d.ts +9 -0
  215. package/build/types-scss/src/shared/components/GenericLink/style.scss.d.ts +1 -0
  216. package/build/types-scss/src/shared/components/Input/theme.scss.d.ts +6 -0
  217. package/build/types-scss/src/shared/components/Modal/base-theme.scss.d.ts +5 -0
  218. package/build/types-scss/src/shared/components/PageLayout/base-theme.scss.d.ts +6 -0
  219. package/build/types-scss/src/shared/components/ScalableRect/style.scss.d.ts +2 -0
  220. package/build/types-scss/src/shared/components/Throbber/theme.scss.d.ts +6 -0
  221. package/build/types-scss/src/shared/components/WithTooltip/default-theme.scss.d.ts +7 -0
  222. package/build/types-scss/src/shared/components/YouTubeVideo/base.scss.d.ts +5 -0
  223. package/build/types-scss/src/shared/components/YouTubeVideo/throbber.scss.d.ts +4 -0
  224. package/config/eslint/jest.json +3 -2
  225. package/config/eslint/typescript.js +34 -0
  226. package/config/jest/default.js +3 -3
  227. package/package.json +75 -33
  228. package/src/client/getInj.ts +43 -0
  229. package/src/client/index.tsx +40 -0
  230. package/src/client/init.ts +47 -0
  231. package/src/index.ts +58 -0
  232. package/src/server/Cache.ts +68 -0
  233. package/src/server/index.ts +230 -0
  234. package/src/server/renderer.tsx +604 -0
  235. package/src/server/server.ts +309 -0
  236. package/src/server/utils/errors.ts +135 -0
  237. package/src/server/utils/index.ts +3 -0
  238. package/src/shared/components/Button/index.tsx +146 -0
  239. package/src/shared/components/Button/style.scss +53 -0
  240. package/src/shared/components/Checkbox/index.tsx +71 -0
  241. package/src/shared/components/Checkbox/theme.scss +43 -0
  242. package/src/shared/components/Dropdown/index.tsx +144 -0
  243. package/src/shared/components/Dropdown/theme.scss +63 -0
  244. package/src/shared/components/GenericLink/index.tsx +157 -0
  245. package/src/shared/components/GenericLink/style.scss +3 -0
  246. package/src/shared/components/Input/index.tsx +59 -0
  247. package/src/shared/components/Input/theme.scss +27 -0
  248. package/src/shared/components/Link.tsx +21 -0
  249. package/src/shared/components/MetaTags.tsx +170 -0
  250. package/src/shared/components/Modal/base-theme.scss +38 -0
  251. package/src/shared/components/Modal/index.tsx +144 -0
  252. package/src/shared/components/Modal/styles.scss +5 -0
  253. package/src/shared/components/NavLink.tsx +13 -0
  254. package/src/shared/components/PageLayout/base-theme.scss +30 -0
  255. package/src/shared/components/PageLayout/index.tsx +76 -0
  256. package/src/shared/components/ScalableRect/index.tsx +84 -0
  257. package/src/shared/components/ScalableRect/style.scss +10 -0
  258. package/src/shared/components/Throbber/index.tsx +43 -0
  259. package/src/shared/components/Throbber/theme.scss +26 -0
  260. package/src/shared/components/WithTooltip/Tooltip.tsx +353 -0
  261. package/src/shared/components/WithTooltip/default-theme.scss +36 -0
  262. package/src/shared/components/WithTooltip/index.tsx +204 -0
  263. package/src/shared/components/YouTubeVideo/base.scss +13 -0
  264. package/src/shared/components/YouTubeVideo/index.tsx +96 -0
  265. package/src/shared/components/YouTubeVideo/throbber.scss +11 -0
  266. package/src/shared/components/index.ts +17 -0
  267. package/src/shared/utils/config.ts +21 -0
  268. package/src/shared/utils/globalState.ts +29 -0
  269. package/src/shared/utils/index.ts +105 -0
  270. package/src/shared/utils/isomorphy/buildInfo.ts +54 -0
  271. package/src/shared/utils/isomorphy/environment-check.ts +18 -0
  272. package/src/shared/utils/isomorphy/index.ts +38 -0
  273. package/src/shared/utils/jest/E2eSsrEnv.ts +250 -0
  274. package/src/shared/utils/jest/global.ts +19 -0
  275. package/src/shared/utils/jest/index.tsx +157 -0
  276. package/src/shared/utils/splitComponent.tsx +255 -0
  277. package/src/shared/utils/time.ts +118 -0
  278. package/src/shared/utils/webpack.ts +45 -0
  279. package/src/styles/_global/reset.css +52 -0
  280. package/src/styles/global.scss +11 -0
  281. package/tsconfig.configs.json +18 -0
  282. package/tsconfig.json +27 -0
  283. package/tsconfig.types.json +53 -0
  284. package/typed-scss-modules.config.ts +9 -0
  285. package/types.d.ts +37 -0
  286. package/{webpack.config.js → webpack.config.ts} +7 -3
  287. package/config/babel/node-ssr.js +0 -85
  288. package/config/babel/webpack.js +0 -122
  289. package/config/webpack/app-base.js +0 -330
  290. package/config/webpack/app-development.js +0 -80
  291. package/config/webpack/app-production.js +0 -60
  292. package/config/webpack/lib-base.js +0 -155
  293. package/config/webpack/lib-development.js +0 -45
  294. package/config/webpack/lib-production.js +0 -44
@@ -0,0 +1,309 @@
1
+ /**
2
+ * Creation of standard ExpressJS server for ReactJS apps.
3
+ */
4
+
5
+ import { sep } from 'path';
6
+ import { pathToFileURL } from 'url';
7
+
8
+ import {
9
+ cloneDeep,
10
+ mapValues,
11
+ pick,
12
+ } from 'lodash';
13
+
14
+ import compression from 'compression';
15
+ import cookieParser from 'cookie-parser';
16
+ import csrf from '@dr.pogodin/csurf';
17
+
18
+ import express, {
19
+ type Express,
20
+ type NextFunction,
21
+ type Request,
22
+ type Response,
23
+ } from 'express';
24
+
25
+ import favicon from 'serve-favicon';
26
+ import helmet, { type HelmetOptions } from 'helmet';
27
+ import loggerMiddleware from 'morgan';
28
+ import requestIp from 'request-ip';
29
+ import { v4 as uuid } from 'uuid';
30
+ import { type Configuration } from 'webpack';
31
+
32
+ import rendererFactory, {
33
+ type LoggerI,
34
+ type OptionsT as RendererOptionsT,
35
+ } from './renderer';
36
+
37
+ import {
38
+ CODES,
39
+ ERRORS,
40
+ getErrorForCode,
41
+ newError,
42
+ } from './utils/errors';
43
+
44
+ export type CspOptionsT =
45
+ Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;
46
+
47
+ interface RequestT extends Request {
48
+ cspNonce: string;
49
+ nonce: string;
50
+ }
51
+
52
+ /**
53
+ * Default Content Security Policy settings.
54
+ * @ignore
55
+ */
56
+ const defaultCspSettings = {
57
+ directives: mapValues(
58
+ helmet.contentSecurityPolicy.getDefaultDirectives(),
59
+
60
+ // 'https:' options (automatic re-write of insecure URLs to secure ones)
61
+ // is removed to facilitate local development with HTTP server. In cloud
62
+ // deployments we assume Apache or Nginx server in front of out app takes
63
+ // care about such re-writes.
64
+ (array) => (array as string[]).filter((item: string) => item !== 'https:'),
65
+ ),
66
+ };
67
+ defaultCspSettings.directives['frame-src'] = [
68
+ "'self'",
69
+
70
+ // YouTube domain is whitelisted to allow <YouTubeVideo> component to work
71
+ // out of box.
72
+ 'https://*.youtube.com',
73
+ ];
74
+ defaultCspSettings.directives['script-src'].push("'unsafe-eval'");
75
+
76
+ // No need for automatic re-writes via Content Security Policy settings:
77
+ // the forefront Apache or Nginx server is supposed to take care of this
78
+ // in production cloud deployments.
79
+ delete defaultCspSettings.directives['upgrade-insecure-requests'];
80
+
81
+ /**
82
+ * @category Utilities
83
+ * @func server/getDefaultCspSettings
84
+ * @global
85
+ * @desc
86
+ * ```js
87
+ * import { server } from '@dr.pogodin/react-utils';
88
+ * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';
89
+ * ```
90
+ * @return {{
91
+ * directives: object
92
+ * }} A deep copy of default CSP settings object used by `react-utils`,
93
+ * with the exception of `nonce-xxx` clause in `script-src` directive,
94
+ * which is added dynamically for each request.
95
+ */
96
+ export function getDefaultCspSettings() {
97
+ return cloneDeep(defaultCspSettings);
98
+ }
99
+
100
+ type ServerT = Express & {
101
+ logger: LoggerI;
102
+ };
103
+
104
+ export type OptionsT = RendererOptionsT & {
105
+ beforeExpressJsError?: (server: ServerT) => Promise<boolean>;
106
+ beforeExpressJsSetup?: (server: ServerT) => Promise<void>;
107
+ cspSettingsHook?: (
108
+ defaultOptions: CspOptionsT,
109
+ req: Request,
110
+ ) => CspOptionsT;
111
+ devMode?: boolean;
112
+ httpsRedirect?: boolean;
113
+ onExpressJsSetup?: (server: ServerT) => Promise<void> | void;
114
+ };
115
+
116
+ export default async function factory(
117
+ webpackConfig: Configuration,
118
+ options: OptionsT,
119
+ ) {
120
+ const rendererOps: RendererOptionsT = pick(options, [
121
+ 'Application',
122
+ 'beforeRender',
123
+ 'favicon',
124
+ 'logger',
125
+ 'maxSsrRounds',
126
+ 'noCsp',
127
+ 'ssrTimeout',
128
+ 'staticCacheController',
129
+ 'staticCacheSize',
130
+ ]);
131
+ const renderer = rendererFactory(webpackConfig, rendererOps);
132
+ const { publicPath } = webpackConfig.output!;
133
+
134
+ const server = express() as ServerT;
135
+
136
+ if (options.beforeExpressJsSetup) {
137
+ await options.beforeExpressJsSetup(server);
138
+ }
139
+
140
+ if (options.logger) server.logger = options.logger;
141
+
142
+ if (options.httpsRedirect) {
143
+ server.use((req, res, next) => {
144
+ const schema = req.headers['x-forwarded-proto'];
145
+ if (schema === 'http') {
146
+ let url = `https://${req.headers.host}`;
147
+ if (req.originalUrl !== '/') url += req.originalUrl;
148
+ return res.redirect(url);
149
+ }
150
+ return next();
151
+ });
152
+ }
153
+
154
+ server.use(compression());
155
+ server.use(
156
+ helmet({
157
+ contentSecurityPolicy: false,
158
+ crossOriginEmbedderPolicy: false,
159
+ crossOriginOpenerPolicy: false,
160
+ crossOriginResourcePolicy: false,
161
+ }),
162
+ );
163
+
164
+ if (!options.noCsp) {
165
+ server.use(
166
+ (req: Request, res: Response, next: NextFunction) => {
167
+ const req2 = req as RequestT;
168
+
169
+ req2.nonce = uuid();
170
+
171
+ // TODO: This is deprecated, but it is kept for now for backward
172
+ // compatibility. Should be removed sometime later.
173
+ req2.cspNonce = req2.nonce;
174
+
175
+ // The deep clone is necessary here to ensure that default value can't be
176
+ // mutated during request processing.
177
+ let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);
178
+ (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);
179
+ if (options.cspSettingsHook) {
180
+ cspSettings = options.cspSettingsHook(cspSettings, req);
181
+ }
182
+ helmet.contentSecurityPolicy(cspSettings)(req, res, next);
183
+ },
184
+ );
185
+ }
186
+
187
+ if (options.favicon) {
188
+ server.use(favicon(options.favicon));
189
+ }
190
+
191
+ server.use('/robots.txt', (req, res) => res.send('User-agent: *\nDisallow:'));
192
+
193
+ server.use(express.json({ limit: '300kb' }));
194
+ server.use(express.urlencoded({ extended: false }));
195
+ server.use(cookieParser());
196
+ server.use(requestIp.mw());
197
+
198
+ server.use(csrf({ cookie: true }));
199
+
200
+ loggerMiddleware.token(
201
+ 'ip',
202
+ (req: Request & { clientIp: string }) => req.clientIp,
203
+ );
204
+ const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';
205
+ server.use(loggerMiddleware(FORMAT, {
206
+ stream: {
207
+ // TODO: This implies the logger is always set. Is it on a higher level?
208
+ // then mark it as always present.
209
+ write: options.logger!.info.bind(options.logger),
210
+ },
211
+ }));
212
+
213
+ // Note: no matter the "public path", we want the service worker, if any,
214
+ // to be served from the root, to have all web app pages in its scope.
215
+ // Thus, this setup to serve it. Probably, need some more configuration
216
+ // for special cases, but this will do for now.
217
+ server.get('/__service-worker.js', express.static(
218
+ webpackConfig.output?.path || '',
219
+ {
220
+ setHeaders: (res) => res.set('Cache-Control', 'no-cache'),
221
+ },
222
+ ));
223
+
224
+ /* Setup of Hot Module Reloading for development environment.
225
+ * These dependencies are not used, nor installed for production use,
226
+ * hence we should violate some import-related lint rules. */
227
+ /* eslint-disable global-require */
228
+ /* eslint-disable import/no-extraneous-dependencies */
229
+ /* eslint-disable import/no-unresolved */
230
+ if (options.devMode) {
231
+ // This is a workaround for SASS bug:
232
+ // https://github.com/dart-lang/sdk/issues/27979
233
+ // which manifests itself sometimes when webpack dev middleware is used
234
+ // (in dev mode), and app modules are imported in some unfortunate ways.
235
+ if (!global.location) {
236
+ global.location = {
237
+ href: `${pathToFileURL(process.cwd()).href}${sep}`,
238
+ } as Location;
239
+ }
240
+
241
+ const webpack = require('webpack');
242
+ const webpackDevMiddleware = require('webpack-dev-middleware');
243
+ const webpackHotMiddleware = require('webpack-hot-middleware');
244
+ const compiler = webpack(webpackConfig);
245
+ server.use(webpackDevMiddleware(compiler, {
246
+ publicPath,
247
+ serverSideRender: true,
248
+ }));
249
+ server.use(webpackHotMiddleware(compiler));
250
+ }
251
+ /* eslint-enable global-require */
252
+ /* eslint-enable import/no-extraneous-dependencies */
253
+ /* eslint-enable import/no-unresolved */
254
+
255
+ server.use(publicPath as string, express.static(webpackConfig.output!.path!));
256
+
257
+ if (options.onExpressJsSetup) {
258
+ await options.onExpressJsSetup(server);
259
+ }
260
+ server.use(renderer);
261
+
262
+ /* Detects 404 errors, and forwards them to the error handler. */
263
+ server.use((req, res, next) => {
264
+ next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));
265
+ });
266
+
267
+ let dontAttachDefaultErrorHandler;
268
+ if (options.beforeExpressJsError) {
269
+ dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);
270
+ }
271
+
272
+ /* Error handler. */
273
+ if (!dontAttachDefaultErrorHandler) {
274
+ // TODO: Do we need this error handler at all? It actually seems to do
275
+ // what the default ExpressJS error handler does anyway, see:
276
+ // https://expressjs.com/en/guide/error-handling.html
277
+ //
278
+ // TODO: It is better to move the default error handler definition
279
+ // to a stand-alone function at top-level, but the use of options.logger
280
+ // prevents to do it without some extra refactoring. Should be done sometime
281
+ // though.
282
+ server.use((
283
+ error: any,
284
+ req: Request,
285
+ res: Response,
286
+ next: NextFunction,
287
+ ) => {
288
+ // TODO: This is needed to correctly handled any errors thrown after
289
+ // sending initial response to the client.
290
+ if (res.headersSent) return next(error);
291
+
292
+ const status = error.status || CODES.INTERNAL_SERVER_ERROR;
293
+ const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;
294
+
295
+ // Log server-side errors always, client-side at debug level only.
296
+ options.logger!.log(serverSide ? 'error' : 'debug', error);
297
+
298
+ let message = error.message || getErrorForCode(status);
299
+ if (serverSide && process.env.NODE_ENV === 'production') {
300
+ message = ERRORS.INTERNAL_SERVER_ERROR;
301
+ }
302
+
303
+ res.status(status).send(message);
304
+ return undefined;
305
+ });
306
+ }
307
+
308
+ return server;
309
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * @category Utilities
3
+ * @module server/errors
4
+ * @desc
5
+ * ```js
6
+ * import { server } from '@dr.pogodin/react-utils';
7
+ * const { errors } = server;
8
+ * ```
9
+ * Server-side helpers for error handling.
10
+ */
11
+
12
+ import {
13
+ StatusCodes as CODES,
14
+ ReasonPhrases as ERRORS,
15
+ getReasonPhrase as getErrorForCode,
16
+ } from 'http-status-codes';
17
+
18
+ import joi from 'joi';
19
+
20
+ /**
21
+ * @static
22
+ * @const CODES
23
+ * @desc An alias for
24
+ * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).
25
+ * It is a map between HTTP status code names and corresponding numeric codes.
26
+ * @example
27
+ * import { server } from '@dr.pogodin/react-utils';
28
+ * const { CODES } = server.errors;
29
+ * console.log(CODES.BAD_REQUEST); // Prints: 400
30
+ */
31
+ export { CODES };
32
+
33
+ /**
34
+ * @static
35
+ * @const ERRORS
36
+ * @desc An alias for
37
+ * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).
38
+ * It is a map between HTTP status code names and their pretty-printed forms.
39
+ * @example
40
+ * import { server } from '@dr.pogodin/react-utils';
41
+ * const { ERRORS } = server.errors;
42
+ * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request
43
+ */
44
+ export { ERRORS };
45
+
46
+ /**
47
+ * @static
48
+ * @func getErrorForCode
49
+ * @desc An alias for
50
+ * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).
51
+ * Given an HTTP code it returns the corresponding error text.
52
+ * @param {number} code HTTP code.
53
+ * @return {string} HTTP error text.
54
+ * @example
55
+ * import { server } from '@dr.pogodin/react-utils';
56
+ * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request
57
+ */
58
+ export { getErrorForCode };
59
+
60
+ /**
61
+ * @static
62
+ * @const joi
63
+ * @desc An alias for [Joi library](https://joi.dev/api/?v=17.4.0),
64
+ * which provides tooling for HTTP request validation. You can use it in any
65
+ * way you would use that library import.
66
+ * @example
67
+ * import { server } from '@dr.pogodin/react-utils';
68
+ * const { joi } = server.errors;
69
+ * const requestBodySchema = joi.object({
70
+ * sampleKey: joi.string().max(16).required(),
71
+ * });
72
+ */
73
+ export { joi };
74
+
75
+ // TODO: It could accept the status code as a constructor argument.
76
+ class ErrorWithStatus extends Error {
77
+ status: number = CODES.INTERNAL_SERVER_ERROR;
78
+ }
79
+
80
+ /**
81
+ * ```js
82
+ * import { server } from '@dr.pogodin/react-utils';
83
+ * const { newError } = server.errors;
84
+ * ```
85
+ * Creates a new `Error` object with given message, and HTTP status code
86
+ * attached as `status` field.
87
+ * @param {string} message Error message.
88
+ * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal
89
+ * Server Error).
90
+ * @return {Error}
91
+ */
92
+ export function newError(message: string, statusCode = CODES.INTERNAL_SERVER_ERROR) {
93
+ const error = new ErrorWithStatus(message);
94
+ error.status = statusCode;
95
+ return error;
96
+ }
97
+
98
+ /**
99
+ * ```js
100
+ * import { server } from '@dr.pogodin/react-utils';
101
+ * const { fail } = server.errors;
102
+ * ```
103
+ * Throws an error with given message and HTTP status code.
104
+ * @param message Error message.
105
+ * @param [statusCode=500] HTTP error code. Defaults to 500 (Internal
106
+ * Server Error).
107
+ */
108
+ export function fail(message: string, statusCode = CODES.INTERNAL_SERVER_ERROR) {
109
+ throw newError(message, statusCode);
110
+ }
111
+
112
+ /**
113
+ * ```js
114
+ * import { server } from '@dr.pogodin/react-utils';
115
+ * const { assert } = server.errors;
116
+ * ```
117
+ * Validates a value using given Joi schema, and throws an error with given
118
+ * message and HTTP status code in case of the validation failure.
119
+ * @param value
120
+ * @param schema
121
+ * @param [message] Error message.
122
+ * @param [statusCode=500] HTTP status code. Defaults to 400 (Bad
123
+ * Request).
124
+ */
125
+ export function assert(
126
+ value: any,
127
+ schema: joi.AnySchema,
128
+ message = '',
129
+ statusCode = CODES.BAD_REQUEST,
130
+ ) {
131
+ const { error } = schema.validate(value, { abortEarly: false });
132
+ if (error) {
133
+ fail(message.concat(message ? '\n' : '', error.message), statusCode);
134
+ }
135
+ }
@@ -0,0 +1,3 @@
1
+ // Aggregates utility modules together.
2
+
3
+ export * as errors from './errors';
@@ -0,0 +1,146 @@
1
+ // The <Button> component implements a standard button / button-like link.
2
+
3
+ import PT from 'prop-types';
4
+ import { type ReactNode } from 'react';
5
+
6
+ import Link from 'components/Link';
7
+
8
+ import themed, { type Theme } from '@dr.pogodin/react-themes';
9
+
10
+ import defaultTheme from './style.scss';
11
+
12
+ type PropsT = {
13
+ active?: boolean;
14
+ children?: ReactNode;
15
+ disabled?: boolean;
16
+ enforceA?: boolean;
17
+ onClick?: React.MouseEventHandler & React.KeyboardEventHandler;
18
+ onMouseDown?: React.MouseEventHandler;
19
+ openNewTab?: boolean;
20
+ replace?: boolean;
21
+ theme: Theme & {
22
+ active?: string;
23
+ button?: string;
24
+ disabled?: string;
25
+ };
26
+ // TODO: It needs a more precise typing of the object option.
27
+ to?: object | string;
28
+ };
29
+
30
+ /* eslint-disable react/function-component-definition */
31
+ const BaseButton: React.FunctionComponent<PropsT> = ({
32
+ active,
33
+ children,
34
+ disabled,
35
+ enforceA,
36
+ onClick,
37
+ onMouseDown,
38
+ openNewTab,
39
+ replace,
40
+ theme,
41
+ to,
42
+ }) => {
43
+ let className = theme.button;
44
+ if (active && theme.active) className += ` ${theme.active}`;
45
+ if (disabled) {
46
+ if (theme.disabled) className += ` ${theme.disabled}`;
47
+ return (
48
+ <div className={className}>
49
+ {children}
50
+ </div>
51
+ );
52
+ }
53
+ if (to) {
54
+ return (
55
+ <Link
56
+ className={className}
57
+ enforceA={enforceA}
58
+ onClick={onClick}
59
+ onMouseDown={onMouseDown}
60
+ openNewTab={openNewTab}
61
+ replace={replace}
62
+ to={to}
63
+ >
64
+ {children}
65
+ </Link>
66
+ );
67
+ }
68
+ return (
69
+ <div
70
+ className={className}
71
+ onClick={onClick}
72
+ onKeyDown={onClick}
73
+ onMouseDown={onMouseDown}
74
+ role="button"
75
+ tabIndex={0}
76
+ >
77
+ {children}
78
+ </div>
79
+ );
80
+ };
81
+
82
+ /**
83
+ * Button component theme: a map of CSS
84
+ * class names to append to button elements:
85
+ * @prop {string} [active] to the root element of active button.
86
+ * @prop {string} [button] to the root element of any button.
87
+ * @prop {string} [disabled] to the root element of disabled button.
88
+ */
89
+ const ThemedButton = themed(BaseButton, 'Button', [
90
+ 'active',
91
+ 'button',
92
+ 'disabled',
93
+ ], defaultTheme);
94
+
95
+ /**
96
+ * Implements themeable buttons, and button-line links (elements which look
97
+ * like buttons, but behave as links) in the same uniform manner.
98
+ * @param {object} [props] Component props.
99
+ * @param {boolean} [props.active] Set `true` to render the button as
100
+ * active, even if it is not active otherwise.
101
+ * @param {boolean} [props.disabled] Set `true` to disable the button.
102
+ * @param {boolean} [props.enforceA] When the button is rendered as `<Link>`
103
+ * component, this prop enforces it to be rendered as a simple `<a>` element
104
+ * (external link), rather than the React router's internal link.
105
+ * See `<Link>` documentation to learn when links are rendered as `<a>`
106
+ * by default.
107
+ * @param {function} [props.onClick] Click event handler.
108
+ * @param {function} [props.onMouseDown] Mouse down event handler.
109
+ * @param {boolean} [props.openNewTab] Set `true` to open link in the new tab.
110
+ * @param {boolean} [props.replace] When the button is rendered as
111
+ * `<Link>`, and the target URL is internal, this property tells that
112
+ * the new route should replace the last record in the browser's history,
113
+ * rather than to be pushed as a new entry into the history stack.
114
+ * @param {ButtonTheme} [props.theme] _Ad hoc_ button theme.
115
+ * @param {object|string} [props.to] If specified, the button will be rendered
116
+ * as `<Link>` (if not disabled), and it will point to the specified location
117
+ * or URL.
118
+ * @param {...any} [props....]
119
+ * [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)
120
+ */
121
+ BaseButton.defaultProps = {
122
+ active: false,
123
+ children: undefined,
124
+ disabled: false,
125
+ enforceA: false,
126
+ onClick: undefined,
127
+ onMouseDown: undefined,
128
+ openNewTab: false,
129
+ replace: false,
130
+ to: undefined,
131
+ };
132
+
133
+ BaseButton.propTypes = {
134
+ active: PT.bool,
135
+ children: PT.node,
136
+ disabled: PT.bool,
137
+ enforceA: PT.bool,
138
+ onClick: PT.func,
139
+ onMouseDown: PT.func,
140
+ openNewTab: PT.bool,
141
+ replace: PT.bool,
142
+ theme: ThemedButton.themeType.isRequired,
143
+ to: PT.oneOfType([PT.object, PT.string]),
144
+ };
145
+
146
+ export default ThemedButton;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The default button theme.
3
+ */
4
+
5
+ *,
6
+ .context,
7
+ .ad.hoc {
8
+ &.button {
9
+ background-image: linear-gradient(to top, lightgray, white 50%, white);
10
+ border: solid 1px gray;
11
+ border-radius: 0.3em;
12
+ color: inherit;
13
+ cursor: pointer;
14
+ display: inline-block;
15
+ font: inherit;
16
+ margin: 0.1em;
17
+ padding: 0.3em 1.2em;
18
+ text-align: center;
19
+ text-decoration: none;
20
+
21
+ &:visited {
22
+ color: inherit;
23
+ }
24
+
25
+ &.active,
26
+ &:active {
27
+ background-image: linear-gradient(to bottom, lightgray, white 50%, white);
28
+ box-shadow: inset 0 1px 3px 0 lightgray;
29
+ border-color: gray;
30
+ }
31
+
32
+ &:focus {
33
+ box-shadow: 0 0 3px 1px lightblue;
34
+ border-color: blue;
35
+ outline: none;
36
+ }
37
+ }
38
+
39
+ /* Additional styling of disabled buttons. */
40
+ &.disabled {
41
+ cursor: not-allowed;
42
+ opacity: 0.33;
43
+
44
+ // Note: this "cancels out" the active state styling of an active button,
45
+ // which is defined above, thus ensuring a click on disabled button does
46
+ // not alter its appearance (does not result in visual press).
47
+ &.active,
48
+ &:active {
49
+ background-image: linear-gradient(to top, lightgray, white 50%, white);
50
+ box-shadow: none;
51
+ }
52
+ }
53
+ }