@dr.pogodin/react-utils 1.49.0 → 1.50.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 (213) hide show
  1. package/babel.scripts.config.js +19 -0
  2. package/build/development/client/getInj.js +18 -29
  3. package/build/development/client/getInj.js.map +1 -1
  4. package/build/development/client/index.js +11 -14
  5. package/build/development/client/index.js.map +1 -1
  6. package/build/development/client/init.js +9 -17
  7. package/build/development/client/init.js.map +1 -1
  8. package/build/development/index.js +26 -4
  9. package/build/development/index.js.map +1 -1
  10. package/build/development/server/Cache.js +15 -20
  11. package/build/development/server/Cache.js.map +1 -1
  12. package/build/development/server/index.js +142 -160
  13. package/build/development/server/index.js.map +1 -1
  14. package/build/development/server/renderer.js +150 -197
  15. package/build/development/server/renderer.js.map +1 -1
  16. package/build/development/server/server.js +63 -86
  17. package/build/development/server/server.js.map +1 -1
  18. package/build/development/server/utils/errors.js +72 -87
  19. package/build/development/server/utils/errors.js.map +1 -1
  20. package/build/development/shared/components/Button/index.js +8 -17
  21. package/build/development/shared/components/Button/index.js.map +1 -1
  22. package/build/development/shared/components/Checkbox/index.js +12 -5
  23. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  24. package/build/development/shared/components/GenericLink/index.js +54 -58
  25. package/build/development/shared/components/GenericLink/index.js.map +1 -1
  26. package/build/development/shared/components/Input/index.js +16 -24
  27. package/build/development/shared/components/Input/index.js.map +1 -1
  28. package/build/development/shared/components/Link.js +2 -5
  29. package/build/development/shared/components/Link.js.map +1 -1
  30. package/build/development/shared/components/Modal/index.js +28 -41
  31. package/build/development/shared/components/Modal/index.js.map +1 -1
  32. package/build/development/shared/components/NavLink.js +2 -3
  33. package/build/development/shared/components/NavLink.js.map +1 -1
  34. package/build/development/shared/components/PageLayout/index.js +19 -20
  35. package/build/development/shared/components/PageLayout/index.js.map +1 -1
  36. package/build/development/shared/components/TextArea/index.js +12 -28
  37. package/build/development/shared/components/TextArea/index.js.map +1 -1
  38. package/build/development/shared/components/Throbber/index.js +11 -12
  39. package/build/development/shared/components/Throbber/index.js.map +1 -1
  40. package/build/development/shared/components/WithTooltip/Tooltip.js +46 -68
  41. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  42. package/build/development/shared/components/WithTooltip/index.js +21 -28
  43. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  44. package/build/development/shared/components/YouTubeVideo/index.js +21 -25
  45. package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
  46. package/build/development/shared/components/index.js +1 -3
  47. package/build/development/shared/components/index.js.map +1 -1
  48. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +6 -7
  49. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  50. package/build/development/shared/components/selectors/CustomDropdown/index.js +7 -9
  51. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  52. package/build/development/shared/components/selectors/NativeDropdown/index.js +23 -27
  53. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  54. package/build/development/shared/components/selectors/Switch/index.js +4 -4
  55. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  56. package/build/development/shared/components/selectors/common.js +2 -5
  57. package/build/development/shared/components/selectors/common.js.map +1 -1
  58. package/build/development/shared/utils/config.js +11 -15
  59. package/build/development/shared/utils/config.js.map +1 -1
  60. package/build/development/shared/utils/globalState.js +1 -7
  61. package/build/development/shared/utils/globalState.js.map +1 -1
  62. package/build/development/shared/utils/index.js +2 -2
  63. package/build/development/shared/utils/index.js.map +1 -1
  64. package/build/development/shared/utils/isomorphy/buildInfo.js +15 -24
  65. package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
  66. package/build/development/shared/utils/isomorphy/environment-check.js +4 -9
  67. package/build/development/shared/utils/isomorphy/environment-check.js.map +1 -1
  68. package/build/development/shared/utils/isomorphy/index.js +17 -23
  69. package/build/development/shared/utils/isomorphy/index.js.map +1 -1
  70. package/build/development/shared/utils/jest/E2eSsrEnv.js +48 -77
  71. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  72. package/build/development/shared/utils/jest/index.js +48 -72
  73. package/build/development/shared/utils/jest/index.js.map +1 -1
  74. package/build/development/shared/utils/splitComponent.js +67 -74
  75. package/build/development/shared/utils/splitComponent.js.map +1 -1
  76. package/build/development/shared/utils/time.js +25 -28
  77. package/build/development/shared/utils/time.js.map +1 -1
  78. package/build/development/shared/utils/webpack.js +22 -29
  79. package/build/development/shared/utils/webpack.js.map +1 -1
  80. package/build/production/client/getInj.js.map +1 -1
  81. package/build/production/client/index.js.map +1 -1
  82. package/build/production/index.js +26 -1
  83. package/build/production/index.js.map +1 -1
  84. package/build/production/server/Cache.js.map +1 -1
  85. package/build/production/server/index.js.map +1 -1
  86. package/build/production/server/renderer.js.map +1 -1
  87. package/build/production/server/server.js.map +1 -1
  88. package/build/production/shared/components/Button/index.js.map +1 -1
  89. package/build/production/shared/components/Checkbox/index.js +1 -1
  90. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  91. package/build/production/shared/components/GenericLink/index.js +2 -2
  92. package/build/production/shared/components/GenericLink/index.js.map +1 -1
  93. package/build/production/shared/components/Input/index.js.map +1 -1
  94. package/build/production/shared/components/Link.js.map +1 -1
  95. package/build/production/shared/components/Modal/index.js.map +1 -1
  96. package/build/production/shared/components/NavLink.js.map +1 -1
  97. package/build/production/shared/components/PageLayout/index.js.map +1 -1
  98. package/build/production/shared/components/TextArea/index.js.map +1 -1
  99. package/build/production/shared/components/Throbber/index.js.map +1 -1
  100. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  101. package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
  102. package/build/production/shared/components/index.js.map +1 -1
  103. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  104. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  105. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  106. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  107. package/build/production/shared/utils/config.js.map +1 -1
  108. package/build/production/shared/utils/index.js.map +1 -1
  109. package/build/production/shared/utils/jest/index.js.map +1 -1
  110. package/build/production/shared/utils/splitComponent.js +20 -3
  111. package/build/production/shared/utils/splitComponent.js.map +1 -1
  112. package/build/production/shared/utils/time.js.map +1 -1
  113. package/build/production/shared/utils/webpack.js.map +1 -1
  114. package/build/types-code/shared/components/Checkbox/index.d.ts +3 -2
  115. package/build/types-code/shared/components/GenericLink/index.d.ts +0 -1
  116. package/build/types-scss/src/shared/components/Checkbox/theme.scss.d.ts +2 -0
  117. package/build/web/client/getInj.js +10 -70
  118. package/build/web/client/getInj.js.map +1 -1
  119. package/build/web/client/index.js +2 -27
  120. package/build/web/client/index.js.map +1 -1
  121. package/build/web/client/init.js +10 -44
  122. package/build/web/client/init.js.map +1 -1
  123. package/build/web/index.js +26 -6
  124. package/build/web/index.js.map +1 -1
  125. package/build/web/server/Cache.js +3 -41
  126. package/build/web/server/Cache.js.map +1 -1
  127. package/build/web/server/index.js +7 -78
  128. package/build/web/server/index.js.map +1 -1
  129. package/build/web/server/renderer.js +61 -420
  130. package/build/web/server/renderer.js.map +1 -1
  131. package/build/web/server/server.js +38 -212
  132. package/build/web/server/server.js.map +1 -1
  133. package/build/web/server/utils/errors.js +9 -48
  134. package/build/web/server/utils/errors.js.map +1 -1
  135. package/build/web/server/utils/index.js +1 -2
  136. package/build/web/server/utils/index.js.map +1 -1
  137. package/build/web/shared/components/Button/index.js +12 -101
  138. package/build/web/shared/components/Button/index.js.map +1 -1
  139. package/build/web/shared/components/Checkbox/index.js +1 -35
  140. package/build/web/shared/components/Checkbox/index.js.map +1 -1
  141. package/build/web/shared/components/Checkbox/theme.scss +22 -0
  142. package/build/web/shared/components/GenericLink/index.js +12 -65
  143. package/build/web/shared/components/GenericLink/index.js.map +1 -1
  144. package/build/web/shared/components/GenericLink/style.scss +1 -0
  145. package/build/web/shared/components/Input/index.js +11 -69
  146. package/build/web/shared/components/Input/index.js.map +1 -1
  147. package/build/web/shared/components/Link.js +2 -12
  148. package/build/web/shared/components/Link.js.map +1 -1
  149. package/build/web/shared/components/Modal/index.js +10 -130
  150. package/build/web/shared/components/Modal/index.js.map +1 -1
  151. package/build/web/shared/components/NavLink.js +2 -10
  152. package/build/web/shared/components/NavLink.js.map +1 -1
  153. package/build/web/shared/components/PageLayout/index.js +2 -27
  154. package/build/web/shared/components/PageLayout/index.js.map +1 -1
  155. package/build/web/shared/components/TextArea/index.js +21 -106
  156. package/build/web/shared/components/TextArea/index.js.map +1 -1
  157. package/build/web/shared/components/Throbber/index.js +2 -24
  158. package/build/web/shared/components/Throbber/index.js.map +1 -1
  159. package/build/web/shared/components/WithTooltip/Tooltip.js +16 -145
  160. package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -1
  161. package/build/web/shared/components/WithTooltip/index.js +12 -104
  162. package/build/web/shared/components/WithTooltip/index.js.map +1 -1
  163. package/build/web/shared/components/YouTubeVideo/index.js +5 -43
  164. package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
  165. package/build/web/shared/components/index.js +1 -15
  166. package/build/web/shared/components/index.js.map +1 -1
  167. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +6 -81
  168. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  169. package/build/web/shared/components/selectors/CustomDropdown/index.js +7 -122
  170. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  171. package/build/web/shared/components/selectors/NativeDropdown/index.js +7 -68
  172. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  173. package/build/web/shared/components/selectors/Switch/index.js +1 -49
  174. package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
  175. package/build/web/shared/components/selectors/common.js +1 -10
  176. package/build/web/shared/components/selectors/common.js.map +1 -1
  177. package/build/web/shared/components/selectors/index.js +1 -3
  178. package/build/web/shared/components/selectors/index.js.map +1 -1
  179. package/build/web/shared/utils/config.js +6 -40
  180. package/build/web/shared/utils/config.js.map +1 -1
  181. package/build/web/shared/utils/globalState.js +2 -11
  182. package/build/web/shared/utils/globalState.js.map +1 -1
  183. package/build/web/shared/utils/index.js +1 -9
  184. package/build/web/shared/utils/index.js.map +1 -1
  185. package/build/web/shared/utils/isomorphy/buildInfo.js +4 -25
  186. package/build/web/shared/utils/isomorphy/buildInfo.js.map +1 -1
  187. package/build/web/shared/utils/isomorphy/environment-check.js +3 -9
  188. package/build/web/shared/utils/isomorphy/environment-check.js.map +1 -1
  189. package/build/web/shared/utils/isomorphy/index.js +5 -27
  190. package/build/web/shared/utils/isomorphy/index.js.map +1 -1
  191. package/build/web/shared/utils/jest/E2eSsrEnv.js +51 -221
  192. package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  193. package/build/web/shared/utils/jest/global.js +1 -3
  194. package/build/web/shared/utils/jest/global.js.map +1 -1
  195. package/build/web/shared/utils/jest/index.js +27 -146
  196. package/build/web/shared/utils/jest/index.js.map +1 -1
  197. package/build/web/shared/utils/splitComponent.js +34 -197
  198. package/build/web/shared/utils/splitComponent.js.map +1 -1
  199. package/build/web/shared/utils/time.js +5 -69
  200. package/build/web/shared/utils/time.js.map +1 -1
  201. package/build/web/shared/utils/webpack.js +6 -53
  202. package/build/web/shared/utils/webpack.js.map +1 -1
  203. package/config/babel/webpack.js +1 -1
  204. package/eslint.config.mjs +1 -0
  205. package/package.json +10 -13
  206. package/bin/build.js +0 -236
  207. package/config/webpack/lib-base.d.ts +0 -22
  208. package/config/webpack/lib-base.js +0 -167
  209. package/config/webpack/lib-development.d.ts +0 -5
  210. package/config/webpack/lib-development.js +0 -35
  211. package/config/webpack/lib-production.d.ts +0 -5
  212. package/config/webpack/lib-production.js +0 -42
  213. package/webpack.config.ts +0 -49
@@ -1,164 +1,152 @@
1
1
  // eslint-disable-next-line import/no-unassigned-import
2
- import 'source-map-support/register.js';
3
- import http from 'node:http';
4
- import https from 'node:https';
5
- import { cloneDeep, defaults } from 'lodash-es';
6
-
7
- // Polyfill required by ReactJS.
2
+ import "source-map-support/register.js";
3
+ import http from "node:http";
4
+ import https from "node:https";
5
+ import { cloneDeep, defaults } from "lodash-es"; // Polyfill required by ReactJS.
8
6
  // TODO: Double-check, if it is still required by React v19?
9
7
  // eslint-disable-next-line import/no-unassigned-import
10
- import 'raf/polyfill.js';
8
+ import "raf/polyfill.js";
11
9
  import { SCRIPT_LOCATIONS, newDefaultLogger } from "./renderer.js";
12
10
  import serverFactory, { getDefaultCspSettings } from "./server.js";
13
11
  export * from "./utils/index.js";
14
- export { SCRIPT_LOCATIONS, getDefaultCspSettings };
15
-
16
- /**
17
- * Normalizes a port into a number, string, or false.
18
- * TODO: Drop this function?
19
- * @param value Port name or number.
20
- * @return Port number (Number), name (String).
21
- */
12
+ export { SCRIPT_LOCATIONS, getDefaultCspSettings }; /**
13
+ * Normalizes a port into a number, string, or false.
14
+ * TODO: Drop this function?
15
+ * @param value Port name or number.
16
+ * @return Port number (Number), name (String).
17
+ */
22
18
  function normalizePort(value) {
23
- const port = typeof value === 'string' ? parseInt(value) : value;
19
+ const port = typeof value === "string" ? parseInt(value) : value;
24
20
  if (Number.isFinite(port)) return port; /* port number */
25
21
  return value; /* named pipe */
26
- }
27
- /**
28
- * Creates and launches web-server for ReactJS application. Allows zero
29
- * or detailed configuration, supports server-side rendering,
30
- * and development tools, including Hot Module Reloading (HMR).
31
- *
32
- * NOTE: Many of options defined below are passed down to the server and
33
- * renderer factories, and their declared default values are set in those
34
- * factories, rather than here.
35
- *
36
- * @param {object} webpackConfig Webpack configuration used to build
37
- * the frontend bundle. In production mode the server will read out of it
38
- * `context`, `publicPath`, and a few other parameters, necessary to locate
39
- * and serve the app bundle. In development mode the server will use entire
40
- * provided config to build the app bundle in memory, and further watch and
41
- * update it via HMR.
42
- * @param {object} [options] Additional parameters.
43
- * @param {Component} [options.Application] The root ReactJS component of
44
- * the app to use for the server-side rendering. When not provided
45
- * the server-side rendering is disabled.
46
- * @param {function} [options.beforeExpressJsError] Asynchronous callback
47
- * (`(server) => Promise<boolean>`) to be executed just before the default error
48
- * handler is added to ExpressJS server. If the callback is provided and its
49
- * result resolves to a truthy value, `react-utils` won't attach the default
50
- * error handler.
51
- * @param {function} [options.beforeExpressJsSetup] Asynchronous callback
52
- * (`(server) => Promise) to be executed right after ExpressJS server creation,
53
- * before any configuration is performed.
54
- * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before
55
- * the server-side rendering. For each incoming request, it will be executed
56
- * just before the HTML markup is generated at the server. It allows to load
57
- * and provide the data necessary for server-side rendering, and also to inject
58
- * additional configuration and scripts into the generated HTML code.
59
- * @param {boolean} [options.noCsp] Set `true` to disable
60
- * Content-Security-Policy (CSP) headers altogether.
61
- * @param {function} [options.cspSettingsHook] A hook allowing
62
- * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)
63
- * settings for [helmet](https://github.com/helmetjs/helmet)'s
64
- * `contentSecurityPolicy` middleware on per-request basis.
65
- *
66
- * If provided it should be a with signature: \
67
- * `(defaultSettings: object, req: object)` &rArr; `object` \
68
- * which gets the default settings (also used without the hook),
69
- * and the incoming request object. The hook response will be passed
70
- * as options to the helmet `contentSecurityPolicy` middleware.
71
- *
72
- * Currently, the default settings is the following object in production
73
- * environment:
74
- * ```js
75
- * {
76
- * directives: {
77
- * defaultSrc: ["'self'"],
78
- * baseUri: ["'self'"],
79
- * blockAllMixedContent: [],
80
- * fontSrc: ["'self'", 'https:', 'data:'],
81
- * frameAncestors: ["'self'"],
82
- * frameSrc: ["'self'", 'https://*.youtube.com'],
83
- * imgSrc: ["'self'", 'data:'],
84
- * objectSrc: ["'none'"],
85
- * scriptSrc: ["'self'", "'unsafe-eval'", `'nonce-UNIQUE_NONCE_VALUE'`],
86
- * scriptSrcAttr: ["'none'"],
87
- * styleSrc: ["'self'", 'https:', "'unsafe-inline'"],
88
- * upgradeInsecureRequests: [] // Removed in dev mode.
89
- * }
90
- * }
91
- * ```
92
- * It matches the default value used by Helmet with a few updates:
93
- * - YouTube host is whitelisted in the `frameSrc` directive to ensure
94
- * the {@link YouTubeVideo} component works.
95
- * - An unique per-request nonce is added to `scriptSrc` directive to
96
- * whitelist auxiliary scripts injected by react-utils. The actual nonce
97
- * value can be fetched by host code via `.nonce` field of `req` argument
98
- * of `.beforeRender` hook.
99
- * - `upgradeInsecureRequests` directive is removed in development mode,
100
- * to simplify local testing with http requests.
101
- * @param {string} [options.defaultLoggerLogLevel='info'] Log level for
102
- * the default logger, which is created if no `logger` option provided.
103
- * @param {boolean} [options.devMode] Pass in `true` to start the server in
104
- * development mode.
105
- * @param {string} [options.favicon] Path to the favicon to use by the server.
106
- * By default no favicon is used.
107
- * @param {object} [options.https] If provided, HTTPS server will be started,
108
- * instead of HTTP otherwise. The object should provide SSL certificate and key
109
- * via two string fields: `cert`, and `key`.
110
- * @param {string} [options.https.cert] SSL Certificate.
111
- * @param {string} [options.https.key] SSL key.
112
- * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable
113
- * automatic redirection of all incoming HTTP requests to HTTPS.
114
- *
115
- * To smoothly use it at `localhost` you need to run the server in HTTPS mode,
116
- * and also properly create and install a self-signed SSL sertificate on your
117
- * system. This article is helpful:
118
- * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)
119
- * @param {Logger} [options.logger] The logger to use at server side.
120
- * By default [`winston`](https://www.npmjs.com/package/winston) logger
121
- * with console transport is used. The logger you provide, or the default
122
- * `winston` logger otherwise, will be attached to the created ExpressJS server
123
- * object.
124
- * @param {function} [options.onExpressJsSetup] An async callback
125
- * (`(server) => Promise`) to be triggered when most of the server
126
- * configuration is completed, just before the server-side renderer,
127
- * and the default error handler are attached. You can use it to mount
128
- * custom API routes. The server-side logger can be accessed as `server.logger`.
129
- * @param {number|string} [options.port=3000] The port to start the server on.
130
- * @param {number} [options.staticCacheSize=1.e7] The maximum
131
- * static cache size in bytes. Defaults to ~10 MB.
132
- * @param {function} [options.staticCacheController] When given, it activates,
133
- * and controls the static caching of generated HTML markup. When this function
134
- * is provided, on each incoming request it is triggered with the request
135
- * passed in as the argument. To attempt to serve the response from the cache
136
- * it should return the object with the following fields:
137
- * - `key: string` &ndash; the cache key for the response;
138
- * - `maxage?: number` &ndash; the maximum age of cached result in ms.
139
- * If undefined - infinite age is assumed.
140
- * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.
141
- * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,
142
- * defaults to 1 second.
143
- * @return Resolves to an object with created Express and HTTP servers.
144
- */
22
+ } /**
23
+ * Creates and launches web-server for ReactJS application. Allows zero
24
+ * or detailed configuration, supports server-side rendering,
25
+ * and development tools, including Hot Module Reloading (HMR).
26
+ *
27
+ * NOTE: Many of options defined below are passed down to the server and
28
+ * renderer factories, and their declared default values are set in those
29
+ * factories, rather than here.
30
+ *
31
+ * @param {object} webpackConfig Webpack configuration used to build
32
+ * the frontend bundle. In production mode the server will read out of it
33
+ * `context`, `publicPath`, and a few other parameters, necessary to locate
34
+ * and serve the app bundle. In development mode the server will use entire
35
+ * provided config to build the app bundle in memory, and further watch and
36
+ * update it via HMR.
37
+ * @param {object} [options] Additional parameters.
38
+ * @param {Component} [options.Application] The root ReactJS component of
39
+ * the app to use for the server-side rendering. When not provided
40
+ * the server-side rendering is disabled.
41
+ * @param {function} [options.beforeExpressJsError] Asynchronous callback
42
+ * (`(server) => Promise<boolean>`) to be executed just before the default error
43
+ * handler is added to ExpressJS server. If the callback is provided and its
44
+ * result resolves to a truthy value, `react-utils` won't attach the default
45
+ * error handler.
46
+ * @param {function} [options.beforeExpressJsSetup] Asynchronous callback
47
+ * (`(server) => Promise) to be executed right after ExpressJS server creation,
48
+ * before any configuration is performed.
49
+ * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before
50
+ * the server-side rendering. For each incoming request, it will be executed
51
+ * just before the HTML markup is generated at the server. It allows to load
52
+ * and provide the data necessary for server-side rendering, and also to inject
53
+ * additional configuration and scripts into the generated HTML code.
54
+ * @param {boolean} [options.noCsp] Set `true` to disable
55
+ * Content-Security-Policy (CSP) headers altogether.
56
+ * @param {function} [options.cspSettingsHook] A hook allowing
57
+ * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)
58
+ * settings for [helmet](https://github.com/helmetjs/helmet)'s
59
+ * `contentSecurityPolicy` middleware on per-request basis.
60
+ *
61
+ * If provided it should be a with signature: \
62
+ * `(defaultSettings: object, req: object)` &rArr; `object` \
63
+ * which gets the default settings (also used without the hook),
64
+ * and the incoming request object. The hook response will be passed
65
+ * as options to the helmet `contentSecurityPolicy` middleware.
66
+ *
67
+ * Currently, the default settings is the following object in production
68
+ * environment:
69
+ * ```js
70
+ * {
71
+ * directives: {
72
+ * defaultSrc: ["'self'"],
73
+ * baseUri: ["'self'"],
74
+ * blockAllMixedContent: [],
75
+ * fontSrc: ["'self'", 'https:', 'data:'],
76
+ * frameAncestors: ["'self'"],
77
+ * frameSrc: ["'self'", 'https://*.youtube.com'],
78
+ * imgSrc: ["'self'", 'data:'],
79
+ * objectSrc: ["'none'"],
80
+ * scriptSrc: ["'self'", "'unsafe-eval'", `'nonce-UNIQUE_NONCE_VALUE'`],
81
+ * scriptSrcAttr: ["'none'"],
82
+ * styleSrc: ["'self'", 'https:', "'unsafe-inline'"],
83
+ * upgradeInsecureRequests: [] // Removed in dev mode.
84
+ * }
85
+ * }
86
+ * ```
87
+ * It matches the default value used by Helmet with a few updates:
88
+ * - YouTube host is whitelisted in the `frameSrc` directive to ensure
89
+ * the {@link YouTubeVideo} component works.
90
+ * - An unique per-request nonce is added to `scriptSrc` directive to
91
+ * whitelist auxiliary scripts injected by react-utils. The actual nonce
92
+ * value can be fetched by host code via `.nonce` field of `req` argument
93
+ * of `.beforeRender` hook.
94
+ * - `upgradeInsecureRequests` directive is removed in development mode,
95
+ * to simplify local testing with http requests.
96
+ * @param {string} [options.defaultLoggerLogLevel='info'] Log level for
97
+ * the default logger, which is created if no `logger` option provided.
98
+ * @param {boolean} [options.devMode] Pass in `true` to start the server in
99
+ * development mode.
100
+ * @param {string} [options.favicon] Path to the favicon to use by the server.
101
+ * By default no favicon is used.
102
+ * @param {object} [options.https] If provided, HTTPS server will be started,
103
+ * instead of HTTP otherwise. The object should provide SSL certificate and key
104
+ * via two string fields: `cert`, and `key`.
105
+ * @param {string} [options.https.cert] SSL Certificate.
106
+ * @param {string} [options.https.key] SSL key.
107
+ * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable
108
+ * automatic redirection of all incoming HTTP requests to HTTPS.
109
+ *
110
+ * To smoothly use it at `localhost` you need to run the server in HTTPS mode,
111
+ * and also properly create and install a self-signed SSL sertificate on your
112
+ * system. This article is helpful:
113
+ * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)
114
+ * @param {Logger} [options.logger] The logger to use at server side.
115
+ * By default [`winston`](https://www.npmjs.com/package/winston) logger
116
+ * with console transport is used. The logger you provide, or the default
117
+ * `winston` logger otherwise, will be attached to the created ExpressJS server
118
+ * object.
119
+ * @param {function} [options.onExpressJsSetup] An async callback
120
+ * (`(server) => Promise`) to be triggered when most of the server
121
+ * configuration is completed, just before the server-side renderer,
122
+ * and the default error handler are attached. You can use it to mount
123
+ * custom API routes. The server-side logger can be accessed as `server.logger`.
124
+ * @param {number|string} [options.port=3000] The port to start the server on.
125
+ * @param {number} [options.staticCacheSize=1.e7] The maximum
126
+ * static cache size in bytes. Defaults to ~10 MB.
127
+ * @param {function} [options.staticCacheController] When given, it activates,
128
+ * and controls the static caching of generated HTML markup. When this function
129
+ * is provided, on each incoming request it is triggered with the request
130
+ * passed in as the argument. To attempt to serve the response from the cache
131
+ * it should return the object with the following fields:
132
+ * - `key: string` &ndash; the cache key for the response;
133
+ * - `maxage?: number` &ndash; the maximum age of cached result in ms.
134
+ * If undefined - infinite age is assumed.
135
+ * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.
136
+ * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,
137
+ * defaults to 1 second.
138
+ * @return Resolves to an object with created Express and HTTP servers.
139
+ */
145
140
  export async function launchServer(webpackConfig, options = {}) {
146
- /* Options normalization. */
147
- const ops = cloneDeep(options);
148
-
149
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
141
+ /* Options normalization. */const ops = cloneDeep(options); // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
150
142
  ops.port = normalizePort(ops.port || process.env.PORT || 3000);
151
143
  defaults(ops, {
152
144
  httpsRedirect: true
153
- });
154
-
155
- // TODO: Need a separate type for normalized options, which guarantees
145
+ }); // TODO: Need a separate type for normalized options, which guarantees
156
146
  // the logger is set!
157
147
  ops.logger ??= newDefaultLogger({
158
148
  defaultLogLevel: ops.defaultLoggerLogLevel
159
- });
160
-
161
- /* Creates servers, resolves and sets the port. */
149
+ }); /* Creates servers, resolves and sets the port. */
162
150
  const expressServer = await serverFactory(webpackConfig, ops);
163
151
  let httpServer;
164
152
  if (ops.https) {
@@ -166,31 +154,25 @@ export async function launchServer(webpackConfig, options = {}) {
166
154
  cert: ops.https.cert,
167
155
  key: ops.https.key
168
156
  }, expressServer);
169
- } else httpServer = http.createServer(expressServer);
170
-
171
- /* Sets error handler for HTTP(S) server. */
172
- httpServer.on('error', error => {
173
- if (error.syscall !== 'listen') throw error;
174
- const bind = typeof ops.port === 'string' ? `Pipe ${ops.port}` : `Port ${ops.port}`;
175
-
176
- /* Human-readable message for some specific listen errors. */
157
+ } else httpServer = http.createServer(expressServer); /* Sets error handler for HTTP(S) server. */
158
+ httpServer.on("error", error => {
159
+ if (error.syscall !== "listen") throw error;
160
+ const bind = typeof ops.port === "string" ? `Pipe ${ops.port}` : `Port ${ops.port}`; /* Human-readable message for some specific listen errors. */
177
161
  switch (error.code) {
178
- case 'EACCES':
162
+ case "EACCES":
179
163
  ops.logger.error(`${bind} requires elevated privileges`);
180
164
  return process.exit(1);
181
- case 'EADDRINUSE':
165
+ case "EADDRINUSE":
182
166
  ops.logger.error(`${bind} is already in use`);
183
167
  return process.exit(1);
184
168
  case undefined:
185
169
  default:
186
170
  throw error;
187
171
  }
188
- });
189
-
190
- /* Listening event handler for HTTP(S) server. */
191
- httpServer.on('listening', () => {
172
+ }); /* Listening event handler for HTTP(S) server. */
173
+ httpServer.on("listening", () => {
192
174
  const addr = httpServer.address();
193
- const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;
175
+ const bind = typeof addr === "string" ? `pipe ${addr}` : `port ${addr.port}`;
194
176
  ops.logger.info(`Server listening on ${bind} in ${process.env.NODE_ENV} mode`);
195
177
  });
196
178
  httpServer.listen(ops.port);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["http","https","cloneDeep","defaults","SCRIPT_LOCATIONS","newDefaultLogger","serverFactory","getDefaultCspSettings","normalizePort","value","port","parseInt","Number","isFinite","launchServer","webpackConfig","options","ops","process","env","PORT","httpsRedirect","logger","defaultLogLevel","defaultLoggerLogLevel","expressServer","httpServer","createServer","cert","key","on","error","syscall","bind","code","exit","undefined","addr","address","info","NODE_ENV","listen"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register.js';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport { cloneDeep, defaults } from 'lodash-es';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill.js';\n\nimport type { Configuration } from 'webpack';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nexport * from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport {\n SCRIPT_LOCATIONS,\n type ServerT,\n getDefaultCspSettings,\n};\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String).\n */\nfunction normalizePort(value: number | string) {\n const port = typeof value === 'string' ? parseInt(value) : value;\n if (Number.isFinite(port)) return port; /* port number */\n return value; /* named pipe */\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` &rArr; `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel='info'] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @return Resolves to an object with created Express and HTTP servers.\n */\nexport async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = typeof ops.port === 'string' ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger!.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger!.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address()!;\n const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger!.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n"],"mappings":"AAAA;AACA,OAAO,gCAAgC;AAEvC,OAAOA,IAAI,MAAM,WAAW;AAC5B,OAAOC,KAAK,MAAM,YAAY;AAE9B,SAASC,SAAS,EAAEC,QAAQ,QAAQ,WAAW;;AAE/C;AACA;AACA;AACA,OAAO,iBAAiB;AAAA,SAIfC,gBAAgB,EAAEC,gBAAgB;AAAA,OAEpCC,aAAa,IAGlBC,qBAAqB;AAAA;AAYvB,SACEH,gBAAgB,EAEhBG,qBAAqB;;AAGvB;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,aAAaA,CAACC,KAAsB,EAAE;EAC7C,MAAMC,IAAI,GAAG,OAAOD,KAAK,KAAK,QAAQ,GAAGE,QAAQ,CAACF,KAAK,CAAC,GAAGA,KAAK;EAChE,IAAIG,MAAM,CAACC,QAAQ,CAACH,IAAI,CAAC,EAAE,OAAOA,IAAI,CAAC,CAAC;EACxC,OAAOD,KAAK,CAAC,CAAC;AAChB;AAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeK,YAAYA,CAChCC,aAA4B,EAC5BC,OAAiB,GAAG,CAAC,CAAC,EAIrB;EACD;EACA,MAAMC,GAAG,GAAGf,SAAS,CAACc,OAAO,CAAC;;EAE9B;EACAC,GAAG,CAACP,IAAI,GAAGF,aAAa,CAACS,GAAG,CAACP,IAAI,IAAIQ,OAAO,CAACC,GAAG,CAACC,IAAI,IAAI,IAAI,CAAC;EAC9DjB,QAAQ,CAACc,GAAG,EAAE;IAAEI,aAAa,EAAE;EAAK,CAAC,CAAC;;EAEtC;EACA;EACAJ,GAAG,CAACK,MAAM,KAAKjB,gBAAgB,CAAC;IAC9BkB,eAAe,EAAEN,GAAG,CAACO;EACvB,CAAC,CAAC;;EAEF;EACA,MAAMC,aAAa,GAAG,MAAMnB,aAAa,CAACS,aAAa,EAAEE,GAAG,CAAC;EAE7D,IAAIS,UAAuB;EAC3B,IAAIT,G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1Cf,OAAO,CAACC,GAAG,CAACqB,QAAQ,OAAO,CAAC;EAChC,CAAC,CAAC;EAEFd,UAAU,CAACe,MAAM,CAACxB,GAAG,CAACP,IAAI,CAAC;EAE3B,OAAO;IACLe,aAAa;IACbC;EACF,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["http","https","cloneDeep","defaults","SCRIPT_LOCATIONS","newDefaultLogger","serverFactory","getDefaultCspSettings","normalizePort","value","port","parseInt","Number","isFinite","launchServer","webpackConfig","options","ops","process","env","PORT","httpsRedirect","logger","defaultLogLevel","defaultLoggerLogLevel","expressServer","httpServer","createServer","cert","key","on","error","syscall","bind","code","exit","undefined","addr","address","info","NODE_ENV","listen"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register.js';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport { cloneDeep, defaults } from 'lodash-es';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill.js';\n\nimport type { Configuration } from 'webpack';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nexport * from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport {\n SCRIPT_LOCATIONS,\n type ServerT,\n getDefaultCspSettings,\n};\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String).\n */\nfunction normalizePort(value: number | string) {\n const port = typeof value === 'string' ? parseInt(value) : value;\n if (Number.isFinite(port)) return port; /* port number */\n return value; /* named pipe */\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` &rArr; `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel='info'] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @return Resolves to an object with created Express and HTTP servers.\n */\nexport async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = typeof ops.port === 'string' ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger!.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger!.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address()!;\n const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger!.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n"],"mappings":"AAAA;AACA,OAAO,gCAAgC;AAEvC,OAAOA,IAAI,MAAM,WAAW;AAC5B,OAAOC,KAAK,MAAM,YAAY;AAE9B,SAASC,SAAS,EAAEC,QAAQ,QAAQ,WAAW,CAE/C;AACA;AACA;AACA,OAAO,iBAAiB;AAIxB,SAASC,gBAAgB,EAAEC,gBAAgB;AAAA,OAEpCC,aAAa,IAGlBC,qBAAqB;AAAA;AAYvB,SACEH,gBAAgB,EAEhBG,qBAAqB,GAGvB;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,aAAaA,CAACC,KAAsB,EAAE;EAC7C,MAAMC,IAAI,GAAG,OAAOD,KAAK,KAAK,QAAQ,GAAGE,QAAQ,CAACF,KAAK,CAAC,GAAGA,KAAK;EAChE,IAAIG,MAAM,CAACC,QAAQ,CAACH,IAAI,CAAC,EAAE,OAAOA,IAAI,CAAE;EACxC,OAAOD,KAAK,CAAE;AAChB,CAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A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