@dr.pogodin/react-utils 1.48.12 → 1.48.14

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 (109) hide show
  1. package/bin/build.js +4 -7
  2. package/build/development/server/index.js +1 -1
  3. package/build/development/server/index.js.map +1 -1
  4. package/build/development/server/renderer.js +7 -5
  5. package/build/development/server/renderer.js.map +1 -1
  6. package/build/development/server/server.js +1 -1
  7. package/build/development/server/server.js.map +1 -1
  8. package/build/development/server/utils/errors.js +1 -0
  9. package/build/development/server/utils/errors.js.map +1 -1
  10. package/build/development/shared/components/Modal/index.js +1 -1
  11. package/build/development/shared/components/Modal/index.js.map +1 -1
  12. package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
  13. package/build/development/shared/utils/jest/E2eSsrEnv.js +5 -5
  14. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  15. package/build/development/shared/utils/jest/index.js +1 -0
  16. package/build/development/shared/utils/jest/index.js.map +1 -1
  17. package/build/development/shared/utils/webpack.js +1 -1
  18. package/build/development/shared/utils/webpack.js.map +1 -1
  19. package/build/production/client/getInj.js +3 -3
  20. package/build/production/client/getInj.js.map +1 -1
  21. package/build/production/client/index.js +1 -1
  22. package/build/production/client/index.js.map +1 -1
  23. package/build/production/client/init.js +3 -3
  24. package/build/production/client/init.js.map +1 -1
  25. package/build/production/index.js +1 -1
  26. package/build/production/index.js.map +1 -1
  27. package/build/production/server/Cache.js +3 -3
  28. package/build/production/server/Cache.js.map +1 -1
  29. package/build/production/server/index.js +2 -2
  30. package/build/production/server/index.js.map +1 -1
  31. package/build/production/server/renderer.js +20 -20
  32. package/build/production/server/renderer.js.map +1 -1
  33. package/build/production/server/server.js +7 -7
  34. package/build/production/server/server.js.map +1 -1
  35. package/build/production/server/utils/errors.js +5 -5
  36. package/build/production/server/utils/errors.js.map +1 -1
  37. package/build/production/shared/components/Button/index.js +3 -3
  38. package/build/production/shared/components/Button/index.js.map +1 -1
  39. package/build/production/shared/components/Checkbox/index.js +1 -1
  40. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  41. package/build/production/shared/components/GenericLink/index.js +3 -3
  42. package/build/production/shared/components/GenericLink/index.js.map +1 -1
  43. package/build/production/shared/components/Input/index.js +2 -2
  44. package/build/production/shared/components/Input/index.js.map +1 -1
  45. package/build/production/shared/components/Modal/index.js +7 -7
  46. package/build/production/shared/components/Modal/index.js.map +1 -1
  47. package/build/production/shared/components/PageLayout/index.js +1 -1
  48. package/build/production/shared/components/PageLayout/index.js.map +1 -1
  49. package/build/production/shared/components/TextArea/index.js +3 -3
  50. package/build/production/shared/components/TextArea/index.js.map +1 -1
  51. package/build/production/shared/components/Throbber/index.js +1 -1
  52. package/build/production/shared/components/Throbber/index.js.map +1 -1
  53. package/build/production/shared/components/WithTooltip/Tooltip.js +6 -6
  54. package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
  55. package/build/production/shared/components/WithTooltip/index.js +4 -4
  56. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  57. package/build/production/shared/components/YouTubeVideo/index.js +1 -1
  58. package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
  59. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +2 -2
  60. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  61. package/build/production/shared/components/selectors/CustomDropdown/index.js +2 -2
  62. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  63. package/build/production/shared/components/selectors/NativeDropdown/index.js +2 -2
  64. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  65. package/build/production/shared/components/selectors/Switch/index.js +1 -1
  66. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  67. package/build/production/shared/components/selectors/common.js +1 -1
  68. package/build/production/shared/components/selectors/common.js.map +1 -1
  69. package/build/production/shared/utils/config.js +1 -1
  70. package/build/production/shared/utils/config.js.map +1 -1
  71. package/build/production/shared/utils/isomorphy/buildInfo.js +2 -2
  72. package/build/production/shared/utils/isomorphy/buildInfo.js.map +1 -1
  73. package/build/production/shared/utils/isomorphy/index.js +4 -4
  74. package/build/production/shared/utils/isomorphy/index.js.map +1 -1
  75. package/build/production/shared/utils/jest/E2eSsrEnv.js +13 -13
  76. package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  77. package/build/production/shared/utils/jest/global.js +1 -1
  78. package/build/production/shared/utils/jest/global.js.map +1 -1
  79. package/build/production/shared/utils/jest/index.js +11 -11
  80. package/build/production/shared/utils/jest/index.js.map +1 -1
  81. package/build/production/shared/utils/splitComponent.js +12 -12
  82. package/build/production/shared/utils/splitComponent.js.map +1 -1
  83. package/build/production/shared/utils/time.js +2 -2
  84. package/build/production/shared/utils/time.js.map +1 -1
  85. package/build/production/shared/utils/webpack.js +4 -4
  86. package/build/production/shared/utils/webpack.js.map +1 -1
  87. package/build/types-code/server/index.d.ts +1 -1
  88. package/build/types-code/server/renderer.d.ts +1 -1
  89. package/build/web/server/index.js +1 -1
  90. package/build/web/server/index.js.map +1 -1
  91. package/build/web/server/renderer.js +7 -5
  92. package/build/web/server/renderer.js.map +1 -1
  93. package/build/web/server/server.js +1 -1
  94. package/build/web/server/server.js.map +1 -1
  95. package/build/web/server/utils/errors.js +1 -0
  96. package/build/web/server/utils/errors.js.map +1 -1
  97. package/build/web/shared/components/Modal/index.js +1 -1
  98. package/build/web/shared/components/Modal/index.js.map +1 -1
  99. package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
  100. package/build/web/shared/utils/jest/E2eSsrEnv.js +5 -5
  101. package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  102. package/build/web/shared/utils/jest/index.js +1 -0
  103. package/build/web/shared/utils/jest/index.js.map +1 -1
  104. package/build/web/shared/utils/webpack.js +1 -1
  105. package/build/web/shared/utils/webpack.js.map +1 -1
  106. package/config/webpack/app-base.js +2 -2
  107. package/config/webpack/app-development.js +1 -1
  108. package/package.json +18 -18
  109. package/tsconfig.json +1 -1
@@ -1,6 +1,6 @@
1
- import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterator.map.js";import"core-js/modules/es.set.difference.v2.js";import"core-js/modules/es.set.intersection.v2.js";import"core-js/modules/es.set.is-disjoint-from.v2.js";import"core-js/modules/es.set.is-subset-of.v2.js";import"core-js/modules/es.set.is-superset-of.v2.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterator.map.js";import"core-js/modules/es.set.difference.v2.js";import"core-js/modules/es.set.intersection.v2.js";import"core-js/modules/es.set.is-disjoint-from.v2.js";import"core-js/modules/es.set.is-subset-of.v2.js";import"core-js/modules/es.set.is-superset-of.v2.js";import"core-js/modules/es.set.symmetric-difference.v2.js";import"core-js/modules/es.set.union.v2.js";/**
1
+ import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterator.map.js";import"core-js/modules/es.set.difference.v2.js";import"core-js/modules/es.set.intersection.v2.js";import"core-js/modules/es.set.is-disjoint-from.v2.js";import"core-js/modules/es.set.is-subset-of.v2.js";import"core-js/modules/es.set.is-superset-of.v2.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterator.map.js";import"core-js/modules/es.json.parse.js";import"core-js/modules/es.json.stringify.js";import"core-js/modules/es.set.difference.v2.js";import"core-js/modules/es.set.intersection.v2.js";import"core-js/modules/es.set.is-disjoint-from.v2.js";import"core-js/modules/es.set.is-subset-of.v2.js";import"core-js/modules/es.set.is-superset-of.v2.js";import"core-js/modules/es.set.symmetric-difference.v2.js";import"core-js/modules/es.set.union.v2.js";/**
2
2
  * ExpressJS middleware for server-side rendering of a ReactJS app.
3
- */import{Buffer}from"node:buffer";import{createCipheriv,randomBytes}from"node:crypto";import fs from"node:fs";import path from"node:path";import{Writable}from"node:stream";import{brotliCompress,brotliDecompress}from"node:zlib";import winston from"winston";import{timer}from"@dr.pogodin/js-utils";import{GlobalStateProvider,SsrContext}from"@dr.pogodin/react-global-state";import{cloneDeep,defaults,get,mapValues}from"lodash-es";import config from"config";import{HelmetProvider}from"@dr.pogodin/react-helmet";import{prerenderToNodeStream}from"react-dom/static";import{StaticRouter}from"react-router";import serializeJs from"serialize-javascript";import{setBuildInfo}from"../shared/utils/isomorphy/buildInfo.js";import Cache from"./Cache.js";// @ts-expect-error "Property 'SECRET' does not exist on type 'IConfig'."
3
+ */import{Buffer}from"node:buffer";import{createCipheriv,randomBytes}from"node:crypto";import fs from"node:fs";import path from"node:path";import{Writable}from"node:stream";import{brotliCompress,brotliDecompress}from"node:zlib";import config from"config";import{cloneDeep,defaults,get,mapValues}from"lodash-es";import{prerenderToNodeStream}from"react-dom/static";import{StaticRouter}from"react-router";import serializeJs from"serialize-javascript";import winston from"winston";import{timer}from"@dr.pogodin/js-utils";import{GlobalStateProvider,SsrContext}from"@dr.pogodin/react-global-state";import{HelmetProvider}from"@dr.pogodin/react-helmet";import{setBuildInfo}from"../shared/utils/isomorphy/buildInfo.js";import Cache from"./Cache.js";// @ts-expect-error "Property 'SECRET' does not exist on type 'IConfig'."
4
4
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
5
5
  import{jsx as _jsx}from"react/jsx-runtime";const{SECRET,...sanitizedConfig}=config;// Note: These type definitions for logger are copied from Winston logger,
6
6
  // then simplified to make it easier to fit an alternative logger into this
@@ -8,7 +8,7 @@ import{jsx as _jsx}from"react/jsx-runtime";const{SECRET,...sanitizedConfig}=conf
8
8
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
9
9
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
10
10
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
11
- export let SCRIPT_LOCATIONS=/*#__PURE__*/function(SCRIPT_LOCATIONS){SCRIPT_LOCATIONS["BODY_OPEN"]="BODY_OPEN";SCRIPT_LOCATIONS["DEFAULT"]="DEFAULT";SCRIPT_LOCATIONS["HEAD_OPEN"]="HEAD_OPEN";return SCRIPT_LOCATIONS}({});export class ServerSsrContext extends SsrContext{chunks=[];status=200;constructor(req,chunkGroups,initialState){super(cloneDeep(initialState)??{});this.chunkGroups=chunkGroups;this.req=req}}/**
11
+ export let SCRIPT_LOCATIONS=/*#__PURE__*/function(SCRIPT_LOCATIONS){SCRIPT_LOCATIONS["BODY_OPEN"]="BODY_OPEN";SCRIPT_LOCATIONS["DEFAULT"]="DEFAULT";SCRIPT_LOCATIONS["HEAD_OPEN"]="HEAD_OPEN";return SCRIPT_LOCATIONS;}({});export class ServerSsrContext extends SsrContext{chunks=[];status=200;constructor(req,chunkGroups,initialState){super(cloneDeep(initialState)??{});this.chunkGroups=chunkGroups;this.req=req;}}/**
12
12
  * Reads build-time information about the app. This information is generated
13
13
  * by our standard Webpack config for apps, and it is written into
14
14
  * ".build-info" file in the context folder specified in Webpack config.
@@ -16,25 +16,25 @@ export let SCRIPT_LOCATIONS=/*#__PURE__*/function(SCRIPT_LOCATIONS){SCRIPT_LOCAT
16
16
  * suitable for cryptographical use.
17
17
  * @param context Webpack context path used during the build.
18
18
  * @return Resolves to the build-time information.
19
- */function getBuildInfo(context){const url=path.resolve(context,".build-info");return JSON.parse(fs.readFileSync(url,"utf8"))}/**
19
+ */function getBuildInfo(context){const url=path.resolve(context,".build-info");return JSON.parse(fs.readFileSync(url,"utf8"));}/**
20
20
  * Attempts to read from disk the named chunk groups mapping generated
21
21
  * by Webpack during the compilation.
22
22
  * It will not work for development builds, where these stats should be captured
23
23
  * via compilator callback.
24
24
  * @param buildDir
25
25
  * @return
26
- */function readChunkGroupsJson(buildDir){const url=path.resolve(buildDir,"__chunk_groups__.json");let res;try{res=JSON.parse(fs.readFileSync(url,"utf8"))}catch{// TODO: Should we message the error here somehow?
27
- res=null}return res}/**
26
+ */function readChunkGroupsJson(buildDir){const url=path.resolve(buildDir,"__chunk_groups__.json");let res;try{res=JSON.parse(fs.readFileSync(url,"utf8"));}catch{// TODO: Should we message the error here somehow?
27
+ res=null;}return res;}/**
28
28
  * Prepares a new Cipher for data encryption.
29
29
  * @param key Encryption key (32-bit random, Base64-encoded key is expected).
30
30
  * @return Returns a tuple of:
31
31
  * 1. cipher - a new Cipher, ready for encryption;
32
32
  * 2. iv - initial vector used by the cipher.
33
- */function prepareCipher(key){const iv=randomBytes(16);const cipher=createCipheriv("AES-256-CBC",Buffer.from(key,"base64"),iv);return[cipher,iv]}/**
33
+ */function prepareCipher(key){const iv=randomBytes(16);const cipher=createCipheriv("AES-256-CBC",Buffer.from(key,"base64"),iv);return[cipher,iv];}/**
34
34
  * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses
35
35
  * are acceptable to the caller.
36
36
  * @param req
37
- */export function isBrotliAcceptable(req){const acceptable=req.get("accept-encoding");if(acceptable){const ops=acceptable.split(",");for(const op of ops){const[type,priority]=op.trim().split(";q=");if((type==="*"||type==="br")&&(!priority||parseFloat(priority)>0)){return true}}}return false}/**
37
+ */export function isBrotliAcceptable(req){const acceptable=req.get("accept-encoding");if(acceptable){const ops=acceptable.split(",");for(const op of ops){const[type,priority]=op.trim().split(";q=");if((type==="*"||type==="br")&&(!priority||parseFloat(priority)>0)){return true;}}}return false;}/**
38
38
  * Given an array of extra script strings / objects, it returns an object with
39
39
  * arrays of scripts to inject in different HTML template locations. During
40
40
  * the script groupping it also filters out any empty scripts.
@@ -47,12 +47,12 @@ res=null}return res}/**
47
47
  * DEFAULT: string[];
48
48
  * HEAD_OPEN: string[];
49
49
  * }}
50
- */function groupExtraScripts(scripts=[]){const res={[SCRIPT_LOCATIONS.BODY_OPEN]:"",[SCRIPT_LOCATIONS.DEFAULT]:"",[SCRIPT_LOCATIONS.HEAD_OPEN]:""};for(const script of scripts){if(typeof script==="string"){if(script)res[SCRIPT_LOCATIONS.DEFAULT]+=script}else if(script.code){if(script.location in res)res[script.location]+=script.code;else throw Error(`Invalid location "${script.location}"`)}}return res}/**
50
+ */function groupExtraScripts(scripts=[]){const res={[SCRIPT_LOCATIONS.BODY_OPEN]:"",[SCRIPT_LOCATIONS.DEFAULT]:"",[SCRIPT_LOCATIONS.HEAD_OPEN]:""};for(const script of scripts){if(typeof script==="string"){if(script)res[SCRIPT_LOCATIONS.DEFAULT]+=script;}else if(script.code){if(script.location in res)res[script.location]+=script.code;else throw Error(`Invalid location "${script.location}"`);}}return res;}/**
51
51
  * Creates a new default (Winston) logger.
52
52
  * @param {object} [options={}]
53
53
  * @param {string} [options.defaultLogLevel='info']
54
54
  * @return {object}
55
- */export function newDefaultLogger({defaultLogLevel="info"}={}){const{format,transports}=winston;return winston.createLogger({format:format.combine(format.splat(),format.timestamp(),format.colorize(),format.printf(({level,message,stack,timestamp,...rest})=>{let res=`${level}\t(at ${timestamp}):\t${message}`;if(Object.keys(rest).length){res+=`\n${JSON.stringify(rest,null,2)}`}if(stack)res+=`\n${stack}`;return res})),level:defaultLogLevel,transports:[new transports.Console]})}/**
55
+ */export function newDefaultLogger({defaultLogLevel="info"}={}){const{format,transports}=winston;return winston.createLogger({format:format.combine(format.splat(),format.timestamp(),format.colorize(),format.printf(({level,message,stack,timestamp,...rest})=>{let res=`${level}\t(at ${timestamp}):\t${message}`;if(Object.keys(rest).length){res+=`\n${JSON.stringify(rest,null,2)}`;}if(stack)res+=`\n${stack}`;return res;})),level:defaultLogLevel,transports:[new transports.Console]});}/**
56
56
  * Creates the middleware.
57
57
  * @param webpackConfig
58
58
  * @param options Additional options:
@@ -90,15 +90,15 @@ const{path:outputPath,publicPath}=webpackConfig.output;const manifestLink=fs.exi
90
90
  const cache=ops.staticCacheController?new Cache(ops.staticCacheSize):null;const CHUNK_GROUPS=readChunkGroupsJson(outputPath);// TODO: Look at it later.
91
91
  // eslint-disable-next-line complexity
92
92
  return async(req,res,next)=>{try{// Ensures any caches always revalidate HTML markup before reuse.
93
- res.set("Cache-Control","no-cache");res.cookie("csrfToken",req.csrfToken());let cacheRef;if(cache){cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){const{buffer,status}=data;if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");if(status!==200)res.status(status);res.send(buffer)}else{await new Promise((done,failed)=>{brotliDecompress(buffer,(error,html)=>{if(error)failed(error);else{let h=html.toString();if(!ops.noCsp){// TODO: Starting from Node v15 we'll be able to use string's
93
+ res.set("Cache-Control","no-cache");res.cookie("csrfToken",req.csrfToken());let cacheRef;if(cache){cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){const{buffer,status}=data;if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");if(status!==200)res.status(status);res.send(buffer);}else{await new Promise((done,failed)=>{brotliDecompress(buffer,(error,html)=>{if(error)failed(error);else{let h=html.toString();if(!ops.noCsp){// TODO: Starting from Node v15 we'll be able to use string's
94
94
  // .replaceAll() method instead relying on reg. expression for
95
95
  // global matching.
96
96
  const regex=new RegExp(buffer.nonce,"g");// TODO: It should be implemented more careful.
97
- h=h.replace(regex,req.nonce)}if(status!==200)res.status(status);res.send(h);done()}})})}return}}}const brr=ops.beforeRender(req,sanitizedConfig);const{configToInject,extraScripts,initialState}=await brr;const[cipher,iv]=prepareCipher(buildInfo.key);let helmet;// Gets the mapping between code chunk names and their asset files.
97
+ h=h.replace(regex,req.nonce);}if(status!==200)res.status(status);res.send(h);done();}});});}return;}}}const brr=ops.beforeRender(req,sanitizedConfig);const{configToInject,extraScripts,initialState}=await brr;const[cipher,iv]=prepareCipher(buildInfo.key);let helmet;// Gets the mapping between code chunk names and their asset files.
98
98
  // These data come from the Webpack compilation, either from the stats
99
99
  // attached to the request (in dev mode), or from a file output during
100
100
  // the build (in prod mode).
101
- let chunkGroups;const webpackStats=get(res.locals,"webpack.devMiddleware.stats");if(webpackStats){chunkGroups=mapValues(webpackStats.toJson({all:false,chunkGroups:true}).namedChunkGroups,item=>item.assets?.map(({name})=>name)??[])}else if(CHUNK_GROUPS)chunkGroups=CHUNK_GROUPS;else chunkGroups={};/* Optional server-side rendering. */const App=ops.Application;let appHtmlMarkup="";const ssrContext=new ServerSsrContext(req,chunkGroups,initialState);let stream;if(App){const ssrStart=Date.now();// TODO: Somehow, without it TS does not realise that
101
+ let chunkGroups;const webpackStats=get(res.locals,"webpack.devMiddleware.stats");if(webpackStats){chunkGroups=mapValues(webpackStats.toJson({all:false,chunkGroups:true}).namedChunkGroups,item=>item.assets?.map(({name})=>name)??[]);}else if(CHUNK_GROUPS)chunkGroups=CHUNK_GROUPS;else chunkGroups={};/* Optional server-side rendering. */const App=ops.Application;let appHtmlMarkup="";const ssrContext=new ServerSsrContext(req,chunkGroups,initialState);let stream;if(App){const ssrStart=Date.now();// TODO: Somehow, without it TS does not realise that
102
102
  // App has been checked to exist.
103
103
  const App2=App;const renderPass=async()=>new Promise((resolveArg,rejectArg)=>{ssrContext.chunks=[];// NOTE: JS does not have problems if resolve() and reject() methods
104
104
  // of a Promise are called multiple times, with different arguments;
@@ -106,12 +106,12 @@ const App2=App;const renderPass=async()=>new Promise((resolveArg,rejectArg)=>{ss
106
106
  // We, however, really want to assert that here, to safeguard against
107
107
  // any future problems due to unexpected internal changes in React,
108
108
  // if any.
109
- let error;const resolve=arg=>{if(error!==undefined)throw Error("Internal error");error=null;resolveArg(arg)};const reject=arg=>{if(error!==undefined&&error!==arg){throw Error("Internal error")}error=arg;rejectArg(arg)};// TODO: prerenderToNodeStream has (abort) "signal" option,
109
+ let error;const resolve=arg=>{if(error!==undefined)throw Error("Internal error");error=null;resolveArg(arg);};const reject=arg=>{if(error!==undefined&&error!==arg){throw Error("Internal error");}error=arg;rejectArg(arg);};// TODO: prerenderToNodeStream has (abort) "signal" option,
110
110
  // and we should wire it up to the SSR timeout below.
111
- const helmetContext={};void prerenderToNodeStream(/*#__PURE__*/_jsx(GlobalStateProvider,{initialState:ssrContext.state,ssrContext:ssrContext,children:/*#__PURE__*/_jsx(StaticRouter,{location:req.url,children:/*#__PURE__*/_jsx(HelmetProvider,{context:helmetContext,children:/*#__PURE__*/_jsx(App2,{})})})}),{onError:reject}).then(result=>{({helmet}=helmetContext);resolve(result.prelude)}).catch(reject)});let ssrRound=0;let bailed=false;for(;ssrRound<ops.maxSsrRounds;++ssrRound){stream=await renderPass();if(!ssrContext.dirty)break;const timeout=ops.ssrTimeout+ssrStart-Date.now();bailed=timeout<=0||!(await Promise.race([Promise.allSettled(ssrContext.pending),timer(timeout).then(()=>false)]));if(bailed)break}let logMsg;if(ssrContext.dirty){// NOTE: In the case of incomplete SSR one more round is necessary
111
+ const helmetContext={};void prerenderToNodeStream(/*#__PURE__*/_jsx(GlobalStateProvider,{initialState:ssrContext.state,ssrContext:ssrContext,children:/*#__PURE__*/_jsx(StaticRouter,{location:req.url,children:/*#__PURE__*/_jsx(HelmetProvider,{context:helmetContext,children:/*#__PURE__*/_jsx(App2,{})})})}),{onError:reject}).then(result=>{({helmet}=helmetContext);resolve(result.prelude);}).catch(reject);});let ssrRound=0;let bailed=false;for(;ssrRound<ops.maxSsrRounds;++ssrRound){stream=await renderPass();if(!ssrContext.dirty)break;const timeout=ops.ssrTimeout+ssrStart-Date.now();bailed=timeout<=0||!(await Promise.race([Promise.allSettled(ssrContext.pending),timer(timeout).then(()=>false)]));if(bailed)break;}let logMsg;if(ssrContext.dirty){// NOTE: In the case of incomplete SSR one more round is necessary
112
112
  // to ensure the correct hydration when some pending promises have
113
113
  // resolved and placed their data into the initial global state.
114
- stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} second(s)`:`SSR bailed out after ${ops.maxSsrRounds} round(s)`}else logMsg=`SSR completed in ${ssrRound+1} round(s)`;ops.logger.log(ssrContext.dirty?"warn":"info",logMsg);if(ssrContext.redirectTo){res.redirect(ssrContext.status,ssrContext.redirectTo);return}await new Promise(ready=>{stream.pipe(new Writable({destroy:ready,write:(chunk,_,done)=>{appHtmlMarkup+=chunk.toString();done()}}))})}/* Encrypts data to be injected into HTML.
114
+ stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} second(s)`:`SSR bailed out after ${ops.maxSsrRounds} round(s)`;}else logMsg=`SSR completed in ${ssrRound+1} round(s)`;ops.logger.log(ssrContext.dirty?"warn":"info",logMsg);if(ssrContext.redirectTo){res.redirect(ssrContext.status,ssrContext.redirectTo);return;}await new Promise(ready=>{stream.pipe(new Writable({destroy:ready,write:(chunk,_,done)=>{appHtmlMarkup+=chunk.toString();done();}}));});}/* Encrypts data to be injected into HTML.
115
115
  * Keep in mind, that this encryption is no way secure: as the JS bundle
116
116
  * contains decryption key and is able to decode it at the client side.
117
117
  * Hovewer, for a number of reasons, encryption of injected data is still
@@ -123,9 +123,9 @@ stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} s
123
123
  // remove or add other entry points, but it requires additional
124
124
  // efforts to figure out how to automatically order them right,
125
125
  // thus for now this handles the default config.
126
- ["main",...ssrContext.chunks].forEach(chunk=>{const assets=chunkGroups[chunk];if(assets){assets.forEach(asset=>{chunkSet.add(asset)})}});let styleChunkString="";let scriptChunkString="";chunkSet.forEach(chunk=>{if(chunk.endsWith(".css")){styleChunkString+=`<link href="${publicPath}${chunk}" rel="stylesheet">`}else if(chunk.endsWith(".js")// In dev mode HMR adds JS updates into asset arrays,
126
+ ["main",...ssrContext.chunks].forEach(chunk=>{const assets=chunkGroups[chunk];if(assets){assets.forEach(asset=>{chunkSet.add(asset);});}});let styleChunkString="";let scriptChunkString="";chunkSet.forEach(chunk=>{if(chunk.endsWith(".css")){styleChunkString+=`<link href="${publicPath}${chunk}" rel="stylesheet">`;}else if(chunk.endsWith(".js")// In dev mode HMR adds JS updates into asset arrays,
127
127
  // and they (updates) should be ignored.
128
- &&!chunk.endsWith(".hot-update.js")){scriptChunkString+=`<script src="${publicPath}${chunk}" type="application/javascript"></script>`}});const grouppedExtraScripts=groupExtraScripts(extraScripts);const faviconLink=ops.favicon?"<link rel=\"shortcut icon\" href=\"/favicon.ico\">":"";const html=`<!DOCTYPE html>
128
+ &&!chunk.endsWith(".hot-update.js")){scriptChunkString+=`<script src="${publicPath}${chunk}" type="application/javascript"></script>`;}});const grouppedExtraScripts=groupExtraScripts(extraScripts);const faviconLink=ops.favicon?"<link rel=\"shortcut icon\" href=\"/favicon.ico\">":"";const html=`<!DOCTYPE html>
129
129
  <html lang="en">
130
130
  <head>
131
131
  ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}
@@ -150,8 +150,8 @@ stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} s
150
150
  </body>
151
151
  </html>`;const status=ssrContext.status||200;if(status!==200)res.status(status);if(cacheRef&&status<500){// Note: waiting for the caching to complete is not strictly necessary,
152
152
  // but it greately simplifies testing, and error reporting.
153
- await new Promise((done,failed)=>{brotliCompress(html,(error,buffer)=>{if(error)failed(error);else{const b=buffer;b.nonce=req.nonce;cache.add({buffer:b,status},cacheRef.key,buffer.length);done()}})})}// Note: as caching code above may throw in some cases, sending response
153
+ await new Promise((done,failed)=>{brotliCompress(html,(error,buffer)=>{if(error)failed(error);else{const b=buffer;b.nonce=req.nonce;cache.add({buffer:b,status},cacheRef.key,buffer.length);done();}});});}// Note: as caching code above may throw in some cases, sending response
154
154
  // before it completes will likely hide the error, making it difficult
155
155
  // to debug. Thus, at least for now, lets send response after it.
156
- res.send(html)}catch(error){next(error)}}}
156
+ res.send(html);}catch(error){next(error);}};}
157
157
  //# sourceMappingURL=renderer.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"renderer.js","names":["Buffer","createCipheriv","randomBytes","fs","path","Writable","brotliCompress","brotliDecompress","winston","timer","GlobalStateProvider","SsrContext","cloneDeep","defaults","get","mapValues","config","HelmetProvider","prerenderToNodeStream","StaticRouter","serializeJs","setBuildInfo","Cache","jsx","_jsx","SECRET","sanitizedConfig","SCRIPT_LOCATIONS","ServerSsrContext","chunks","status","constructor","req","chunkGroups","initialState","getBuildInfo","context","url","resolve","JSON","parse","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","iv","cipher","from","isBrotliAcceptable","acceptable","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","beforeRender","Promise","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","outputPath","publicPath","output","manifestLink","existsSync","cache","staticCacheController","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","helmet","webpackStats","locals","toJson","all","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","reject","helmetContext","state","children","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","logMsg","log","redirectTo","redirect","ready","pipe","destroy","write","chunk","_","payload","CONFIG","ISTATE","ignoreFunction","unsafe","INJ","concat","update","final","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","b"],"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 type { Request, RequestHandler } from 'express';\nimport type { ComponentType } from 'react';\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';\n\nimport {\n cloneDeep,\n defaults,\n get,\n mapValues,\n} from 'lodash-es';\n\nimport config from 'config';\n\nimport { type HelmetDataContext, HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\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, ...sanitizedConfig } = 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 redirectTo?: string;\n\n req: Request;\n\n status: number = 200;\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\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\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\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, sanitizedConfig as unknown as ConfigT);\n const { configToInject, extraScripts, initialState } = await brr;\n\n const [cipher, iv] = prepareCipher(buildInfo.key);\n\n let helmet: HelmetDataContext['helmet'];\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) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name)\n ?? [],\n );\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 const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n 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 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 const helmetContext = {} as HelmetDataContext;\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\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 ?? sanitizedConfig,\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 ? '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet?.title.toString() ?? ''}\n ${helmet?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmet?.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":"00BAAA;AACA;AACA,GAEA,OAASA,MAAM,KAAQ,aAAa,CACpC,OAAwBC,cAAc,CAAEC,WAAW,KAAQ,aAAa,CACxE,MAAO,CAAAC,EAAE,KAAM,SAAS,CACxB,MAAO,CAAAC,IAAI,KAAM,WAAW,CAC5B,OAASC,QAAQ,KAAQ,aAAa,CACtC,OAASC,cAAc,CAAEC,gBAAgB,KAAQ,WAAW,CAK5D,MAAO,CAAAC,OAAO,KAAM,SAAS,CAE7B,OAASC,KAAK,KAAQ,sBAAsB,CAC5C,OAASC,mBAAmB,CAAEC,UAAU,KAAQ,gCAAgC,CAEhF,OACEC,SAAS,CACTC,QAAQ,CACRC,GAAG,CACHC,SAAS,KACJ,WAAW,CAElB,MAAO,CAAAC,MAAM,KAAM,QAAQ,CAE3B,OAAiCC,cAAc,KAAQ,0BAA0B,CACjF,OAASC,qBAAqB,KAAQ,kBAAkB,CACxD,OAASC,YAAY,KAAQ,cAAc,CAC3C,MAAO,CAAAC,WAAW,KAAM,sBAAsB,QACpBC,YAAY,oDAI/B,CAAAC,KAAK,kBAEZ;AACA;AAAA,OAAAC,GAAA,IAAAC,IAAA,yBACA,KAAM,CAAEC,MAAM,CAAE,GAAGC,eAAgB,CAAC,CAAGV,MAAM,CAE7C;AACA;AACA;AACA;AAMA;AAMA;AASA,UAAY,CAAAW,gBAAgB,uBAAhBA,gBAAgB,EAAhBA,gBAAgB,0BAAhBA,gBAAgB,sBAAhBA,gBAAgB,gCAAhB,CAAAA,gBAAgB,MAM5B,MAAO,MAAM,CAAAC,gBAAgB,QACnB,CAAAjB,UACuB,CAG/BkB,MAAM,CAAa,EAAE,CAMrBC,MAAM,CAAW,GAAG,CAEpBC,WAAWA,CACTC,GAAY,CACZC,WAAyB,CACzBC,YAAqB,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AAM,CAACA,MAAM,CAAC,CAEtC,GAAIgF,QAAQ,EAAIhF,MAAM,CAAG,GAAG,CAAE,CAC5B;AACA;AACA,KAAM,IAAI,CAAA6D,OAAO,CAAO,CAACwB,IAAI,CAAEC,MAAM,GAAK,CACxC9G,cAAc,CAACgH,IAAI,CAAE,CAACD,KAAK,CAAEL,MAAM,GAAK,CACtC,GAAIK,KAAK,CAAED,MAAM,CAACC,KAAK,CAAC,CAAC,IACpB,CACH,KAAM,CAAAoF,CAAC,CAAGzF,MAAoC,CAC9CyF,CAAC,CAAC9E,KAAK,CAAI3F,GAAG,CAEX2F,KAAK,CACRpB,KAAK,CAAEwF,GAAG,CAAC,CAAE/E,MAAM,CAAEyF,CAAC,CAAE3K,MAAO,CAAC,CAAEgF,QAAQ,CAAChE,GAAG,CAAEkE,MAAM,CAAC5B,MAAM,CAAC,CAC9D+B,IAAI,CAAC,CACP,CACF,CAAC,CACH,CAAC,CACH,CAEA;AACA;AACA;AACAvE,GAAG,CAACsE,IAAI,CAACI,IAAI,CACf,CAAE,MAAOD,KAAK,CAAE,CACdX,IAAI,CAACW,KAAK,CACZ,CACF,CACF","ignoreList":[]}
1
+ {"version":3,"file":"renderer.js","names":["Buffer","createCipheriv","randomBytes","fs","path","Writable","brotliCompress","brotliDecompress","config","cloneDeep","defaults","get","mapValues","prerenderToNodeStream","StaticRouter","serializeJs","winston","timer","GlobalStateProvider","SsrContext","HelmetProvider","setBuildInfo","Cache","jsx","_jsx","SECRET","sanitizedConfig","SCRIPT_LOCATIONS","ServerSsrContext","chunks","status","constructor","req","chunkGroups","initialState","getBuildInfo","context","url","resolve","JSON","parse","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","iv","cipher","from","isBrotliAcceptable","acceptable","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","beforeRender","Promise","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","outputPath","publicPath","output","manifestLink","existsSync","cache","staticCacheController","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","helmet","webpackStats","locals","toJson","all","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","reject","helmetContext","state","children","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","logMsg","log","redirectTo","redirect","ready","pipe","destroy","write","chunk","_","payload","CONFIG","ISTATE","ignoreFunction","unsafe","INJ","concat","update","final","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","b"],"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 { type HelmetDataContext, HelmetProvider } 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, ...sanitizedConfig } = 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 redirectTo?: string;\n\n req: Request;\n\n status: number = 200;\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\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\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\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, sanitizedConfig as unknown as ConfigT);\n const { configToInject, extraScripts, initialState } = await brr;\n\n const [cipher, iv] = prepareCipher(buildInfo.key);\n\n let helmet: HelmetDataContext['helmet'];\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) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name)\n ?? [],\n );\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 const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n 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 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 const helmetContext = {} as HelmetDataContext;\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\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 ?? sanitizedConfig,\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 ? '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet?.title.toString() ?? ''}\n ${helmet?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmet?.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":"g6BAAA;AACA;AACA,GAEA,OAASA,MAA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AIA,MAAM,GAAK,GAAG,CAAEc,GAAG,CAACd,MAAM,CAACA,MAAM,CAAC,CAEtC,GAAIgF,QAAQ,EAAIhF,MAAM,CAAG,GAAG,CAAE,CAC5B;AACA;AACA,KAAM,IAAI,CAAA6D,OAAO,CAAO,CAACwB,IAAI,CAAEC,MAAM,GAAK,CACxC9G,cAAc,CAACgH,IAAI,CAAE,CAACD,KAAK,CAAEL,MAAM,GAAK,CACtC,GAAIK,KAAK,CAAED,MAAM,CAACC,KAAK,CAAC,CAAC,IACpB,CACH,KAAM,CAAAoF,CAAC,CAAGzF,MAAoC,CAC9CyF,CAAC,CAAC9E,KAAK,CAAI3F,GAAG,CAEX2F,KAAK,CACRpB,KAAK,CAAEwF,GAAG,CAAC,CAAE/E,MAAM,CAAEyF,CAAC,CAAE3K,MAAO,CAAC,CAAEgF,QAAQ,CAAChE,GAAG,CAAEkE,MAAM,CAAC5B,MAAM,CAAC,CAC9D+B,IAAI,CAAC,CAAC,CACR,CACF,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA;AACA;AACA;AACAvE,GAAG,CAACsE,IAAI,CAACI,IAAI,CAAC,CAChB,CAAE,MAAOD,KAAK,CAAE,CACdX,IAAI,CAACW,KAAK,CAAC,CACb,CACF,CAAC,CACH","ignoreList":[]}
@@ -1,6 +1,6 @@
1
1
  import"core-js/modules/es.iterator.filter.js";import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";/**
2
2
  * Creation of standard ExpressJS server for ReactJS apps.
3
- */import{sep}from"node:path";import{pathToFileURL}from"node:url";import{cloneDeep,mapValues,pick}from"lodash-es";import compression from"compression";import cookieParser from"cookie-parser";import express from"express";import helmet from"helmet";import loggerMiddleware from"morgan";import requestIp from"request-ip";import favicon from"serve-favicon";import{v4 as uuid}from"uuid";import csrf from"@dr.pogodin/csurf";import rendererFactory from"./renderer.js";import{CODES,ERRORS,getErrorForCode,newError}from"./utils/errors.js";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
3
+ */import{sep}from"node:path";import{pathToFileURL}from"node:url";import compression from"compression";import cookieParser from"cookie-parser";import express from"express";import helmet from"helmet";import{cloneDeep,mapValues,pick}from"lodash-es";import loggerMiddleware from"morgan";import requestIp from"request-ip";import favicon from"serve-favicon";import{v4 as uuid}from"uuid";import csrf from"@dr.pogodin/csurf";import rendererFactory from"./renderer.js";import{CODES,ERRORS,getErrorForCode,newError}from"./utils/errors.js";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
4
4
  /**
5
5
  * Default Content Security Policy settings.
6
6
  * @ignore
@@ -10,7 +10,7 @@ import"core-js/modules/es.iterator.filter.js";import"core-js/modules/es.array.pu
10
10
  // care about such re-writes.
11
11
  array=>array.filter(item=>item!=="https:"))};defaultCspSettings.directives["frame-src"]=["'self'",// YouTube domain is whitelisted to allow <YouTubeVideo> component to work
12
12
  // out of box.
13
- "https://*.youtube.com"];{const directives=defaultCspSettings.directives["script-src"];if(directives)directives.push("'unsafe-eval'");else defaultCspSettings.directives["script-src"]=["'unsafe-eval'"]}// No need for automatic re-writes via Content Security Policy settings:
13
+ "https://*.youtube.com"];{const directives=defaultCspSettings.directives["script-src"];if(directives)directives.push("'unsafe-eval'");else defaultCspSettings.directives["script-src"]=["'unsafe-eval'"];}// No need for automatic re-writes via Content Security Policy settings:
14
14
  // the forefront Apache or Nginx server is supposed to take care of this
15
15
  // in production cloud deployments.
16
16
  delete defaultCspSettings.directives["upgrade-insecure-requests"];/**
@@ -27,11 +27,11 @@ delete defaultCspSettings.directives["upgrade-insecure-requests"];/**
27
27
  * }} A deep copy of default CSP settings object used by `react-utils`,
28
28
  * with the exception of `nonce-xxx` clause in `script-src` directive,
29
29
  * which is added dynamically for each request.
30
- */export function getDefaultCspSettings(){return cloneDeep(defaultCspSettings)}export default async function factory(webpackConfig,options){const rendererOps=pick(options,["Application","beforeRender","favicon","logger","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=rendererFactory(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=express();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server)}if(options.logger)server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;res.redirect(url);return}next()})}server.use(compression());server.use(helmet({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{const req2=req;req2.nonce=uuid();// TODO: This is deprecated, but it is kept for now for backward
30
+ */export function getDefaultCspSettings(){return cloneDeep(defaultCspSettings);}export default async function factory(webpackConfig,options){const rendererOps=pick(options,["Application","beforeRender","favicon","logger","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=rendererFactory(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=express();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server);}if(options.logger)server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;res.redirect(url);return;}next();});}server.use(compression());server.use(helmet({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{const req2=req;req2.nonce=uuid();// TODO: This is deprecated, but it is kept for now for backward
31
31
  // compatibility. Should be removed sometime later.
32
32
  req2.cspNonce=req2.nonce;// The deep clone is necessary here to ensure that default value can't be
33
33
  // mutated during request processing.
34
- let cspSettings=cloneDeep(defaultCspSettings);(cspSettings.directives?.["script-src"]).push(`'nonce-${req2.nonce}'`);if(options.cspSettingsHook){cspSettings=options.cspSettingsHook(cspSettings,req)}helmet.contentSecurityPolicy(cspSettings)(req,res,next)})}if(options.favicon){server.use(favicon(options.favicon))}server.use("/robots.txt",(req,res)=>{res.send("User-agent: *\nDisallow:")});server.use(express.json({limit:"300kb"}));server.use(express.urlencoded({extended:false}));server.use(cookieParser(options.cookieSignatureSecret));server.use(requestIp.mw());server.use(csrf({cookie:true,ignoreRequest:options.csrfIgnoreRequest}));loggerMiddleware.token("ip",req=>req.clientIp);const FORMAT=":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";server.use(loggerMiddleware(FORMAT,{stream:{// TODO: This implies the logger is always set. Is it on a higher level?
34
+ let cspSettings=cloneDeep(defaultCspSettings);(cspSettings.directives?.["script-src"]).push(`'nonce-${req2.nonce}'`);if(options.cspSettingsHook){cspSettings=options.cspSettingsHook(cspSettings,req);}helmet.contentSecurityPolicy(cspSettings)(req,res,next);});}if(options.favicon){server.use(favicon(options.favicon));}server.use("/robots.txt",(req,res)=>{res.send("User-agent: *\nDisallow:");});server.use(express.json({limit:"300kb"}));server.use(express.urlencoded({extended:false}));server.use(cookieParser(options.cookieSignatureSecret));server.use(requestIp.mw());server.use(csrf({cookie:true,ignoreRequest:options.csrfIgnoreRequest}));loggerMiddleware.token("ip",req=>req.clientIp);const FORMAT=":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";server.use(loggerMiddleware(FORMAT,{stream:{// TODO: This implies the logger is always set. Is it on a higher level?
35
35
  // then mark it as always present.
36
36
  write:options.logger.info.bind(options.logger)}}));// Note: no matter the "public path", we want the service worker, if any,
37
37
  // to be served from the root, to have all web app pages in its scope.
@@ -45,7 +45,7 @@ server.get("/__service-worker.js",express.static(webpackConfig.output?.path??"",
45
45
  // (in dev mode), and app modules are imported in some unfortunate ways.
46
46
  // TODO: Double-check, what is going on here.
47
47
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
48
- if(!global.location){global.location={href:`${pathToFileURL(process.cwd()).href}${sep}`}}const{default:webpack}=await import(/* webpackChunkName: "server-side-code" */"webpack");const{default:webpackDevMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-dev-middleware");const{default:webpackHotMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-hot-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable import/no-extraneous-dependencies */server.use(publicPath,express.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use((req,res,next)=>{next(newError(ERRORS.NOT_FOUND,CODES.NOT_FOUND))});let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: Do we need this error handler at all? It actually seems to do
48
+ if(!global.location){global.location={href:`${pathToFileURL(process.cwd()).href}${sep}`};}const{default:webpack}=await import(/* webpackChunkName: "server-side-code" */"webpack");const{default:webpackDevMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-dev-middleware");const{default:webpackHotMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-hot-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler));}/* eslint-enable import/no-extraneous-dependencies */server.use(publicPath,express.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server);}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use((req,res,next)=>{next(newError(ERRORS.NOT_FOUND,CODES.NOT_FOUND));});let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server);}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: Do we need this error handler at all? It actually seems to do
49
49
  // what the default ExpressJS error handler does anyway, see:
50
50
  // https://expressjs.com/en/guide/error-handling.html
51
51
  //
@@ -55,6 +55,6 @@ if(!global.location){global.location={href:`${pathToFileURL(process.cwd()).href}
55
55
  // though.
56
56
  server.use((error,req,res,next)=>{// TODO: This is needed to correctly handled any errors thrown after
57
57
  // sending initial response to the client.
58
- if(res.headersSent){next(error);return}const status=error.status??CODES.INTERNAL_SERVER_ERROR;const serverSide=status>=CODES.INTERNAL_SERVER_ERROR;// Log server-side errors always, client-side at debug level only.
59
- options.logger.log(serverSide?"error":"debug",error.toString());let message=error.message||getErrorForCode(status);if(serverSide&&process.env.NODE_ENV==="production"){message=ERRORS.INTERNAL_SERVER_ERROR}res.status(status).send(message)})}return server}
58
+ if(res.headersSent){next(error);return;}const status=error.status??CODES.INTERNAL_SERVER_ERROR;const serverSide=status>=CODES.INTERNAL_SERVER_ERROR;// Log server-side errors always, client-side at debug level only.
59
+ options.logger.log(serverSide?"error":"debug",error.toString());let message=error.message||getErrorForCode(status);if(serverSide&&process.env.NODE_ENV==="production"){message=ERRORS.INTERNAL_SERVER_ERROR;}res.status(status).send(message);});}return server;}
60
60
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["sep","pathToFileURL","cloneDeep","mapValues","pick","compression","cookieParser","express","helmet","loggerMiddleware","requestIp","favicon","v4","uuid","csrf","rendererFactory","CODES","ERRORS","getErrorForCode","newError","defaultCspSettings","directives","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","cspNonce","cspSettings","cspSettingsHook","send","json","limit","urlencoded","extended","cookieSignatureSecret","mw","cookie","ignoreRequest","csrfIgnoreRequest","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","process","cwd","default","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","NOT_FOUND","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","env","NODE_ENV"],"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 { cloneDeep, mapValues, pick } from 'lodash-es';\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 loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport favicon from 'serve-favicon';\nimport { v4 as uuid } from 'uuid';\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 = uuid();\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 { default: webpackHotMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-hot-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\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 const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\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":"wLAAA;AACA;AACA,GAEA,OAASA,GAAG,KAAQ,WAAW,CAC/B,OAASC,aAAa,KAAQ,UAAU,CAExC,OAASC,SAAS,CAAEC,SAAS,CAAEC,IAAI,KAAQ,WAAW,CAEtD,MAAO,CAAAC,WAAW,KAAM,aAAa,CACrC,MAAO,CAAAC,YAAY,KAAM,eAAe,CAExC,MAAO,CAAAC,OAAO,KAKP,SAAS,CAEhB,MAAO,CAAAC,MAAM,KAA8B,QAAQ,CACnD,MAAO,CAAAC,gBAAgB,KAAM,QAAQ,CACrC,MAAO,CAAAC,SAAS,KAAM,YAAY,CAClC,MAAO,CAAAC,OAAO,KAAM,eAAe,CACnC,OAASC,EAAE,GAAI,CAAAC,IAAI,KAAQ,MAAM,CAIjC,MAAO,CAAAC,IAAI,KAAM,mBAAmB,OAE7B,CAAAC,eAAe,4BAMpBC,KAAK,CACLC,MAAM,CACNC,eAAe,CACfC,QAAQ,yBAKV;AAMA;AACA;AACA;AACA,GACA,KAAM,CAAAC,kBAAkB,CAAG,CACzBC,UAAU,CAAElB,SAAS,CACnBK,MAAM,CAACc,qBAAqB,CAACC,oBAAoB,CAAC,CAAC,CAEnD;AACA;AACA;AACA;AACCC,KAAK,EAAMA,KAAK,CAAcC,MAAM,CAAEC,IAAY,EAAKA,IAAI,GAAK,QAAQ,CAC3E,CACF,CAAC,CACDN,kBAAk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reList":[]}
1
+ {"version":3,"file":"server.js","names":["sep","pathToFileURL","compression","cookieParser","express","helmet","cloneDeep","mapValues","pick","loggerMiddleware","requestIp","favicon","v4","uuid","csrf","rendererFactory","CODES","ERRORS","getErrorForCode","newError","defaultCspSettings","directives","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","cspNonce","cspSettings","cspSettingsHook","send","json","limit","urlencoded","extended","cookieSignatureSecret","mw","cookie","ignoreRequest","csrfIgnoreRequest","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","process","cwd","default","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","NOT_FOUND","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","env","NODE_ENV"],"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';\nimport { v4 as uuid } from 'uuid';\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 = uuid();\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 { default: webpackHotMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-hot-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\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 const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\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":"wLAAA;AACA;AACA,GAEA,OAASA,GAAG,KAAQ,WAAW,CAC/B,OAASC,aAAa,KAAQ,UAAU,CAExC,MAAO,CAAAC,WAAW,KAAM,aAAa,CACrC,MAAO,CAAAC,YAAY,KAAM,eAAe,CAExC,MAAO,CAAAC,OAAO,KAKP,SAAS,CAEhB,MAAO,CAAAC,MAAM,KAA8B,QAAQ,CACnD,OAASC,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f,CACH;AACA;AACA,GAAID,GAAG,CAACwD,WAAW,CAAE,CACnBvD,IAAI,CAACsD,KAAK,CAAC,CACX,OACF,CAEA,KAAM,CAAAE,MAAM,CAAGF,KAAK,CAACE,MAAM,EAAInF,KAAK,CAACoF,qBAAqB,CAC1D,KAAM,CAAAC,UAAU,CAAGF,MAAM,EAAKnF,KAAK,CAACoF,qBAAgC,CAEpE;AACArE,OAAO,CAACO,MAAM,CAAEgE,GAAG,CAACD,UAAU,CAAG,OAAO,CAAG,OAAO,CAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC,CAErE,GAAI,CAAAC,OAAO,CAAGP,KAAK,CAACO,OAAO,EAAItF,eAAe,CAACiF,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAIhB,OAAO,CAACoB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDF,OAAO,CAAGvF,MAAM,CAACmF,qBAAqB,CACxC,CAEA1D,GAAG,CAACyD,MAAM,CAACA,MAAM,CAAC,CAACxC,IAAI,CAAC6C,OAAO,CAAC,CAClC,CAAC,CAAC,CACJ,CAEA,MAAO,CAAApE,MAAM,CACf","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- /**
1
+ import"core-js/modules/es.json.stringify.js";/**
2
2
  * @category Utilities
3
3
  * @module server/errors
4
4
  * @desc
@@ -39,7 +39,7 @@
39
39
  * import { server } from '@dr.pogodin/react-utils';
40
40
  * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request
41
41
  */export{getErrorForCode};// TODO: It could accept the status code as a constructor argument.
42
- class ErrorWithStatus extends Error{status=CODES.INTERNAL_SERVER_ERROR}/**
42
+ class ErrorWithStatus extends Error{status=CODES.INTERNAL_SERVER_ERROR;}/**
43
43
  * ```js
44
44
  * import { server } from '@dr.pogodin/react-utils';
45
45
  * const { newError } = server.errors;
@@ -50,9 +50,9 @@ class ErrorWithStatus extends Error{status=CODES.INTERNAL_SERVER_ERROR}/**
50
50
  * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal
51
51
  * Server Error).
52
52
  * @return {Error}
53
- */export function newError(message,statusCode=CODES.INTERNAL_SERVER_ERROR){const error=new ErrorWithStatus(message);error.status=statusCode;return error}/**
53
+ */export function newError(message,statusCode=CODES.INTERNAL_SERVER_ERROR){const error=new ErrorWithStatus(message);error.status=statusCode;return error;}/**
54
54
  * Throws an error with given message and HTTP status code.
55
- */export function fail(message,statusCode=CODES.INTERNAL_SERVER_ERROR){throw newError(message,statusCode)}/**
55
+ */export function fail(message,statusCode=CODES.INTERNAL_SERVER_ERROR){throw newError(message,statusCode);}/**
56
56
  * Validates the `value` against the given "standard" validation `schema`.
57
57
  * Resolves to the correctly typed `value`, if it has passed the validation;
58
58
  * otherwise throws an error.
@@ -61,5 +61,5 @@ class ErrorWithStatus extends Error{status=CODES.INTERNAL_SERVER_ERROR}/**
61
61
  * @param [message] Optional error message, to prepend the validation error
62
62
  * message.
63
63
  * @param [statusCode=400] HTTP status code. Defaults to 400 (Bad Request).
64
- */export async function assert(value,schema,message="",statusCode=CODES.BAD_REQUEST){let result=schema["~standard"].validate(value);if(result instanceof Promise)result=await result;if(result.issues){let error=JSON.stringify(result.issues,null,2);if(message)error=`${message}\n\n${error}`;throw fail(error,statusCode)}return result.value}
64
+ */export async function assert(value,schema,message="",statusCode=CODES.BAD_REQUEST){let result=schema["~standard"].validate(value);if(result instanceof Promise)result=await result;if(result.issues){let error=JSON.stringify(result.issues,null,2);if(message)error=`${message}\n\n${error}`;throw fail(error,statusCode);}return result.value;}
65
65
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":["StatusCodes","CODES","ReasonPhrases","ERRORS","getReasonPhrase","getErrorForCode","ErrorWithStatus","Error","status","INTERNAL_SERVER_ERROR","newError","message","statusCode","error","fail","assert","value","schema","BAD_REQUEST","result","validate","Promise","issues","JSON","stringify"],"sources":["../../../../src/server/utils/errors.ts"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n// TODO: It could accept the status code as a constructor argument.\nclass ErrorWithStatus extends Error {\n status: number = CODES.INTERNAL_SERVER_ERROR;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(\n message: string,\n statusCode = CODES.INTERNAL_SERVER_ERROR,\n): ErrorWithStatus {\n const error = new ErrorWithStatus(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * Throws an error with given message and HTTP status code.\n */\nexport function fail(\n message: string,\n statusCode: CODES = CODES.INTERNAL_SERVER_ERROR,\n): Error {\n throw newError(message, statusCode);\n}\n\n/**\n * Validates the `value` against the given \"standard\" validation `schema`.\n * Resolves to the correctly typed `value`, if it has passed the validation;\n * otherwise throws an error.\n * @param value The value to validate.\n * @param schema The \"standard\" validation schema to use.\n * @param [message] Optional error message, to prepend the validation error\n * message.\n * @param [statusCode=400] HTTP status code. Defaults to 400 (Bad Request).\n */\nexport async function assert<T extends StandardSchemaV1>(\n value: unknown,\n schema: T,\n message = '',\n statusCode = CODES.BAD_REQUEST,\n): Promise<StandardSchemaV1.InferOutput<T>> {\n let result = schema['~standard'].validate(value);\n if (result instanceof Promise) result = await result;\n\n if (result.issues) {\n let error = JSON.stringify(result.issues, null, 2);\n if (message) error = `${message}\\n\\n${error}`;\n throw fail(error, statusCode);\n }\n\n return result.value;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAEA,OACEA,WAAW,GAAI,CAAAC,KAAK,CACpBC,aAAa,GAAI,CAAAC,MAAM,CACvBC,eAAe,GAAI,CAAAC,eAAe,KAC7B,mBAAmB,CAI1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,OAASJ,KAAK,EAEd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,OAASE,MAAM,EAEf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,OAASE,eAAe,EAExB;AACA,KAAM,CAAAC,eAAe,QAAS,CAAAC,KAAM,CAClCC,MAAM,CAAWP,KAAK,CAACQ,qBACzB,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,QAAQA,CACtBC,OAAe,CACfC,UAAU,CAAGX,KAAK,CAACQ,qBAAqB,CACvB,CACjB,KAAM,CAAAI,KAAK,CAAG,GAAI,CAAAP,eAAe,CAACK,OAAO,CAAC,CAC1CE,KAAK,CAACL,MAAM,CAAGI,UAAU,CACzB,MAAO,CAAAC,KACT,CAEA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,IAAIA,CAClBH,OAAe,CACfC,UAAiB,CAAGX,KAAK,CAACQ,qBAAqB,CACxC,CACP,KAAM,CAAAC,QAAQ,CAACC,OAAO,CAAEC,UAAU,CACpC,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,eAAe,CAAAG,MAAMA,CAC1BC,KAAc,CACdC,MAAS,CACTN,OAAO,CAAG,EAAE,CACZC,UAAU,CAAGX,KAAK,CAACiB,WAAW,CACY,CAC1C,GAAI,CAAAC,MAAM,CAAGF,MAAM,CAAC,WAAW,CAAC,CAACG,QAAQ,CAACJ,KAAK,CAAC,CAChD,GAAIG,MAAM,WAAY,CAAAE,OAAO,CAAEF,MAAM,CAAG,KAAM,CAAAA,MAAM,CAEpD,GAAIA,MAAM,CAACG,MAAM,CAAE,CACjB,GAAI,CAAAT,KAAK,CAAGU,IAAI,CAACC,SAAS,CAACL,MAAM,CAACG,MAAM,CAAE,IAAI,CAAE,CAAC,CAAC,CAClD,GAAIX,OAAO,CAAEE,KAAK,CAAG,GAAGF,OAAO,OAAOE,KAAK,EAAE,CAC7C,KAAM,CAAAC,IAAI,CAACD,KAAK,CAAED,UAAU,CAC9B,CAEA,MAAO,CAAAO,MAAM,CAACH,KAChB","ignoreList":[]}
1
+ {"version":3,"file":"errors.js","names":["StatusCodes","CODES","ReasonPhrases","ERRORS","getReasonPhrase","getErrorForCode","ErrorWithStatus","Error","status","INTERNAL_SERVER_ERROR","newError","message","statusCode","error","fail","assert","value","schema","BAD_REQUEST","result","validate","Promise","issues","JSON","stringify"],"sources":["../../../../src/server/utils/errors.ts"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n// TODO: It could accept the status code as a constructor argument.\nclass ErrorWithStatus extends Error {\n status: number = CODES.INTERNAL_SERVER_ERROR;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(\n message: string,\n statusCode = CODES.INTERNAL_SERVER_ERROR,\n): ErrorWithStatus {\n const error = new ErrorWithStatus(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * Throws an error with given message and HTTP status code.\n */\nexport function fail(\n message: string,\n statusCode: CODES = CODES.INTERNAL_SERVER_ERROR,\n): Error {\n throw newError(message, statusCode);\n}\n\n/**\n * Validates the `value` against the given \"standard\" validation `schema`.\n * Resolves to the correctly typed `value`, if it has passed the validation;\n * otherwise throws an error.\n * @param value The value to validate.\n * @param schema The \"standard\" validation schema to use.\n * @param [message] Optional error message, to prepend the validation error\n * message.\n * @param [statusCode=400] HTTP status code. Defaults to 400 (Bad Request).\n */\nexport async function assert<T extends StandardSchemaV1>(\n value: unknown,\n schema: T,\n message = '',\n statusCode = CODES.BAD_REQUEST,\n): Promise<StandardSchemaV1.InferOutput<T>> {\n let result = schema['~standard'].validate(value);\n if (result instanceof Promise) result = await result;\n\n if (result.issues) {\n let error = JSON.stringify(result.issues, null, 2);\n if (message) error = `${message}\\n\\n${error}`;\n throw fail(error, statusCode);\n }\n\n return result.value;\n}\n"],"mappings":"6CAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAEA,OACEA,WAAW,GAAI,CAAAC,KAAK,CACpBC,aAAa,GAAI,CAAAC,MAAM,CACvBC,eAAe,GAAI,CAAAC,eAAe,KAC7B,mBAAmB,CAI1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,OAASJ,KAAK,EAEd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,OAASE,MAAM,EAEf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,OAASE,eAAe,EAExB;AACA,KAAM,CAAAC,eAAe,QAAS,CAAAC,KAAM,CAClCC,MAAM,CAAWP,KAAK,CAACQ,qBAAqB,CAC9C,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC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