@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.
@@ -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":"iRAQA,mEACA,8BATA;AACA;AACA,G,CAEA,yC,CAEA;AACA;AAIA;AACA,2CACA,GAAI,MAAOA,CAAAA,UAAP,GAAsB,WAA1B,CAAuC,CACrCC,MAAM,CAACC,cAAP,CAAwBF,UACzB,CAED;AACA,6CACA,GAAI,CAACC,MAAM,CAACE,mBAAZ,CAAiC,CAC/B,GAAMC,CAAAA,KAAK,CAAGC,QAAQ,CAACC,aAAT,CAAuB,oBAAvB,CAAd,CACA,GAAIF,KAAJ,CAAWC,QAAQ,CAACE,oBAAT,CAA8B,MAA9B,EAAsC,CAAtC,EAAyCC,WAAzC,CAAqDJ,KAArD,CACZ,CAED,yE,CACA,+BACA,GAAQK,CAAAA,gBAAR,CAA6BR,MAAM,CAACC,cAApC,CAAQO,gBAAR,CACA,GAAIA,gBAAJ,CAAsB,CACpB,YAAsBR,MAAtB,CAAQS,SAAR,SAAQA,SAAR,CACA,GAAI,iBAAmBA,CAAAA,SAAvB,CAAkC,CAChCT,MAAM,CAACU,gBAAP,CAAwB,MAAxB,oFAAgC,kLAEVD,CAAAA,SAAS,CACxBE,aADe,CACDC,QADC,CACQ,sBADR,CAFU,QAEtBC,GAFsB,eAI5BC,OAAO,CAACC,GAAR,CAAY,gBAAZ,CAA8BF,GAA9B,EAJ4B,+EAM5BC,OAAO,CAACC,GAAR,CAAY,yBAAZ,cAN4B,mEAAhC,GASD,CACF,CACD,8B,CAEA,+CACA,GAAIf,MAAM,CAACgB,GAAX,CAAgB,CACd,GAAQC,CAAAA,GAAR,CAAgBjB,MAAM,CAACC,cAAvB,CAAQgB,GAAR,CACA,GAAIC,CAAAA,IAAI,CAAGC,eAAMC,IAAN,CAAWC,QAAX,CAAoBrB,MAAM,CAACgB,GAA3B,CAAX,CACA,GAAMM,CAAAA,QAAQ,CAAGH,eAAMI,MAAN,CAAaC,cAAb,CAA4B,SAA5B,CAAuCP,GAAvC,CAAjB,CACAK,QAAQ,CAACG,KAAT,CAAe,CAAEC,EAAE,CAAER,IAAI,CAACS,KAAL,CAAW,CAAX,CAAc,EAAd,CAAN,CAAf,EACAL,QAAQ,CAACM,MAAT,CAAgBT,eAAMC,IAAN,CAAWS,YAAX,CAAwBX,IAAI,CAACS,KAAL,CAAW,EAAX,CAAxB,CAAhB,EACAL,QAAQ,CAACQ,MAAT,GAEAZ,IAAI,CAAGC,eAAMC,IAAN,CAAWW,UAAX,CAAsBT,QAAQ,CAACU,MAAT,CAAgBd,IAAtC,CAAP,CACAA,IAAI,CAAGe,IAAI,YAAKf,IAAL,MAAX,CAA0B;AAE1BlB,MAAM,CAACkC,YAAP,CAAsBhB,IAAI,CAACgB,YAA3B,CACAlC,MAAM,CAACmC,MAAP,CAAgBjB,IAAI,CAACiB,MAArB,CACAnC,MAAM,CAACoC,MAAP,CAAgBlB,IAAI,CAACkB,MACtB,CAdD,IAcO,CACL;AACA;AACApC,MAAM,CAACkC,YAAP,CAAsB,EAAtB,CACAlC,MAAM,CAACmC,MAAP,CAAgB,EACjB"}
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":"iRAQA,mEACA,8BATA;AACA;AACA,G,CAEA,yC,CAEA;AACA;AAIA;AACA,2CAC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AN,CAAf,EACAL,QAAQ,CAACM,MAAT,CAAgBT,eAAMC,IAAN,CAAWS,YAAX,CAAwBX,IAAI,CAACS,KAAL,CAAW,EAAX,CAAxB,CAAhB,EACAL,QAAQ,CAACQ,MAAT,GAEAZ,IAAI,CAAGC,eAAMC,IAAN,CAAWW,UAAX,CAAsBT,QAAQ,CAACU,MAAT,CAAgBd,IAAtC,CAAP,CACAA,IAAI,CAAGe,IAAI,YAAKf,IAAL,MAAX,CAA0B;AAE1BnB,MAAM,CAACmC,YAAP,CAAsBhB,IAAI,CAACgB,YAA3B,CACAnC,MAAM,CAACoC,MAAP,CAAgBjB,IAAI,CAACiB,MAArB,CACApC,MAAM,CAACqC,MAAP,CAAgBlB,IAAI,CAACkB,MACtB,CAdD,IAcO,CACL;AACA;AACArC,MAAM,CAACmC,YAAP,CAAsB,EAAtB,CACAnC,MAAM,CAACoC,MAAP,CAAgB,EACjB"}
@@ -1,2 +1,2 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={server:true,api:true,PT:true,getGlobalState:true,GlobalStateProvider:true,useAsyncCollection:true,useAsyncData:true,useGlobalState:true};Object.defineProperty(exports,"GlobalStateProvider",{enumerable:true,get:function(){return _reactGlobalState.GlobalStateProvider}});exports.PT=void 0;Object.defineProperty(exports,"api",{enumerable:true,get:function(){return _axios.default}});Object.defineProperty(exports,"getGlobalState",{enumerable:true,get:function(){return _reactGlobalState.getGlobalState}});exports.server=void 0;Object.defineProperty(exports,"useAsyncCollection",{enumerable:true,get:function(){return _reactGlobalState.useAsyncCollection}});Object.defineProperty(exports,"useAsyncData",{enumerable:true,get:function(){return _reactGlobalState.useAsyncData}});Object.defineProperty(exports,"useGlobalState",{enumerable:true,get:function(){return _reactGlobalState.useGlobalState}});var _utils=require("./shared/utils");Object.keys(_utils).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===_utils[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _utils[key]}})});var _axios=_interopRequireDefault(require("axios"));var _PT=_interopRequireWildcard(require("prop-types"));exports.PT=_PT;var _reactGlobalState=require("@dr.pogodin/react-global-state");var _components=require("./shared/components");Object.keys(_components).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===_components[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _components[key]}})});function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap;var cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj.default=obj;if(cache){cache.set(obj,newObj)}return newObj}const server=_utils.webpack.requireWeak("./server",__dirname);exports.server=server;
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={server:true,api:true,PT:true,getGlobalState:true,getSsrContext:true,GlobalStateProvider:true,useAsyncCollection:true,useAsyncData:true,useGlobalState:true};Object.defineProperty(exports,"GlobalStateProvider",{enumerable:true,get:function(){return _reactGlobalState.GlobalStateProvider}});exports.PT=void 0;Object.defineProperty(exports,"api",{enumerable:true,get:function(){return _axios.default}});Object.defineProperty(exports,"getGlobalState",{enumerable:true,get:function(){return _reactGlobalState.getGlobalState}});Object.defineProperty(exports,"getSsrContext",{enumerable:true,get:function(){return _reactGlobalState.getSsrContext}});exports.server=void 0;Object.defineProperty(exports,"useAsyncCollection",{enumerable:true,get:function(){return _reactGlobalState.useAsyncCollection}});Object.defineProperty(exports,"useAsyncData",{enumerable:true,get:function(){return _reactGlobalState.useAsyncData}});Object.defineProperty(exports,"useGlobalState",{enumerable:true,get:function(){return _reactGlobalState.useGlobalState}});var _utils=require("./shared/utils");Object.keys(_utils).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===_utils[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _utils[key]}})});var _axios=_interopRequireDefault(require("axios"));var _PT=_interopRequireWildcard(require("prop-types"));exports.PT=_PT;var _reactGlobalState=require("@dr.pogodin/react-global-state");var _components=require("./shared/components");Object.keys(_components).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===_components[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _components[key]}})});function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap;var cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj.default=obj;if(cache){cache.set(obj,newObj)}return newObj}const server=_utils.webpack.requireWeak("./server",__dirname);exports.server=server;
2
2
  //# sourceMappingURL=index.js.map
@@ -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":"yiCAEA,qCAgBA,wSAZA,oD,sEAGA,gEAQA,sW,o9BAbA,KAAMA,CAAAA,MAAM,CAAGC,eAAQC,WAAR,YAAgCC,SAAhC,CAAf,C"}
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":"orCAEA,qCAiBA,wSAbA,oD,sEAGA,gEASA,sW,o9BAdA,KAAMA,CAAAA,MAAM,CAAGC,eAAQC,WAAR,YAAgCC,SAAhC,CAAf,C"}
@@ -76,17 +76,17 @@
76
76
  * @return {function} Created middleware.
77
77
  */function factory(webpackConfig,options){const ops=(0,_lodash.defaults)((0,_lodash.clone)(options),{beforeRender:()=>Promise.resolve({}),maxSsrRounds:10,ssrTimeout:1000,staticCacheSize:1.e7});const buildInfo=ops.buildInfo||getBuildInfo(webpackConfig.context);global.TRU_BUILD_INFO=buildInfo;// publicPath from webpack.output has a trailing slash at the end.
78
78
  const{publicPath,path:outputPath}=webpackConfig.output;const manifestLink=_fs.default.existsSync(`${outputPath}/manifest.json`)?`<link rel="manifest" href="${publicPath}manifest.json">`:"";const cache=ops.staticCacheController?new _Cache.default(ops.staticCacheSize):null;const CHUNK_GROUPS=readChunkGroupsJson(outputPath);return async(req,res,next)=>{try{// Ensures any caches always revalidate HTML markup before reuse.
79
- res.set("Cache-Control","no-cache");let cacheRef;if(cache){cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");res.send(data)}else{(0,_zlib.brotliDecompress)(data,(error,html)=>{if(error)next(error);else{let h=html.toString();if(!ops.noCsp){// TODO: Starting from Node v15 we'll be able to use string's
79
+ res.set("Cache-Control","no-cache");let cacheRef;if(cache){cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){const{buffer,status}=data;if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");if(status!==200)res.status(status);res.send(buffer)}else{await new Promise((done,failed)=>{(0,_zlib.brotliDecompress)(buffer,(error,html)=>{if(error)failed(error);else{let h=html.toString();if(!ops.noCsp){// TODO: Starting from Node v15 we'll be able to use string's
80
80
  // .replaceAll() method instead relying on reg. expression for
81
81
  // global matching.
82
- const regex=new RegExp(data.nonce,"g");h=h.replace(regex,req.nonce)}res.send(h)}})}return}}}const[{configToInject,extraScripts,initialState},{cipher,iv}]=await Promise.all([ops.beforeRender(req,sanitizedConfig),prepareCipher(buildInfo.key)]);let helmet;/* Optional server-side rendering. */let App=ops.Application;const ssrContext={req,state:(0,_lodash.cloneDeep)(initialState||{}),// Array of chunk names encountered during the rendering.
82
+ const regex=new RegExp(buffer.nonce,"g");h=h.replace(regex,req.nonce)}if(status!==200)res.status(status);res.send(h);done()}})})}return}}}const[{configToInject,extraScripts,initialState},{cipher,iv}]=await Promise.all([ops.beforeRender(req,sanitizedConfig),prepareCipher(buildInfo.key)]);let helmet;/* Optional server-side rendering. */let App=ops.Application;const ssrContext={req,state:(0,_lodash.cloneDeep)(initialState||{}),// Array of chunk names encountered during the rendering.
83
83
  chunks:[]};let stream;if(App){const ssrStart=Date.now();const renderPass=async()=>{ssrContext.chunks=[];return new Promise((resolve,reject)=>{const pipeableStream=(0,_server.renderToPipeableStream)(/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactGlobalState.GlobalStateProvider,{initialState:ssrContext.state,ssrContext:ssrContext,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_server2.StaticRouter,{location:req.url,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(App,{})})}),{onAllReady:()=>resolve(pipeableStream),onError:reject})})};for(let round=0;round<ops.maxSsrRounds;++round){stream=await renderPass();// eslint-disable-line no-await-in-loop
84
84
  if(!ssrContext.dirty)break;/* eslint-disable no-await-in-loop */const timeout=ops.ssrTimeout+ssrStart-Date.now();const ok=timeout>0&&(await Promise.race([Promise.allSettled(ssrContext.pending),_time.default.timer(timeout).then(()=>false)]));if(!ok)break;/* eslint-enable no-await-in-loop */}App="";stream.pipe(new _stream.Writable({write:(chunk,_,done)=>{App+=chunk.toString();done()}}));/* This takes care about server-side rendering of page title and meta tags
85
85
  * (still demands injection into HTML template, which happens below). */helmet=_reactHelmet.Helmet.renderStatic()}let chunkGroups;const webpackStats=(0,_lodash.get)(res.locals,"webpack.devMiddleware.stats");if(webpackStats){chunkGroups=(0,_lodash.mapValues)(webpackStats.toJson({all:false,chunkGroups:true}).namedChunkGroups,item=>item.assets.map(({name})=>name))}else if(CHUNK_GROUPS)chunkGroups=CHUNK_GROUPS;else chunkGroups={};/* Encrypts data to be injected into HTML.
86
86
  * Keep in mind, that this encryption is no way secure: as the JS bundle
87
87
  * contains decryption key and is able to decode it at the client side.
88
88
  * Hovewer, for a number of reasons, encryption of injected data is still
89
- * better than injection of a plain text. */delete ssrContext.state.dr_pogodin_react_utils___split_components;const payload=(0,_serializeJavascript.default)({CHUNK_GROUPS:chunkGroups,CONFIG:configToInject||sanitizedConfig,ISTATE:ssrContext.state},{ignoreFunction:true,unsafe:true});cipher.update(_nodeForge.default.util.createBuffer(payload,"utf8"));cipher.finish();const INJ=_nodeForge.default.util.encode64(`${iv}${cipher.output.data}`);if(ssrContext.status)res.status(ssrContext.status);const chunkSet=new Set;// TODO: "main" chunk has to be added explicitly,
89
+ * better than injection of a plain text. */delete ssrContext.state.dr_pogodin_react_utils___split_components;const payload=(0,_serializeJavascript.default)({CHUNK_GROUPS:chunkGroups,CONFIG:configToInject||sanitizedConfig,ISTATE:ssrContext.state},{ignoreFunction:true,unsafe:true});cipher.update(_nodeForge.default.util.createBuffer(payload,"utf8"));cipher.finish();const INJ=_nodeForge.default.util.encode64(`${iv}${cipher.output.data}`);const status=ssrContext.status||200;if(status!==200)res.status(status);const chunkSet=new Set;// TODO: "main" chunk has to be added explicitly,
90
90
  // because unlike all other chunks they are not managed by <CodeSplit>
91
91
  // component, thus they are not added to the ssrContext.chunks
92
92
  // automatically. Actually, names of these entry chunks should be
@@ -125,6 +125,8 @@ if(!ssrContext.dirty)break;/* eslint-disable no-await-in-loop */const timeout=op
125
125
  ${scriptChunkString}
126
126
  ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}
127
127
  </body>
128
- </html>`;res.send(html);if(cacheRef){(0,_zlib.brotliCompress)(html,(error,buffer)=>{if(error)throw error;buffer.nonce=req.nonce;// eslint-disable-line no-param-reassign
129
- cache.add(buffer,cacheRef.key)})}}catch(error){next(error)}}}
128
+ </html>`;res.send(html);if(cacheRef&&status<500){// Note: waiting for the caching to complete is not strictly necessary,
129
+ // but it greately simplifies testing, and error reporting.
130
+ await new Promise((done,failed)=>{(0,_zlib.brotliCompress)(html,(error,buffer)=>{if(error)failed(error);else{buffer.nonce=req.nonce;// eslint-disable-line no-param-reassign
131
+ cache.add({buffer,status},cacheRef.key);done()}})})}}catch(error){next(error)}}}
130
132
  //# sourceMappingURL=renderer.js.map
@@ -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":"+PAIA,8BAEA,gEAEA,8BAUA,sDACA,6DACA,8CACA,kDACA,0BAEA,wCACA,yCACA,gDACA,iFAEA,kEAEA,sD,6CA/BA;AACA;AACA,GA+BA,KAAMA,CAAAA,eAAe,CAAG,iBAAKC,eAAL,CAAa,QAAb,CAAxB,CAEO,KAAMC,CAAAA,gBAAgB,CAAG,CAC9BC,SAAS,CAAE,WADmB,CAE9BC,OAAO,CAAE,SAFqB,CAG9BC,SAAS,CAAE,WAHmB,CAAzB,CAMP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,0CACA,QAASC,CAAAA,YAAT,CAAsBC,OAAtB,CAA+B,CAC7B,KAAMC,CAAAA,GAAG,CAAGC,cAAKC,OAAL,CAAaH,OAAb,CAAsB,aAAtB,CAAZ,CACA,MAAOI,CAAAA,IAAI,CAACC,KAAL,CAAWC,YAAGC,YAAH,CAAgBN,GAAhB,CAAX,CACR,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAASO,CAAAA,mBAAT,CAA6BC,QAA7B,CAAuC,C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,CAIA,KAAM3E,CAAAA,IAAI,CAAI;AACpB;AACA;AACA,cAAcyE,oBAAoB,CAAClJ,gBAAgB,CAACG,SAAlB,CAA6B;AAC/D,cAAciF,MAAM,CAAGA,MAAM,CAACiE,KAAP,CAAa1E,QAAb,EAAH,CAA6B,EAAG;AACpD,cAAcS,MAAM,CAAGA,MAAM,CAACkE,IAAP,CAAY3E,QAAZ,EAAH,CAA4B,EAAG;AACnD;AACA,cAAcf,YAAa;AAC3B,cAAcmF,gBAAiB;AAC/B,cAAcI,WAAY;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAcD,oBAAoB,CAAClJ,gBAAgB,CAACC,SAAlB,CAA6B;AAC/D,mCAAmCoF,GAAG,EAAI,EAAG;AAC7C;AACA;AACA;AACA,gBAAgBrD,GAAG,CAACsC,KAAJ,CAAY,EAAZ,CAAkB,UAASzC,GAAG,CAACiD,KAAM,GAAG;AACxD;AACA,4BAA4ByD,GAAI;AAChC;AACA,cAAcS,iBAAkB;AAChC,cAAcE,oBAAoB,CAAClJ,gBAAgB,CAACE,OAAlB,CAA2B;AAC7D;AACA,gBA7BM,CA+BAa,GAAG,CAACwD,IAAJ,CAASE,IAAT,EAEA,GAAIL,QAAJ,CAAc,CACZ,yBAAeK,IAAf,CAAqB,CAACD,KAAD,CAAQ+E,MAAR,GAAmB,CACtC,GAAI/E,KAAJ,CAAW,KAAMA,CAAAA,KAAN,CACX+E,MAAM,CAACzE,KAAP,CAAejD,GAAG,CAACiD,KAAnB,CAA0B;AAC1BhB,KAAK,CAACgF,GAAN,CAAUS,MAAV,CAAkBnF,QAAQ,CAAClD,GAA3B,CACD,CAJD,CAKD,CACF,CAAC,MAAOsD,KAAP,CAAc,CACdN,IAAI,CAACM,KAAD,CACL,CACF,CACF"}
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":"+PAIA,8BAEA,gEAEA,8BAUA,sDACA,6DACA,8CACA,kDACA,0BAEA,wCACA,yCACA,gDACA,iFAEA,kEAEA,sD,6CA/BA;AACA;AACA,GA+BA,KAAMA,CAAAA,eAAe,CAAG,iBAAKC,eAAL,CAAa,QAAb,CAAxB,CAEO,KAAMC,CAAAA,gBAAgB,CAAG,CAC9BC,SAAS,CAAE,WADmB,CAE9BC,OAAO,CAAE,SAFqB,CAG9BC,SAAS,CAAE,WAHmB,CAAzB,CAMP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,0CACA,QAASC,CAAAA,YAAT,CAAsBC,OAAtB,CAA+B,CAC7B,KAAMC,CAAAA,GAAG,CAAGC,cAAKC,OAAL,CAAaH,OAAb,CAAsB,aAAtB,CAAZ,CACA,MAAOI,CAAAA,IAAI,CAACC,KAAL,CAAWC,YAAGC,YAAH,CAAgBN,GAAhB,CAAX,CACR,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAASO,CAAAA,mBAAT,CAA6BC,QAA7B,CAAuC,CACrC,KAAMR,CAAAA,GAAG,CAAGC,cAAKC,OAAL,CAAaM,QAAb,CAAuB,uBAAvB,CAAZ,C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GAAIM,KAAJ,CAAWD,MAAM,CAACC,KAAD,CAAN,CAAX,IACK,CACHN,MAAM,CAACY,KAAP,CAAerD,GAAG,CAACqD,KAAnB,CAA0B;AAC1BpB,KAAK,CAACkF,GAAN,CAAU,CAAE1E,MAAF,CAAUC,MAAV,CAAV,CAA8BH,QAAQ,CAAClD,GAAvC,EACAwD,IAAI,EACL,CACF,CAPD,CAQD,CATK,CAUP,CACF,CAAC,MAAOE,KAAP,CAAc,CACdV,IAAI,CAACU,KAAD,CACL,CACF,CACF"}
@@ -36,7 +36,7 @@ let cspSettings=(0,_lodash.cloneDeep)(defaultCspSettings);cspSettings.directives
36
36
  // https://github.com/dart-lang/sdk/issues/27979
37
37
  // which manifests itself sometimes when webpack dev middleware is used
38
38
  // (in dev mode), and app modules are imported in some unfortunate ways.
39
- if(!global.location){global.location={href:`${(0,_url.pathToFileURL)(process.cwd()).href}${_path.sep}`}}const webpack=require("webpack");const webpackDevMiddleware=require("webpack-dev-middleware");const webpackHotMiddleware=require("webpack-hot-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable global-require */ /* eslint-enable import/no-extraneous-dependencies */ /* eslint-enable import/no-unresolved */server.use(publicPath,_express.default.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use(()=>(0,_errors.fail)(_errors.ERRORS.NOT_FOUND,_errors.CODES.NOT_FOUND));let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: It is better to move the default error handler definition
39
+ if(!global.location){global.location={href:`${(0,_url.pathToFileURL)(process.cwd()).href}${_path.sep}`}}const webpack=require("webpack");const webpackDevMiddleware=require("webpack-dev-middleware");const webpackHotMiddleware=require("webpack-hot-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable global-require */ /* eslint-enable import/no-extraneous-dependencies */ /* eslint-enable import/no-unresolved */server.use(publicPath,_express.default.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use((req,res,next)=>{next((0,_errors.newError)(_errors.ERRORS.NOT_FOUND,_errors.CODES.NOT_FOUND))});let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: It is better to move the default error handler definition
40
40
  // to a stand-alone function at top-level, but the use of options.logger
41
41
  // prevents to do it without some extra refactoring. Should be done sometime
42
42
  // though.
@@ -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":"qOAIA,0BACA,wBAEA,8BAMA,gEAC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AACA,mCACA3D,MAAM,CAACI,GAAP,CAAW,CAACyD,KAAD,CAAQxD,GAAR,CAAaC,GAAb,CAAkBC,IAAlB,GAA2B,CACtC,kCACE,KAAMuD,CAAAA,MAAM,CAAGD,KAAK,CAACC,MAAN,EAAgBJ,cAAMK,qBAArC,CACA,KAAMC,CAAAA,UAAU,CAAGF,MAAM,EAAIJ,cAAMK,qBAAnC,CAEA;AACApE,OAAO,CAACO,MAAR,CAAe+D,GAAf,CAAmBD,UAAU,CAAG,OAAH,CAAa,OAA1C,CAAmDH,KAAnD,EAEA,GAAIK,CAAAA,OAAO,CAAGL,KAAK,CAACK,OAAN,EAAiB,4BAAgBJ,MAAhB,CAA/B,CACA,GAAIE,UAAU,EAAIpB,OAAO,CAACuB,GAAR,CAAYC,QAAZ,GAAyB,YAA3C,CAAyD,CACvDF,OAAO,CAAGV,eAAOO,qBAClB,CAEDzD,GAAG,CAACwD,MAAJ,CAAWA,MAAX,EAAmBvC,IAAnB,CAAwB2C,OAAxB,CACD,CAdD,CAeD,CAED,MAAOlE,CAAAA,MACR"}
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":"qOAIA,0BACA,wBAEA,8BAMA,gEACA,mEACA,wDACA,mEACA,sDACA,sDACA,6DACA,0BAEA,4DAEA,sCAxBA;AACA;AACA,G,CA6BA;AACA;AACA;AACA,GACA,KAAMA,CAAAA,kBAAkB,CAAG,CACzBC,UAAU,CAAE,sBACVC,gBAAOC,qBAAP,CAA6BC,oBAA7B,EADU,CAGV;AACA;AACA;AACA;AACCC,KAAD,EAAWA,KAAK,CAACC,MAAN,CAAcC,IAAD,EAAUA,IAAI,GAAK,QAAhC,CAPD,CADa,CAA3B,CAWAP,kBAAkB,CAACC,UAAnB,CAA8B,WAA9B,EAA6C,CAC3C,QAD2C,CAG3C;AACA;AACA,uBAL2C,CAA7C,CAOAD,kBAAkB,CAACC,UAAnB,CAA8B,YAA9B,EAA4CO,IAA5C,CAAiD,eAAjD,EAEA;AACA;AACA;AACA,MAAOR,CAAAA,kBAAkB,CAACC,UAAnB,CAA8B,2BAA9B,CAAP,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAASQ,CAAAA,qBAAT,EAAiC,CACtC,MAAO,sBAAUT,kBAAV,CACR,CAEc,cAAeU,CAAAA,OAAf,CAAuBC,aAAvB,CAAsCC,OAAtC,CAA+C,CAC5D,KAAMC,CAAAA,WAAW,CAAG,iBAAKD,OAAL,CAAc,CAChC,aADgC,CAEhC,cAFgC,CAGhC,SAHgC,CAIhC,cAJgC,CAKhC,OALgC,CAMhC,YANgC,CAOhC,uBAPgC,CAQhC,iBARgC,CAAd,CAApB,CAUA,KAAME,CAAAA,QAAQ,CAAG,sBAAgBH,aAAhB,CAA+BE,WAA/B,CAAjB,CACA,KAAM,CAAEE,UAAF,EAAiBJ,aAAa,CAACK,MAArC,CAEA,KAAMC,CAAAA,MAAM,CAAG,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AAIE,CAAAA,6BAAJ,CACA,GAAIhE,OAAO,CAACiE,oBAAZ,CAAkC,CAChCD,6BAA6B,CAAG,KAAMhE,CAAAA,OAAO,CAACiE,oBAAR,CAA6B5D,MAA7B,CACvC,CAED,oBACA,GAAI,CAAC2D,6BAAL,CAAoC,CAClC;AACA;AACA;AACA;AACA,mCACA3D,MAAM,CAACI,GAAP,CAAW,CAACyD,KAAD,CAAQxD,GAAR,CAAaC,GAAb,CAAkBC,IAAlB,GAA2B,CACtC,kCACE,KAAMuD,CAAAA,MAAM,CAAGD,KAAK,CAACC,MAAN,EAAgBJ,cAAMK,qBAArC,CACA,KAAMC,CAAAA,UAAU,CAAGF,MAAM,EAAIJ,cAAMK,qBAAnC,CAEA;AACApE,OAAO,CAACO,MAAR,CAAe+D,GAAf,CAAmBD,UAAU,CAAG,OAAH,CAAa,OAA1C,CAAmDH,KAAnD,EAEA,GAAIK,CAAAA,OAAO,CAAGL,KAAK,CAACK,OAAN,EAAiB,4BAAgBJ,MAAhB,CAA/B,CACA,GAAIE,UAAU,EAAIpB,OAAO,CAACuB,GAAR,CAAYC,QAAZ,GAAyB,YAA3C,CAAyD,CACvDF,OAAO,CAAGV,eAAOO,qBAClB,CAEDzD,GAAG,CAACwD,MAAJ,CAAWA,MAAX,EAAmBvC,IAAnB,CAAwB2C,OAAxB,CACD,CAdD,CAeD,CAED,MAAOlE,CAAAA,MACR"}
@@ -16,23 +16,24 @@
16
16
  /* eslint-disable import/no-extraneous-dependencies */ /* eslint-enable import/no-extraneous-dependencies */class E2eSsrEnv extends _jestEnvironmentJsdom.default{/**
17
17
  * Loads Webpack config, and exposes it to the environment via global
18
18
  * webpackConfig object.
19
- */loadWebpackConfig(){let options=this.pragmas["webpack-config-options"];options=options?JSON.parse(options):{};(0,_lodash.defaults)(options,{context:this.testFolder,dontEmitBuildInfo:true});let factory=this.pragmas["webpack-config-factory"]||"";factory=require(_path.default.resolve(this.rootDir,factory));this.global.webpackConfig=factory(options);this.global.buildInfo=factory.buildInfo}/**
19
+ */loadWebpackConfig(){let options=this.pragmas["webpack-config-options"];options=options?JSON.parse(options):{};(0,_lodash.defaults)(options,{context:this.testFolder,fs:this.global.webpackOutputFs});let factory=this.pragmas["webpack-config-factory"]||"";factory=require(_path.default.resolve(this.rootDir,factory));this.global.webpackConfig=factory(options);const fs=this.global.webpackOutputFs;let buildInfo=`${options.context}/.build-info`;if(fs.existsSync(buildInfo)){buildInfo=fs.readFileSync(buildInfo,"utf8");this.global.buildInfo=JSON.parse(buildInfo)}}/**
20
20
  * Executes Webpack build.
21
21
  * @return {Promise}
22
- */async runWebpack(){this.loadWebpackConfig();const compiler=(0,_webpack.default)(this.global.webpackConfig);const fs=(0,_memfs.createFsFromVolume)(new _memfs.Volume);compiler.outputFileSystem=fs;return new Promise((done,fail)=>{compiler.run((err,stats)=>{if(err)fail(err);this.global.webpackOutputFs=fs;this.global.webpackStats=stats.toJson();// Keeps reference to the raw Webpack stats object, which should be
22
+ */async runWebpack(){this.loadWebpackConfig();const compiler=(0,_webpack.default)(this.global.webpackConfig);compiler.outputFileSystem=this.global.webpackOutputFs;return new Promise((done,fail)=>{compiler.run((err,stats)=>{if(err)fail(err);this.global.webpackStats=stats.toJson();// Keeps reference to the raw Webpack stats object, which should be
23
23
  // explicitly passed to the server-side renderer alongside the request,
24
24
  // so that it can to pick up asset paths for different named chunks.
25
- this.webpackStats=stats;done()})})}async runSsr(){let options=this.pragmas["ssr-options"];options=options?JSON.parse(options):{};// Note: This enables Babel transformation for the code dynamically loaded
25
+ this.webpackStats=stats;done()})})}async runSsr(){let options=this.pragmas["ssr-options"];options=options?JSON.parse(options):{};let root;switch(options.root){case"TEST":root=this.testFolder;break;default:root=process.cwd();}// Note: This enables Babel transformation for the code dynamically loaded
26
26
  // below, as the usual Jest Babel setup does not seem to apply to
27
27
  // the environment code, and imports from it.
28
- (0,_register.default)({envName:options.babelEnv,extensions:[".js",".jsx",".svg"]});if(!options.buildInfo)options.buildInfo=this.global.buildInfo;if(options.entry){const p=_path.default.resolve(this.testFolder,options.entry);options.Application=require(p)[options.entryExportName||"default"]}const renderer=(0,_renderer.default)(this.global.webpackConfig,options);const markup=await new Promise((done,fail)=>{renderer(this.ssrRequest,// TODO: This will do for now, with the current implementation of
28
+ (0,_register.default)({envName:options.babelEnv,extensions:[".js",".jsx",".svg"],root});if(!options.buildInfo)options.buildInfo=this.global.buildInfo;if(options.entry){const p=_path.default.resolve(this.testFolder,options.entry);options.Application=require(p)[options.entryExportName||"default"]}const renderer=(0,_renderer.default)(this.global.webpackConfig,options);let status=200;// OK
29
+ const markup=await new Promise((done,fail)=>{renderer(this.ssrRequest,// TODO: This will do for now, with the current implementation of
29
30
  // the renderer, but it will require a rework once the renderer is
30
31
  // updated to do streaming.
31
- {send:done,set:_lodash.noop,// This is how up-to-date Webpack stats are passed to the server in
32
+ {send:done,set:_lodash.noop,status:value=>{status=value},// This is how up-to-date Webpack stats are passed to the server in
32
33
  // development mode, and we use this here always, instead of having
33
34
  // to pass some information via filesystem.
34
- locals:{webpack:{devMiddleware:{stats:this.webpackStats}}}},error=>{if(error)fail(error);else done("")})});this.global.ssrMarkup=markup;this.global.ssrOptions=options}constructor(config,context){const pragmas=context.docblockPragmas;let request=pragmas["ssr-request"];request=request?JSON.parse(request):{};if(!request.url)request.url="/";// This ensures the initial JsDom URL matches the value we use for SSR.
35
- (0,_lodash.set)(config.projectConfig,"testEnvironmentOptions.url",`http://localhost${request.url}`);super(config,context);this.global.dom=this.dom;// Extracts necessary settings from config and context.
35
+ locals:{webpack:{devMiddleware:{stats:this.webpackStats}}}},error=>{if(error)fail(error);else done("")})});this.global.ssrMarkup=markup;this.global.ssrOptions=options;this.global.ssrStatus=status}constructor(config,context){const pragmas=context.docblockPragmas;let request=pragmas["ssr-request"];request=request?JSON.parse(request):{};if(!request.url)request.url="/";// This ensures the initial JsDom URL matches the value we use for SSR.
36
+ (0,_lodash.set)(config.projectConfig,"testEnvironmentOptions.url",`http://localhost${request.url}`);super(config,context);this.global.dom=this.dom;this.global.webpackOutputFs=(0,_memfs.createFsFromVolume)(new _memfs.Volume);// Extracts necessary settings from config and context.
36
37
  const{projectConfig}=config;this.rootDir=projectConfig.rootDir;this.testFolder=_path.default.dirname(context.testPath);this.withSsr=!pragmas["no-ssr"];this.ssrRequest=request;this.pragmas=pragmas}async setup(){await super.setup();await this.runWebpack();if(this.withSsr)await this.runSsr();this.global.REACT_UTILS_FORCE_CLIENT_SIDE=true}async teardown(){delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;// Resets module cache and @babel/register. Effectively this ensures that
37
38
  // the next time an instance of this environment is set up, all modules are
38
39
  // transformed by Babel from scratch, thus taking into account the latest
@@ -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":"gLAiBA,kDACA,0EAEA,8BAKA,iEACA,oFACA,4BACA,wDA5BA;AACA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Z,CAA4C,IAC7C,CAEa,KAARC,CAAAA,QAAQ,EAAG,CACf,MAAO,MAAKjD,MAAL,CAAYgD,6BAAnB,CAEA;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAP,CAAYvD,OAAO,CAACwD,KAApB,EAA2BC,OAA3B,CAAoCC,GAAD,EAAS,CAC1C,MAAO1D,CAAAA,OAAO,CAACwD,KAAR,CAAcE,GAAd,CACR,CAFD,EAGAC,kBAASC,MAAT,GACA,MAAMP,QAAN,EACD,CAlJ6C,C"}
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":"gLAiBA,kDACA,0EAEA,8BAKA,iEACA,oFACA,4BACA,wDA5BA;AACA;AACA;AACA;AACA;AACA,G,CACA,8D,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAOA;AACA;AACA,sD,CAKA,qDAEe,KAAMA,CAAAA,SAAN,QAAwBC,8BAAS,CAC9C;AACF;AACA;AACA,KACEC,iBAAiB,EAAG,CAClB,GAAIC,CAAAA,OAAO,CAAG,KAAKC,OAAL,CAAa,wBAAb,CAAd,CACAD,OAAO,CAAGA,OAAO,CAAGE,IAAI,CAACC,KAAL,CAAWH,OAAX,CAAH,CAAyB,EAA1C,CACA,qBAASA,OAAT,CAAkB,CAChBI,OAAO,CAAE,KAAKC,UADE,CAEhBC,EAAE,CAAE,KAAKC,MAAL,CAAYC,eAFA,CAAlB,EAKA,GAAIC,CAAAA,OAAO,CAAG,KAAKR,OAAL,CAAa,wBAAb,GAA0C,EAAxD,CACAQ,OAAO,CAAGC,OAAO,CAACC,cAAKC,OAAL,CAAa,KAAKC,OAAlB,CAA2BJ,OAA3B,CAAD,CAAjB,CACA,KAAKF,MAAL,CAAYO,aAAZ,CAA4BL,OAAO,CAACT,OAAD,CAAnC,CAEA,KAAMM,CAAAA,EAAE,CAAG,KAAKC,MAAL,CAAYC,eAAvB,CACA,GAAIO,CAAAA,SAAS,CAAI,GAAEf,OAAO,CAACI,OAAQ,cAAnC,CACA,GAAIE,EAAE,CAACU,UAAH,CAAcD,SAAd,CAAJ,CAA8B,CAC5BA,SAAS,CAAGT,EAAE,CAACW,YAAH,CAAgBF,SAAhB,CAA2B,MAA3B,CAAZ,CACA,KAAKR,MAAL,CAAYQ,SAAZ,CAAwBb,IAAI,CAACC,KAAL,CAAWY,SAAX,CACzB,CACF,CAED;AACF;AACA;AACA,KACkB,KAAVG,CAAAA,UAAU,EA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