@dr.pogodin/react-utils 1.17.2 → 1.17.5

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.
@@ -36,7 +36,9 @@ if (!window.TRU_KEEP_INJ_SCRIPT) {
36
36
  /* eslint-disable no-console */
37
37
 
38
38
 
39
- var useServiceWorker = window.TRU_BUILD_INFO.useServiceWorker;
39
+ var _window$TRU_BUILD_INF = window.TRU_BUILD_INFO,
40
+ publicPath = _window$TRU_BUILD_INF.publicPath,
41
+ useServiceWorker = _window$TRU_BUILD_INF.useServiceWorker;
40
42
 
41
43
  if (useServiceWorker) {
42
44
  var _window = window,
@@ -51,7 +53,7 @@ if (useServiceWorker) {
51
53
  case 0:
52
54
  _context.prev = 0;
53
55
  _context.next = 3;
54
- return navigator.serviceWorker.register('/__service-worker.js');
56
+ return navigator.serviceWorker.register("".concat(publicPath, "/__service-worker.js"));
55
57
 
56
58
  case 3:
57
59
  reg = _context.sent;
@@ -1 +1 @@
1
- {"version":3,"file":"init.js","names":["BUILD_INFO","window","TRU_BUILD_INFO","TRU_KEEP_INJ_SCRIPT","block","document","querySelector","getElementsByTagName","removeChild","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 { 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('/__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;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ATc,CASY;;EAE1BlB,MAAM,CAACkC,YAAP,GAAsBhB,IAAI,CAACgB,YAA3B;EACAlC,MAAM,CAACmC,MAAP,GAAgBjB,IAAI,CAACiB,MAArB;EACAnC,MAAM,CAACoC,MAAP,GAAgBlB,IAAI,CAACkB,MAArB;AACD,CAdD,MAcO;EACL;EACA;EACApC,MAAM,CAACkC,YAAP,GAAsB,EAAtB;EACAlC,MAAM,CAACmC,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","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;c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oC,MAAP,GAAgB,EAAhB;AACD"}
@@ -10,6 +10,7 @@ var _exportNames = {
10
10
  api: true,
11
11
  PT: true,
12
12
  getGlobalState: true,
13
+ getSsrContext: true,
13
14
  GlobalStateProvider: true,
14
15
  useAsyncCollection: true,
15
16
  useAsyncData: true,
@@ -34,6 +35,12 @@ Object.defineProperty(exports, "getGlobalState", {
34
35
  return _reactGlobalState.getGlobalState;
35
36
  }
36
37
  });
38
+ Object.defineProperty(exports, "getSsrContext", {
39
+ enumerable: true,
40
+ get: function () {
41
+ return _reactGlobalState.getSsrContext;
42
+ }
43
+ });
37
44
  exports.server = void 0;
38
45
  Object.defineProperty(exports, "useAsyncCollection", {
39
46
  enumerable: true,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["server","webpack","requireWeak","__dirname"],"sources":["../../src/index.js"],"sourcesContent":["import 'styles/global.scss';\n\nimport { webpack } from 'utils';\n\nconst server = webpack.requireWeak('./server', __dirname);\n\nexport { default as api } from 'axios';\nexport * as PT from 'prop-types';\n\nexport {\n getGlobalState,\n GlobalStateProvider,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\nexport * from 'utils';\n\nexport { server };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA;;AAgBA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AAZA;;;;;;AAGA;;AAQA;;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;;;;;AAbA,MAAMA,MAAM,GAAGC,eAAQC,WAAR,aAAgCC,SAAhC,CAAf"}
1
+ {"version":3,"file":"index.js","names":["server","webpack","requireWeak","__dirname"],"sources":["../../src/index.js"],"sourcesContent":["import 'styles/global.scss';\n\nimport { webpack } from 'utils';\n\nconst server = webpack.requireWeak('./server', __dirname);\n\nexport { default as api } from 'axios';\nexport * as PT from 'prop-types';\n\nexport {\n getGlobalState,\n getSsrContext,\n GlobalStateProvider,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\nexport * from 'utils';\n\nexport { server };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA;;AAiBA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AAbA;;;;;;AAGA;;AASA;;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;;;;;AAdA,MAAMA,MAAM,GAAGC,eAAQC,WAAR,aAAgCC,SAAhC,CAAf"}
@@ -244,25 +244,35 @@ function factory(webpackConfig, options) {
244
244
  const data = cache.get(cacheRef);
245
245
 
246
246
  if (data !== null) {
247
+ const {
248
+ buffer,
249
+ status
250
+ } = data;
251
+
247
252
  if (ops.noCsp && isBrotliAcceptable(req)) {
248
253
  res.set('Content-Type', 'text/html');
249
254
  res.set('Content-Encoding', 'br');
250
- res.send(data);
255
+ if (status !== 200) res.status(status);
256
+ res.send(buffer);
251
257
  } else {
252
- (0, _zlib.brotliDecompress)(data, (error, html) => {
253
- if (error) next(error);else {
254
- let h = html.toString();
255
-
256
- if (!ops.noCsp) {
257
- // TODO: Starting from Node v15 we'll be able to use string's
258
- // .replaceAll() method instead relying on reg. expression for
259
- // global matching.
260
- const regex = new RegExp(data.nonce, 'g');
261
- h = h.replace(regex, req.nonce);
258
+ await new Promise((done, failed) => {
259
+ (0, _zlib.brotliDecompress)(buffer, (error, html) => {
260
+ if (error) failed(error);else {
261
+ let h = html.toString();
262
+
263
+ if (!ops.noCsp) {
264
+ // TODO: Starting from Node v15 we'll be able to use string's
265
+ // .replaceAll() method instead relying on reg. expression for
266
+ // global matching.
267
+ const regex = new RegExp(buffer.nonce, 'g');
268
+ h = h.replace(regex, req.nonce);
269
+ }
270
+
271
+ if (status !== 200) res.status(status);
272
+ res.send(h);
273
+ done();
262
274
  }
263
-
264
- res.send(h);
265
- }
275
+ });
266
276
  });
267
277
  }
268
278
 
@@ -368,7 +378,8 @@ function factory(webpackConfig, options) {
368
378
 
369
379
  const INJ = _nodeForge.default.util.encode64(`${iv}${cipher.output.data}`);
370
380
 
371
- if (ssrContext.status) res.status(ssrContext.status);
381
+ const status = ssrContext.status || 200;
382
+ if (status !== 200) res.status(status);
372
383
  const chunkSet = new Set(); // TODO: "main" chunk has to be added explicitly,
373
384
  // because unlike all other chunks they are not managed by <CodeSplit>
374
385
  // component, thus they are not added to the ssrContext.chunks
@@ -427,12 +438,21 @@ function factory(webpackConfig, options) {
427
438
  </html>`;
428
439
  res.send(html);
429
440
 
430
- if (cacheRef) {
431
- (0, _zlib.brotliCompress)(html, (error, buffer) => {
432
- if (error) throw error;
433
- buffer.nonce = req.nonce; // eslint-disable-line no-param-reassign
434
-
435
- cache.add(buffer, cacheRef.key);
441
+ if (cacheRef && status < 500) {
442
+ // Note: waiting for the caching to complete is not strictly necessary,
443
+ // but it greately simplifies testing, and error reporting.
444
+ await new Promise((done, failed) => {
445
+ (0, _zlib.brotliCompress)(html, (error, buffer) => {
446
+ if (error) failed(error);else {
447
+ buffer.nonce = req.nonce; // eslint-disable-line no-param-reassign
448
+
449
+ cache.add({
450
+ buffer,
451
+ status
452
+ }, cacheRef.key);
453
+ done();
454
+ }
455
+ });
436
456
  });
437
457
  }
438
458
  } catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"renderer.js","names":["sanitizedConfig","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","code","location","undefined","Error","factory","webpackConfig","options","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","buildInfo","global","TRU_BUILD_INFO","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cacheRef","data","noCsp","send","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","initialState","all","helmet","App","Application","ssrContext","state","chunks","stream","ssrStart","Date","now","renderPass","pipeableStream","onAllReady","onError","round","dirty","timeout","ok","race","allSettled","pending","time","timer","then","pipe","Writable","write","chunk","_","done","Helmet","renderStatic","chunkGroups","webpackStats","locals","toJson","namedChunkGroups","item","assets","map","name","dr_pogodin_react_utils___split_components","payload","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","status","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","buffer"],"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';\n\nimport time from 'utils/time';\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 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 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 if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n res.send(data);\n } else {\n brotliDecompress(data, (error, html) => {\n if (error) next(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(data.nonce, 'g');\n h = h.replace(regex, req.nonce);\n }\n res.send(h);\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 for (let round = 0; round < ops.maxSsrRounds; ++round) {\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 const ok = timeout > 0 && await Promise.race([\n Promise.allSettled(ssrContext.pending),\n time.timer(timeout).then(() => false),\n ]);\n if (!ok) break;\n /* eslint-enable no-await-in-loop */\n }\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 if (ssrContext.status) res.status(ssrContext.status);\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 res.send(html);\n\n if (cacheRef) {\n brotliCompress(html, (error, buffer) => {\n if (error) throw error;\n buffer.nonce = req.nonce; // eslint-disable-line no-param-reassign\n cache.add(buffer, cacheRef.key);\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;;AAEA;;AAEA;;;;AA/BA;AACA;AACA;AA+BA,MAAMA,eAAe,GAAG,kBAAKC,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,cAAKC,OAAL,CAAaH,OAAb,EAAsB,aAAtB,CAAZ;;EACA,OAAOI,IAAI,CAACC,KAAL,CAAWC,YAAGC,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,cAAKC,OAAL,CAAaM,QAAb,EAAuB,uBAAvB,CAAZ;;EACA,IAAIC,GAAJ;;EACA,IAAI;IACFA,GAAG,GAAGN,IAAI,CAACC,KAAL,CAAWC,YAAGC,YAAH,CAAgBN,GAAhB,CAAX,CAAN;EACD,CAFD,CAEE,OAAOU,GAAP,EAAY;IACZD,GAAG,GAAG,IAAN;EACD;;EACD,OAAOA,GAAP;AACD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACA,SAASE,aAAT,CAAuBC,GAAvB,EAA4B;EAC1B,OAAO,IAAIC,OAAJ,CAAY,CAACX,OAAD,EAAUY,MAAV,KAAqB;IACtCC,mBAAMC,MAAN,C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BAAoB,CAAClJ,gBAAgB,CAACE,OAAlB,CAA2B;AAC7D;AACA,gBA7BM;MA+BAa,GAAG,CAACwD,IAAJ,CAASE,IAAT;;MAEA,IAAIL,QAAJ,EAAc;QACZ,0BAAeK,IAAf,EAAqB,CAACD,KAAD,EAAQ+E,MAAR,KAAmB;UACtC,IAAI/E,KAAJ,EAAW,MAAMA,KAAN;UACX+E,MAAM,CAACzE,KAAP,GAAejD,GAAG,CAACiD,KAAnB,CAFsC,CAEZ;;UAC1BhB,KAAK,CAACgF,GAAN,CAAUS,MAAV,EAAkBnF,QAAQ,CAAClD,GAA3B;QACD,CAJD;MAKD;IACF,CA/ND,CA+NE,OAAOsD,KAAP,EAAc;MACdN,IAAI,CAACM,KAAD,CAAJ;IACD;EACF,CAnOD;AAoOD"}
1
+ {"version":3,"file":"renderer.js","names":["sanitizedConfig","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","code","location","undefined","Error","factory","webpackConfig","options","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","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","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","initialState","all","helmet","App","Application","ssrContext","state","chunks","stream","ssrStart","Date","now","renderPass","pipeableStream","onAllReady","onError","round","dirty","timeout","ok","race","allSettled","pending","time","timer","then","pipe","Writable","write","chunk","_","Helmet","renderStatic","chunkGroups","webpackStats","locals","toJson","namedChunkGroups","item","assets","map","name","dr_pogodin_react_utils___split_components","payload","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta"],"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';\n\nimport time from 'utils/time';\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 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 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 for (let round = 0; round < ops.maxSsrRounds; ++round) {\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 const ok = timeout > 0 && await Promise.race([\n Promise.allSettled(ssrContext.pending),\n time.timer(timeout).then(() => false),\n ]);\n if (!ok) break;\n /* eslint-enable no-await-in-loop */\n }\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 status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\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 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;;AAEA;;AAEA;;;;AA/BA;AACA;AACA;AA+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3C,GAAG,CAACqD,KAAM,GAAG;AACxD;AACA,4BAA4BwD,GAAI;AAChC;AACA,cAAcQ,iBAAkB;AAChC,cAAcE,oBAAoB,CAACpJ,gBAAgB,CAACE,OAAlB,CAA2B;AAC7D;AACA,gBA7BM;MA+BAa,GAAG,CAAC0D,IAAJ,CAASI,IAAT;;MAEA,IAAIT,QAAQ,IAAIG,MAAM,GAAG,GAAzB,EAA8B;QAC5B;QACA;QACA,MAAM,IAAIpD,OAAJ,CAAY,CAACuD,IAAD,EAAOC,MAAP,KAAkB;UAClC,0BAAeE,IAAf,EAAqB,CAACD,KAAD,EAAQN,MAAR,KAAmB;YACtC,IAAIM,KAAJ,EAAWD,MAAM,CAACC,KAAD,CAAN,CAAX,KACK;cACHN,MAAM,CAACY,KAAP,GAAerD,GAAG,CAACqD,KAAnB,CADG,CACuB;;cAC1BpB,KAAK,CAACkF,GAAN,CAAU;gBAAE1E,MAAF;gBAAUC;cAAV,CAAV,EAA8BH,QAAQ,CAAClD,GAAvC;cACAwD,IAAI;YACL;UACF,CAPD;QAQD,CATK,CAAN;MAUD;IACF,CA7OD,CA6OE,OAAOE,KAAP,EAAc;MACdV,IAAI,CAACU,KAAD,CAAJ;IACD;EACF,CAjPD;AAkPD"}
@@ -210,7 +210,9 @@ async function factory(webpackConfig, options) {
210
210
  server.use(renderer);
211
211
  /* Detects 404 errors, and forwards them to the error handler. */
212
212
 
213
- server.use(() => (0, _errors.fail)(_errors.ERRORS.NOT_FOUND, _errors.CODES.NOT_FOUND));
213
+ server.use((req, res, next) => {
214
+ next((0, _errors.newError)(_errors.ERRORS.NOT_FOUND, _errors.CODES.NOT_FOUND));
215
+ });
214
216
  let dontAttachDefaultErrorHandler;
215
217
 
216
218
  if (options.beforeExpressJsError) {
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["defaultCspSettings","directives","helmet","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","nonce","cspNonce","cspSettings","cspSettingsHook","favicon","send","express","json","limit","urlencoded","extended","requestIp","mw","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","header","devMode","global","location","href","process","cwd","sep","webpack","require","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","static","path","onExpressJsSetup","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","status","INTERNAL_SERVER_ERROR","serverSide","log","message","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 fail,\n getErrorForCode,\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 '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(() => fail(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\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,uBACVC,gBAAOC,qBAAP,CAA6BC,oBAA7B,EADU,EAGV;EACA;EACA;EACA;EACCC,KAAD,IAAWA,KAAK,CAACC,MAAN,CAAcC,IAAD,IAAUA,IAAI,KAAK,QAAhC,CAPD;AADa,CAA3B;AAWAP,kBAAkB,CAACC,UAAnB,CAA8B,WAA9B,IAA6C,CAC3C,QAD2C,EAG3C;AACA;AACA,uBAL2C,CAA7C;AAOAD,kBAAkB,CAACC,UAAnB,CAA8B,YAA9B,EAA4CO,IAA5C,CAAiD,eAAjD,E,CAEA;AACA;AACA;;AACA,OAAOR,kBAAkB,CAACC,UAAnB,CAA8B,2BAA9B,CAAP;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACO,SAASQ,qBAAT,GAAiC;EACtC,OAAO,uBAAU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B;;EAEA,IAAI3D,OAAO,CAAC4D,gBAAZ,EAA8B;IAC5B,MAAM5D,OAAO,CAAC4D,gBAAR,CAAyBvD,MAAzB,CAAN;EACD;;EACDA,MAAM,CAACI,GAAP,CAAWP,QAAX;EAEA;;EACAG,MAAM,CAACI,GAAP,CAAW,MAAM,kBAAKoD,eAAOC,SAAZ,EAAuBC,cAAMD,SAA7B,CAAjB;EAEA,IAAIE,6BAAJ;;EACA,IAAIhE,OAAO,CAACiE,oBAAZ,EAAkC;IAChCD,6BAA6B,GAAG,MAAMhE,OAAO,CAACiE,oBAAR,CAA6B5D,MAA7B,CAAtC;EACD;EAED;;;EACA,IAAI,CAAC2D,6BAAL,EAAoC;IAClC;IACA;IACA;IACA;;IACA;IACA3D,MAAM,CAACI,GAAP,CAAW,CAACyD,KAAD,EAAQxD,GAAR,EAAaC,GAAb,EAAkBC,IAAlB,KAA2B;MACtC;MACE,MAAMuD,MAAM,GAAGD,KAAK,CAACC,MAAN,IAAgBJ,cAAMK,qBAArC;MACA,MAAMC,UAAU,GAAGF,MAAM,IAAIJ,cAAMK,qBAAnC,CAHoC,CAKpC;;MACApE,OAAO,CAACO,MAAR,CAAe+D,GAAf,CAAmBD,UAAU,GAAG,OAAH,GAAa,OAA1C,EAAmDH,KAAnD;MAEA,IAAIK,OAAO,GAAGL,KAAK,CAACK,OAAN,IAAiB,6BAAgBJ,MAAhB,CAA/B;;MACA,IAAIE,UAAU,IAAIpB,OAAO,CAACuB,GAAR,CAAYC,QAAZ,KAAyB,YAA3C,EAAyD;QACvDF,OAAO,GAAGV,eAAOO,qBAAjB;MACD;;MAEDzD,GAAG,CAACwD,MAAJ,CAAWA,MAAX,EAAmBvC,IAAnB,CAAwB2C,OAAxB;IACD,CAdD;EAeD;;EAED,OAAOlE,MAAP;AACD"}
1
+ {"version":3,"file":"server.js","names":["defaultCspSettings","directives","helmet","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","nonce","cspNonce","cspSettings","cspSettingsHook","favicon","send","express","json","limit","urlencoded","extended","requestIp","mw","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","header","devMode","global","location","href","process","cwd","sep","webpack","require","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","static","path","onExpressJsSetup","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","status","INTERNAL_SERVER_ERROR","serverSide","log","message","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 '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,uBACVC,gBAAOC,qBAAP,CAA6BC,oBAA7B,EADU,EAGV;EACA;EACA;EACA;EACCC,KAAD,IAAWA,KAAK,CAACC,MAAN,CAAcC,IAAD,IAAUA,IAAI,KAAK,QAAhC,CAPD;AADa,CAA3B;AAWAP,kBAAkB,CAACC,UAAnB,CAA8B,WAA9B,IAA6C,CAC3C,QAD2C,EAG3C;AACA;AACA,uBAL2C,CAA7C;AAOAD,kBAAkB,CAACC,UAAnB,CAA8B,YAA9B,EAA4CO,IAA5C,CAAiD,eAAjD,E,CAEA;AACA;AACA;;AACA,OAAOR,kBAAkB,CAACC,UAAnB,CAA8B,2BAA9B,CAAP;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACO,SAASQ,qBAA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53,18 @@ class E2eSsrEnv extends _jestEnvironmentJsdom.default {
53
53
  options = options ? JSON.parse(options) : {};
54
54
  (0, _lodash.defaults)(options, {
55
55
  context: this.testFolder,
56
- dontEmitBuildInfo: true
56
+ fs: this.global.webpackOutputFs
57
57
  });
58
58
  let factory = this.pragmas['webpack-config-factory'] || '';
59
59
  factory = require(_path.default.resolve(this.rootDir, factory));
60
60
  this.global.webpackConfig = factory(options);
61
- this.global.buildInfo = factory.buildInfo;
61
+ const fs = this.global.webpackOutputFs;
62
+ let buildInfo = `${options.context}/.build-info`;
63
+
64
+ if (fs.existsSync(buildInfo)) {
65
+ buildInfo = fs.readFileSync(buildInfo, 'utf8');
66
+ this.global.buildInfo = JSON.parse(buildInfo);
67
+ }
62
68
  }
63
69
  /**
64
70
  * Executes Webpack build.
@@ -69,12 +75,10 @@ class E2eSsrEnv extends _jestEnvironmentJsdom.default {
69
75
  async runWebpack() {
70
76
  this.loadWebpackConfig();
71
77
  const compiler = (0, _webpack.default)(this.global.webpackConfig);
72
- const fs = (0, _memfs.createFsFromVolume)(new _memfs.Volume());
73
- compiler.outputFileSystem = fs;
78
+ compiler.outputFileSystem = this.global.webpackOutputFs;
74
79
  return new Promise((done, fail) => {
75
80
  compiler.run((err, stats) => {
76
81
  if (err) fail(err);
77
- this.global.webpackOutputFs = fs;
78
82
  this.global.webpackStats = stats.toJson(); // Keeps reference to the raw Webpack stats object, which should be
79
83
  // explicitly passed to the server-side renderer alongside the request,
80
84
  // so that it can to pick up asset paths for different named chunks.
@@ -87,13 +91,25 @@ class E2eSsrEnv extends _jestEnvironmentJsdom.default {
87
91
 
88
92
  async runSsr() {
89
93
  let options = this.pragmas['ssr-options'];
90
- options = options ? JSON.parse(options) : {}; // Note: This enables Babel transformation for the code dynamically loaded
94
+ options = options ? JSON.parse(options) : {};
95
+ let root;
96
+
97
+ switch (options.root) {
98
+ case 'TEST':
99
+ root = this.testFolder;
100
+ break;
101
+
102
+ default:
103
+ root = process.cwd();
104
+ } // Note: This enables Babel transformation for the code dynamically loaded
91
105
  // below, as the usual Jest Babel setup does not seem to apply to
92
106
  // the environment code, and imports from it.
93
107
 
108
+
94
109
  (0, _register.default)({
95
110
  envName: options.babelEnv,
96
- extensions: ['.js', '.jsx', '.svg']
111
+ extensions: ['.js', '.jsx', '.svg'],
112
+ root
97
113
  });
98
114
  if (!options.buildInfo) options.buildInfo = this.global.buildInfo;
99
115
 
@@ -104,6 +120,8 @@ class E2eSsrEnv extends _jestEnvironmentJsdom.default {
104
120
  }
105
121
 
106
122
  const renderer = (0, _renderer.default)(this.global.webpackConfig, options);
123
+ let status = 200; // OK
124
+
107
125
  const markup = await new Promise((done, fail) => {
108
126
  renderer(this.ssrRequest, // TODO: This will do for now, with the current implementation of
109
127
  // the renderer, but it will require a rework once the renderer is
@@ -111,6 +129,9 @@ class E2eSsrEnv extends _jestEnvironmentJsdom.default {
111
129
  {
112
130
  send: done,
113
131
  set: _lodash.noop,
132
+ status: value => {
133
+ status = value;
134
+ },
114
135
  // This is how up-to-date Webpack stats are passed to the server in
115
136
  // development mode, and we use this here always, instead of having
116
137
  // to pass some information via filesystem.
@@ -127,6 +148,7 @@ class E2eSsrEnv extends _jestEnvironmentJsdom.default {
127
148
  });
128
149
  this.global.ssrMarkup = markup;
129
150
  this.global.ssrOptions = options;
151
+ this.global.ssrStatus = status;
130
152
  }
131
153
 
132
154
  constructor(config, context) {
@@ -137,7 +159,8 @@ class E2eSsrEnv extends _jestEnvironmentJsdom.default {
137
159
 
138
160
  (0, _lodash.set)(config.projectConfig, 'testEnvironmentOptions.url', `http://localhost${request.url}`);
139
161
  super(config, context);
140
- this.global.dom = this.dom; // Extracts necessary settings from config and context.
162
+ this.global.dom = this.dom;
163
+ this.global.webpackOutputFs = (0, _memfs.createFsFromVolume)(new _memfs.Volume()); // Extracts necessary settings from config and context.
141
164
 
142
165
  const {
143
166
  projectConfig
@@ -1 +1 @@
1
- {"version":3,"file":"E2eSsrEnv.js","names":["E2eSsrEnv","JsdomEnv","loadWebpackConfig","options","pragmas","JSON","parse","context","testFolder","dontEmitBuildInfo","factory","require","path","resolve","rootDir","global","webpackConfig","buildInfo","runWebpack","compiler","fs","Volume","outputFileSystem","Promise","done","fail","run","err","stats","webpackOutputFs","webpackStats","toJson","runSsr","envName","babelEnv","extensions","entry","p","Application","entryExportName","renderer","markup","ssrRequest","send","set","noop","locals","webpack","devMiddleware","error","ssrMarkup","ssrOptions","constructor","config","docblockPragmas","request","url","projectConfig","dom","dirname","testPath","withSsr","setup","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","cache","forEach","key","register","revert"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.js"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n/* eslint-disable global-require, import/no-dynamic-require */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\nimport path from 'path';\nimport ssrFactory from 'server/renderer';\n\nimport { defaults, noop, set } from 'lodash';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register';\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { createFsFromVolume, Volume } from 'memfs';\nimport webpack from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nexport default class E2eSsrEnv extends JsdomEnv {\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n loadWebpackConfig() {\n let options = this.pragmas['webpack-config-options'];\n options = options ? JSON.parse(options) : {};\n defaults(options, {\n context: this.testFolder,\n dontEmitBuildInfo: true,\n });\n\n let factory = this.pragmas['webpack-config-factory'] || '';\n factory = require(path.resolve(this.rootDir, factory));\n this.global.webpackConfig = factory(options);\n this.global.buildInfo = factory.buildInfo;\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack() {\n this.loadWebpackConfig();\n\n const compiler = webpack(this.global.webpackConfig);\n const fs = createFsFromVolume(new Volume());\n compiler.outputFileSystem = fs;\n return new Promise((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n this.global.webpackOutputFs = fs;\n this.global.webpackStats = stats.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr() {\n let options = this.pragmas['ssr-options'];\n options = options ? JSON.parse(options) : {};\n\n // Note: This enables Babel transformation for the code dynamically loaded\n // below, as the usual Jest Babel setup does not seem to apply to\n // the environment code, and imports from it.\n register({\n envName: options.babelEnv,\n extensions: ['.js', '.jsx', '.svg'],\n });\n\n if (!options.buildInfo) options.buildInfo = this.global.buildInfo;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry);\n options.Application = require(p)[options.entryExportName || 'default'];\n }\n\n const renderer = ssrFactory(this.global.webpackConfig, options);\n const markup = await new Promise((done, fail) => {\n renderer(\n this.ssrRequest,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n {\n send: done,\n set: noop,\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n },\n\n (error) => {\n if (error) fail(error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n }\n\n constructor(config, context) {\n const pragmas = context.docblockPragmas;\n let request = pragmas['ssr-request'];\n request = request ? JSON.parse(request) : {};\n if (!request.url) request.url = '/';\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n }\n\n async setup() {\n await super.setup();\n await this.runWebpack();\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown() {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n super.teardown();\n }\n}\n"],"mappings":";;;;;;;;;AAiBA;;AACA;;AAEA;;AAKA;;AACA;;AACA;;AACA;;AA5BA;AACA;AACA;AACA;AACA;AACA;;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAOA;AACA;;AACA;;AAKA;AAEe,MAAMA,SAAN,SAAwBC,6BAAxB,CAAiC;EAC9C;AACF;AACA;AACA;EACEC,iBAAiB,GAAG;IAClB,IAAIC,OAAO,GAAG,KAAKC,OAAL,CAAa,wBAAb,CAAd;IACAD,OAAO,GAAGA,OAAO,GAAGE,IAAI,CAACC,KAAL,CAAWH,OAAX,CAAH,GAAyB,EAA1C;IACA,sBAASA,OAAT,EAAkB;MAChBI,OAAO,EAAE,KAAKC,UADE;MAEhBC,iBAAiB,EAAE;IAFH,CAAlB;IAKA,IAAIC,OAAO,GAAG,KAAKN,OAAL,CAAa,wBAAb,KAA0C,EAAxD;IAC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GAAb,EAAkBD,OAAO,CAACC,GAAR,GAAc,GAAd,CAJS,CAM3B;;IACA,iBACEH,MAAM,CAACI,aADT,EAEE,4BAFF,EAGG,mBAAkBF,OAAO,CAACC,GAAI,EAHjC;IAMA,MAAMH,MAAN,EAAc9C,OAAd;IAEA,KAAKQ,MAAL,CAAY2C,GAAZ,GAAkB,KAAKA,GAAvB,CAf2B,CAiB3B;;IACA,MAAM;MAAED;IAAF,IAAoBJ,MAA1B;IACA,KAAKvC,OAAL,GAAe2C,aAAa,CAAC3C,OAA7B;IACA,KAAKN,UAAL,GAAkBI,cAAK+C,OAAL,CAAapD,OAAO,CAACqD,QAArB,CAAlB;IACA,KAAKC,OAAL,GAAe,CAACzD,OAAO,CAAC,QAAD,CAAvB;IACA,KAAKsC,UAAL,GAAkBa,OAAlB;IACA,KAAKnD,OAAL,GAAeA,OAAf;EACD;;EAEU,MAAL0D,KAAK,GAAG;IACZ,MAAM,MAAMA,KAAN,EAAN;IACA,MAAM,KAAK5C,UAAL,EAAN;IACA,IAAI,KAAK2C,OAAT,EAAkB,MAAM,KAAK7B,MAAL,EAAN;IAClB,KAAKjB,MAAL,CAAYgD,6BAAZ,GAA4C,IAA5C;EACD;;EAEa,MAARC,QAAQ,GAAG;IACf,OAAO,KAAKjD,MAAL,CAAYgD,6BAAnB,CADe,CAGf;IACA;IACA;IACA;IACA;IACA;;IACAE,MAAM,CAACC,IAAP,CAAYvD,OAAO,CAACwD,KAApB,EAA2BC,OAA3B,CAAoCC,GAAD,IAAS;MAC1C,OAAO1D,OAAO,CAACwD,KAAR,CAAcE,GAAd,CAAP;IACD,CAFD;;IAGAC,kBAASC,MAAT;;IACA,MAAMP,QAAN;EACD;;AAlJ6C"}
1
+ {"version":3,"file":"E2eSsrEnv.js","names":["E2eSsrEnv","JsdomEnv","loadWebpackConfig","options","pragmas","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factory","require","path","resolve","rootDir","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","compiler","outputFileSystem","Promise","done","fail","run","err","stats","webpackStats","toJson","runSsr","root","process","cwd","envName","babelEnv","extensions","entry","p","Application","entryExportName","renderer","status","markup","ssrRequest","send","set","noop","value","locals","webpack","devMiddleware","error","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","request","url","projectConfig","dom","Volume","dirname","testPath","withSsr","setup","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","cache","forEach","key","register","revert"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.js"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n/* eslint-disable global-require, import/no-dynamic-require */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\nimport path from 'path';\nimport ssrFactory from 'server/renderer';\n\nimport { defaults, noop, set } from 'lodash';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register';\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { createFsFromVolume, Volume } from 'memfs';\nimport webpack from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nexport default class E2eSsrEnv extends JsdomEnv {\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n loadWebpackConfig() {\n let options = this.pragmas['webpack-config-options'];\n options = options ? JSON.parse(options) : {};\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n let factory = this.pragmas['webpack-config-factory'] || '';\n factory = require(path.resolve(this.rootDir, factory));\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8');\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack() {\n this.loadWebpackConfig();\n\n const compiler = webpack(this.global.webpackConfig);\n compiler.outputFileSystem = this.global.webpackOutputFs;\n return new Promise((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n\n this.global.webpackStats = stats.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr() {\n let options = this.pragmas['ssr-options'];\n options = options ? JSON.parse(options) : {};\n\n let root;\n switch (options.root) {\n case 'TEST': root = this.testFolder; break;\n default: root = process.cwd();\n }\n\n // Note: This enables Babel transformation for the code dynamically loaded\n // below, as the usual Jest Babel setup does not seem to apply to\n // the environment code, and imports from it.\n register({\n envName: options.babelEnv,\n extensions: ['.js', '.jsx', '.svg'],\n root,\n });\n\n if (!options.buildInfo) options.buildInfo = this.global.buildInfo;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry);\n options.Application = require(p)[options.entryExportName || 'default'];\n }\n\n const renderer = ssrFactory(this.global.webpackConfig, options);\n let status = 200; // OK\n const markup = await new Promise((done, fail) => {\n renderer(\n this.ssrRequest,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n {\n send: done,\n set: noop,\n status: (value) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n },\n\n (error) => {\n if (error) fail(error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n }\n\n constructor(config, context) {\n const pragmas = context.docblockPragmas;\n let request = pragmas['ssr-request'];\n request = request ? JSON.parse(request) : {};\n if (!request.url) request.url = '/';\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n }\n\n async setup() {\n await super.setup();\n await this.runWebpack();\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown() {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n super.teardown();\n }\n}\n"],"mappings":";;;;;;;;;AAiBA;;AACA;;AAEA;;AAKA;;AACA;;AACA;;AACA;;AA5BA;AACA;AACA;AACA;AACA;AACA;;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAOA;AACA;;AACA;;AAKA;AAEe,MAAMA,SAAN,SAAwBC,6BAAxB,CAAiC;EAC9C;AACF;AACA;AACA;EACEC,iBAAiB,GAAG;IAClB,IAAIC,OAAO,GAAG,KAAKC,OAAL,CAAa,wBAAb,CAAd;IACAD,OAAO,GAAGA,OAAO,GAAGE,IAAI,CAACC,KAAL,CAAWH,OAAX,CAAH,GAAyB,EAA1C;IACA,sBAASA,O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OAAO,CAAC,QAAD,CAAvB;IACA,KAAK0C,UAAL,GAAkBe,OAAlB;IACA,KAAKzD,OAAL,GAAeA,OAAf;EACD;;EAEU,MAALiE,KAAK,GAAG;IACZ,MAAM,MAAMA,KAAN,EAAN;IACA,MAAM,KAAKhD,UAAL,EAAN;IACA,IAAI,KAAK+C,OAAT,EAAkB,MAAM,KAAKpC,MAAL,EAAN;IAClB,KAAKtB,MAAL,CAAY4D,6BAAZ,GAA4C,IAA5C;EACD;;EAEa,MAARC,QAAQ,GAAG;IACf,OAAO,KAAK7D,MAAL,CAAY4D,6BAAnB,CADe,CAGf;IACA;IACA;IACA;IACA;IACA;;IACAE,MAAM,CAACC,IAAP,CAAY5D,OAAO,CAAC6D,KAApB,EAA2BC,OAA3B,CAAoCC,GAAD,IAAS;MAC1C,OAAO/D,OAAO,CAAC6D,KAAR,CAAcE,GAAd,CAAP;IACD,CAFD;;IAGAC,kBAASC,MAAT;;IACA,MAAMP,QAAN;EACD;;AApK6C"}
@@ -36,7 +36,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac
36
36
  \**********************/
37
37
  /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
38
38
 
39
- eval("var __dirname = \"/\";\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"Barrier\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.Barrier; },\n/* harmony export */ \"BaseModal\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.BaseModal; },\n/* harmony export */ \"Button\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Button; },\n/* harmony export */ \"Checkbox\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Checkbox; },\n/* harmony export */ \"Dropdown\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Dropdown; },\n/* harmony export */ \"Emitter\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.Emitter; },\n/* harmony export */ \"GlobalStateProvider\": function() { return /* reexport safe */ _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__.GlobalStateProvider; },\n/* harmony export */ \"Input\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Input; },\n/* harmony export */ \"JU\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.JU; },\n/* harmony export */ \"Link\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Link; },\n/* harmony export */ \"MetaTags\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.MetaTags; },\n/* harmony export */ \"Modal\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Modal; },\n/* harmony export */ \"NavLink\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.NavLink; },\n/* harmony export */ \"PT\": function() { return /* reexport module object */ prop_types__WEBPACK_IMPORTED_MODULE_3__; },\n/* harmony export */ \"PageLayout\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.PageLayout; },\n/* harmony export */ \"ScalableRect\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.ScalableRect; },\n/* harmony export */ \"Semaphore\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.Semaphore; },\n/* harmony export */ \"ThemeProvider\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.ThemeProvider; },\n/* harmony export */ \"Throbber\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Throbber; },\n/* harmony export */ \"WithTooltip\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.WithTooltip; },\n/* harmony export */ \"YouTubeVideo\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.YouTubeVideo; },\n/* harmony export */ \"api\": function() { return /* reexport default from dynamic */ axios__WEBPACK_IMPORTED_MODULE_2___default.a; },\n/* harmony export */ \"client\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.client; },\n/* harmony export */ \"config\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.config; },\n/* harmony export */ \"getGlobalState\": function() { return /* reexport safe */ _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__.getGlobalState; },\n/* harmony export */ \"isomorphy\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.isomorphy; },\n/* harmony export */ \"newBarrier\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.newBarrier; },\n/* harmony export */ \"server\": function() { return /* binding */ server; },\n/* harmony export */ \"splitComponent\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.splitComponent; },\n/* harmony export */ \"themed\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.themed; },\n/* harmony export */ \"time\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.time; },\n/* harmony export */ \"useAsyncCollection\": function() { return /* reexport safe */ _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__.useAsyncCollection; },\n/* harmony export */ \"useAsyncData\": function() { return /* reexport safe */ _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__.useAsyncData; },\n/* harmony export */ \"useGlobalState\": function() { return /* reexport safe */ _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__.useGlobalState; },\n/* harmony export */ \"webpack\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.webpack; },\n/* harmony export */ \"withRetries\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.withRetries; }\n/* harmony export */ });\n/* harmony import */ var _styles_global_scss__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./styles/global.scss */ \"./src/styles/global.scss\");\n/* harmony import */ var _shared_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shared/utils */ \"./src/shared/utils/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! axios */ \"axios\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! prop-types */ \"prop-types\");\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @dr.pogodin/react-global-state */ \"@dr.pogodin/react-global-state\");\n/* harmony import */ var _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony import */ var _shared_components__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./shared/components */ \"./src/shared/components/index.js\");\n\n\nvar server = _shared_utils__WEBPACK_IMPORTED_MODULE_1__.webpack.requireWeak('./server', __dirname);\n\n\n\n\n\n\n\n\n//# sourceURL=webpack://@dr.pogodin/react-utils/./src/index.js?");
39
+ eval("var __dirname = \"/\";\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"Barrier\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.Barrier; },\n/* harmony export */ \"BaseModal\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.BaseModal; },\n/* harmony export */ \"Button\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Button; },\n/* harmony export */ \"Checkbox\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Checkbox; },\n/* harmony export */ \"Dropdown\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Dropdown; },\n/* harmony export */ \"Emitter\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.Emitter; },\n/* harmony export */ \"GlobalStateProvider\": function() { return /* reexport safe */ _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__.GlobalStateProvider; },\n/* harmony export */ \"Input\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Input; },\n/* harmony export */ \"JU\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.JU; },\n/* harmony export */ \"Link\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Link; },\n/* harmony export */ \"MetaTags\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.MetaTags; },\n/* harmony export */ \"Modal\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Modal; },\n/* harmony export */ \"NavLink\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.NavLink; },\n/* harmony export */ \"PT\": function() { return /* reexport module object */ prop_types__WEBPACK_IMPORTED_MODULE_3__; },\n/* harmony export */ \"PageLayout\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.PageLayout; },\n/* harmony export */ \"ScalableRect\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.ScalableRect; },\n/* harmony export */ \"Semaphore\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.Semaphore; },\n/* harmony export */ \"ThemeProvider\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.ThemeProvider; },\n/* harmony export */ \"Throbber\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.Throbber; },\n/* harmony export */ \"WithTooltip\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.WithTooltip; },\n/* harmony export */ \"YouTubeVideo\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.YouTubeVideo; },\n/* harmony export */ \"api\": function() { return /* reexport default from dynamic */ axios__WEBPACK_IMPORTED_MODULE_2___default.a; },\n/* harmony export */ \"client\": function() { return /* reexport safe */ _shared_components__WEBPACK_IMPORTED_MODULE_5__.client; },\n/* harmony export */ \"config\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.config; },\n/* harmony export */ \"getGlobalState\": function() { return /* reexport safe */ _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__.getGlobalState; },\n/* harmony export */ \"getSsrContext\": function() { return /* reexport safe */ _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__.getSsrContext; },\n/* harmony export */ \"isomorphy\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.isomorphy; },\n/* harmony export */ \"newBarrier\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.newBarrier; },\n/* harmony export */ \"server\": function() { return /* binding */ server; },\n/* harmony export */ \"splitComponent\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.splitComponent; },\n/* harmony export */ \"themed\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.themed; },\n/* harmony export */ \"time\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.time; },\n/* harmony export */ \"useAsyncCollection\": function() { return /* reexport safe */ _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__.useAsyncCollection; },\n/* harmony export */ \"useAsyncData\": function() { return /* reexport safe */ _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__.useAsyncData; },\n/* harmony export */ \"useGlobalState\": function() { return /* reexport safe */ _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__.useGlobalState; },\n/* harmony export */ \"webpack\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.webpack; },\n/* harmony export */ \"withRetries\": function() { return /* reexport safe */ _shared_utils__WEBPACK_IMPORTED_MODULE_1__.withRetries; }\n/* harmony export */ });\n/* harmony import */ var _styles_global_scss__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./styles/global.scss */ \"./src/styles/global.scss\");\n/* harmony import */ var _shared_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shared/utils */ \"./src/shared/utils/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! axios */ \"axios\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! prop-types */ \"prop-types\");\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @dr.pogodin/react-global-state */ \"@dr.pogodin/react-global-state\");\n/* harmony import */ var _dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_dr_pogodin_react_global_state__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony import */ var _shared_components__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./shared/components */ \"./src/shared/components/index.js\");\n\n\nvar server = _shared_utils__WEBPACK_IMPORTED_MODULE_1__.webpack.requireWeak('./server', __dirname);\n\n\n\n\n\n\n\n\n//# sourceURL=webpack://@dr.pogodin/react-utils/./src/index.js?");
40
40
 
41
41
  /***/ }),
42
42
 
@@ -4,7 +4,7 @@
4
4
  // is bundled into client-side code.
5
5
  /* `BUILD_INFO` is always injected by Webpack build, but this check is needed
6
6
  * to adopt the code for usage in tests. */if(typeof BUILD_INFO!=="undefined"){window.TRU_BUILD_INFO=BUILD_INFO}/* Removes data injection script out of the document.
7
- * The if block is here for test purposes. */if(!window.TRU_KEEP_INJ_SCRIPT){var block=document.querySelector("script[id=\"inj\"]");if(block)document.getElementsByTagName("body")[0].removeChild(block)}/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */ /* eslint-disable no-console */var useServiceWorker=window.TRU_BUILD_INFO.useServiceWorker;if(useServiceWorker){var _window=window,navigator=_window.navigator;if("serviceWorker"in navigator){window.addEventListener("load",/*#__PURE__*/(0,_asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee(){var reg;return _regenerator.default.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.prev=0;_context.next=3;return navigator.serviceWorker.register("/__service-worker.js");case 3:reg=_context.sent;console.log("SW registered:",reg);_context.next=10;break;case 7:_context.prev=7;_context.t0=_context["catch"](0);console.log("SW registration failed:",_context.t0);case 10:case"end":return _context.stop();}}},_callee,null,[[0,7]])})))}}/* eslint-enable no-console */ /* Decodes data injected at the server side. */if(window.INJ){var key=window.TRU_BUILD_INFO.key;var data=_forge.default.util.decode64(window.INJ);var decipher=_forge.default.cipher.createDecipher("AES-CBC",key);decipher.start({iv:data.slice(0,32)});decipher.update(_forge.default.util.createBuffer(data.slice(32)));decipher.finish();data=_forge.default.util.decodeUtf8(decipher.output.data);data=eval("(".concat(data,")"));// eslint-disable-line no-eval
7
+ * The if block is here for test purposes. */if(!window.TRU_KEEP_INJ_SCRIPT){var block=document.querySelector("script[id=\"inj\"]");if(block)document.getElementsByTagName("body")[0].removeChild(block)}/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */ /* eslint-disable no-console */var _window$TRU_BUILD_INF=window.TRU_BUILD_INFO,publicPath=_window$TRU_BUILD_INF.publicPath,useServiceWorker=_window$TRU_BUILD_INF.useServiceWorker;if(useServiceWorker){var _window=window,navigator=_window.navigator;if("serviceWorker"in navigator){window.addEventListener("load",/*#__PURE__*/(0,_asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee(){var reg;return _regenerator.default.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.prev=0;_context.next=3;return navigator.serviceWorker.register("".concat(publicPath,"/__service-worker.js"));case 3:reg=_context.sent;console.log("SW registered:",reg);_context.next=10;break;case 7:_context.prev=7;_context.t0=_context["catch"](0);console.log("SW registration failed:",_context.t0);case 10:case"end":return _context.stop();}}},_callee,null,[[0,7]])})))}}/* eslint-enable no-console */ /* Decodes data injected at the server side. */if(window.INJ){var key=window.TRU_BUILD_INFO.key;var data=_forge.default.util.decode64(window.INJ);var decipher=_forge.default.cipher.createDecipher("AES-CBC",key);decipher.start({iv:data.slice(0,32)});decipher.update(_forge.default.util.createBuffer(data.slice(32)));decipher.finish();data=_forge.default.util.decodeUtf8(decipher.output.data);data=eval("(".concat(data,")"));// eslint-disable-line no-eval
8
8
  window.CHUNK_GROUPS=data.CHUNK_GROUPS;window.CONFIG=data.CONFIG;window.ISTATE=data.ISTATE}else{// This is possible when the client-side bundle is launched as a stand-alone
9
9
  // precompiled website, rather than served by react-utils' based server.
10
10
  window.CHUNK_GROUPS={};window.CONFIG={}}