@dr.pogodin/react-utils 1.57.0 → 1.58.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 (128) hide show
  1. package/build/development/server/Cache.js +7 -7
  2. package/build/development/server/Cache.js.map +1 -1
  3. package/build/development/server/index.js +6 -3
  4. package/build/development/server/index.js.map +1 -1
  5. package/build/development/server/renderer.js +18 -7
  6. package/build/development/server/renderer.js.map +1 -1
  7. package/build/development/server/server.js +12 -6
  8. package/build/development/server/server.js.map +1 -1
  9. package/build/development/server/utils/errors.js +10 -10
  10. package/build/development/server/utils/errors.js.map +1 -1
  11. package/build/development/shared/components/Button/index.js +1 -1
  12. package/build/development/shared/components/Button/index.js.map +1 -1
  13. package/build/development/shared/components/Checkbox/index.js +5 -5
  14. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  15. package/build/development/shared/components/Input/index.js +3 -3
  16. package/build/development/shared/components/Input/index.js.map +1 -1
  17. package/build/development/shared/components/Modal/index.js +3 -0
  18. package/build/development/shared/components/Modal/index.js.map +1 -1
  19. package/build/development/shared/components/TextArea/index.js +3 -3
  20. package/build/development/shared/components/TextArea/index.js.map +1 -1
  21. package/build/development/shared/components/WithTooltip/Tooltip.js +2 -2
  22. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  23. package/build/development/shared/components/WithTooltip/index.js +3 -1
  24. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  25. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +4 -1
  26. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  27. package/build/development/shared/components/selectors/CustomDropdown/index.js +7 -4
  28. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  29. package/build/development/shared/components/selectors/NativeDropdown/index.js +3 -3
  30. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  31. package/build/development/shared/components/selectors/Switch/index.js +2 -2
  32. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  33. package/build/development/shared/utils/config.js.map +1 -1
  34. package/build/development/shared/utils/jest/E2eSsrEnv/index.js +7 -6
  35. package/build/development/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
  36. package/build/development/shared/utils/jest/index.js +2 -1
  37. package/build/development/shared/utils/jest/index.js.map +1 -1
  38. package/build/development/shared/utils/splitComponent.js +10 -8
  39. package/build/development/shared/utils/splitComponent.js.map +1 -1
  40. package/build/development/shared/utils/webpack.js +2 -1
  41. package/build/development/shared/utils/webpack.js.map +1 -1
  42. package/build/production/server/Cache.js +3 -3
  43. package/build/production/server/Cache.js.map +1 -1
  44. package/build/production/server/index.js +1 -1
  45. package/build/production/server/index.js.map +1 -1
  46. package/build/production/server/renderer.js +9 -9
  47. package/build/production/server/renderer.js.map +1 -1
  48. package/build/production/server/server.js +6 -6
  49. package/build/production/server/server.js.map +1 -1
  50. package/build/production/server/utils/errors.js +1 -1
  51. package/build/production/server/utils/errors.js.map +1 -1
  52. package/build/production/shared/components/Button/index.js +1 -1
  53. package/build/production/shared/components/Button/index.js.map +1 -1
  54. package/build/production/shared/components/Checkbox/index.js +1 -1
  55. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  56. package/build/production/shared/components/Input/index.js +1 -1
  57. package/build/production/shared/components/Input/index.js.map +1 -1
  58. package/build/production/shared/components/Modal/index.js +1 -1
  59. package/build/production/shared/components/Modal/index.js.map +1 -1
  60. package/build/production/shared/components/TextArea/index.js +1 -1
  61. package/build/production/shared/components/TextArea/index.js.map +1 -1
  62. package/build/production/shared/components/WithTooltip/Tooltip.js +1 -1
  63. package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
  64. package/build/production/shared/components/WithTooltip/index.js +2 -2
  65. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  66. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  67. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  68. package/build/production/shared/components/selectors/CustomDropdown/index.js +1 -1
  69. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  70. package/build/production/shared/components/selectors/NativeDropdown/index.js +2 -2
  71. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  72. package/build/production/shared/components/selectors/Switch/index.js +1 -1
  73. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  74. package/build/production/shared/utils/config.js.map +1 -1
  75. package/build/production/shared/utils/jest/E2eSsrEnv/index.js +2 -2
  76. package/build/production/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
  77. package/build/production/shared/utils/jest/index.js +2 -2
  78. package/build/production/shared/utils/jest/index.js.map +1 -1
  79. package/build/production/shared/utils/splitComponent.js +3 -3
  80. package/build/production/shared/utils/splitComponent.js.map +1 -1
  81. package/build/production/shared/utils/webpack.js +3 -2
  82. package/build/production/shared/utils/webpack.js.map +1 -1
  83. package/build/types-code/shared/utils/config.d.ts +1 -1
  84. package/build/web/server/Cache.js +3 -3
  85. package/build/web/server/Cache.js.map +1 -1
  86. package/build/web/server/index.js +1 -1
  87. package/build/web/server/index.js.map +1 -1
  88. package/build/web/server/renderer.js +9 -9
  89. package/build/web/server/renderer.js.map +1 -1
  90. package/build/web/server/server.js +6 -6
  91. package/build/web/server/server.js.map +1 -1
  92. package/build/web/server/utils/errors.js +1 -1
  93. package/build/web/server/utils/errors.js.map +1 -1
  94. package/build/web/shared/components/Button/index.js +1 -1
  95. package/build/web/shared/components/Button/index.js.map +1 -1
  96. package/build/web/shared/components/Checkbox/index.js +1 -1
  97. package/build/web/shared/components/Checkbox/index.js.map +1 -1
  98. package/build/web/shared/components/Input/index.js +1 -1
  99. package/build/web/shared/components/Input/index.js.map +1 -1
  100. package/build/web/shared/components/Modal/index.js +1 -1
  101. package/build/web/shared/components/Modal/index.js.map +1 -1
  102. package/build/web/shared/components/TextArea/index.js +1 -1
  103. package/build/web/shared/components/TextArea/index.js.map +1 -1
  104. package/build/web/shared/components/WithTooltip/Tooltip.js +1 -1
  105. package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -1
  106. package/build/web/shared/components/WithTooltip/index.js +2 -2
  107. package/build/web/shared/components/WithTooltip/index.js.map +1 -1
  108. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  109. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  110. package/build/web/shared/components/selectors/CustomDropdown/index.js +1 -1
  111. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  112. package/build/web/shared/components/selectors/NativeDropdown/index.js +2 -2
  113. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  114. package/build/web/shared/components/selectors/Switch/index.js +1 -1
  115. package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
  116. package/build/web/shared/utils/config.js.map +1 -1
  117. package/build/web/shared/utils/jest/E2eSsrEnv/index.js +2 -2
  118. package/build/web/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
  119. package/build/web/shared/utils/jest/index.js +2 -2
  120. package/build/web/shared/utils/jest/index.js.map +1 -1
  121. package/build/web/shared/utils/splitComponent.js +3 -3
  122. package/build/web/shared/utils/splitComponent.js.map +1 -1
  123. package/build/web/shared/utils/webpack.js +3 -2
  124. package/build/web/shared/utils/webpack.js.map +1 -1
  125. package/config/babel/webpack.js +6 -1
  126. package/config/webpack/app-base.js +16 -6
  127. package/config/webpack/app-development.js +2 -0
  128. package/package.json +21 -19
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Implements the static cache.
3
3
  */export default class Cache {
4
- items = {};
4
+ items = new Map();
5
5
  size = 0;
6
6
  constructor(maxSize) {
7
7
  this.maxSize = maxSize;
@@ -17,7 +17,7 @@
17
17
  key,
18
18
  maxage = Number.MAX_VALUE
19
19
  }) {
20
- const item = this.items[key];
20
+ const item = this.items.get(key);
21
21
  return item && Date.now() - item.timestamp < maxage ? item.data : null;
22
22
  } /**
23
23
  * Adds item to cache.
@@ -26,20 +26,20 @@
26
26
  * @param size Byte size of the item.
27
27
  */
28
28
  add(data, key, size) {
29
- const cached = this.items[key];
29
+ const cached = this.items.get(key);
30
30
  if (cached) this.size -= cached.size;
31
- this.items[key] = {
31
+ this.items.set(key, {
32
32
  data,
33
33
  size,
34
34
  timestamp: Date.now()
35
- };
35
+ });
36
36
  this.size += size;
37
37
  if (this.size > this.maxSize) {
38
- const entries = Object.entries(this.items);
38
+ const entries = [...this.items.entries()];
39
39
  entries.sort((a, b) => a[1].timestamp - b[1].timestamp);
40
40
  for (const entry of entries) {
41
41
  const [itemKey, item] = entry;
42
- delete this.items[itemKey];
42
+ this.items.delete(itemKey);
43
43
  this.size -= item.size;
44
44
  if (this.size < this.maxSize / 2) break;
45
45
  }
@@ -1 +1 @@
1
- {"version":3,"file":"Cache.js","names":[],"sources":["../../../src/server/Cache.ts"],"sourcesContent":["type CachedItemT<DatumT> = {\n data: DatumT;\n size: number;\n timestamp: number;\n};\n\n/**\n * Implements the static cache.\n */\nexport default class Cache<DatumT> {\n private items: Record<string, CachedItemT<DatumT>> = {};\n\n private size = 0;\n\n constructor(private maxSize: number) { }\n\n /**\n * Cache lookup.\n * @param key Item key to look for.\n * @param [maxage=Number.MAX_VALUE] Optional. The maximum age of\n * cached item to serve. Default to infinite.\n * @returns Cached item, or null if the item is absent in cache,\n * or stale.\n */\n get({\n key,\n maxage = Number.MAX_VALUE,\n }: {\n key: string;\n maxage?: number;\n }): DatumT | null {\n const item = this.items[key];\n return item && Date.now() - item.timestamp < maxage ? item.data : null;\n }\n\n /**\n * Adds item to cache.\n * @param data Item to add.\n * @param key Key to store the item at.\n * @param size Byte size of the item.\n */\n add(data: DatumT, key: string, size: number): void {\n const cached = this.items[key];\n if (cached) this.size -= cached.size;\n\n this.items[key] = { data, size, timestamp: Date.now() };\n this.size += size;\n\n if (this.size > this.maxSize) {\n const entries = Object.entries(this.items);\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp);\n\n for (const entry of entries) {\n const [itemKey, item] = entry;\n delete this.items[itemKey];\n this.size -=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AC3B,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,KAAK;QAC7B,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC;QAC1B,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI;QACtB,IAAI,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,OAAO,GAAG,CAAC,EAAE;MACpC;IACF;EACF;AACF","ignoreList":[]}
1
+ {"version":3,"file":"Cache.js","names":[],"sources":["../../../src/server/Cache.ts"],"sourcesContent":["type CachedItemT<DatumT> = {\n data: DatumT;\n size: number;\n timestamp: number;\n};\n\n/**\n * Implements the static cache.\n */\nexport default class Cache<DatumT> {\n private items = new Map<string, CachedItemT<DatumT>>();\n\n private size = 0;\n\n constructor(private maxSize: number) { }\n\n /**\n * Cache lookup.\n * @param key Item key to look for.\n * @param [maxage=Number.MAX_VALUE] Optional. The maximum age of\n * cached item to serve. Default to infinite.\n * @returns Cached item, or null if the item is absent in cache,\n * or stale.\n */\n get({\n key,\n maxage = Number.MAX_VALUE,\n }: {\n key: string;\n maxage?: number;\n }): DatumT | null {\n const item = this.items.get(key);\n return item && Date.now() - item.timestamp < maxage ? item.data : null;\n }\n\n /**\n * Adds item to cache.\n * @param data Item to add.\n * @param key Key to store the item at.\n * @param size Byte size of the item.\n */\n add(data: DatumT, key: string, size: number): void {\n const cached = this.items.get(key);\n if (cached) this.size -= cached.size;\n\n this.items.set(key, { data, size, timestamp: Date.now() });\n this.size += size;\n\n if (this.size > this.maxSize) {\n const entries = [...this.items.entries()];\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp);\n\n for (const entry of entries) {\n const [itemKey, item] = entry;\n this.items.delete(itemKey);\n this.size -= item.size;\n if (this.size < this.maxSize / 2) break;\n }\n }\n }\n}\n"],"mappings":"AAMA;AACA;AACA,GACA,eAAe,MAAM,KAAc;EACzB,KAAK,GAAG,IAAI,GAAkC,CAAlC,CAAkC;EAE9C,IAAI,GAAG,CAAC;EAEhB,WAAW,CAA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,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI;QACtB,IAAI,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,OAAO,GAAG,CAAC,EAAE;MACpC;IACF;EACF;AACF","ignoreList":[]}
@@ -157,7 +157,8 @@ export async function launchServer(webpackConfig, options = {}) {
157
157
  } else httpServer = http.createServer(expressServer); /* Sets error handler for HTTP(S) server. */
158
158
  httpServer.on("error", error => {
159
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. */
160
+ const bind = typeof ops.port === "string" ? `Pipe ${ops.port}` : `Port ${ops.port ? ops.port.toString() : "undefined"}`;
161
+ if (!ops.logger) throw Error("Missing logger"); /* Human-readable message for some specific listen errors. */
161
162
  switch (error.code) {
162
163
  case "EACCES":
163
164
  ops.logger.error(`${bind} requires elevated privileges`);
@@ -172,8 +173,10 @@ export async function launchServer(webpackConfig, options = {}) {
172
173
  }); /* Listening event handler for HTTP(S) server. */
173
174
  httpServer.on("listening", () => {
174
175
  const addr = httpServer.address();
175
- const bind = typeof addr === "string" ? `pipe ${addr}` : `port ${addr.port}`;
176
- ops.logger.info(`Server listening on ${bind} in ${process.env.NODE_ENV} mode`);
176
+ if (!addr) throw Error("Missing address");
177
+ const bind = typeof addr === "string" ? `pipe ${addr}` : `port ${addr.port.toString()}`;
178
+ if (!ops.logger) throw Error("Missing logger");
179
+ ops.logger.info(`Server listening on ${bind} in ${process.env.NODE_ENV ?? "undefined"} mode`);
177
180
  });
178
181
  httpServer.listen(ops.port);
179
182
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"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,OAAO,IAAI,MAAM,WAAW;AAC5B,OAAO,KAAK,MAAM,YAAY;AAE9B,SAAS,SAAS,EAAE,QAAQ,QAAQ,WAAW,CAE/C;AACA;AACA;AACA,OAAO,iBAAiB;AAAC,SAIhB,gBAAgB,EAAE,gBAAgB;AAAA,OAEpC,aAAa,IAGlB,qBAAqB;AAAA;AAYvB,SACE,gBAAgB,EAEhB,qBAAqB,GAGvB;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,KAAsB,EAAE;EAC7C,MAAM,IAAI,GAAG,OAAO,KAAK,KAAK,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,KAAK;EAChE,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,IAAI,CAAE;EACxC,OAAO,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,eAAe,YAAY,CAChC,aAA4B,EAC5B,OAAiB,GAAG,CAAC,CAAC,EAIrB;EACD,4BACA,MAAM,GAAG,GAAG,SAAS,CAAC,OAAO,CAAC,CAE9B;EACA,GAAG,CAAC,IAAI,GAAG,aAAa,CAAC,GAAG,CAAC,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,IAAI,CAAC;EAC9D,QAAQ,CAAC,GAAG,EAAE;IAAE,aAAa,EAAE;EA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I,GAAG,OAAO,IAAI,KAAK,QAAQ,GAAG,QAAQ,IAAI,EAAE,GAAG,QAAQ,IAAI,CAAC,IAAI,EAAE;IAC5E,GAAG,CAAC,MAAM,CAAE,IAAI,CAAC,uBAAuB,IAAI,OAC1C,OAAO,CAAC,GAAG,CAAC,QAAQ,OAAO,CAAC;EAChC,CAAC,CAAC;EAEF,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC;EAE3B,OAAO;IACL,aAAa;IACb;EACF,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"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'\n ? `Pipe ${ops.port}`\n : `Port ${ops.port ? ops.port.toString() : 'undefined'}`;\n\n if (!ops.logger) throw Error('Missing logger');\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 if (!addr) throw Error('Missing address');\n\n const bind = typeof addr === 'string'\n ? `pipe ${addr}` : `port ${addr.port.toString()}`;\n\n if (!ops.logger) throw Error('Missing logger');\n ops.logger.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV ?? 'undefined'} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n"],"mappings":"AAAA;AACA,OAAO,gCAAgC;AAEvC,OAAO,IAAI,MAAM,WAAW;AAC5B,OAAO,KAAK,MAAM,YAAY;AAE9B,SAAS,SAAS,EAAE,QAAQ,QAAQ,WAAW,CAE/C;AACA;AACA;AACA,OAAO,iBAAiB;AAAC,SAIhB,gBAAgB,EAAE,gBAAgB;AAAA,OAEpC,aAAa,IAGlB,qBAAqB;AAAA;AAYvB,SACE,gBAAgB,EAEhB,qBAAqB,GAGvB;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,KAAsB,EAAE;EAC7C,MAAM,IAAI,GAAG,OAAO,KAAK,KAAK,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,KAAK;EAChE,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,IAAI,CAAE;EACxC,OAAO,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;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,CAAC,GAAG,CAAC,IAAI,CAAC;EAE3B,OAAO;IACL,aAAa;IACb;EACF,CAAC;AACH","ignoreList":[]}
@@ -1,7 +1,7 @@
1
- import _JSON$parse from "core-js-pure/stable/json/parse.js";
2
- import _JSON$stringify from "core-js-pure/stable/json/stringify.js"; /**
3
- * ExpressJS middleware for server-side rendering of a ReactJS app.
4
- */
1
+ import _JSON$parse from "core-js-pure/features/json/parse.js";
2
+ import _JSON$stringify from "core-js-pure/features/json/stringify.js"; /**
3
+ * ExpressJS middleware for server-side rendering of a ReactJS app.
4
+ */
5
5
  import { Buffer } from "node:buffer";
6
6
  import { createCipheriv, randomBytes } from "node:crypto";
7
7
  import fs from "node:fs";
@@ -231,13 +231,17 @@ export default function factory(webpackConfig, options) {
231
231
  ops.logger ??= newDefaultLogger({
232
232
  defaultLogLevel: ops.defaultLoggerLogLevel
233
233
  });
234
+ if (!webpackConfig.context) throw Error("Missing Webpack context");
234
235
  const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context);
235
- setBuildInfo(buildInfo); // publicPath from webpack.output has a trailing slash at the end.
236
+ setBuildInfo(buildInfo);
237
+ if (!webpackConfig.output) throw Error("Missing Webpack output config"); // publicPath from webpack.output has a trailing slash at the end.
236
238
  const {
237
239
  path: outputPath,
238
240
  publicPath
239
241
  } = webpackConfig.output;
242
+ if (!outputPath) throw Error("Missing output path");
240
243
  const manifestLink = fs.existsSync(`${outputPath}/manifest.json`) ? `<link rel="manifest" href="${publicPath}manifest.json">` : ""; // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
244
+ if (ops.staticCacheSize === undefined) throw Error("Missing staticCacheSize");
241
245
  const cache = ops.staticCacheController ? new Cache(ops.staticCacheSize) : null;
242
246
  const CHUNK_GROUPS = readChunkGroupsJson(outputPath); // TODO: Look at it later.
243
247
  // eslint-disable-next-line complexity
@@ -248,6 +252,7 @@ export default function factory(webpackConfig, options) {
248
252
  res.cookie("csrfToken", req.csrfToken());
249
253
  let cacheRef;
250
254
  if (cache) {
255
+ if (!ops.staticCacheController) throw Error("Missing staticCacheController");
251
256
  cacheRef = ops.staticCacheController(req);
252
257
  if (cacheRef) {
253
258
  const data = cache.get(cacheRef);
@@ -284,6 +289,7 @@ export default function factory(webpackConfig, options) {
284
289
  }
285
290
  }
286
291
  }
292
+ if (!ops.beforeRender) throw Error("Missing beforeRender");
287
293
  const brr = ops.beforeRender(req, publicConfig);
288
294
  const {
289
295
  configToInject,
@@ -355,9 +361,11 @@ export default function factory(webpackConfig, options) {
355
361
  });
356
362
  let ssrRound = 0;
357
363
  let bailed = false;
364
+ if (ops.maxSsrRounds === undefined) throw Error("Missing maxSsrRounds");
358
365
  for (; ssrRound < ops.maxSsrRounds; ++ssrRound) {
359
366
  stream = await renderPass();
360
367
  if (!ssrContext.dirty) break;
368
+ if (ops.ssrTimeout === undefined) throw Error("Missing SSR timeout");
361
369
  const timeout = ops.ssrTimeout + ssrStart - Date.now();
362
370
  bailed = timeout <= 0 || !(await Promise.race([Promise.allSettled(ssrContext.pending), timer(timeout).then(() => false)]));
363
371
  if (bailed) break;
@@ -368,8 +376,10 @@ export default function factory(webpackConfig, options) {
368
376
  // to ensure the correct hydration when some pending promises have
369
377
  // resolved and placed their data into the initial global state.
370
378
  stream = await renderPass();
371
- logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)` : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;
372
- } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;
379
+ if (ops.ssrTimeout === undefined) throw Error("Missing SSR timeout");
380
+ logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout.toString()} second(s)` : `SSR bailed out after ${ops.maxSsrRounds.toString()} round(s)`;
381
+ } else logMsg = `SSR completed in ${(ssrRound + 1).toString()} round(s)`;
382
+ if (!ops.logger) throw Error("Missing logger");
373
383
  ops.logger.log(ssrContext.dirty ? "warn" : "info", logMsg);
374
384
  if (ssrContext.redirectTo) {
375
385
  res.redirect(ssrContext.status, ssrContext.redirectTo);
@@ -465,6 +475,7 @@ export default function factory(webpackConfig, options) {
465
475
  if (error) failed(error);else {
466
476
  const b = buffer;
467
477
  b.nonce = req.nonce;
478
+ if (cache === null) throw Error("Missing cache");
468
479
  cache.add({
469
480
  buffer: b,
470
481
  status
@@ -1 +1 @@
1
- {"version":3,"file":"renderer.js","names":[],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { type Cipheriv, createCipheriv, randomBytes } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport config from 'config';\nimport type { Request, RequestHandler } from 'express';\n\nimport {\n cloneDeep,\n defaults,\n get,\n mapValues,\n} from 'lodash-es';\n\nimport type { ComponentType } from 'react';\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { timer } from '@dr.pogodin/js-utils';\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { HelmetProvider, type HelmetServerState } from '@dr.pogodin/react-helmet';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport Cache from './Cache';\n\n// @ts-expect-error \"Property 'SECRET' does not exist on type 'IConfig'.\"\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst { SECRET, ...publicConfig } = config.util.toObject(config);\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (level: string, message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LeveledLogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nexport class ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n private pRedirectTo?: string;\n private pStatus: number = 200;\n\n req: Request;\n\n get redirectTo(): string | undefined {\n return this.pRedirectTo;\n }\n\n get status(): number {\n return this.pStatus;\n }\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) ?? ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n\n /**\n * Sets status code and `redirectTo` value.\n */\n setStatus(status: number, redirectTo?: string): void {\n this.pRedirectTo = redirectTo;\n this.pStatus = status;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8')) as BuildInfoT;\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8')) as Record<string, string[]>;\n } catch {\n // TODO: Should we message the error here somehow?\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random, Base64-encoded key is expected).\n * @return Returns a tuple of:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string): [cipher: Cipheriv, iv: Buffer] {\n const iv = randomBytes(16);\n const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);\n return [cipher, iv];\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param req\n */\nexport function isBrotliAcceptable(req: Request): boolean {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (const op of ops) {\n const [type, priority] = op.trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<ScriptT | string> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (const script of scripts) {\n if (typeof script === 'string') {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (script.location in res) res[script.location] += script.code;\n else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}): winston.Logger {\n const { format, transports } = winston;\n return winston.createLogger({\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n stack,\n timestamp,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\n transports: [new transports.Console()],\n });\n}\n\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: unknown;\n};\n\nexport type BeforeRenderT = (\n req: Request,\n config: ConfigT,\n) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\n/**\n * Deduces the map of code chunk groups from the Webpack compilation Stats.\n */\nexport function deduceChunkGroups(stats: Stats): ChunkGroupsT {\n return mapValues(\n stats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name) ?? [],\n );\n}\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n\n /** Allows to pass chunk groups explicitly, at the renderer creation time;\n * intended for test purposes. */\n chunkGroups?: ChunkGroupsT;\n\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n staticCacheSize?: number;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [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 [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [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 * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults({ ...options }, {\n beforeRender: async () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context!);\n setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { path: outputPath, publicPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath as string}manifest.json\">` : '';\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface BufferWithNonce extends ArrayBuffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n // TODO: Look at it later.\n // eslint-disable-next-line complexity\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n\n // TODO: It should be implemented more careful.\n h = h.replace(regex, (req as unknown as {\n nonce: string;\n }).nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const brr = ops.beforeRender!(req, publicConfig);\n const { configToInject, extraScripts, initialState } = await brr;\n\n const [cipher, iv] = prepareCipher(buildInfo.key);\n\n let helmetState: HelmetServerState | undefined;\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats') as Stats | undefined;\n if (webpackStats) chunkGroups = deduceChunkGroups(webpackStats);\n else if (options.chunkGroups) ({ chunkGroups } = options);\n else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: NodeJS.ReadableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n // TODO: I guess, if we refactor the rendering pass function\n // (promise) using less Promises, but Barrier instead - it might\n // become a better understandable.\n const resolve = (arg: NodeJS.ReadableStream) => {\n // NOTE: The error might be set via the `onError` handler passed\n // into the prerenderToNodeStream() call below (which will reject\n // the rendering pass promise), after which the this resolve()\n // will be called from .then() handler, and we should just ignore\n // it, and do nothing.\n if (!error) resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n\n // TODO: Perhaps assert \"arg instanceof Error\"?\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n rejectArg(arg as Error);\n };\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider\n onServerState={(state) => {\n helmetState = state;\n }}\n >\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then(\n (result) => {\n resolve(result.prelude);\n },\n reject,\n );\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\n const timeout = ops.ssrTimeout! + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject ?? publicConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n\n const INJ = Buffer.concat([\n iv,\n cipher.update(payload, 'utf8'),\n cipher.final(),\n ]).toString('base64');\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) {\n assets.forEach((asset) => {\n chunkSet.add(asset);\n });\n }\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath as string}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath as string}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon\n // NOTE: It is not a mistake that the \"/favicon.ico\" path is hard-coded\n // here! Note, that during the server setup the \"favicon\" middleware is\n // configured to serve the given `ops.favicon` from the \"/favicon.ico\"\n // path.\n ? '<link rel=\"icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmetState?.title.toString() ?? ''}\n ${helmetState?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmetState?.link.toString() ?? ''}${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n const b = buffer as unknown as BufferWithNonce;\n b.nonce = (req as unknown as {\n nonce: string;\n }).nonce;\n cache!.add({ buffer: b, status }, cacheRef.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":";oEAAA;AACA;AACA;AAEA,SAAS,MAAM,QAAQ,aAAa;AACpC,SAAwB,cAAc,EAAE,WAAW,QAAQ,aAAa;AACxE,OAAO,EAAE,MAAM,SAAS;AACxB,OAAO,IAAI,MAAM,WAAW;AAC5B,SAAS,QAAQ,QAAQ,aAAa;AACtC,SAAS,cAAc,EAAE,gBAAgB,QAAQ,WAAW;AAE5D,OAAO,MAAM,MAAM,QAAQ;AAG3B,SACE,SAAS,EACT,QAAQ,EACR,GAAG,EACH,SAAS,QACJ,WAAW;AAGlB,SAAS,qBAAqB,QAAQ,kBAAkB;AACxD,SAAS,YAAY,QAAQ,cAAc;AAC3C,OAAO,WAAW,MAAM,sBAAsB;AAE9C,OAAO,OAAO,MAAM,SAAS;AAE7B,SAAS,KAAK,QAAQ,sBAAsB;AAC5C,SAAS,mBAAmB,EAAE,UAAU,QAAQ,gCAAgC;AAChF,SAAS,cAAc,QAAgC,0BAA0B;AAAC,SAGxD,YAAY;AAAA,OAE/B,KAAK,mBAEZ;AACA;AAAA;AACA,MAAM;EAAE,MAAM;EAAE,GAAG;AAAa,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAEhE;AACA;AACA;AACA;AAMA;AAMA;AASA,WAAY,gBAAgB,0BAAhB,gBAAgB;EAAhB,gBAAgB;EAAhB,gBAAgB;EAAhB,gBAAgB;EAAA,OAAhB,gBAAgB;AAAA;AAM5B,OAAO,MAAM,gBAAgB,SACnB,UACuB;EAC/B,WAAW;EAEX,MAAM,GAAa,EAAE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":"renderer.js","names":[],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { type Cipheriv, createCipheriv, randomBytes } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport config from 'config';\nimport type { Request, RequestHandler } from 'express';\n\nimport {\n cloneDeep,\n defaults,\n get,\n mapValues,\n} from 'lodash-es';\n\nimport type { ComponentType } from 'react';\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { timer } from '@dr.pogodin/js-utils';\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { HelmetProvider, type HelmetServerState } from '@dr.pogodin/react-helmet';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport Cache from './Cache';\n\n// @ts-expect-error \"Property 'SECRET' does not exist on type 'IConfig'.\"\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst { SECRET, ...publicConfig } = config.util.toObject(config);\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (level: string, message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LeveledLogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nexport class ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n private pRedirectTo?: string;\n private pStatus: number = 200;\n\n req: Request;\n\n get redirectTo(): string | undefined {\n return this.pRedirectTo;\n }\n\n get status(): number {\n return this.pStatus;\n }\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) ?? ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n\n /**\n * Sets status code and `redirectTo` value.\n */\n setStatus(status: number, redirectTo?: string): void {\n this.pRedirectTo = redirectTo;\n this.pStatus = status;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8')) as BuildInfoT;\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8')) as Record<string, string[]>;\n } catch {\n // TODO: Should we message the error here somehow?\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random, Base64-encoded key is expected).\n * @return Returns a tuple of:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string): [cipher: Cipheriv, iv: Buffer] {\n const iv = randomBytes(16);\n const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);\n return [cipher, iv];\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param req\n */\nexport function isBrotliAcceptable(req: Request): boolean {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (const op of ops) {\n const [type, priority] = op.trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<ScriptT | string> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (const script of scripts) {\n if (typeof script === 'string') {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (script.location in res) res[script.location] += script.code;\n else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}): winston.Logger {\n const { format, transports } = winston;\n return winston.createLogger({\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n stack,\n timestamp,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\n transports: [new transports.Console()],\n });\n}\n\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: unknown;\n};\n\nexport type BeforeRenderT = (\n req: Request,\n config: ConfigT,\n) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\n/**\n * Deduces the map of code chunk groups from the Webpack compilation Stats.\n */\nexport function deduceChunkGroups(stats: Stats): ChunkGroupsT {\n return mapValues(\n stats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name) ?? [],\n );\n}\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n\n /** Allows to pass chunk groups explicitly, at the renderer creation time;\n * intended for test purposes. */\n chunkGroups?: ChunkGroupsT;\n\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n staticCacheSize?: number;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [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 [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [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 * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults({ ...options }, {\n beforeRender: async () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n if (!webpackConfig.context) throw Error('Missing Webpack context');\n const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context);\n setBuildInfo(buildInfo);\n\n if (!webpackConfig.output) throw Error('Missing Webpack output config');\n // publicPath from webpack.output has a trailing slash at the end.\n const { path: outputPath, publicPath } = webpackConfig.output;\n if (!outputPath) throw Error('Missing output path');\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath as string}manifest.json\">` : '';\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface BufferWithNonce extends ArrayBuffer {\n nonce: string;\n }\n\n if (ops.staticCacheSize === undefined) throw Error('Missing staticCacheSize');\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath);\n\n // TODO: Look at it later.\n // eslint-disable-next-line complexity\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n if (!ops.staticCacheController) throw Error('Missing staticCacheController');\n cacheRef = ops.staticCacheController(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n\n // TODO: It should be implemented more careful.\n h = h.replace(regex, (req as unknown as {\n nonce: string;\n }).nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n if (!ops.beforeRender) throw Error('Missing beforeRender');\n const brr = ops.beforeRender(req, publicConfig);\n const { configToInject, extraScripts, initialState } = await brr;\n\n const [cipher, iv] = prepareCipher(buildInfo.key);\n\n let helmetState: HelmetServerState | undefined;\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats') as Stats | undefined;\n if (webpackStats) chunkGroups = deduceChunkGroups(webpackStats);\n else if (options.chunkGroups) ({ chunkGroups } = options);\n else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: NodeJS.ReadableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n // TODO: I guess, if we refactor the rendering pass function\n // (promise) using less Promises, but Barrier instead - it might\n // become a better understandable.\n const resolve = (arg: NodeJS.ReadableStream) => {\n // NOTE: The error might be set via the `onError` handler passed\n // into the prerenderToNodeStream() call below (which will reject\n // the rendering pass promise), after which the this resolve()\n // will be called from .then() handler, and we should just ignore\n // it, and do nothing.\n if (!error) resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n\n // TODO: Perhaps assert \"arg instanceof Error\"?\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n rejectArg(arg as Error);\n };\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider\n onServerState={(state) => {\n helmetState = state;\n }}\n >\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then(\n (result) => {\n resolve(result.prelude);\n },\n reject,\n );\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n if (ops.maxSsrRounds === undefined) throw Error('Missing maxSsrRounds');\n for (; ssrRound < ops.maxSsrRounds; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\n if (ops.ssrTimeout === undefined) throw Error('Missing SSR timeout');\n const timeout = ops.ssrTimeout + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n if (ops.ssrTimeout === undefined) throw Error('Missing SSR timeout');\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout.toString()} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds.toString()} round(s)`;\n } else logMsg = `SSR completed in ${(ssrRound + 1).toString()} round(s)`;\n\n if (!ops.logger) throw Error('Missing logger');\n ops.logger.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\n\n await new Promise((ready) => {\n stream.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject ?? publicConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n\n const INJ = Buffer.concat([\n iv,\n cipher.update(payload, 'utf8'),\n cipher.final(),\n ]).toString('base64');\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) {\n assets.forEach((asset) => {\n chunkSet.add(asset);\n });\n }\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath as string}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath as string}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon\n // NOTE: It is not a mistake that the \"/favicon.ico\" path is hard-coded\n // here! Note, that during the server setup the \"favicon\" middleware is\n // configured to serve the given `ops.favicon` from the \"/favicon.ico\"\n // path.\n ? '<link rel=\"icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmetState?.title.toString() ?? ''}\n ${helmetState?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmetState?.link.toString() ?? ''}${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n const b = buffer as unknown as BufferWithNonce;\n b.nonce = (req as unknown as {\n nonce: string;\n }).nonce;\n if (cache === null) throw Error('Missing cache');\n cache.add({ buffer: b, status }, cacheRef.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":";sEAAA;AACA;AACA;AAEA,SAAS,MAAM,QAAQ,aAAa;AACpC,SAAwB,cAAc,EAAE,WAAW,QAAQ,aAAa;AACxE,OAAO,EAAE,MAAM,SAAS;AACxB,OAAO,IAAI,MAAM,WAAW;AAC5B,SAAS,QAAQ,QAAQ,aAAa;AACtC,SAAS,cAAc,EAAE,gBAAgB,QAAQ,WAAW;AAE5D,OAAO,MAAM,MAAM,QAAQ;AAG3B,SACE,SAAS,EACT,QAAQ,EACR,GAAG,EACH,SAAS,QACJ,WAAW;AAGlB,SAAS,qBAAqB,QAAQ,kBAAkB;AACxD,SAAS,YAAY,QAAQ,cAAc;AAC3C,OAAO,WAAW,MAAM,sBAAsB;AAE9C,OAAO,OAAO,MAAM,SAAS;AAE7B,SAAS,KAAK,QAAQ,sBAAsB;AAC5C,SAAS,mBAAmB,EAAE,UAAU,QAAQ,gCAAgC;AAChF,SAAS,cAAc,QAAgC,0BAA0B;AAAC,SAGxD,YAAY;AAAA,OAE/B,KAAK,mBAEZ;AACA;AAAA;AACA,MAAM;EAAE,MAAM;EAAE,GAAG;AAAa,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAEhE;AACA;AACA;AACA;AAMA;AAMA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AACzB;AACA;AACA;AACA;AACA;AACA,iDAAiD,GAAG;AACpD;AACA;AACA,cAAc,oBAAoB,CAAC,gBAAgB,CAAC,SAAS,CAAC;AAC9D,mCAAmC,aAAa;AAChD,cAAc,iBAAiB;AAC/B,cAAc,oBAAoB,CAAC,gBAAgB,CAAC,OAAO,CAAC;AAC5D;AACA,gBAAgB;MAEV,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,IAAI,GAAG;MACvC,IAAI,MAAM,KAAK,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC;MAEtC,IAAI,QAAQ,IAAI,MAAM,GAAG,GAAG,EAAE;QAC5B;QACA;QACA,MAAM,IAAI,OAAO,CAAO,CAAC,IAAI,EAAE,MAAM,KAAK;UACxC,cAAc,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK;YACtC,IAAI,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,KACpB;cACH,MAAM,CAAC,GAAG,MAAoC;cAC9C,CAAC,CAAC,KAAK,GAAI,GAAG,CAEX,KAAK;cACR,IAAI,KAAK,KAAK,IAAI,EAAE,MAAM,KAAK,CAAC,eAAe,CAAC;cAChD,KAAK,CAAC,GAAG,CAAC;gBAAE,MAAM,EAAE,CAAC;gBAAE;cAAO,CAAC,EAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC;cAC7D,IAAI,CAAC,CAAC;YACR;UACF,CAAC,CAAC;QACJ,CAAC,CAAC;MACJ,CAEA;MACA;MACA;MACA,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC;IAChB,CAAE,QAAO,KAAK,EAAE;MACd,IAAI,CAAC,KAAK,CAAC;IACb;EACF,CAAC;AACH","ignoreList":[]}
@@ -1,6 +1,6 @@
1
- import _pushInstanceProperty from "core-js-pure/stable/instance/push.js"; /**
2
- * Creation of standard ExpressJS server for ReactJS apps.
3
- */
1
+ import _pushInstanceProperty from "core-js-pure/features/instance/push.js"; /**
2
+ * Creation of standard ExpressJS server for ReactJS apps.
3
+ */
4
4
  import { sep } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import compression from "compression";
@@ -57,6 +57,7 @@ export function getDefaultCspSettings() {
57
57
  export default async function factory(webpackConfig, options) {
58
58
  const rendererOps = pick(options, ["Application", "beforeRender", "favicon", "logger", "maxSsrRounds", "noCsp", "ssrTimeout", "staticCacheController", "staticCacheSize"]);
59
59
  const renderer = rendererFactory(webpackConfig, rendererOps);
60
+ if (!webpackConfig.output) throw Error("Missing output config");
60
61
  const {
61
62
  publicPath
62
63
  } = webpackConfig.output;
@@ -69,6 +70,7 @@ export default async function factory(webpackConfig, options) {
69
70
  server.use((req, res, next) => {
70
71
  const schema = req.headers["x-forwarded-proto"];
71
72
  if (schema === "http") {
73
+ if (!req.headers.host) throw Error("Missing host name");
72
74
  let url = `https://${req.headers.host}`;
73
75
  if (req.originalUrl !== "/") url += req.originalUrl;
74
76
  res.redirect(url);
@@ -119,6 +121,7 @@ export default async function factory(webpackConfig, options) {
119
121
  ignoreRequest: options.csrfIgnoreRequest
120
122
  }));
121
123
  loggerMiddleware.token("ip", req => req.clientIp);
124
+ if (!options.logger) throw Error("Missing logger");
122
125
  const FORMAT = ":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";
123
126
  server.use(loggerMiddleware(FORMAT, {
124
127
  stream: {
@@ -130,7 +133,7 @@ export default async function factory(webpackConfig, options) {
130
133
  // to be served from the root, to have all web app pages in its scope.
131
134
  // Thus, this setup to serve it. Probably, need some more configuration
132
135
  // for special cases, but this will do for now.
133
- server.get("/__service-worker.js", express.static(webpackConfig.output?.path ?? "", {
136
+ server.get("/__service-worker.js", express.static(webpackConfig.output.path ?? "", {
134
137
  setHeaders: res => res.set("Cache-Control", "no-cache")
135
138
  })); /* Setup of Hot Module Reloading for development environment.
136
139
  * These dependencies are not used, nor installed for production use,
@@ -160,7 +163,9 @@ export default async function factory(webpackConfig, options) {
160
163
  serverSideRender: true
161
164
  }));
162
165
  } /* eslint-enable import/no-extraneous-dependencies */
163
- server.use(publicPath, express.static(webpackConfig.output.path));
166
+ const outputPath = webpackConfig.output.path;
167
+ if (!outputPath) throw Error("Missing output path");
168
+ server.use(publicPath, express.static(outputPath));
164
169
  if (options.onExpressJsSetup) {
165
170
  await options.onExpressJsSetup(server);
166
171
  }
@@ -189,7 +194,8 @@ export default async function factory(webpackConfig, options) {
189
194
  return;
190
195
  }
191
196
  const status = error.status ?? CODES.INTERNAL_SERVER_ERROR; // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
192
- const serverSide = status >= CODES.INTERNAL_SERVER_ERROR; // Log server-side errors always, client-side at debug level only.
197
+ const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;
198
+ if (!options.logger) throw Error("Missing logger"); // Log server-side errors always, client-side at debug level only.
193
199
  options.logger.log(serverSide ? "error" : "debug", error.stack ?? error.toString());
194
200
  let message = error.message || getErrorForCode(status);
195
201
  if (serverSide && process.env.NODE_ENV === "production") {
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":[],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport helmet, { type HelmetOptions } from 'helmet';\nimport { cloneDeep, mapValues, pick } from 'lodash-es';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport favicon from 'serve-favicon';\n\nimport type { Configuration } from 'webpack';\n\nimport csrf from '@dr.pogodin/csurf';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => Promise<boolean> | boolean;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n csrfIgnoreRequest?: (req: Request) => boolean;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = globalThis.crypto.randomUUID();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({\n cookie: true,\n ignoreRequest: options.csrfIgnoreRequest,\n }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const { default: webpack } = await import(/* webpackChunkName: \"server-side-code\" */ 'webpack');\n\n const { default: webpackDevMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-dev-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n\n server.use(webpackDevMiddleware(compiler, {\n hot: true,\n publicPath,\n serverSideRender: true,\n }));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(\n serverSide ? 'error' : 'debug',\n error.stack ?? error.toString(),\n );\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":"yEAAA;AACA;AACA;AAEA,SAAS,GAAG,QAAQ,WAAW;AAC/B,SAAS,aAAa,QAAQ,UAAU;AAExC,OAAO,WAAW,MAAM,aAAa;AACrC,OAAO,YAAY,MAAM,eAAe;AAExC,OAAO,OAAO,MAKP,SAAS;AAEhB,OAAO,MAAM,MAA8B,QAAQ;AACnD,SAAS,SAAS,EAAE,SAAS,EAAE,IAAI,QAAQ,WAAW;AACtD,OAAO,gBAAgB,MAAM,QAAQ;AACrC,OAAO,SAAS,M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["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport helmet, { type HelmetOptions } from 'helmet';\nimport { cloneDeep, mapValues, pick } from 'lodash-es';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport favicon from 'serve-favicon';\n\nimport type { Configuration } from 'webpack';\n\nimport csrf from '@dr.pogodin/csurf';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => Promise<boolean> | boolean;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n csrfIgnoreRequest?: (req: Request) => boolean;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n if (!webpackConfig.output) throw Error('Missing output config');\n const { publicPath } = webpackConfig.output;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n if (!req.headers.host) throw Error('Missing host name');\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = globalThis.crypto.randomUUID();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({\n cookie: true,\n ignoreRequest: options.csrfIgnoreRequest,\n }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n if (!options.logger) throw Error('Missing logger');\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const { default: webpack } = await import(/* webpackChunkName: \"server-side-code\" */ 'webpack');\n\n const { default: webpackDevMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-dev-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n\n server.use(webpackDevMiddleware(compiler, {\n hot: true,\n publicPath,\n serverSideRender: true,\n }));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n const outputPath = webpackConfig.output.path;\n if (!outputPath) throw Error('Missing output path');\n server.use(publicPath as string, express.static(outputPath));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n if (!options.logger) throw Error('Missing logger');\n // Log server-side errors always, client-side at debug level only.\n options.logger.log(\n serverSide ? 'error' : 'debug',\n error.stack ?? error.toString(),\n );\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":"2EAAA;AACA;AACA;AAEA,SAAS,GAAG,QAAQ,WAAW;AAC/B,SAAS,aAAa,QAAQ,UAAU;AAExC,OAAO,WAAW,MAAM,aAAa;AACrC,OAAO,YAAY,MAAM,eAAe;AAExC,OAAO,OAAO,MAKP,SAAS;AAEhB,OAAO,MAAM,MAA8B,QAAQ;AACnD,SAAS,SAAS,EAAE,SAAS,EAAE,IAAI,QAAQ,WAAW;AACtD,OAAO,gBAAgB,MAAM,QAAQ;AACrC,OAAO,SAAS,MAAM,YAAY;AAClC,OAAO,OAAO,MAAM,eAAe;AAInC,OAAO,IAAI,MAAM,mBAAmB;AAAC,OAE9B,eAAe;AAAA,SAMpB,KAAK,EACL,MAAM,EACN,eAAe,EACf,QAAQ,4BAKV;AAMA;AACA;AACA;AACA;AACA,MAAM,kBAAkB,GAAG;EACzB,UAAU,EAAE,SAAS,CACnB,MAAM,CAAC,qBAAqB,CAAC,oBAAoB,CAAC,CAAC;EAEnD;EACA;EACA;EACA;EACC,KAAK,IAAM,KAAK,CAAc,MAAM,CAAE,IAAY,IAAK,IAAI,KAAK,QAAQ,CAC3E;AACF,CAAC;AACD,kBAAkB,CAAC,UAAU,CAAC,WAAW,CAAC,GAAG,CAC3C,QAAQ;AAER;AACA;AACA,uBAAuB,CACxB;AAED;EACE,MAAM,UAAU,GAAG,kBAAkB,CAAC,UAAU,CAAC,YAAY,CAAC;EAC9D,IAAI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EACjC,IAAI,OAAO,CAAC,oBAAoB,EAAE;IAChC,6BAA6B,GAAG,MAAM,OAAO,CAAC,oBAAoB,CAAC,MAAM,CAAC;EAC5E,CAEA;EACA,IAAI,CAAC,6BAA6B,EAAE;IAClC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,MAAM,CAAC,GAAG,CAAC,CACT,KAEC,EACD,GAAY,EACZ,GAAa,EACb,IAAkB,KACf;MACH;MACA;MACA,IAAI,GAAG,CAAC,WAAW,EAAE;QACnB,IAAI,CAAC,KAAK,CAAC;QACX;MACF;MAEA,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAE1D;MACA,MAAM,UAAU,GAAG,MAAM,IAAI,KAAK,CAAC,qBAAqB;MAExD,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,KAAK,CAAC,gBAAgB,CAAC,CAClD;MACA,OAAO,CAAC,MAAM,CAAC,GAAG,CAChB,UAAU,GAAG,OAAO,GAAG,OAAO,EAC9B,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,QAAQ,CAAC,CAChC,CAAC;MAED,IAAI,OAAO,GAAG,KAAK,CAAC,OAAO,IAAI,eAAe,CAAC,MAAM,CAAC;MACtD,IAAI,UAAU,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,EAAE;QACvD,OAAO,GAAG,MAAM,CAAC,qBAAqB;MACxC;MAEA,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC;IAClC,CAAC,CAAC;EACJ;EAEA,OAAO,MAAM;AACf","ignoreList":[]}
@@ -1,13 +1,13 @@
1
- import _JSON$stringify from "core-js-pure/stable/json/stringify.js"; /**
2
- * @category Utilities
3
- * @module server/errors
4
- * @desc
5
- * ```js
6
- * import { server } from '@dr.pogodin/react-utils';
7
- * const { errors } = server;
8
- * ```
9
- * Server-side helpers for error handling.
10
- */
1
+ import _JSON$stringify from "core-js-pure/features/json/stringify.js"; /**
2
+ * @category Utilities
3
+ * @module server/errors
4
+ * @desc
5
+ * ```js
6
+ * import { server } from '@dr.pogodin/react-utils';
7
+ * const { errors } = server;
8
+ * ```
9
+ * Server-side helpers for error handling.
10
+ */
11
11
  import { StatusCodes as CODES, ReasonPhrases as ERRORS, getReasonPhrase as getErrorForCode } from "http-status-codes"; /**
12
12
  * @static
13
13
  * @const CODES