@dr.pogodin/react-utils 1.18.0 → 1.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,9 +23,9 @@ var _jsxRuntime = require("react/jsx-runtime");
23
23
  * @param {object} [options={}] Optional. Additional settings.
24
24
  */
25
25
  function Launch(Application) {
26
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
27
- var container = document.getElementById('react-view');
28
- var scene = /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactGlobalState.GlobalStateProvider, {
26
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
27
+ const container = document.getElementById('react-view');
28
+ const scene = /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactGlobalState.GlobalStateProvider, {
29
29
  initialState: window.ISTATE,
30
30
  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactRouterDom.BrowserRouter, {
31
31
  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(Application, {})
@@ -33,7 +33,7 @@ function Launch(Application) {
33
33
  });
34
34
 
35
35
  if (options.dontHydrate) {
36
- var root = (0, _client.createRoot)(container);
36
+ const root = (0, _client.createRoot)(container);
37
37
  root.render(scene);
38
38
  } else (0, _client.hydrateRoot)(container, scene);
39
39
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Launch","Application","options","container","document","getElementById","scene","window","ISTATE","dontHydrate","root","createRoot","render","hydrateRoot"],"sources":["../../../src/client/index.jsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document, window */\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { BrowserRouter } from 'react-router-dom';\n\n/**\n * Prepares and launches the app at client side.\n * @param {object} Application Root application component\n * @param {object} [options={}] Optional. Additional settings.\n */\nexport default function Launch(Application, options = {}) {\n const container = document.getElementById('react-view');\n const scene = (\n <GlobalStateProvider initialState={window.ISTATE}>\n <BrowserRouter>\n <Application />\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":";;;;;;;AAGA;;AAEA;;AACA;;;;AANA;;AACA;;AAOA;AACA;AACA;AACA;AACA;AACe,SAASA,MAAT,CAAgBC,WAAhB,EAA2C;EAAA,IAAdC,OAAc,uEAAJ,EAAI;EACxD,IAAMC,SAAS,GAAGC,QAAQ,CAACC,cAAT,CAAwB,YAAxB,CAAlB;EACA,IAAMC,KAAK,gBACT,qBAAC,qCAAD;IAAqB,YAAY,EAAEC,MAAM,CAACC,MAA1C;IAAA,uBACE,qBAAC,6BAAD;MAAA,uBACE,qBAAC,WAAD;IADF;EADF,EADF;;EAQA,IAAIN,OAAO,CAACO,WAAZ,EAAyB;IACvB,IAAMC,IAAI,GAAG,IAAAC,kBAAA,EAAWR,SAAX,CAAb;IACAO,IAAI,CAACE,MAAL,CAAYN,KAAZ;EACD,CAHD,MAGO,IAAAO,mBAAA,EAAYV,SAAZ,EAAuBG,KAAvB;AACR"}
1
+ {"version":3,"file":"index.js","names":["Launch","Application","options","container","document","getElementById","scene","window","ISTATE","dontHydrate","root","createRoot","render","hydrateRoot"],"sources":["../../../src/client/index.jsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document, window */\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { BrowserRouter } from 'react-router-dom';\n\n/**\n * Prepares and launches the app at client side.\n * @param {object} Application Root application component\n * @param {object} [options={}] Optional. Additional settings.\n */\nexport default function Launch(Application, options = {}) {\n const container = document.getElementById('react-view');\n const scene = (\n <GlobalStateProvider initialState={window.ISTATE}>\n <BrowserRouter>\n <Application />\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":";;;;;;;AAGA;;AAEA;;AACA;;;;AANA;;AACA;;AAOA;AACA;AACA;AACA;AACA;AACe,SAASA,MAAT,CAAgBC,WAAhB,EAA2C;EAAA,IAAdC,OAAc,uEAAJ,EAAI;EACxD,MAAMC,SAAS,GAAGC,QAAQ,CAACC,cAAT,CAAwB,YAAxB,CAAlB;EACA,MAAMC,KAAK,gBACT,qBAAC,qCAAD;IAAqB,YAAY,EAAEC,MAAM,CAACC,MAA1C;IAAA,uBACE,qBAAC,6BAAD;MAAA,uBACE,qBAAC,WAAD;IADF;EADF,EADF;;EAQA,IAAIN,OAAO,CAACO,WAAZ,EAAyB;IACvB,MAAMC,IAAI,GAAG,IAAAC,kBAAA,EAAWR,SAAX,CAAb;IACAO,IAAI,CAACE,MAAL,CAAYN,KAAZ;EACD,CAHD,MAGO,IAAAO,mBAAA,EAAYV,SAAZ,EAAuBG,KAAvB;AACR"}
@@ -2,10 +2,6 @@
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
4
 
5
- var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
6
-
7
- var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
8
-
9
5
  var _forge = _interopRequireDefault(require("node-forge/lib/forge"));
10
6
 
11
7
  require("node-forge/lib/aes");
@@ -28,7 +24,7 @@ if (typeof BUILD_INFO !== 'undefined') {
28
24
 
29
25
 
30
26
  if (!window.TRU_KEEP_INJ_SCRIPT) {
31
- var block = document.querySelector('script[id="inj"]');
27
+ const block = document.querySelector('script[id="inj"]');
32
28
  if (block) document.getElementsByTagName('body')[0].removeChild(block);
33
29
  }
34
30
  /* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */
@@ -36,43 +32,25 @@ if (!window.TRU_KEEP_INJ_SCRIPT) {
36
32
  /* eslint-disable no-console */
37
33
 
38
34
 
39
- var _window$TRU_BUILD_INF = window.TRU_BUILD_INFO,
40
- publicPath = _window$TRU_BUILD_INF.publicPath,
41
- useServiceWorker = _window$TRU_BUILD_INF.useServiceWorker;
35
+ const {
36
+ publicPath,
37
+ useServiceWorker
38
+ } = window.TRU_BUILD_INFO;
42
39
 
43
40
  if (useServiceWorker) {
44
- var _window = window,
45
- navigator = _window.navigator;
41
+ const {
42
+ navigator
43
+ } = window;
46
44
 
47
45
  if ('serviceWorker' in navigator) {
48
- window.addEventListener('load', /*#__PURE__*/(0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() {
49
- var reg;
50
- return _regenerator.default.wrap(function _callee$(_context) {
51
- while (1) {
52
- switch (_context.prev = _context.next) {
53
- case 0:
54
- _context.prev = 0;
55
- _context.next = 3;
56
- return navigator.serviceWorker.register("".concat(publicPath, "/__service-worker.js"));
57
-
58
- case 3:
59
- reg = _context.sent;
60
- console.log('SW registered:', reg);
61
- _context.next = 10;
62
- break;
63
-
64
- case 7:
65
- _context.prev = 7;
66
- _context.t0 = _context["catch"](0);
67
- console.log('SW registration failed:', _context.t0);
68
-
69
- case 10:
70
- case "end":
71
- return _context.stop();
72
- }
73
- }
74
- }, _callee, null, [[0, 7]]);
75
- })));
46
+ window.addEventListener('load', async () => {
47
+ try {
48
+ const reg = await navigator.serviceWorker.register("".concat(publicPath, "/__service-worker.js"));
49
+ console.log('SW registered:', reg);
50
+ } catch (err) {
51
+ console.log('SW registration failed:', err);
52
+ }
53
+ });
76
54
  }
77
55
  }
78
56
  /* eslint-enable no-console */
@@ -81,11 +59,13 @@ if (useServiceWorker) {
81
59
 
82
60
 
83
61
  if (window.INJ) {
84
- var key = window.TRU_BUILD_INFO.key;
62
+ const {
63
+ key
64
+ } = window.TRU_BUILD_INFO;
85
65
 
86
- var data = _forge.default.util.decode64(window.INJ);
66
+ let data = _forge.default.util.decode64(window.INJ);
87
67
 
88
- var decipher = _forge.default.cipher.createDecipher('AES-CBC', key);
68
+ const decipher = _forge.default.cipher.createDecipher('AES-CBC', key);
89
69
 
90
70
  decipher.start({
91
71
  iv: data.slice(0, 32)
@@ -1 +1 @@
1
- {"version":3,"file":"init.js","names":["BUILD_INFO","window","TRU_BUILD_INFO","TRU_KEEP_INJ_SCRIPT","block","document","querySelector","getElementsByTagName","removeChild","publicPath","useServiceWorker","navigator","addEventListener","serviceWorker","register","reg","console","log","INJ","key","data","forge","util","decode64","decipher","cipher","createDecipher","start","iv","slice","update","createBuffer","finish","decodeUtf8","output","eval","CHUNK_GROUPS","CONFIG","ISTATE"],"sources":["../../../src/client/init.js"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global BUILD_INFO, document, window */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\nimport 'node-forge/lib/aes';\n\n/* `BUILD_INFO` is always injected by Webpack build, but this check is needed\n * to adopt the code for usage in tests. */\nif (typeof BUILD_INFO !== 'undefined') {\n window.TRU_BUILD_INFO = BUILD_INFO;\n}\n\n/* Removes data injection script out of the document.\n * The if block is here for test purposes. */\nif (!window.TRU_KEEP_INJ_SCRIPT) {\n const block = document.querySelector('script[id=\"inj\"]');\n if (block) document.getElementsByTagName('body')[0].removeChild(block);\n}\n\n/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */\n/* eslint-disable no-console */\nconst { publicPath, useServiceWorker } = window.TRU_BUILD_INFO;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', async () => {\n try {\n const reg = await navigator\n .serviceWorker.register(`${publicPath}/__service-worker.js`);\n console.log('SW registered:', reg);\n } catch (err) {\n console.log('SW registration failed:', err);\n }\n });\n }\n}\n/* eslint-enable no-console */\n\n/* Decodes data injected at the server side. */\nif (window.INJ) {\n const { key } = window.TRU_BUILD_INFO;\n let data = forge.util.decode64(window.INJ);\n const decipher = forge.cipher.createDecipher('AES-CBC', key);\n decipher.start({ iv: data.slice(0, 32) });\n decipher.update(forge.util.createBuffer(data.slice(32)));\n decipher.finish();\n\n data = forge.util.decodeUtf8(decipher.output.data);\n data = eval(`(${data})`); // eslint-disable-line no-eval\n\n window.CHUNK_GROUPS = data.CHUNK_GROUPS;\n window.CONFIG = data.CONFIG;\n window.ISTATE = data.ISTATE;\n} else {\n // This is possible when the client-side bundle is launched as a stand-alone\n // precompiled website, rather than served by react-utils' based server.\n window.CHUNK_GROUPS = {};\n window.CONFIG = {};\n}\n"],"mappings":";;;;;;;;AAQA;;AACA;;AATA;AACA;AACA;;AAEA;AAEA;AACA;;AAIA;AACA;AACA,IAAI,OAAOA,UAAP,KAAsB,WAA1B,EAAuC;EACrCC,MAAM,CAACC,cAAP,GAAwBF,UAAxB;AACD;AAED;AACA;;;AACA,IAAI,CAACC,MAAM,CAACE,mBAAZ,EAAiC;EAC/B,IAAMC,KAAK,GAAGC,QAAQ,CAACC,aAAT,CAAuB,kBAAvB,CAAd;EACA,IAAIF,KAAJ,EAAWC,QAAQ,CAACE,oBAAT,CAA8B,MAA9B,EAAsC,CAAtC,EAAyCC,WAAzC,CAAqDJ,KAArD;AACZ;AAED;;AACA;;;AACA,4BAAyCH,MAAM,CAACC,cAAhD;AAAA,IAAQO,UAAR,yBAAQA,UAAR;AAAA,IAAoBC,gBAApB,yBAAoBA,gBAApB;;AACA,IAAIA,gBAAJ,EAAsB;EACpB,cAAsBT,MAAtB;EAAA,IAAQU,SAAR,WAAQA,SAAR;;EACA,IAAI,mBAAmBA,SAAvB,EAAkC;IAChCV,MAAM,CAACW,gBAAP,CAAwB,MAAxB,uFAAgC;MAAA;MAAA;QAAA;UAAA;YAAA;cAAA;cAAA;cAAA,OAEVD,SAAS,CACxBE,aADe,CACDC,QADC,WACWL,UADX,0BAFU;;YAAA;cAEtBM,GAFsB;cAI5BC,OAAO,CAACC,GAAR,CAAY,gBAAZ,EAA8BF,GAA9B;cAJ4B;cAAA;;YAAA;cAAA;cAAA;cAM5BC,OAAO,CAACC,GAAR,CAAY,yBAAZ;;YAN4B;YAAA;cAAA;UAAA;QAAA;MAAA;IAAA,CAAhC;EASD;AACF;AACD;;AAEA;;;AACA,IAAIhB,MAAM,CAACiB,GAAX,EAAgB;EACd,IAAQC,GAAR,GAAgBlB,MAAM,CAACC,cAAvB,CAAQiB,GAAR;;EACA,IAAIC,IAAI,GAAGC,cAAA,CAAMC,IAAN,CAAWC,QAAX,CAAoBtB,MAAM,CAACiB,GAA3B,CAAX;;EACA,IAAMM,QAAQ,GAAGH,cAAA,CAAMI,MAAN,CAAaC,cAAb,CAA4B,SAA5B,EAAuCP,GAAvC,CAAjB;;EACAK,QAAQ,CAACG,KAAT,CAAe;IAAEC,EAAE,EAAER,IAAI,CAACS,KAAL,CAAW,CAAX,EAAc,EAAd;EAAN,CAAf;EACAL,QAAQ,CAACM,MAAT,CAAgBT,cAAA,CAAMC,IAAN,CAAWS,YAAX,CAAwBX,IAAI,CAACS,KAAL,CAAW,EAAX,CAAxB,CAAhB;EACAL,QAAQ,CAACQ,MAAT;EAEAZ,IAAI,GAAGC,cAAA,CAAMC,IAAN,CAAWW,UAAX,CAAsBT,QAAQ,CAACU,MAAT,CAAgBd,IAAtC,CAAP;EACAA,IAAI,GAAGe,IAAI,YAAKf,IAAL,OAAX,CATc,CASY;;EAE1BnB,MAAM,CAACmC,YAAP,GAAsBhB,IAAI,CAACgB,YAA3B;EACAnC,MAAM,CAACoC,MAAP,GAAgBjB,IAAI,CAACiB,MAArB;EACApC,MAAM,CAACqC,MAAP,GAAgBlB,IAAI,CAACkB,MAArB;AACD,CAdD,MAcO;EACL;EACA;EACArC,MAAM,CAACmC,YAAP,GAAsB,EAAtB;EACAnC,MAAM,CAACoC,MAAP,GAAgB,EAAhB;AACD"}
1
+ {"version":3,"file":"init.js","names":["BUILD_INFO","window","TRU_BUILD_INFO","TRU_KEEP_INJ_SCRIPT","block","document","querySelector","getElementsByTagName","removeChild","publicPath","useServiceWorker","navigator","addEventListener","reg","serviceWorker","register","console","log","err","INJ","key","data","forge","util","decode64","decipher","cipher","createDecipher","start","iv","slice","update","createBuffer","finish","decodeUtf8","output","eval","CHUNK_GROUPS","CONFIG","ISTATE"],"sources":["../../../src/client/init.js"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global BUILD_INFO, document, window */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\nimport 'node-forge/lib/aes';\n\n/* `BUILD_INFO` is always injected by Webpack build, but this check is needed\n * to adopt the code for usage in tests. */\nif (typeof BUILD_INFO !== 'undefined') {\n window.TRU_BUILD_INFO = BUILD_INFO;\n}\n\n/* Removes data injection script out of the document.\n * The if block is here for test purposes. */\nif (!window.TRU_KEEP_INJ_SCRIPT) {\n const block = document.querySelector('script[id=\"inj\"]');\n if (block) document.getElementsByTagName('body')[0].removeChild(block);\n}\n\n/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */\n/* eslint-disable no-console */\nconst { publicPath, useServiceWorker } = window.TRU_BUILD_INFO;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', async () => {\n try {\n const reg = await navigator\n .serviceWorker.register(`${publicPath}/__service-worker.js`);\n console.log('SW registered:', reg);\n } catch (err) {\n console.log('SW registration failed:', err);\n }\n });\n }\n}\n/* eslint-enable no-console */\n\n/* Decodes data injected at the server side. */\nif (window.INJ) {\n const { key } = window.TRU_BUILD_INFO;\n let data = forge.util.decode64(window.INJ);\n const decipher = forge.cipher.createDecipher('AES-CBC', key);\n decipher.start({ iv: data.slice(0, 32) });\n decipher.update(forge.util.createBuffer(data.slice(32)));\n decipher.finish();\n\n data = forge.util.decodeUtf8(decipher.output.data);\n data = eval(`(${data})`); // eslint-disable-line no-eval\n\n window.CHUNK_GROUPS = data.CHUNK_GROUPS;\n window.CONFIG = data.CONFIG;\n window.ISTATE = data.ISTATE;\n} else {\n // This is possible when the client-side bundle is launched as a stand-alone\n // precompiled website, rather than served by react-utils' based server.\n window.CHUNK_GROUPS = {};\n window.CONFIG =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AAT,CAAe;IAAEC,EAAE,EAAER,IAAI,CAACS,KAAL,CAAW,CAAX,EAAc,EAAd;EAAN,CAAf;EACAL,QAAQ,CAACM,MAAT,CAAgBT,cAAA,CAAMC,IAAN,CAAWS,YAAX,CAAwBX,IAAI,CAACS,KAAL,CAAW,EAAX,CAAxB,CAAhB;EACAL,QAAQ,CAACQ,MAAT;EAEAZ,IAAI,GAAGC,cAAA,CAAMC,IAAN,CAAWW,UAAX,CAAsBT,QAAQ,CAACU,MAAT,CAAgBd,IAAtC,CAAP;EACAA,IAAI,GAAGe,IAAI,YAAKf,IAAL,OAAX,CATc,CASY;;EAE1BpB,MAAM,CAACoC,YAAP,GAAsBhB,IAAI,CAACgB,YAA3B;EACApC,MAAM,CAACqC,MAAP,GAAgBjB,IAAI,CAACiB,MAArB;EACArC,MAAM,CAACsC,MAAP,GAAgBlB,IAAI,CAACkB,MAArB;AACD,CAdD,MAcO;EACL;EACA;EACAtC,MAAM,CAACoC,YAAP,GAAsB,EAAtB;EACApC,MAAM,CAACqC,MAAP,GAAgB,EAAhB;AACD"}
@@ -498,7 +498,6 @@ function factory(webpackConfig, options) {
498
498
  </html>`;
499
499
  const status = ssrContext.status || 200;
500
500
  if (status !== 200) res.status(status);
501
- res.send(html);
502
501
 
503
502
  if (cacheRef && status < 500) {
504
503
  // Note: waiting for the caching to complete is not strictly necessary,
@@ -516,7 +515,12 @@ function factory(webpackConfig, options) {
516
515
  }
517
516
  });
518
517
  });
519
- }
518
+ } // Note: as caching code above may throw in some cases, sending response
519
+ // before it completes will likely hide the error, making it difficult
520
+ // to debug. Thus, at least for now, lets send response after it.
521
+
522
+
523
+ res.send(html);
520
524
  } catch (error) {
521
525
  next(error);
522
526
  }
@@ -1 +1 @@
1
- {"version":3,"file":"renderer.js","names":["sanitizedConfig","omit","config","SCRIPT_LOCATIONS","BODY_OPEN","DEFAULT","HEAD_OPEN","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","err","prepareCipher","key","Promise","reject","forge","random","getBytes","iv","cipher","createCipher","start","isBrotliAcceptable","req","acceptable","get","ops","split","i","length","type","priority","trim","parseFloat","groupExtraScripts","scripts","script","isString","code","location","undefined","Error","newDefaultLogger","defaultLogLevel","format","transports","winston","createLogger","level","combine","splat","timestamp","colorize","printf","message","stack","rest","Object","keys","stringify","Console","factory","webpackConfig","options","defaults","clone","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","global","TRU_BUILD_INFO","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cacheRef","data","buffer","status","noCsp","send","done","failed","brotliDecompress","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","initialState","all","helmet","App","Application","ssrContext","state","cloneDeep","chunks","stream","ssrStart","Date","now","renderPass","pipeableStream","renderToPipeableStream","onAllReady","onError","ssrRound","bailed","dirty","timeout","race","allSettled","pending","timer","then","logMsg","log","pipe","Writable","write","chunk","_","Helmet","renderStatic","chunkGroups","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","dr_pogodin_react_utils___split_components","payload","serializeJs","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","brotliCompress"],"sources":["../../../src/server/renderer.jsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Writable } from 'stream';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport {\n clone,\n cloneDeep,\n defaults,\n isString,\n get,\n mapValues,\n omit,\n} from 'lodash';\n\nimport config from 'config';\nimport forge from 'node-forge';\nimport fs from 'fs';\nimport path from 'path';\nimport { brotliCompress, brotliDecompress } from 'zlib';\n\nimport { renderToPipeableStream } from 'react-dom/server';\nimport { Helmet } from 'react-helmet';\nimport { StaticRouter } from 'react-router-dom/server';\nimport serializeJs from 'serialize-javascript';\nimport { timer } from 'utils/time';\nimport winston from 'winston';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\nexport const SCRIPT_LOCATIONS = {\n BODY_OPEN: 'BODY_OPEN',\n DEFAULT: 'DEFAULT',\n HEAD_OPEN: 'HEAD_OPEN',\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 * @ignore\n * @param {String} context Webpack context path used during the build.\n * @return {Object} Resolves to the build-time information.\n */\nfunction getBuildInfo(context) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url));\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 * @ignore\n * @param {string} buildDir\n * @return {object}\n */\nfunction readChunkGroupsJson(buildDir) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url));\n } catch (err) {\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @ignore\n * @param {String} key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return {Promise} Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key) {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param {object} req\n * @return {boolean}\n * @ignore\n */\nexport function isBrotliAcceptable(req) {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (let i = 0; i < ops.length; ++i) {\n const [type, priority] = ops[i].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 = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (let i = 0; i < scripts.length; ++i) {\n const script = scripts[i];\n if (isString(script)) {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (res[script.location] !== undefined) {\n 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} = {}) {\n const { format, transports } = winston;\n return winston.createLogger({\n level: defaultLogLevel,\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp}):\\t${message}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack}`;\n return res;\n },\n ),\n ),\n transports: [new transports.Console()],\n });\n}\n\n/**\n * Creates the middleware.\n * @param {object} webpackConfig\n * @param {object} options Additional options:\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {object} [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 {boolean} [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param {boolean} [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 {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return {function} Created middleware.\n */\nexport default function factory(webpackConfig, options) {\n const ops = defaults(clone(options), {\n beforeRender: () => 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 if (ops.logger === undefined) {\n ops.logger = newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n }\n\n const buildInfo = ops.buildInfo || getBuildInfo(webpackConfig.context);\n global.TRU_BUILD_INFO = buildInfo;\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath}manifest.json\">` : '';\n\n const cache = ops.staticCacheController\n ? new Cache(ops.staticCacheSize) : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath);\n\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 let cacheRef;\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((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 h = h.replace(regex, req.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 [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n ops.beforeRender(req, sanitizedConfig),\n prepareCipher(buildInfo.key),\n ]);\n\n let helmet;\n\n /* Optional server-side rendering. */\n let App = ops.Application;\n const ssrContext = {\n req,\n state: cloneDeep(initialState || {}),\n\n // Array of chunk names encountered during the rendering.\n chunks: [],\n };\n let stream;\n if (App) {\n const ssrStart = Date.now();\n\n const renderPass = async () => {\n ssrContext.chunks = [];\n return new Promise((resolve, reject) => {\n const pipeableStream = renderToPipeableStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <App />\n </StaticRouter>\n </GlobalStateProvider>,\n {\n onAllReady: () => resolve(pipeableStream),\n onError: reject,\n },\n );\n });\n };\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds; ++ssrRound) {\n stream = await renderPass(); // eslint-disable-line no-await-in-loop\n\n if (!ssrContext.dirty) break;\n\n /* eslint-disable no-await-in-loop */\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 /* eslint-enable no-await-in-loop */\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 App = '';\n stream.pipe(new Writable({\n write: (chunk, _, done) => {\n App += chunk.toString();\n done();\n },\n }));\n\n /* This takes care about server-side rendering of page title and meta tags\n * (still demands injection into HTML template, which happens below). */\n helmet = Helmet.renderStatic();\n }\n\n let chunkGroups;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets.map(({ name }) => name),\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\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 delete ssrContext.state.dr_pogodin_react_utils___split_components;\n\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 cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const chunkSet = new Set();\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) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath}${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}${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 ? helmet.title.toString() : ''}\n ${helmet ? helmet.meta.toString() : ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${App || ''}</div>\n <script\n id=\"inj\"\n type=\"application/javascript\"\n ${ops.noCsp ? '' : `nonce=\"${req.nonce}\"`}\n >\n window.INJ=\"${INJ}\"\n </script>\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 res.send(html);\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((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n buffer.nonce = req.nonce; // eslint-disable-line no-param-reassign\n cache.add({ buffer, status }, cacheRef.key);\n done();\n }\n });\n });\n }\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;AAIA;;AAEA;;AAEA;;AAUA;;AACA;;AACA;;AACA;;AACA;;AAEA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA;;;;AA/BA;AACA;AACA;AA+BA,MAAMA,eAAe,GAAG,IAAAC,YAAA,EAAKC,eAAL,EAAa,QAAb,CAAxB;AAEO,MAAMC,gBAAgB,GAAG;EAC9BC,SAAS,EAAE,WADmB;EAE9BC,OAAO,EAAE,SAFqB;EAG9BC,SAAS,EAAE;AAHmB,CAAzB;AAMP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AACA,SAASC,YAAT,CAAsBC,OAAtB,EAA+B;EAC7B,MAAMC,GAAG,GAAGC,aAAA,CAAKC,OAAL,CAAaH,OAAb,EAAsB,aAAtB,CAAZ;;EACA,OAAOI,IAAI,CAACC,KAAL,CAAWC,WAAA,CAAGC,YAAH,CAAgBN,GAAhB,CAAX,CAAP;AACD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACA,SAASO,mBAAT,CAA6BC,QAA7B,EAAuC;EACrC,MAAMR,GAAG,GAAGC,aAAA,CAAKC,OAAL,CAAaM,QAAb,EAAuB,uBAAvB,CAAZ;;EACA,IAAIC,GAAJ;;EACA,IAAI;IACFA,GAAG,GAAGN,IAAI,CAACC,KAAL,CAAWC,WAAA,CAAGC,YAAH,CAAgBN,GAAhB,CAAX,CAAN;EACD,CAFD,CAEE,OAAOU,GAAP,EAAY;IACZD,G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5B;QACA;QACA,MAAM,IAAI5E,OAAJ,CAAY,CAAC+E,IAAD,EAAOC,MAAP,KAAkB;UAClC,IAAAoF,oBAAA,EAAejF,IAAf,EAAqB,CAACD,KAAD,EAAQP,MAAR,KAAmB;YACtC,IAAIO,KAAJ,EAAWF,MAAM,CAACE,KAAD,CAAN,CAAX,KACK;cACHP,MAAM,CAACa,KAAP,GAAe9E,GAAG,CAAC8E,KAAnB,CADG,CACuB;;cAC1BrB,KAAK,CAACwF,GAAN,CAAU;gBAAEhF,MAAF;gBAAUC;cAAV,CAAV,EAA8BH,QAAQ,CAAC1E,GAAvC;cACAgF,IAAI;YACL;UACF,CAPD;QAQD,CATK,CAAN;MAUD;IACF,CA3PD,CA2PE,OAAOG,KAAP,EAAc;MACdX,IAAI,CAACW,KAAD,CAAJ;IACD;EACF,CA/PD;AAgQD"}
1
+ {"version":3,"file":"renderer.js","names":["sanitizedConfig","omit","config","SCRIPT_LOCATIONS","BODY_OPEN","DEFAULT","HEAD_OPEN","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","err","prepareCipher","key","Promise","reject","forge","random","getBytes","iv","cipher","createCipher","start","isBrotliAcceptable","req","acceptable","get","ops","split","i","length","type","priority","trim","parseFloat","groupExtraScripts","scripts","script","isString","code","location","undefined","Error","newDefaultLogger","defaultLogLevel","format","transports","winston","createLogger","level","combine","splat","timestamp","colorize","printf","message","stack","rest","Object","keys","stringify","Console","factory","webpackConfig","options","defaults","clone","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","global","TRU_BUILD_INFO","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cacheRef","data","buffer","status","noCsp","send","done","failed","brotliDecompress","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","initialState","all","helmet","App","Application","ssrContext","state","cloneDeep","chunks","stream","ssrStart","Date","now","renderPass","pipeableStream","renderToPipeableStream","onAllReady","onError","ssrRound","bailed","dirty","timeout","race","allSettled","pending","timer","then","logMsg","log","pipe","Writable","write","chunk","_","Helmet","renderStatic","chunkGroups","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","dr_pogodin_react_utils___split_components","payload","serializeJs","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","brotliCompress"],"sources":["../../../src/server/renderer.jsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Writable } from 'stream';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport {\n clone,\n cloneDeep,\n defaults,\n isString,\n get,\n mapValues,\n omit,\n} from 'lodash';\n\nimport config from 'config';\nimport forge from 'node-forge';\nimport fs from 'fs';\nimport path from 'path';\nimport { brotliCompress, brotliDecompress } from 'zlib';\n\nimport { renderToPipeableStream } from 'react-dom/server';\nimport { Helmet } from 'react-helmet';\nimport { StaticRouter } from 'react-router-dom/server';\nimport serializeJs from 'serialize-javascript';\nimport { timer } from 'utils/time';\nimport winston from 'winston';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\nexport const SCRIPT_LOCATIONS = {\n BODY_OPEN: 'BODY_OPEN',\n DEFAULT: 'DEFAULT',\n HEAD_OPEN: 'HEAD_OPEN',\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 * @ignore\n * @param {String} context Webpack context path used during the build.\n * @return {Object} Resolves to the build-time information.\n */\nfunction getBuildInfo(context) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url));\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 * @ignore\n * @param {string} buildDir\n * @return {object}\n */\nfunction readChunkGroupsJson(buildDir) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url));\n } catch (err) {\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @ignore\n * @param {String} key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return {Promise} Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key) {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param {object} req\n * @return {boolean}\n * @ignore\n */\nexport function isBrotliAcceptable(req) {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (let i = 0; i < ops.length; ++i) {\n const [type, priority] = ops[i].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 = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (let i = 0; i < scripts.length; ++i) {\n const script = scripts[i];\n if (isString(script)) {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (res[script.location] !== undefined) {\n 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} = {}) {\n const { format, transports } = winston;\n return winston.createLogger({\n level: defaultLogLevel,\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp}):\\t${message}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack}`;\n return res;\n },\n ),\n ),\n transports: [new transports.Console()],\n });\n}\n\n/**\n * Creates the middleware.\n * @param {object} webpackConfig\n * @param {object} options Additional options:\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {object} [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 {boolean} [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param {boolean} [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 {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return {function} Created middleware.\n */\nexport default function factory(webpackConfig, options) {\n const ops = defaults(clone(options), {\n beforeRender: () => 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 if (ops.logger === undefined) {\n ops.logger = newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n }\n\n const buildInfo = ops.buildInfo || getBuildInfo(webpackConfig.context);\n global.TRU_BUILD_INFO = buildInfo;\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath}manifest.json\">` : '';\n\n const cache = ops.staticCacheController\n ? new Cache(ops.staticCacheSize) : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath);\n\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 let cacheRef;\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((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 h = h.replace(regex, req.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 [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n ops.beforeRender(req, sanitizedConfig),\n prepareCipher(buildInfo.key),\n ]);\n\n let helmet;\n\n /* Optional server-side rendering. */\n let App = ops.Application;\n const ssrContext = {\n req,\n state: cloneDeep(initialState || {}),\n\n // Array of chunk names encountered during the rendering.\n chunks: [],\n };\n let stream;\n if (App) {\n const ssrStart = Date.now();\n\n const renderPass = async () => {\n ssrContext.chunks = [];\n return new Promise((resolve, reject) => {\n const pipeableStream = renderToPipeableStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <App />\n </StaticRouter>\n </GlobalStateProvider>,\n {\n onAllReady: () => resolve(pipeableStream),\n onError: reject,\n },\n );\n });\n };\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds; ++ssrRound) {\n stream = await renderPass(); // eslint-disable-line no-await-in-loop\n\n if (!ssrContext.dirty) break;\n\n /* eslint-disable no-await-in-loop */\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 /* eslint-enable no-await-in-loop */\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 App = '';\n stream.pipe(new Writable({\n write: (chunk, _, done) => {\n App += chunk.toString();\n done();\n },\n }));\n\n /* This takes care about server-side rendering of page title and meta tags\n * (still demands injection into HTML template, which happens below). */\n helmet = Helmet.renderStatic();\n }\n\n let chunkGroups;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets.map(({ name }) => name),\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\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 delete ssrContext.state.dr_pogodin_react_utils___split_components;\n\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 cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const chunkSet = new Set();\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) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath}${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}${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 ? helmet.title.toString() : ''}\n ${helmet ? helmet.meta.toString() : ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${App || ''}</div>\n <script\n id=\"inj\"\n type=\"application/javascript\"\n ${ops.noCsp ? '' : `nonce=\"${req.nonce}\"`}\n >\n window.INJ=\"${INJ}\"\n </script>\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((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n buffer.nonce = req.nonce; // eslint-disable-line no-param-reassign\n cache.add({ buffer, status }, cacheRef.key);\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":";;;;;;;;;;;;AAIA;;AAEA;;AAEA;;AAUA;;AACA;;AACA;;AACA;;AACA;;AAEA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA;;;;AA/BA;AACA;AACA;AA+BA,MAAMA,eAAe,GAAG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PD,CA+PE,OAAOD,KAAP,EAAc;MACdX,IAAI,CAACW,KAAD,CAAJ;IACD;EACF,CAnQD;AAoQD"}
@@ -222,14 +222,18 @@ async function factory(webpackConfig, options) {
222
222
 
223
223
 
224
224
  if (!dontAttachDefaultErrorHandler) {
225
+ // TODO: Do we need this error handler at all? It actually seems to do
226
+ // what the default ExpressJS error handler does anyway, see:
227
+ // https://expressjs.com/en/guide/error-handling.html
228
+ //
225
229
  // TODO: It is better to move the default error handler definition
226
230
  // to a stand-alone function at top-level, but the use of options.logger
227
231
  // prevents to do it without some extra refactoring. Should be done sometime
228
232
  // though.
229
-
230
- /* eslint-disable no-unused-vars */
231
233
  server.use((error, req, res, next) => {
232
- /* eslint-enable no-unused-vars */
234
+ // TODO: This is needed to correctly handled any errors thrown after
235
+ // sending initial response to the client.
236
+ if (res.headersSent) return next(error);
233
237
  const status = error.status || _errors.CODES.INTERNAL_SERVER_ERROR;
234
238
  const serverSide = status >= _errors.CODES.INTERNAL_SERVER_ERROR; // Log server-side errors always, client-side at debug level only.
235
239
 
@@ -241,6 +245,7 @@ async function factory(webpackConfig, options) {
241
245
  }
242
246
 
243
247
  res.status(status).send(message);
248
+ return undefined;
244
249
  });
245
250
  }
246
251
 
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","requestIp","mw","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","header","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","require","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","static","path","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","status","INTERNAL_SERVER_ERROR","serverSide","log","message","getErrorForCode","env","NODE_ENV"],"sources":["../../../src/server/server.js"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport express from 'express';\nimport favicon from 'serve-favicon';\nimport helmet from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport rendererFactory from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\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.filter((item) => 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];\ndefaultCspSettings.directives['script-src'].push(\"'unsafe-eval'\");\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 return cloneDeep(defaultCspSettings);\n}\n\nexport default async function factory(webpackConfig, options) {\n const rendererOps = 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();\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n 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 return res.redirect(url);\n }\n return 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((req, res, next) => {\n req.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req.cspNonce = req.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 = cloneDeep(defaultCspSettings);\n cspSettings.directives['script-src'].push(`'nonce-${req.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n });\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => res.send('User-agent: *\\nDisallow:'));\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n loggerMiddleware.token('ip', (req) => req.clientIp);\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n write: options.logger.info.bind(options.logger),\n },\n }));\n\n /* Ensures no caching for the service worker script. */\n server.use(`${publicPath}service-worker.js`, (req, res, next) => {\n res.header('Cache-Control', 'no-cache');\n next();\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 global-require */\n /* eslint-disable import/no-extraneous-dependencies */\n /* eslint-disable import/no-unresolved */\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 if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n };\n }\n\n const webpack = require('webpack');\n const webpackDevMiddleware = require('webpack-dev-middleware');\n const webpackHotMiddleware = require('webpack-hot-middleware');\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable global-require */\n /* eslint-enable import/no-extraneous-dependencies */\n /* eslint-enable import/no-unresolved */\n\n server.use(publicPath, 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: 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 /* eslint-disable no-unused-vars */\n server.use((error, req, res, next) => {\n /* eslint-enable no-unused-vars */\n const status = error.status || CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger.log(serverSide ? 'error' : 'debug', error);\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":";;;;;;;;;;AAIA;;AACA;;AAEA;;AAMA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AAxBA;AACA;AACA;;AA6BA;AACA;AACA;AACA;AACA,MAAMA,kBAAkB,GAAG;EACzBC,UAAU,EAAE,IAAAC,iBAAA,EACVC,eAAA,CAAOC,qBAAP,CAA6BC,oBAA7B,EADU,EAGV;EACA;EACA;EACA;EACCC,KAAD,IAAWA,KAAK,CAACC,MAAN,CAAcC,IAAD,IAAUA,IAAI,KAAK,QAAhC,CAPD;AADa,CAA3B;AAWAR,kBAAkB,CAACC,UAAnB,CAA8B,WAA9B,IAA6C,CAC3C,QAD2C,EAG3C;AACA;AACA,uBAL2C,CAA7C;AAOAD,kBAAkB,CAACC,UAAnB,CAA8B,YAA9B,EAA4CQ,IAA5C,CAAiD,eAAjD,E,CAEA;AACA;AACA;;AACA,OAAOT,kBAAkB,CAACC,UAAnB,CAA8B,2BAA9B,CAAP;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACO,SAASS,qBAAT,GAAiC;EACtC,OAAO,IAAAC,iBAAA,EAAUX,kBAAV,CAAP;AACD;;AAEc,eAAeY,OAAf,CAAuBC,aAAvB,EAAsCC,OAAtC,EAA+C;EAC5D,MAAMC,WAAW,GAAG,IAAAC,YAAA,EAAKF,OAAL,EAAc,CAChC,aADgC,EAEhC,cAFgC,EAGhC,SAHgC,EAIhC,QAJgC,EAKhC,cALgC,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ACD"}
1
+ {"version":3,"file":"server.js","names":["defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","requestIp","mw","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","header","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","require","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","static","path","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","message","getErrorForCode","env","NODE_ENV","undefined"],"sources":["../../../src/server/server.js"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport express from 'express';\nimport favicon from 'serve-favicon';\nimport helmet from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport rendererFactory from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\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.filter((item) => 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];\ndefaultCspSettings.directives['script-src'].push(\"'unsafe-eval'\");\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 return cloneDeep(defaultCspSettings);\n}\n\nexport default async function factory(webpackConfig, options) {\n const rendererOps = 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();\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n 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 return res.redirect(url);\n }\n return 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((req, res, next) => {\n req.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req.cspNonce = req.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 = cloneDeep(defaultCspSettings);\n cspSettings.directives['script-src'].push(`'nonce-${req.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n });\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => res.send('User-agent: *\\nDisallow:'));\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n loggerMiddleware.token('ip', (req) => req.clientIp);\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n write: options.logger.info.bind(options.logger),\n },\n }));\n\n /* Ensures no caching for the service worker script. */\n server.use(`${publicPath}service-worker.js`, (req, res, next) => {\n res.header('Cache-Control', 'no-cache');\n next();\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 global-require */\n /* eslint-disable import/no-extraneous-dependencies */\n /* eslint-disable import/no-unresolved */\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 if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n };\n }\n\n const webpack = require('webpack');\n const webpackDevMiddleware = require('webpack-dev-middleware');\n const webpackHotMiddleware = require('webpack-hot-middleware');\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable global-require */\n /* eslint-enable import/no-extraneous-dependencies */\n /* eslint-enable import/no-unresolved */\n\n server.use(publicPath, 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((error, req, res, next) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) return next(error);\n\n const status = error.status || CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger.log(serverSide ? 'error' : 'debug', error);\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 return undefined;\n });\n }\n\n return server;\n}\n"],"mappings":";;;;;;;;;;AAIA;;AACA;;AAEA;;AAMA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AAxBA;AACA;AACA;;AA6BA;AACA;AACA;AACA;AACA,MAAMA,kBAAkB,GAAG;EACzBC,UAAU,EAAE,IAAAC,iBAAA,EACVC,eAAA,CAAOC,qBAAP,CAA6BC,oBAA7B,EADU,EAGV;EACA;EACA;EACA;EACCC,KAAD,IAAWA,KAAK,CAACC,MAAN,CAAcC,IAAD,IAAUA,IAAI,KAAK,QAAhC,CAPD;AADa,CAA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