@dr.pogodin/react-utils 1.49.1 → 1.50.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/babel.scripts.config.js +19 -0
  2. package/bin/build.js +274 -164
  3. package/build/development/client/getInj.js +18 -29
  4. package/build/development/client/getInj.js.map +1 -1
  5. package/build/development/client/index.js +11 -14
  6. package/build/development/client/index.js.map +1 -1
  7. package/build/development/client/init.js +9 -17
  8. package/build/development/client/init.js.map +1 -1
  9. package/build/development/index.js +26 -4
  10. package/build/development/index.js.map +1 -1
  11. package/build/development/server/Cache.js +15 -20
  12. package/build/development/server/Cache.js.map +1 -1
  13. package/build/development/server/index.js +142 -160
  14. package/build/development/server/index.js.map +1 -1
  15. package/build/development/server/renderer.js +150 -197
  16. package/build/development/server/renderer.js.map +1 -1
  17. package/build/development/server/server.js +63 -86
  18. package/build/development/server/server.js.map +1 -1
  19. package/build/development/server/utils/errors.js +72 -87
  20. package/build/development/server/utils/errors.js.map +1 -1
  21. package/build/development/shared/components/Button/index.js +8 -17
  22. package/build/development/shared/components/Button/index.js.map +1 -1
  23. package/build/development/shared/components/Checkbox/index.js +4 -4
  24. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  25. package/build/development/shared/components/GenericLink/index.js +54 -58
  26. package/build/development/shared/components/GenericLink/index.js.map +1 -1
  27. package/build/development/shared/components/Input/index.js +16 -24
  28. package/build/development/shared/components/Input/index.js.map +1 -1
  29. package/build/development/shared/components/Link.js +2 -5
  30. package/build/development/shared/components/Link.js.map +1 -1
  31. package/build/development/shared/components/Modal/index.js +28 -41
  32. package/build/development/shared/components/Modal/index.js.map +1 -1
  33. package/build/development/shared/components/NavLink.js +2 -3
  34. package/build/development/shared/components/NavLink.js.map +1 -1
  35. package/build/development/shared/components/PageLayout/index.js +19 -20
  36. package/build/development/shared/components/PageLayout/index.js.map +1 -1
  37. package/build/development/shared/components/TextArea/index.js +12 -28
  38. package/build/development/shared/components/TextArea/index.js.map +1 -1
  39. package/build/development/shared/components/Throbber/index.js +11 -12
  40. package/build/development/shared/components/Throbber/index.js.map +1 -1
  41. package/build/development/shared/components/WithTooltip/Tooltip.js +46 -68
  42. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  43. package/build/development/shared/components/WithTooltip/index.js +21 -28
  44. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  45. package/build/development/shared/components/YouTubeVideo/index.js +21 -25
  46. package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
  47. package/build/development/shared/components/index.js +1 -3
  48. package/build/development/shared/components/index.js.map +1 -1
  49. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +6 -7
  50. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  51. package/build/development/shared/components/selectors/CustomDropdown/index.js +7 -9
  52. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  53. package/build/development/shared/components/selectors/NativeDropdown/index.js +23 -27
  54. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  55. package/build/development/shared/components/selectors/Switch/index.js +4 -4
  56. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  57. package/build/development/shared/components/selectors/common.js +2 -5
  58. package/build/development/shared/components/selectors/common.js.map +1 -1
  59. package/build/development/shared/utils/config.js +11 -15
  60. package/build/development/shared/utils/config.js.map +1 -1
  61. package/build/development/shared/utils/globalState.js +1 -7
  62. package/build/development/shared/utils/globalState.js.map +1 -1
  63. package/build/development/shared/utils/index.js +2 -2
  64. package/build/development/shared/utils/index.js.map +1 -1
  65. package/build/development/shared/utils/isomorphy/buildInfo.js +15 -24
  66. package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
  67. package/build/development/shared/utils/isomorphy/environment-check.js +4 -9
  68. package/build/development/shared/utils/isomorphy/environment-check.js.map +1 -1
  69. package/build/development/shared/utils/isomorphy/index.js +17 -23
  70. package/build/development/shared/utils/isomorphy/index.js.map +1 -1
  71. package/build/development/shared/utils/jest/E2eSsrEnv.js +48 -77
  72. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  73. package/build/development/shared/utils/jest/index.js +48 -72
  74. package/build/development/shared/utils/jest/index.js.map +1 -1
  75. package/build/development/shared/utils/splitComponent.js +67 -74
  76. package/build/development/shared/utils/splitComponent.js.map +1 -1
  77. package/build/development/shared/utils/time.js +25 -28
  78. package/build/development/shared/utils/time.js.map +1 -1
  79. package/build/development/shared/utils/webpack.js +22 -29
  80. package/build/development/shared/utils/webpack.js.map +1 -1
  81. package/build/production/client/getInj.js.map +1 -1
  82. package/build/production/client/index.js.map +1 -1
  83. package/build/production/index.js +26 -1
  84. package/build/production/index.js.map +1 -1
  85. package/build/production/server/Cache.js.map +1 -1
  86. package/build/production/server/index.js.map +1 -1
  87. package/build/production/server/renderer.js.map +1 -1
  88. package/build/production/server/server.js.map +1 -1
  89. package/build/production/shared/components/Button/index.js.map +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/GenericLink/index.d.ts +0 -1
  115. package/build/web/client/getInj.js +10 -70
  116. package/build/web/client/getInj.js.map +1 -1
  117. package/build/web/client/index.js +2 -27
  118. package/build/web/client/index.js.map +1 -1
  119. package/build/web/client/init.js +10 -44
  120. package/build/web/client/init.js.map +1 -1
  121. package/build/web/index.js +26 -6
  122. package/build/web/index.js.map +1 -1
  123. package/build/web/server/Cache.js +3 -41
  124. package/build/web/server/Cache.js.map +1 -1
  125. package/build/web/server/index.js +7 -78
  126. package/build/web/server/index.js.map +1 -1
  127. package/build/web/server/renderer.js +61 -420
  128. package/build/web/server/renderer.js.map +1 -1
  129. package/build/web/server/server.js +38 -212
  130. package/build/web/server/server.js.map +1 -1
  131. package/build/web/server/utils/errors.js +9 -48
  132. package/build/web/server/utils/errors.js.map +1 -1
  133. package/build/web/server/utils/index.js +1 -2
  134. package/build/web/server/utils/index.js.map +1 -1
  135. package/build/web/shared/components/Button/index.js +12 -101
  136. package/build/web/shared/components/Button/index.js.map +1 -1
  137. package/build/web/shared/components/Checkbox/index.js +1 -40
  138. package/build/web/shared/components/Checkbox/index.js.map +1 -1
  139. package/build/web/shared/components/Checkbox/theme.scss +1 -0
  140. package/build/web/shared/components/GenericLink/index.js +12 -65
  141. package/build/web/shared/components/GenericLink/index.js.map +1 -1
  142. package/build/web/shared/components/GenericLink/style.scss +1 -0
  143. package/build/web/shared/components/Input/index.js +11 -69
  144. package/build/web/shared/components/Input/index.js.map +1 -1
  145. package/build/web/shared/components/Link.js +2 -12
  146. package/build/web/shared/components/Link.js.map +1 -1
  147. package/build/web/shared/components/Modal/index.js +10 -130
  148. package/build/web/shared/components/Modal/index.js.map +1 -1
  149. package/build/web/shared/components/NavLink.js +2 -10
  150. package/build/web/shared/components/NavLink.js.map +1 -1
  151. package/build/web/shared/components/PageLayout/index.js +2 -27
  152. package/build/web/shared/components/PageLayout/index.js.map +1 -1
  153. package/build/web/shared/components/TextArea/index.js +21 -106
  154. package/build/web/shared/components/TextArea/index.js.map +1 -1
  155. package/build/web/shared/components/Throbber/index.js +2 -24
  156. package/build/web/shared/components/Throbber/index.js.map +1 -1
  157. package/build/web/shared/components/WithTooltip/Tooltip.js +16 -145
  158. package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -1
  159. package/build/web/shared/components/WithTooltip/index.js +12 -104
  160. package/build/web/shared/components/WithTooltip/index.js.map +1 -1
  161. package/build/web/shared/components/YouTubeVideo/index.js +5 -43
  162. package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
  163. package/build/web/shared/components/index.js +1 -15
  164. package/build/web/shared/components/index.js.map +1 -1
  165. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +6 -81
  166. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  167. package/build/web/shared/components/selectors/CustomDropdown/index.js +7 -122
  168. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  169. package/build/web/shared/components/selectors/NativeDropdown/index.js +7 -68
  170. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  171. package/build/web/shared/components/selectors/Switch/index.js +1 -49
  172. package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
  173. package/build/web/shared/components/selectors/common.js +1 -10
  174. package/build/web/shared/components/selectors/common.js.map +1 -1
  175. package/build/web/shared/components/selectors/index.js +1 -3
  176. package/build/web/shared/components/selectors/index.js.map +1 -1
  177. package/build/web/shared/utils/config.js +6 -40
  178. package/build/web/shared/utils/config.js.map +1 -1
  179. package/build/web/shared/utils/globalState.js +2 -11
  180. package/build/web/shared/utils/globalState.js.map +1 -1
  181. package/build/web/shared/utils/index.js +1 -9
  182. package/build/web/shared/utils/index.js.map +1 -1
  183. package/build/web/shared/utils/isomorphy/buildInfo.js +4 -25
  184. package/build/web/shared/utils/isomorphy/buildInfo.js.map +1 -1
  185. package/build/web/shared/utils/isomorphy/environment-check.js +3 -9
  186. package/build/web/shared/utils/isomorphy/environment-check.js.map +1 -1
  187. package/build/web/shared/utils/isomorphy/index.js +5 -27
  188. package/build/web/shared/utils/isomorphy/index.js.map +1 -1
  189. package/build/web/shared/utils/jest/E2eSsrEnv.js +51 -221
  190. package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  191. package/build/web/shared/utils/jest/global.js +1 -3
  192. package/build/web/shared/utils/jest/global.js.map +1 -1
  193. package/build/web/shared/utils/jest/index.js +27 -146
  194. package/build/web/shared/utils/jest/index.js.map +1 -1
  195. package/build/web/shared/utils/splitComponent.js +34 -197
  196. package/build/web/shared/utils/splitComponent.js.map +1 -1
  197. package/build/web/shared/utils/time.js +5 -69
  198. package/build/web/shared/utils/time.js.map +1 -1
  199. package/build/web/shared/utils/webpack.js +6 -53
  200. package/build/web/shared/utils/webpack.js.map +1 -1
  201. package/config/babel/webpack.js +1 -1
  202. package/eslint.config.mjs +1 -0
  203. package/package.json +5 -8
  204. package/config/webpack/lib-base.d.ts +0 -22
  205. package/config/webpack/lib-base.js +0 -167
  206. package/config/webpack/lib-development.d.ts +0 -5
  207. package/config/webpack/lib-development.js +0 -35
  208. package/config/webpack/lib-production.d.ts +0 -5
  209. package/config/webpack/lib-production.js +0 -42
  210. package/webpack.config.ts +0 -49
@@ -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,GAAG,CAAChB,KAAK,EAAE;IACbyB,UAAU,GAAGzB,KAAK,CAAC0B,YAAY,CAAC;MAC9BC,IAAI,EAAEX,GAAG,CAAChB,KAAK,CAAC2B,IAAI;MACpBC,GAAG,EAAEZ,GAAG,CAAChB,KAAK,CAAC4B;IACjB,CAAC,EAAEJ,aAAsC,CAAC;EAC5C,CAAC,MAAMC,UAAU,GAAG1B,IAAI,CAAC2B,YAAY,CAACF,aAAsC,CAAC;;EAE7E;EACAC,UAAU,CAACI,EAAE,CAAC,OAAO,EAAGC,KAAY,IAAK;IACvC,IAAKA,KAAK,CAA0BC,OAAO,KAAK,QAAQ,EAAE,MAAMD,KAAK;IACrE,MAAME,IAAI,GAAG,OAAOhB,GAAG,CAACP,IAAI,KAAK,QAAQ,GAAG,QAAQO,GAAG,CAACP,IAAI,EAAE,GAAG,QAAQO,GAAG,CAACP,IAAI,EAAE;;IAEnF;IACA,QAASqB,KAAK,CAAuBG,IAAI;MACvC,KAAK,QAAQ;QACXjB,GAAG,CAACK,MAAM,CAAES,KAAK,CAAC,GAAGE,IAAI,+BAA+B,CAAC;QACzD,OAAOf,OAAO,CAACiB,IAAI,CAAC,CAAC,CAAC;MACxB,KAAK,YAAY;QACflB,GAAG,CAACK,MAAM,CAAES,KAAK,CAAC,GAAGE,IAAI,oBAAoB,CAAC;QAC9C,OAAOf,OAAO,CAACiB,IAAI,CAAC,CAAC,CAAC;MACxB,KAAKC,SAAS;MACd;QACE,MAAML,KAAK;IACf;EACF,CAAC,CAAC;;EAEF;EACAL,UAAU,CAACI,EAAE,CAAC,WAAW,EAAE,MAAM;IAC/B,MAAMO,IAAI,GAAGX,UAAU,CAACY,OAAO,CAAC,CAAE;IAClC,MAAML,IAAI,GAAG,OAAOI,IAAI,KAAK,QAAQ,GAAG,QAAQA,IAAI,EAAE,GAAG,QAAQA,IAAI,CAAC3B,IAAI,EAAE;IAC5EO,GAAG,CAACK,MAAM,CAAEiB,IAAI,CAAC,uBAAuBN,IAAI,OAC1Cf,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;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,4BACA,MAAMC,GAAG,GAAGf,SAAS,CAACc,OAAO,CAAC,CAE9B;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,CAEtC;EACA;EACAJ,GAAG,CAACK,MAAM,KAAKjB,gBAAgB,CAAC;IAC9BkB,eAAe,EAAEN,GAAG,CAACO;EACvB,CAAC,CAAC,CAEF;EACA,MAAMC,aAAa,GAAG,MAAMnB,aAAa,CAACS,aAAa,EAAEE,GAAG,CAAC;EAE7D,IAAIS,UAAuB;EAC3B,IAAIT,GAAG,CAAChB,KAAK,EAAE;IACbyB,UAAU,GAAGzB,KAAK,CAAC0B,YAAY,CAAC;MAC9BC,IAAI,EAAEX,GAAG,CAAChB,KAAK,CAAC2B,IAAI;MACpBC,GAAG,EAAEZ,GAAG,CAAChB,KAAK,CAAC4B;IACjB,CAAC,EAAEJ,aAAsC,CAAC;EAC5C,CAAC,MAAMC,UAAU,GAAG1B,IAAI,CAAC2B,YAAY,CAACF,aAAsC,CAAC,CAE7E;EACAC,UAAU,CAACI,EAAE,CAAC,OAAO,EAAGC,KAAY,IAAK;IACvC,IAAKA,KAAK,CAA0BC,OAAO,KAAK,QAAQ,EAAE,MAAMD,KAAK;IACrE,MAAME,IAAI,GAAG,OAAOhB,GAAG,CAACP,IAAI,KAAK,QAAQ,GAAG,QAAQO,GAAG,CAACP,IAAI,EAAE,GAAG,QAAQO,GAAG,CAACP,IAAI,EAAE,CAEnF;IACA,QAASqB,KAAK,CAAuBG,IAAI;MACvC,KAAK,QAAQ;QACXjB,GAAG,CAACK,MAAM,CAAES,KAAK,CAAC,GAAGE,IAAI,+BAA+B,CAAC;QACzD,OAAOf,OAAO,CAACiB,IAAI,CAAC,CAAC,CAAC;MACxB,KAAK,YAAY;QACflB,GAAG,CAACK,MAAM,CAAES,KAAK,CAAC,GAAGE,IAAI,oBAAoB,CAAC;QAC9C,OAAOf,OAAO,CAACiB,IAAI,CAAC,CAAC,CAAC;MACxB,KAAKC,SAAS;MACd;QACE,MAAML,KAAK;IACf;EACF,CAAC,CAAC,CAEF;EACAL,UAAU,CAACI,EAAE,CAAC,WAAW,EAAE,MAAM;IAC/B,MAAMO,IAAI,GAAGX,UAAU,CAACY,OAAO,CAAC,CAAE;IAClC,MAAML,IAAI,GAAG,OAAOI,IAAI,KAAK,QAAQ,GAAG,QAAQA,IAAI,EAAE,GAAG,QAAQA,IAAI,CAAC3B,IAAI,EAAE;IAC5EO,GAAG,CAACK,MAAM,CAAEiB,IAAI,CAAC,uBAAuBN,IAAI,OAC1Cf,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":[]}
@@ -16,26 +16,24 @@ import "core-js/modules/es.set.is-disjoint-from.v2.js";
16
16
  import "core-js/modules/es.set.is-subset-of.v2.js";
17
17
  import "core-js/modules/es.set.is-superset-of.v2.js";
18
18
  import "core-js/modules/es.set.symmetric-difference.v2.js";
19
- import "core-js/modules/es.set.union.v2.js";
20
- /**
21
- * ExpressJS middleware for server-side rendering of a ReactJS app.
22
- */
23
-
24
- import { Buffer } from 'node:buffer';
25
- import { createCipheriv, randomBytes } from 'node:crypto';
26
- import fs from 'node:fs';
27
- import path from 'node:path';
28
- import { Writable } from 'node:stream';
29
- import { brotliCompress, brotliDecompress } from 'node:zlib';
30
- import config from 'config';
31
- import { cloneDeep, defaults, get, mapValues } from 'lodash-es';
32
- import { prerenderToNodeStream } from 'react-dom/static';
33
- import { StaticRouter } from 'react-router';
34
- import serializeJs from 'serialize-javascript';
35
- import winston from 'winston';
36
- import { timer } from '@dr.pogodin/js-utils';
37
- import { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';
38
- import { HelmetProvider } from '@dr.pogodin/react-helmet';
19
+ import "core-js/modules/es.set.union.v2.js"; /**
20
+ * ExpressJS middleware for server-side rendering of a ReactJS app.
21
+ */
22
+ import { Buffer } from "node:buffer";
23
+ import { createCipheriv, randomBytes } from "node:crypto";
24
+ import fs from "node:fs";
25
+ import path from "node:path";
26
+ import { Writable } from "node:stream";
27
+ import { brotliCompress, brotliDecompress } from "node:zlib";
28
+ import config from "config";
29
+ import { cloneDeep, defaults, get, mapValues } from "lodash-es";
30
+ import { prerenderToNodeStream } from "react-dom/static";
31
+ import { StaticRouter } from "react-router";
32
+ import serializeJs from "serialize-javascript";
33
+ import winston from "winston";
34
+ import { timer } from "@dr.pogodin/js-utils";
35
+ import { GlobalStateProvider, SsrContext } from "@dr.pogodin/react-global-state";
36
+ import { HelmetProvider } from "@dr.pogodin/react-helmet";
39
37
  import { setBuildInfo } from "../shared/utils/isomorphy/buildInfo.js";
40
38
  import Cache from "./Cache.js"; // @ts-expect-error "Property 'SECRET' does not exist on type 'IConfig'."
41
39
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -43,17 +41,12 @@ import { jsx as _jsx } from "react/jsx-runtime";
43
41
  const {
44
42
  SECRET,
45
43
  ...sanitizedConfig
46
- } = config.util.toObject(config);
47
-
48
- // Note: These type definitions for logger are copied from Winston logger,
44
+ } = config.util.toObject(config); // Note: These type definitions for logger are copied from Winston logger,
49
45
  // then simplified to make it easier to fit an alternative logger into this
50
46
  // interface.
51
47
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
52
-
53
48
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
54
-
55
49
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
56
-
57
50
  export let SCRIPT_LOCATIONS = /*#__PURE__*/function (SCRIPT_LOCATIONS) {
58
51
  SCRIPT_LOCATIONS["BODY_OPEN"] = "BODY_OPEN";
59
52
  SCRIPT_LOCATIONS["DEFAULT"] = "DEFAULT";
@@ -68,111 +61,100 @@ export class ServerSsrContext extends SsrContext {
68
61
  this.chunkGroups = chunkGroups;
69
62
  this.req = req;
70
63
  }
71
- }
72
- /**
73
- * Reads build-time information about the app. This information is generated
74
- * by our standard Webpack config for apps, and it is written into
75
- * ".build-info" file in the context folder specified in Webpack config.
76
- * At the moment, that file contains build timestamp and a random 32-bit key,
77
- * suitable for cryptographical use.
78
- * @param context Webpack context path used during the build.
79
- * @return Resolves to the build-time information.
80
- */
64
+ } /**
65
+ * Reads build-time information about the app. This information is generated
66
+ * by our standard Webpack config for apps, and it is written into
67
+ * ".build-info" file in the context folder specified in Webpack config.
68
+ * At the moment, that file contains build timestamp and a random 32-bit key,
69
+ * suitable for cryptographical use.
70
+ * @param context Webpack context path used during the build.
71
+ * @return Resolves to the build-time information.
72
+ */
81
73
  function getBuildInfo(context) {
82
- const url = path.resolve(context, '.build-info');
83
- return JSON.parse(fs.readFileSync(url, 'utf8'));
84
- }
85
-
86
- /**
87
- * Attempts to read from disk the named chunk groups mapping generated
88
- * by Webpack during the compilation.
89
- * It will not work for development builds, where these stats should be captured
90
- * via compilator callback.
91
- * @param buildDir
92
- * @return
93
- */
74
+ const url = path.resolve(context, ".build-info");
75
+ return JSON.parse(fs.readFileSync(url, "utf8"));
76
+ } /**
77
+ * Attempts to read from disk the named chunk groups mapping generated
78
+ * by Webpack during the compilation.
79
+ * It will not work for development builds, where these stats should be captured
80
+ * via compilator callback.
81
+ * @param buildDir
82
+ * @return
83
+ */
94
84
  function readChunkGroupsJson(buildDir) {
95
- const url = path.resolve(buildDir, '__chunk_groups__.json');
85
+ const url = path.resolve(buildDir, "__chunk_groups__.json");
96
86
  let res;
97
87
  try {
98
- res = JSON.parse(fs.readFileSync(url, 'utf8'));
88
+ res = JSON.parse(fs.readFileSync(url, "utf8"));
99
89
  } catch {
100
90
  // TODO: Should we message the error here somehow?
101
91
  res = null;
102
92
  }
103
93
  return res;
104
- }
105
-
106
- /**
107
- * Prepares a new Cipher for data encryption.
108
- * @param key Encryption key (32-bit random, Base64-encoded key is expected).
109
- * @return Returns a tuple of:
110
- * 1. cipher - a new Cipher, ready for encryption;
111
- * 2. iv - initial vector used by the cipher.
112
- */
94
+ } /**
95
+ * Prepares a new Cipher for data encryption.
96
+ * @param key Encryption key (32-bit random, Base64-encoded key is expected).
97
+ * @return Returns a tuple of:
98
+ * 1. cipher - a new Cipher, ready for encryption;
99
+ * 2. iv - initial vector used by the cipher.
100
+ */
113
101
  function prepareCipher(key) {
114
102
  const iv = randomBytes(16);
115
- const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);
103
+ const cipher = createCipheriv("AES-256-CBC", Buffer.from(key, "base64"), iv);
116
104
  return [cipher, iv];
117
- }
118
-
119
- /**
120
- * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses
121
- * are acceptable to the caller.
122
- * @param req
123
- */
105
+ } /**
106
+ * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses
107
+ * are acceptable to the caller.
108
+ * @param req
109
+ */
124
110
  export function isBrotliAcceptable(req) {
125
- const acceptable = req.get('accept-encoding');
111
+ const acceptable = req.get("accept-encoding");
126
112
  if (acceptable) {
127
- const ops = acceptable.split(',');
113
+ const ops = acceptable.split(",");
128
114
  for (const op of ops) {
129
- const [type, priority] = op.trim().split(';q=');
130
- if ((type === '*' || type === 'br') && (!priority || parseFloat(priority) > 0)) {
115
+ const [type, priority] = op.trim().split(";q=");
116
+ if ((type === "*" || type === "br") && (!priority || parseFloat(priority) > 0)) {
131
117
  return true;
132
118
  }
133
119
  }
134
120
  }
135
121
  return false;
136
- }
137
-
138
- /**
139
- * Given an array of extra script strings / objects, it returns an object with
140
- * arrays of scripts to inject in different HTML template locations. During
141
- * the script groupping it also filters out any empty scripts.
142
- * @param {({
143
- * code: string;
144
- * location: string;
145
- * }|string)[]} [scripts=[]]
146
- * @return {{
147
- * BODY_OPEN: string[];
148
- * DEFAULT: string[];
149
- * HEAD_OPEN: string[];
150
- * }}
151
- */
122
+ } /**
123
+ * Given an array of extra script strings / objects, it returns an object with
124
+ * arrays of scripts to inject in different HTML template locations. During
125
+ * the script groupping it also filters out any empty scripts.
126
+ * @param {({
127
+ * code: string;
128
+ * location: string;
129
+ * }|string)[]} [scripts=[]]
130
+ * @return {{
131
+ * BODY_OPEN: string[];
132
+ * DEFAULT: string[];
133
+ * HEAD_OPEN: string[];
134
+ * }}
135
+ */
152
136
  function groupExtraScripts(scripts = []) {
153
137
  const res = {
154
- [SCRIPT_LOCATIONS.BODY_OPEN]: '',
155
- [SCRIPT_LOCATIONS.DEFAULT]: '',
156
- [SCRIPT_LOCATIONS.HEAD_OPEN]: ''
138
+ [SCRIPT_LOCATIONS.BODY_OPEN]: "",
139
+ [SCRIPT_LOCATIONS.DEFAULT]: "",
140
+ [SCRIPT_LOCATIONS.HEAD_OPEN]: ""
157
141
  };
158
142
  for (const script of scripts) {
159
- if (typeof script === 'string') {
143
+ if (typeof script === "string") {
160
144
  if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;
161
145
  } else if (script.code) {
162
146
  if (script.location in res) res[script.location] += script.code;else throw Error(`Invalid location "${script.location}"`);
163
147
  }
164
148
  }
165
149
  return res;
166
- }
167
-
168
- /**
169
- * Creates a new default (Winston) logger.
170
- * @param {object} [options={}]
171
- * @param {string} [options.defaultLogLevel='info']
172
- * @return {object}
173
- */
150
+ } /**
151
+ * Creates a new default (Winston) logger.
152
+ * @param {object} [options={}]
153
+ * @param {string} [options.defaultLogLevel='info']
154
+ * @return {object}
155
+ */
174
156
  export function newDefaultLogger({
175
- defaultLogLevel = 'info'
157
+ defaultLogLevel = "info"
176
158
  } = {}) {
177
159
  const {
178
160
  format,
@@ -196,38 +178,37 @@ export function newDefaultLogger({
196
178
  level: defaultLogLevel,
197
179
  transports: [new transports.Console()]
198
180
  });
199
- }
200
- /**
201
- * Creates the middleware.
202
- * @param webpackConfig
203
- * @param options Additional options:
204
- * @param [options.Application] The root ReactJS component of
205
- * the app to use for the server-side rendering. When not provided
206
- * the server-side rendering is disabled.
207
- * @param [options.buildInfo] "Build info" object to use. If provided,
208
- * it will be used, instead of trying to load from the filesystem the one
209
- * generated by the Webpack build. It is intended for test environments,
210
- * where passing this stuff via file system is no bueno.
211
- * @param [options.favicon] `true` will include favicon
212
- * link into the rendered HTML templates.
213
- * @param [options.noCsp] `true` means that no
214
- * Content-Security-Policy (CSP) is used by server, thus the renderer
215
- * may cut a few corners.
216
- * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.
217
- * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,
218
- * defaults to 1 second.
219
- * @param [options.staticCacheSize=1.e7] The maximum
220
- * static cache size in bytes. Defaults to ~10 MB.
221
- * @param [options.staticCacheController] When given, it activates,
222
- * and controls the static caching of generated HTML markup. When this function
223
- * is provided, on each incoming request it is triggered with the request
224
- * passed in as the argument. To attempt to serve the response from the cache
225
- * it should return the object with the following fields:
226
- * - `key: string` &ndash; the cache key for the response;
227
- * - `maxage?: number` &ndash; the maximum age of cached result in ms.
228
- * If undefined - infinite age is assumed.
229
- * @return Created middleware.
230
- */
181
+ } /**
182
+ * Creates the middleware.
183
+ * @param webpackConfig
184
+ * @param options Additional options:
185
+ * @param [options.Application] The root ReactJS component of
186
+ * the app to use for the server-side rendering. When not provided
187
+ * the server-side rendering is disabled.
188
+ * @param [options.buildInfo] "Build info" object to use. If provided,
189
+ * it will be used, instead of trying to load from the filesystem the one
190
+ * generated by the Webpack build. It is intended for test environments,
191
+ * where passing this stuff via file system is no bueno.
192
+ * @param [options.favicon] `true` will include favicon
193
+ * link into the rendered HTML templates.
194
+ * @param [options.noCsp] `true` means that no
195
+ * Content-Security-Policy (CSP) is used by server, thus the renderer
196
+ * may cut a few corners.
197
+ * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.
198
+ * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,
199
+ * defaults to 1 second.
200
+ * @param [options.staticCacheSize=1.e7] The maximum
201
+ * static cache size in bytes. Defaults to ~10 MB.
202
+ * @param [options.staticCacheController] When given, it activates,
203
+ * and controls the static caching of generated HTML markup. When this function
204
+ * is provided, on each incoming request it is triggered with the request
205
+ * passed in as the argument. To attempt to serve the response from the cache
206
+ * it should return the object with the following fields:
207
+ * - `key: string` &ndash; the cache key for the response;
208
+ * - `maxage?: number` &ndash; the maximum age of cached result in ms.
209
+ * If undefined - infinite age is assumed.
210
+ * @return Created middleware.
211
+ */
231
212
  export default function factory(webpackConfig, options) {
232
213
  const ops = defaults({
233
214
  ...options
@@ -236,36 +217,27 @@ export default function factory(webpackConfig, options) {
236
217
  maxSsrRounds: 10,
237
218
  ssrTimeout: 1000,
238
219
  staticCacheSize: 1.e7
239
- });
240
-
241
- // Note: in normal use the default logger is created and set in the root
220
+ }); // Note: in normal use the default logger is created and set in the root
242
221
  // server function, and this initialization is for testing uses, where
243
222
  // renderer is imported directly.
244
223
  ops.logger ??= newDefaultLogger({
245
224
  defaultLogLevel: ops.defaultLoggerLogLevel
246
225
  });
247
226
  const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context);
248
- setBuildInfo(buildInfo);
249
-
250
- // publicPath from webpack.output has a trailing slash at the end.
227
+ setBuildInfo(buildInfo); // publicPath from webpack.output has a trailing slash at the end.
251
228
  const {
252
229
  path: outputPath,
253
230
  publicPath
254
231
  } = webpackConfig.output;
255
- const manifestLink = fs.existsSync(`${outputPath}/manifest.json`) ? `<link rel="manifest" href="${publicPath}manifest.json">` : '';
256
-
257
- // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
258
-
232
+ const manifestLink = fs.existsSync(`${outputPath}/manifest.json`) ? `<link rel="manifest" href="${publicPath}manifest.json">` : ""; // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
259
233
  const cache = ops.staticCacheController ? new Cache(ops.staticCacheSize) : null;
260
- const CHUNK_GROUPS = readChunkGroupsJson(outputPath);
261
-
262
- // TODO: Look at it later.
234
+ const CHUNK_GROUPS = readChunkGroupsJson(outputPath); // TODO: Look at it later.
263
235
  // eslint-disable-next-line complexity
264
236
  return async (req, res, next) => {
265
237
  try {
266
238
  // Ensures any caches always revalidate HTML markup before reuse.
267
- res.set('Cache-Control', 'no-cache');
268
- res.cookie('csrfToken', req.csrfToken());
239
+ res.set("Cache-Control", "no-cache");
240
+ res.cookie("csrfToken", req.csrfToken());
269
241
  let cacheRef;
270
242
  if (cache) {
271
243
  cacheRef = ops.staticCacheController(req);
@@ -277,8 +249,8 @@ export default function factory(webpackConfig, options) {
277
249
  status
278
250
  } = data;
279
251
  if (ops.noCsp && isBrotliAcceptable(req)) {
280
- res.set('Content-Type', 'text/html');
281
- res.set('Content-Encoding', 'br');
252
+ res.set("Content-Type", "text/html");
253
+ res.set("Content-Encoding", "br");
282
254
  if (status !== 200) res.status(status);
283
255
  res.send(buffer);
284
256
  } else {
@@ -290,9 +262,7 @@ export default function factory(webpackConfig, options) {
290
262
  // TODO: Starting from Node v15 we'll be able to use string's
291
263
  // .replaceAll() method instead relying on reg. expression for
292
264
  // global matching.
293
- const regex = new RegExp(buffer.nonce, 'g');
294
-
295
- // TODO: It should be implemented more careful.
265
+ const regex = new RegExp(buffer.nonce, "g"); // TODO: It should be implemented more careful.
296
266
  h = h.replace(regex, req.nonce);
297
267
  }
298
268
  if (status !== 200) res.status(status);
@@ -313,14 +283,12 @@ export default function factory(webpackConfig, options) {
313
283
  initialState
314
284
  } = await brr;
315
285
  const [cipher, iv] = prepareCipher(buildInfo.key);
316
- let helmet;
317
-
318
- // Gets the mapping between code chunk names and their asset files.
286
+ let helmet; // Gets the mapping between code chunk names and their asset files.
319
287
  // These data come from the Webpack compilation, either from the stats
320
288
  // attached to the request (in dev mode), or from a file output during
321
289
  // the build (in prod mode).
322
290
  let chunkGroups;
323
- const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');
291
+ const webpackStats = get(res.locals, "webpack.devMiddleware.stats");
324
292
  if (webpackStats) {
325
293
  chunkGroups = mapValues(webpackStats.toJson({
326
294
  all: false,
@@ -328,23 +296,17 @@ export default function factory(webpackConfig, options) {
328
296
  }).namedChunkGroups, item => item.assets?.map(({
329
297
  name
330
298
  }) => name) ?? []);
331
- } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;else chunkGroups = {};
332
-
333
- /* Optional server-side rendering. */
299
+ } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;else chunkGroups = {}; /* Optional server-side rendering. */
334
300
  const App = ops.Application;
335
- let appHtmlMarkup = '';
301
+ let appHtmlMarkup = "";
336
302
  const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);
337
303
  let stream;
338
304
  if (App) {
339
- const ssrStart = Date.now();
340
-
341
- // TODO: Somehow, without it TS does not realise that
305
+ const ssrStart = Date.now(); // TODO: Somehow, without it TS does not realise that
342
306
  // App has been checked to exist.
343
307
  const App2 = App;
344
308
  const renderPass = async () => new Promise((resolveArg, rejectArg) => {
345
- ssrContext.chunks = [];
346
-
347
- // NOTE: JS does not have problems if resolve() and reject() methods
309
+ ssrContext.chunks = []; // NOTE: JS does not have problems if resolve() and reject() methods
348
310
  // of a Promise are called multiple times, with different arguments;
349
311
  // it only respects the first call, and ignores subsequent ones.
350
312
  // We, however, really want to assert that here, to safeguard against
@@ -352,19 +314,17 @@ export default function factory(webpackConfig, options) {
352
314
  // if any.
353
315
  let error;
354
316
  const resolve = arg => {
355
- if (error !== undefined) throw Error('Internal error');
317
+ if (error !== undefined) throw Error("Internal error");
356
318
  error = null;
357
319
  resolveArg(arg);
358
320
  };
359
321
  const reject = arg => {
360
322
  if (error !== undefined && error !== arg) {
361
- throw Error('Internal error');
323
+ throw Error("Internal error");
362
324
  }
363
325
  error = arg;
364
326
  rejectArg(arg);
365
- };
366
-
367
- // TODO: prerenderToNodeStream has (abort) "signal" option,
327
+ }; // TODO: prerenderToNodeStream has (abort) "signal" option,
368
328
  // and we should wire it up to the SSR timeout below.
369
329
  const helmetContext = {};
370
330
  void prerenderToNodeStream(/*#__PURE__*/_jsx(GlobalStateProvider, {
@@ -403,7 +363,7 @@ export default function factory(webpackConfig, options) {
403
363
  stream = await renderPass();
404
364
  logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)` : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;
405
365
  } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;
406
- ops.logger.log(ssrContext.dirty ? 'warn' : 'info', logMsg);
366
+ ops.logger.log(ssrContext.dirty ? "warn" : "info", logMsg);
407
367
  if (ssrContext.redirectTo) {
408
368
  res.redirect(ssrContext.status, ssrContext.redirectTo);
409
369
  return;
@@ -417,13 +377,11 @@ export default function factory(webpackConfig, options) {
417
377
  }
418
378
  }));
419
379
  });
420
- }
421
-
422
- /* Encrypts data to be injected into HTML.
423
- * Keep in mind, that this encryption is no way secure: as the JS bundle
424
- * contains decryption key and is able to decode it at the client side.
425
- * Hovewer, for a number of reasons, encryption of injected data is still
426
- * better than injection of a plain text. */
380
+ } /* Encrypts data to be injected into HTML.
381
+ * Keep in mind, that this encryption is no way secure: as the JS bundle
382
+ * contains decryption key and is able to decode it at the client side.
383
+ * Hovewer, for a number of reasons, encryption of injected data is still
384
+ * better than injection of a plain text. */
427
385
  const payload = serializeJs({
428
386
  CHUNK_GROUPS: chunkGroups,
429
387
  CONFIG: configToInject ?? sanitizedConfig,
@@ -432,10 +390,8 @@ export default function factory(webpackConfig, options) {
432
390
  ignoreFunction: true,
433
391
  unsafe: true
434
392
  });
435
- const INJ = Buffer.concat([iv, cipher.update(payload, 'utf8'), cipher.final()]).toString('base64');
436
- const chunkSet = new Set();
437
-
438
- // TODO: "main" chunk has to be added explicitly,
393
+ const INJ = Buffer.concat([iv, cipher.update(payload, "utf8"), cipher.final()]).toString("base64");
394
+ const chunkSet = new Set(); // TODO: "main" chunk has to be added explicitly,
439
395
  // because unlike all other chunks they are not managed by <CodeSplit>
440
396
  // component, thus they are not added to the ssrContext.chunks
441
397
  // automatically. Actually, names of these entry chunks should be
@@ -443,7 +399,7 @@ export default function factory(webpackConfig, options) {
443
399
  // remove or add other entry points, but it requires additional
444
400
  // efforts to figure out how to automatically order them right,
445
401
  // thus for now this handles the default config.
446
- ['main', ...ssrContext.chunks].forEach(chunk => {
402
+ ["main", ...ssrContext.chunks].forEach(chunk => {
447
403
  const assets = chunkGroups[chunk];
448
404
  if (assets) {
449
405
  assets.forEach(asset => {
@@ -451,29 +407,28 @@ export default function factory(webpackConfig, options) {
451
407
  });
452
408
  }
453
409
  });
454
- let styleChunkString = '';
455
- let scriptChunkString = '';
410
+ let styleChunkString = "";
411
+ let scriptChunkString = "";
456
412
  chunkSet.forEach(chunk => {
457
- if (chunk.endsWith('.css')) {
413
+ if (chunk.endsWith(".css")) {
458
414
  styleChunkString += `<link href="${publicPath}${chunk}" rel="stylesheet">`;
459
- } else if (chunk.endsWith('.js')
460
- // In dev mode HMR adds JS updates into asset arrays,
415
+ } else if (chunk.endsWith(".js") // In dev mode HMR adds JS updates into asset arrays,
461
416
  // and they (updates) should be ignored.
462
- && !chunk.endsWith('.hot-update.js')) {
417
+ && !chunk.endsWith(".hot-update.js")) {
463
418
  scriptChunkString += `<script src="${publicPath}${chunk}" type="application/javascript"></script>`;
464
419
  }
465
420
  });
466
421
  const grouppedExtraScripts = groupExtraScripts(extraScripts);
467
- const faviconLink = ops.favicon ? '<link rel="shortcut icon" href="/favicon.ico">' : '';
422
+ const faviconLink = ops.favicon ? "<link rel=\"shortcut icon\" href=\"/favicon.ico\">" : "";
468
423
  const html = `<!DOCTYPE html>
469
424
  <html lang="en">
470
425
  <head>
471
426
  ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}
472
- ${helmet?.title.toString() ?? ''}
473
- ${helmet?.meta.toString() ?? ''}
427
+ ${helmet?.title.toString() ?? ""}
428
+ ${helmet?.meta.toString() ?? ""}
474
429
  <meta name="theme-color" content="#FFFFFF">
475
430
  ${manifestLink}
476
- ${helmet?.link.toString() ?? ''}${styleChunkString}
431
+ ${helmet?.link.toString() ?? ""}${styleChunkString}
477
432
  ${faviconLink}
478
433
  <meta charset="utf-8">
479
434
  <meta
@@ -507,9 +462,7 @@ export default function factory(webpackConfig, options) {
507
462
  }
508
463
  });
509
464
  });
510
- }
511
-
512
- // Note: as caching code above may throw in some cases, sending response
465
+ } // Note: as caching code above may throw in some cases, sending response
513
466
  // before it completes will likely hide the error, making it difficult
514
467
  // to debug. Thus, at least for now, lets send response after it.
515
468
  res.send(html);