@dr.pogodin/react-utils 1.15.7 → 1.16.2
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.
- package/build/development/client/index.js +11 -5
- package/build/development/client/index.js.map +1 -1
- package/build/development/server/renderer.js +78 -36
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/shared/components/CodeSplit/index.js +108 -9
- package/build/development/shared/components/CodeSplit/index.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +2 -3
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/utils/jest.js +14 -77
- package/build/development/shared/utils/jest.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +12 -13
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/time.js +11 -22
- package/build/development/shared/utils/time.js.map +1 -1
- package/build/development/web.bundle.js +21 -41
- package/build/production/client/index.js +3 -2
- package/build/production/client/index.js.map +1 -1
- package/build/production/server/renderer.js +26 -13
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/shared/components/CodeSplit/index.js +8 -5
- package/build/production/shared/components/CodeSplit/index.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +2 -3
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/utils/jest.js +6 -28
- package/build/production/shared/utils/jest.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +6 -7
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/time.js +6 -20
- package/build/production/shared/utils/time.js.map +1 -1
- package/build/production/web.bundle.js +1 -1
- package/build/production/web.bundle.js.LICENSE.txt +2 -7
- package/build/production/web.bundle.js.map +1 -1
- package/package.json +25 -25
- package/build/development/shared/components/CodeSplit/ClientSide.js +0 -155
- package/build/development/shared/components/CodeSplit/ClientSide.js.map +0 -1
- package/build/development/shared/components/CodeSplit/ServerSide.js +0 -111
- package/build/development/shared/components/CodeSplit/ServerSide.js.map +0 -1
- package/build/production/shared/components/CodeSplit/ClientSide.js +0 -21
- package/build/production/shared/components/CodeSplit/ClientSide.js.map +0 -1
- package/build/production/shared/components/CodeSplit/ServerSide.js +0 -18
- package/build/production/shared/components/CodeSplit/ServerSide.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.SCRIPT_LOCATIONS=void 0;exports.default=factory;exports.isBrotliAcceptable=isBrotliAcceptable;var _reactGlobalState=require("@dr.pogodin/react-global-state");var _lodash=require("lodash");var _config=_interopRequireDefault(require("config"));var _nodeForge=_interopRequireDefault(require("node-forge"));var _fs=_interopRequireDefault(require("fs"));var _path=_interopRequireDefault(require("path"));var _zlib=require("zlib");var _server=
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.SCRIPT_LOCATIONS=void 0;exports.default=factory;exports.isBrotliAcceptable=isBrotliAcceptable;var _stream=require("stream");var _reactGlobalState=require("@dr.pogodin/react-global-state");var _lodash=require("lodash");var _config=_interopRequireDefault(require("config"));var _nodeForge=_interopRequireDefault(require("node-forge"));var _fs=_interopRequireDefault(require("fs"));var _path=_interopRequireDefault(require("path"));var _zlib=require("zlib");var _server=require("react-dom/server");var _reactHelmet=require("react-helmet");var _server2=require("react-router-dom/server");var _serializeJavascript=_interopRequireDefault(require("serialize-javascript"));var _time=_interopRequireDefault(require("../shared/utils/time"));var _Cache=_interopRequireDefault(require("./Cache"));var _jsxRuntime=require("react/jsx-runtime");/**
|
|
2
2
|
* ExpressJS middleware for server-side rendering of a ReactJS app.
|
|
3
3
|
*/const sanitizedConfig=(0,_lodash.omit)(_config.default,"SECRET");const SCRIPT_LOCATIONS={BODY_OPEN:"BODY_OPEN",DEFAULT:"DEFAULT",HEAD_OPEN:"HEAD_OPEN"};/**
|
|
4
4
|
* Reads build-time information about the app. This information is generated
|
|
@@ -32,6 +32,19 @@
|
|
|
32
32
|
* @return {boolean}
|
|
33
33
|
* @ignore
|
|
34
34
|
*/function isBrotliAcceptable(req){const acceptable=req.get("accept-encoding");if(acceptable){const ops=acceptable.split(",");for(let i=0;i<ops.length;++i){const[type,priority]=ops[i].trim().split(";q=");if((type==="*"||type==="br")&&(!priority||parseFloat(priority)>0)){return true}}}return false}/**
|
|
35
|
+
* Given an array of extra script strings / objects, it returns an object with
|
|
36
|
+
* arrays of scripts to inject in different HTML template locations. During
|
|
37
|
+
* the script groupping it also filters out any empty scripts.
|
|
38
|
+
* @param {({
|
|
39
|
+
* code: string;
|
|
40
|
+
* location: string;
|
|
41
|
+
* }|string)[]} [scripts=[]]
|
|
42
|
+
* @return {{
|
|
43
|
+
* BODY_OPEN: string[];
|
|
44
|
+
* DEFAULT: string[];
|
|
45
|
+
* HEAD_OPEN: string[];
|
|
46
|
+
* }}
|
|
47
|
+
*/function groupExtraScripts(scripts=[]){const res={[SCRIPT_LOCATIONS.BODY_OPEN]:"",[SCRIPT_LOCATIONS.DEFAULT]:"",[SCRIPT_LOCATIONS.HEAD_OPEN]:""};for(let i=0;i<scripts.length;++i){const script=scripts[i];if((0,_lodash.isString)(script)){if(script)res[SCRIPT_LOCATIONS.DEFAULT]+=script}else if(script.code){if(res[script.location]!==undefined){res[script.location]+=script.code}else throw Error(`Invalid location "${script.location}"`)}}return res}/**
|
|
35
48
|
* Creates the middleware.
|
|
36
49
|
* @param {object} webpackConfig
|
|
37
50
|
* @param {object} options Additional options:
|
|
@@ -42,16 +55,16 @@
|
|
|
42
55
|
* may cut a few corners.
|
|
43
56
|
* @param {number} options.maxSsrRounds
|
|
44
57
|
* @param {number} options.ssrTimeout
|
|
58
|
+
* @param {function} [options.staticCacheController]
|
|
45
59
|
* @return {function} Created middleware.
|
|
46
60
|
*/function factory(webpackConfig,options){const buildInfo=getBuildInfo(webpackConfig.context);global.TRU_BUILD_INFO=buildInfo;// publicPath from webpack.output has a trailing slash at the end.
|
|
47
|
-
const{publicPath,path:outputPath}=webpackConfig.output;
|
|
48
|
-
// and serve them without a need to unpacking server-side.
|
|
49
|
-
const cache=options.staticCacheController?new _Cache.default(options.staticCacheSize):null;const CHUNK_GROUPS=readChunkGroupsJson(outputPath);const ops=(0,_lodash.defaults)((0,_lodash.clone)(options),{beforeRender:()=>Promise.resolve({})});return async(req,res,next)=>{try{// Ensures any caches always revalidate HTML markup before reuse.
|
|
61
|
+
const{publicPath,path:outputPath}=webpackConfig.output;const manifestLink=_fs.default.existsSync(`${outputPath}/manifest.json`)?`<link rel="manifest" href="${publicPath}manifest.json">`:"";const cache=options.staticCacheController?new _Cache.default(options.staticCacheSize):null;const CHUNK_GROUPS=readChunkGroupsJson(outputPath);const ops=(0,_lodash.defaults)((0,_lodash.clone)(options),{beforeRender:()=>Promise.resolve({})});return async(req,res,next)=>{try{// Ensures any caches always revalidate HTML markup before reuse.
|
|
50
62
|
res.set("Cache-Control","no-cache");let cacheRef;if(cache){cacheRef=options.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){if(options.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(!options.noCsp){// TODO: Starting from Node v15 we'll be able to use string's
|
|
51
63
|
// .replaceAll() method instead relying on reg. expression for
|
|
52
64
|
// global matching.
|
|
53
65
|
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=options.Application;const ssrContext={req,state:(0,_lodash.cloneDeep)(initialState||{}),// Array of chunk names encountered during the rendering.
|
|
54
|
-
chunks:[]};if(App){
|
|
66
|
+
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<options.maxSsrRounds;++round){stream=await renderPass();// eslint-disable-line no-await-in-loop
|
|
67
|
+
if(!ssrContext.dirty)break;/* eslint-disable no-await-in-loop */const timeout=options.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
|
|
55
68
|
* (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.
|
|
56
69
|
* Keep in mind, that this encryption is no way secure: as the JS bundle
|
|
57
70
|
* contains decryption key and is able to decode it at the client side.
|
|
@@ -64,26 +77,26 @@ chunks:[]};if(App){let markup;const ssrStart=Date.now();for(let round=0;round<op
|
|
|
64
77
|
// remove or add other entry points, but it requires additional
|
|
65
78
|
// efforts to figure out how to automatically order them right,
|
|
66
79
|
// thus for now this handles the default config.
|
|
67
|
-
["main",...ssrContext.chunks].forEach(chunk=>{const assets=chunkGroups[chunk];if(assets)assets.forEach(asset=>chunkSet.add(asset))});let styleChunkString="";let scriptChunkString="";chunkSet.forEach(chunk=>{if(chunk.endsWith(".css")){styleChunkString+=`<link href="${publicPath}${chunk}" rel="stylesheet"
|
|
80
|
+
["main",...ssrContext.chunks].forEach(chunk=>{const assets=chunkGroups[chunk];if(assets)assets.forEach(asset=>chunkSet.add(asset))});let styleChunkString="";let scriptChunkString="";chunkSet.forEach(chunk=>{if(chunk.endsWith(".css")){styleChunkString+=`<link href="${publicPath}${chunk}" rel="stylesheet">`}else if(chunk.endsWith(".js")// In dev mode HMR adds JS updates into asset arrays,
|
|
68
81
|
// and they (updates) should be ignored.
|
|
69
|
-
&&!chunk.endsWith(".hot-update.js")){scriptChunkString+=`<script src="${publicPath}${chunk}" type="application/javascript"></script>`}});
|
|
82
|
+
&&!chunk.endsWith(".hot-update.js")){scriptChunkString+=`<script src="${publicPath}${chunk}" type="application/javascript"></script>`}});const grouppedExtraScripts=groupExtraScripts(extraScripts);const faviconLink=ops.favicon?"<link rel=\"shortcut icon\" href=\"/favicon.ico\">":"";const html=`<!DOCTYPE html>
|
|
70
83
|
<html lang="en">
|
|
71
84
|
<head>
|
|
72
|
-
${
|
|
85
|
+
${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}
|
|
73
86
|
${helmet?helmet.title.toString():""}
|
|
74
87
|
${helmet?helmet.meta.toString():""}
|
|
75
|
-
<meta name="theme-color" content="#FFFFFF"
|
|
88
|
+
<meta name="theme-color" content="#FFFFFF">
|
|
76
89
|
${manifestLink}
|
|
77
90
|
${styleChunkString}
|
|
78
91
|
${faviconLink}
|
|
79
|
-
<meta charset="utf-8"
|
|
92
|
+
<meta charset="utf-8">
|
|
80
93
|
<meta
|
|
81
94
|
content="width=device-width,initial-scale=1.0"
|
|
82
95
|
name="viewport"
|
|
83
|
-
|
|
96
|
+
>
|
|
84
97
|
</head>
|
|
85
98
|
<body>
|
|
86
|
-
${
|
|
99
|
+
${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}
|
|
87
100
|
<div id="react-view">${App||""}</div>
|
|
88
101
|
<script
|
|
89
102
|
id="inj"
|
|
@@ -93,7 +106,7 @@ chunks:[]};if(App){let markup;const ssrStart=Date.now();for(let round=0;round<op
|
|
|
93
106
|
window.INJ="${INJ}"
|
|
94
107
|
</script>
|
|
95
108
|
${scriptChunkString}
|
|
96
|
-
${
|
|
109
|
+
${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}
|
|
97
110
|
</body>
|
|
98
111
|
</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
|
|
99
112
|
cache.add(buffer,cacheRef.key)})}}catch(error){next(error)}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/server/renderer.jsx"],"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","factory","webpackConfig","options","buildInfo","global","TRU_BUILD_INFO","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","staticCacheSize","CHUNK_GROUPS","beforeRender","next","set","cacheRef","data","noCsp","send","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","initialState","all","helmet","App","Application","ssrContext","state","chunks","markup","ssrStart","Date","now","round","maxSsrRounds","ReactDOM","renderToString","dirty","timeout","ssrTimeout","ok","race","allSettled","pending","time","timer","then","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","chunk","asset","add","styleChunkString","scriptChunkString","endsWith","bodyOpenExtraScripts","defaultExtraScripts","headOpenExtraScripts","filter","script","location","code","join","faviconLink","favicon","title","meta","buffer"],"mappings":"+PAIA,gEAEA,8BAWA,sDACA,6DACA,8CACA,kDACA,0BAEA,gEACA,yCACA,gDACA,iFAEA,kEAEA,sD,6CA9BA;AACA;AACA,GA8BA,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,CACA,GAAIC,CAAAA,GAAJ,CACA,GAAI,CACFA,GAAG,CAAGN,IAAI,CAACC,KAAL,CAAWC,YAAGC,YAAH,CAAgBN,GAAhB,CAAX,CACP,CAAC,MAAOU,GAAP,CAAY,CACZD,GAAG,CAAG,IACP,CACD,MAAOA,CAAAA,GACR,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAASE,CAAAA,aAAT,CAAuBC,GAAvB,CAA4B,CAC1B,MAAO,IAAIC,CAAAA,OAAJ,CAAY,CAACX,OAAD,CAAUY,MAAV,GAAqB,CACtCC,mBAAMC,MAAN,CAAaC,QAAb,CAA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AoB,EAAI,EAAG;AACzC,cAAc3D,MAAM,CAAGA,MAAM,CAACmE,KAAP,CAAa5E,QAAb,EAAH,CAA6B,EAAG;AACpD,cAAcS,MAAM,CAAGA,MAAM,CAACoE,IAAP,CAAY7E,QAAZ,EAAH,CAA4B,EAAG;AACnD;AACA,cAAcjB,YAAa;AAC3B,cAAcgF,gBAAiB;AAC/B,cAAcW,WAAY;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAcR,oBAAoB,EAAI,EAAG;AACzC,mCAAmCxD,GAAG,EAAI,EAAG;AAC7C;AACA;AACA;AACA,gBAAgBlC,OAAO,CAACmB,KAAR,CAAgB,EAAhB,CAAsB,UAAShC,GAAG,CAACwC,KAAM,GAAG;AAC5D;AACA,4BAA4BmD,GAAI;AAChC;AACA,cAAcU,iBAAkB;AAChC,cAAcG,mBAAmB,EAAI,EAAG;AACxC;AACA,gBA7BM,CA+BAtH,GAAG,CAAC+C,IAAJ,CAASE,IAAT,EAEA,GAAIL,QAAJ,CAAc,CACZ,yBAAeK,IAAf,CAAqB,CAACD,KAAD,CAAQiF,MAAR,GAAmB,CACtC,GAAIjF,KAAJ,CAAW,KAAMA,CAAAA,KAAN,CACXiF,MAAM,CAAC3E,KAAP,CAAexC,GAAG,CAACwC,KAAnB,CAA0B;AAC1BlB,KAAK,CAAC6E,GAAN,CAAUgB,MAAV,CAAkBrF,QAAQ,CAACzC,GAA3B,CACD,CAJD,CAKD,CACF,CAAC,MAAO6C,KAAP,CAAc,CACdN,IAAI,CAACM,KAAD,CACL,CACF,CACF","sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport {\n clone,\n cloneDeep,\n defaults,\n isObject,\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 ReactDOM 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 * Creates the middleware.\n * @param {object} webpackConfig\n * @param {object} options Additional options:\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\n * @param {number} options.ssrTimeout\n * @return {function} Created middleware.\n */\nexport default function factory(webpackConfig, options) {\n const buildInfo = getBuildInfo(webpackConfig.context);\n\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 let manifestLink = fs.existsSync(`${outputPath}/manifest.json`);\n manifestLink = manifestLink ? (\n `<link rel=\"manifest\" href=\"${publicPath}manifest.json\"></link>`\n ) : '';\n\n // TODO: Update the caching mechanics to stored cached data gzipped,\n // and serve them without a need to unpacking server-side.\n const cache = options.staticCacheController\n ? new Cache(options.staticCacheSize) : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath);\n\n const ops = defaults(clone(options), {\n beforeRender: () => Promise.resolve({}),\n });\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 = options.staticCacheController(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n if (options.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 (!options.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 = options.Application;\n const ssrContext = {\n req,\n state: cloneDeep(initialState || {}),\n\n // Array of chunk names encountered during the rendering.\n chunks: [],\n };\n if (App) {\n let markup;\n const ssrStart = Date.now();\n for (let round = 0; round < options.maxSsrRounds; ++round) {\n ssrContext.chunks = [];\n markup = ReactDOM.renderToString((\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <App />\n </StaticRouter>\n </GlobalStateProvider>\n ));\n\n if (!ssrContext.dirty) break;\n\n /* eslint-disable no-await-in-loop */\n const timeout = options.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 App = markup;\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 let bodyOpenExtraScripts;\n let defaultExtraScripts;\n let headOpenExtraScripts;\n if (extraScripts) {\n bodyOpenExtraScripts = extraScripts\n .filter((script) => isObject(script)\n && script.location === SCRIPT_LOCATIONS.BODY_OPEN)\n .map((script) => script.code)\n .join('');\n defaultExtraScripts = extraScripts\n .filter((script) => isString(script)\n || script.location === SCRIPT_LOCATIONS.DEFAULT)\n .map((script) => (isString(script) ? script : script.code))\n .join('');\n headOpenExtraScripts = extraScripts\n .filter((script) => isObject(script)\n && script.location === SCRIPT_LOCATIONS.HEAD_OPEN)\n .map((script) => script.code)\n .join('');\n }\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 ${headOpenExtraScripts || ''}\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 ${bodyOpenExtraScripts || ''}\n <div id=\"react-view\">${App || ''}</div>\n <script\n id=\"inj\"\n type=\"application/javascript\"\n ${options.noCsp ? '' : `nonce=\"${req.nonce}\"`}\n >\n window.INJ=\"${INJ}\"\n </script>\n ${scriptChunkString}\n ${defaultExtraScripts || ''}\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"],"file":"renderer.js"}
|
|
1
|
+
{"version":3,"sources":["../../../src/server/renderer.jsx"],"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","buildInfo","global","TRU_BUILD_INFO","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","staticCacheSize","CHUNK_GROUPS","beforeRender","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","maxSsrRounds","dirty","timeout","ssrTimeout","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"],"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,CACA,GAAIC,CAAAA,GAAJ,CACA,GAAI,CACFA,GAAG,CAAGN,IAAI,CAACC,KAAL,CAAWC,YAA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AACA;AACA;AACA,cAAcD,oBAAoB,CAAClJ,gBAAgB,CAACC,SAAlB,CAA6B;AAC/D,mCAAmCkF,GAAG,EAAI,EAAG;AAC7C;AACA;AACA;AACA,gBAAgBlC,OAAO,CAACmB,KAAR,CAAgB,EAAhB,CAAsB,UAASvC,GAAG,CAAC+C,KAAM,GAAG;AAC5D;AACA,4BAA4B2D,GAAI;AAChC;AACA,cAAcS,iBAAkB;AAChC,cAAcE,oBAAoB,CAAClJ,gBAAgB,CAACE,OAAlB,CAA2B;AAC7D;AACA,gBA7BM,CA+BAa,GAAG,CAACsD,IAAJ,CAASE,IAAT,EAEA,GAAIL,QAAJ,CAAc,CACZ,yBAAeK,IAAf,CAAqB,CAACD,KAAD,CAAQiF,MAAR,GAAmB,CACtC,GAAIjF,KAAJ,CAAW,KAAMA,CAAAA,KAAN,CACXiF,MAAM,CAAC3E,KAAP,CAAe/C,GAAG,CAAC+C,KAAnB,CAA0B;AAC1BlB,KAAK,CAACoF,GAAN,CAAUS,MAAV,CAAkBrF,QAAQ,CAAChD,GAA3B,CACD,CAJD,CAKD,CACF,CAAC,MAAOoD,KAAP,CAAc,CACdN,IAAI,CAACM,KAAD,CACL,CACF,CACF","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 {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\n * @param {number} options.ssrTimeout\n * @param {function} [options.staticCacheController]\n * @return {function} Created middleware.\n */\nexport default function factory(webpackConfig, options) {\n const buildInfo = getBuildInfo(webpackConfig.context);\n\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 = options.staticCacheController\n ? new Cache(options.staticCacheSize) : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath);\n\n const ops = defaults(clone(options), {\n beforeRender: () => Promise.resolve({}),\n });\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 = options.staticCacheController(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n if (options.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 (!options.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 = options.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 < options.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 = options.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 ${options.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"],"file":"renderer.js"}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=CodeSplit;var _propTypes=_interopRequireDefault(require("prop-types"));var _react=require("react");var _reactGlobalState=require("@dr.pogodin/react-global-state");var _Barrier=require("../../utils/Barrier");var _isomorphy=require("../../utils/isomorphy");var _jsxRuntime=require("react/jsx-runtime");/* eslint-disable react/jsx-props-no-spreading */ /* global document, window */function CodeSplit({children,chunkName,getComponent,placeholder,...props}){const{current:heap}=(0,_react.useRef)({mounted:false,pendingStyles:[]});const{publicPath}=(0,_isomorphy.getBuildInfo)();// TODO: Not sure whether it is fine for the inner React.lazy() mechanics
|
|
2
|
+
// if we dynamically create the lazy component inside a render of another
|
|
3
|
+
// component, or does it expect we only create it once on outside of any
|
|
4
|
+
// component.
|
|
5
|
+
const LazyComponent=/*#__PURE__*/(0,_react.lazy)(async()=>{const res=await getComponent();if(heap.pendingStyles.length)await Promise.all(heap.pendingStyles);return res.default?res:{default:res}});if(_isomorphy.IS_SERVER_SIDE){const{chunks}=(0,_reactGlobalState.getGlobalState)().ssrContext;if(chunks.includes(chunkName)){throw Error(`Chunk name clash for "${chunkName}"`)}else chunks.push(chunkName)}else if(!heap.mounted){heap.mounted=true;window.CHUNK_GROUPS[chunkName].forEach(asset=>{if(!asset.endsWith(".css"))return;const path=`${publicPath}/${asset}`;let link=document.querySelector(`link[href="${path}"]`);if(!link){link=document.createElement("link");link.setAttribute("href",path);link.setAttribute("rel","stylesheet");const barrier=(0,_Barrier.newBarrier)();link.onload=barrier.resolve;// Even if the style load failed, still allow to mount the component,
|
|
6
|
+
// abeit with broken styling.
|
|
7
|
+
link.onerror=barrier.resolve;heap.pendingStyles.push(barrier);const head=document.querySelector("head");head.appendChild(link)}window.STYLESHEET_USAGE_COUNTERS||={};window.STYLESHEET_USAGE_COUNTERS[path]||=0;++window.STYLESHEET_USAGE_COUNTERS[path]})}// This effectively fires only once, just before the component unmounts.
|
|
8
|
+
(0,_react.useEffect)(()=>()=>{heap.mounted=false;window.CHUNK_GROUPS[chunkName].forEach(item=>{if(!item.endsWith(".css"))return;const path=`${publicPath}/${item}`;if(--window.STYLESHEET_USAGE_COUNTERS[path]<=0){const link=document.querySelector(`link[href="${path}"]`);const head=document.querySelector("head");head.removeChild(link)}})},[chunkName,heap,publicPath]);return/*#__PURE__*/(0,_jsxRuntime.jsx)(_react.Suspense,{fallback:placeholder,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(LazyComponent,{...props,children:children})})}CodeSplit.propTypes={children:_propTypes.default.node,chunkName:_propTypes.default.string.isRequired,getComponent:_propTypes.default.func.isRequired,placeholder:_propTypes.default.node};CodeSplit.defaultProps={children:undefined,placeholder:undefined};
|
|
6
9
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/shared/components/CodeSplit/index.jsx"],"names":["
|
|
1
|
+
{"version":3,"sources":["../../../../../src/shared/components/CodeSplit/index.jsx"],"names":["CodeSplit","children","chunkName","getComponent","placeholder","props","current","heap","mounted","pendingStyles","publicPath","LazyComponent","res","length","Promise","all","default","IS_SERVER_SIDE","chunks","ssrContext","includes","Error","push","window","CHUNK_GROUPS","forEach","asset","endsWith","path","link","document","querySelector","createElement","setAttribute","barrier","onload","resolve","onerror","head","appendChild","STYLESHEET_USAGE_COUNTERS","item","removeChild","propTypes","PT","node","string","isRequired","func","defaultProps","undefined"],"mappings":"mLAGA,6DAEA,4BAOA,gEACA,4CACA,gD,6CAdA,iD,CACA,6BAee,QAASA,CAAAA,SAAT,CAAmB,CAChCC,QADgC,CAEhCC,SAFgC,CAGhCC,YAHgC,CAIhCC,WAJgC,CAKhC,GAAGC,KAL6B,CAAnB,CAMZ,CACD,KAAM,CAAEC,OAAO,CAAEC,IAAX,EAAoB,kBAAO,CAC/BC,OAAO,CAAE,KADsB,CAE/BC,aAAa,CAAE,EAFgB,CAAP,CAA1B,CAIA,KAAM,CAAEC,UAAF,EAAiB,6BAAvB,CAEA;AACA;AACA;AACA;AACA,KAAMC,CAAAA,aAAa,cAAG,gBAAK,SAAY,CACrC,KAA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AAH,CAAUC,UAFD,CAGpB5C,YAAY,CAAEyC,mBAAGI,IAAH,CAAQD,UAHF,CAIpB3C,WAAW,CAAEwC,mBAAGC,IAJI,CAAtB,CAOA7C,SAAS,CAACiD,YAAV,CAAyB,CACvBhD,QAAQ,CAAEiD,SADa,CAEvB9C,WAAW,CAAE8C,SAFU,CAAzB","sourcesContent":["/* eslint-disable react/jsx-props-no-spreading */\n/* global document, window */\n\nimport PT from 'prop-types';\n\nimport {\n lazy,\n Suspense,\n useEffect,\n useRef,\n} from 'react';\n\nimport { getGlobalState } from '@dr.pogodin/react-global-state';\nimport { newBarrier } from 'utils/Barrier';\nimport { getBuildInfo, IS_SERVER_SIDE } from 'utils/isomorphy';\n\nexport default function CodeSplit({\n children,\n chunkName,\n getComponent,\n placeholder,\n ...props\n}) {\n const { current: heap } = useRef({\n mounted: false,\n pendingStyles: [],\n });\n const { publicPath } = getBuildInfo();\n\n // TODO: Not sure whether it is fine for the inner React.lazy() mechanics\n // if we dynamically create the lazy component inside a render of another\n // component, or does it expect we only create it once on outside of any\n // component.\n const LazyComponent = lazy(async () => {\n const res = await getComponent();\n if (heap.pendingStyles.length) await Promise.all(heap.pendingStyles);\n return res.default ? res : { default: res };\n });\n\n if (IS_SERVER_SIDE) {\n const { chunks } = getGlobalState().ssrContext;\n if (chunks.includes(chunkName)) {\n throw Error(`Chunk name clash for \"${chunkName}\"`);\n } else chunks.push(chunkName);\n } else if (!heap.mounted) {\n heap.mounted = true;\n\n window.CHUNK_GROUPS[chunkName].forEach((asset) => {\n if (!asset.endsWith('.css')) return;\n const path = `${publicPath}/${asset}`;\n let link = document.querySelector(`link[href=\"${path}\"]`);\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('href', path);\n link.setAttribute('rel', 'stylesheet');\n\n const barrier = newBarrier();\n link.onload = barrier.resolve;\n\n // Even if the style load failed, still allow to mount the component,\n // abeit with broken styling.\n link.onerror = barrier.resolve;\n\n heap.pendingStyles.push(barrier);\n\n const head = document.querySelector('head');\n head.appendChild(link);\n }\n window.STYLESHEET_USAGE_COUNTERS ||= {};\n window.STYLESHEET_USAGE_COUNTERS[path] ||= 0;\n ++window.STYLESHEET_USAGE_COUNTERS[path];\n });\n }\n\n // This effectively fires only once, just before the component unmounts.\n useEffect(() => () => {\n heap.mounted = false;\n window.CHUNK_GROUPS[chunkName].forEach((item) => {\n if (!item.endsWith('.css')) return;\n const path = `${publicPath}/${item}`;\n if (--window.STYLESHEET_USAGE_COUNTERS[path] <= 0) {\n const link = document.querySelector(`link[href=\"${path}\"]`);\n const head = document.querySelector('head');\n head.removeChild(link);\n }\n });\n }, [chunkName, heap, publicPath]);\n\n return (\n <Suspense fallback={placeholder}>\n <LazyComponent {...props}>\n {children}\n </LazyComponent>\n </Suspense>\n );\n}\n\nCodeSplit.propTypes = {\n children: PT.node,\n chunkName: PT.string.isRequired,\n getComponent: PT.func.isRequired,\n placeholder: PT.node,\n};\n\nCodeSplit.defaultProps = {\n children: undefined,\n placeholder: undefined,\n};\n"],"file":"index.js"}
|
|
@@ -2,12 +2,11 @@
|
|
|
2
2
|
* The `<Modal>` component implements a simple themeable modal window, wrapped
|
|
3
3
|
* into the default theme. `<BaseModal>` exposes the base non-themed component.
|
|
4
4
|
* **Children:** Component children are rendered as the modal content.
|
|
5
|
-
* @param {object} props Component properties.
|
|
5
|
+
* @param {object} props Component properties. Beside props documented below,
|
|
6
|
+
* [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties) are supported as well.
|
|
6
7
|
* @param {function} [props.onCancel] The callback to trigger when user
|
|
7
8
|
* clicks outside the modal, or presses Escape. It is expected to hide the
|
|
8
9
|
* modal.
|
|
9
10
|
* @param {ModalTheme} [props.theme] _Ad hoc_ theme.
|
|
10
|
-
* @param {...any} [props....]
|
|
11
|
-
* [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)
|
|
12
11
|
*/function BaseModal({children,onCancel,theme}){const containerRef=(0,_react.useRef)();const overlayRef=(0,_react.useRef)();const[portal,setPortal]=(0,_react.useState)();(0,_react.useEffect)(()=>{const p=document.createElement("div");document.body.classList.add("scrolling-disabled-by-modal");document.body.appendChild(p);setPortal(p);return()=>{document.body.classList.remove("scrolling-disabled-by-modal");document.body.removeChild(p)}},[]);const focusLast=(0,_react.useMemo)(()=>/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{onFocus:()=>{const elems=containerRef.current.querySelectorAll("*");for(let i=elems.length-1;i>=0;--i){elems[i].focus();if(document.activeElement===elems[i])return}overlayRef.current.focus()}/* eslint-disable jsx-a11y/no-noninteractive-tabindex */,tabIndex:"0"/* eslint-enable jsx-a11y/no-noninteractive-tabindex */}),[]);return portal?/*#__PURE__*/_reactDom.default.createPortal(/*#__PURE__*/(0,_jsxRuntime.jsxs)(_jsxRuntime.Fragment,{children:[focusLast,/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{"aria-label":"Cancel",className:theme.overlay,onClick:()=>onCancel(),onKeyDown:e=>{if(e.key==="Escape")onCancel()},ref:node=>{if(node&&node!==overlayRef.current){overlayRef.current=node;node.focus()}},role:"button",tabIndex:"0"}),/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{"aria-modal":"true",className:theme.container,onWheel:event=>event.stopPropagation(),ref:containerRef,role:"dialog",children:children}),/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{onFocus:()=>{overlayRef.current.focus()}/* eslint-disable jsx-a11y/no-noninteractive-tabindex */,tabIndex:"0"/* eslint-enable jsx-a11y/no-noninteractive-tabindex */}),focusLast]}),portal):null}const ThemedModal=(0,_reactThemes.default)("Modal",["container","overlay"],baseTheme)(BaseModal);BaseModal.propTypes={onCancel:_propTypes.default.func,children:_propTypes.default.node,theme:ThemedModal.themeType.isRequired};BaseModal.defaultProps={onCancel:_lodash.noop,children:null};var _default=ThemedModal;/* Non-themed version of the Modal. */exports.default=_default;
|
|
13
12
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/shared/components/Modal/index.jsx"],"names":["BaseModal","children","onCancel","theme","containerRef","overlayRef","portal","setPortal","p","document","createElement","body","classList","add","appendChild","remove","removeChild","focusLast","elems","current","querySelectorAll","i","length","focus","activeElement","ReactDom","createPortal","overlay","e","key","node","container","event","stopPropagation","ThemedModal","baseTheme","propTypes","PT","func","themeType","isRequired","defaultProps","noop"],"mappings":"4MAEA,8BACA,4BAMA,2DACA,6DACA,6E,6CAXA,qB,0GAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA
|
|
1
|
+
{"version":3,"sources":["../../../../../src/shared/components/Modal/index.jsx"],"names":["BaseModal","children","onCancel","theme","containerRef","overlayRef","portal","setPortal","p","document","createElement","body","classList","add","appendChild","remove","removeChild","focusLast","elems","current","querySelectorAll","i","length","focus","activeElement","ReactDom","createPortal","overlay","e","key","node","container","event","stopPropagation","ThemedModal","baseTheme","propTypes","PT","func","themeType","isRequired","defaultProps","noop"],"mappings":"4MAEA,8BACA,4BAMA,2DACA,6DACA,6E,6CAXA,qB,0GAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAASA,CAAAA,SAAT,CAAmB,CACjBC,QADiB,CAEjBC,QAFiB,CAGjBC,KAHiB,CAAnB,CAIG,CACD,KAAMC,CAAAA,YAAY,CAAG,mBAArB,CACA,KAAMC,CAAAA,UAAU,CAAG,mBAAnB,CACA,KAAM,CAACC,MAAD,CAASC,SAAT,EAAsB,qBAA5B,CAEA,qBAAU,IAAM,CACd,KAAMC,CAAAA,CAAC,CAAGC,QAAQ,CAACC,aAAT,CAAuB,KAAvB,CAAV,CACAD,QAAQ,CAACE,IAAT,CAAcC,SAAd,CAAwBC,GAAxB,CAA4B,6BAA5B,EACAJ,QAAQ,CAACE,IAAT,CAAcG,WAAd,CAA0BN,CAA1B,EACAD,SAAS,CAACC,CAAD,CAAT,CACA,MAAO,IAAM,CACXC,QAAQ,CAACE,IAA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AAGC,KAAD,EAAWA,KAAK,CAACC,eAAN,EAHtB,CAIE,GAAG,CAAE7B,YAJP,CAKE,IAAI,CAAC,QALP,UAOGH,QAPH,EAlBF,cA2BE,2BACE,OAAO,CAAE,IAAM,CACbI,UAAU,CAACc,OAAX,CAAmBI,KAAnB,EACD,CACD,wDAJF,CAKE,QAAQ,CAAC,GACT,uDANF,EA3BF,CAmCGN,SAnCH,GAFY,CAwCdX,MAxCc,CAAH,CAyCT,IACL,CAED,KAAM4B,CAAAA,WAAW,CAAG,yBAClB,OADkB,CAElB,CACE,WADF,CAEE,SAFF,CAFkB,CAMlBC,SANkB,EAOlBnC,SAPkB,CAApB,CASAA,SAAS,CAACoC,SAAV,CAAsB,CACpBlC,QAAQ,CAAEmC,mBAAGC,IADO,CAEpBrC,QAAQ,CAAEoC,mBAAGP,IAFO,CAGpB3B,KAAK,CAAE+B,WAAW,CAACK,SAAZ,CAAsBC,UAHT,CAAtB,CAMAxC,SAAS,CAACyC,YAAV,CAAyB,CACvBvC,QAAQ,CAAEwC,YADa,CAEvBzC,QAAQ,CAAE,IAFa,CAAzB,C,aAKeiC,W,CAEf,sC","sourcesContent":["/* global document */\n\nimport { noop } from 'lodash';\nimport {\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport ReactDom from 'react-dom';\nimport PT from 'prop-types';\nimport themed from '@dr.pogodin/react-themes';\n\nimport baseTheme from './base-theme.scss';\nimport './styles.scss';\n\n/**\n * The `<Modal>` component implements a simple themeable modal window, wrapped\n * into the default theme. `<BaseModal>` exposes the base non-themed component.\n * **Children:** Component children are rendered as the modal content.\n * @param {object} props Component properties. Beside props documented below,\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties) are supported as well.\n * @param {function} [props.onCancel] The callback to trigger when user\n * clicks outside the modal, or presses Escape. It is expected to hide the\n * modal.\n * @param {ModalTheme} [props.theme] _Ad hoc_ theme.\n */\nfunction BaseModal({\n children,\n onCancel,\n theme,\n}) {\n const containerRef = useRef();\n const overlayRef = useRef();\n const [portal, setPortal] = useState();\n\n useEffect(() => {\n const p = document.createElement('div');\n document.body.classList.add('scrolling-disabled-by-modal');\n document.body.appendChild(p);\n setPortal(p);\n return () => {\n document.body.classList.remove('scrolling-disabled-by-modal');\n document.body.removeChild(p);\n };\n }, []);\n\n const focusLast = useMemo(() => (\n <div\n onFocus={() => {\n const elems = containerRef.current.querySelectorAll('*');\n for (let i = elems.length - 1; i >= 0; --i) {\n elems[i].focus();\n if (document.activeElement === elems[i]) return;\n }\n overlayRef.current.focus();\n }}\n /* eslint-disable jsx-a11y/no-noninteractive-tabindex */\n tabIndex=\"0\"\n /* eslint-enable jsx-a11y/no-noninteractive-tabindex */\n />\n ), []);\n\n return portal ? ReactDom.createPortal(\n (\n <>\n {focusLast}\n <div\n aria-label=\"Cancel\"\n className={theme.overlay}\n onClick={() => onCancel()}\n onKeyDown={(e) => {\n if (e.key === 'Escape') onCancel();\n }}\n ref={(node) => {\n if (node && node !== overlayRef.current) {\n overlayRef.current = node;\n node.focus();\n }\n }}\n role=\"button\"\n tabIndex=\"0\"\n />\n <div\n aria-modal=\"true\"\n className={theme.container}\n onWheel={(event) => event.stopPropagation()}\n ref={containerRef}\n role=\"dialog\"\n >\n {children}\n </div>\n <div\n onFocus={() => {\n overlayRef.current.focus();\n }}\n /* eslint-disable jsx-a11y/no-noninteractive-tabindex */\n tabIndex=\"0\"\n /* eslint-enable jsx-a11y/no-noninteractive-tabindex */\n />\n {focusLast}\n </>\n ),\n portal,\n ) : null;\n}\n\nconst ThemedModal = themed(\n 'Modal',\n [\n 'container',\n 'overlay',\n ],\n baseTheme,\n)(BaseModal);\n\nBaseModal.propTypes = {\n onCancel: PT.func,\n children: PT.node,\n theme: ThemedModal.themeType.isRequired,\n};\n\nBaseModal.defaultProps = {\n onCancel: noop,\n children: null,\n};\n\nexport default ThemedModal;\n\n/* Non-themed version of the Modal. */\nexport { BaseModal };\n"],"file":"index.js"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"act",{enumerable:true,get:function(){return _testUtils.act}});exports.
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"act",{enumerable:true,get:function(){return _testUtils.act}});exports.getMockUuid=getMockUuid;exports.mockClientSide=mockClientSide;exports.mockTimer=mockTimer;exports.mount=mount;exports.render=render;exports.shallowRender=shallowRender;exports.shallowSnapshot=shallowSnapshot;exports.simulate=void 0;exports.snapshot=snapshot;exports.unmockClientSide=unmockClientSide;var _mockdate=_interopRequireDefault(require("mockdate"));var _client=require("react-dom/client");var _testUtils=_interopRequireWildcard(require("react-dom/test-utils"));var _reactTestRenderer=_interopRequireDefault(require("react-test-renderer"));var _shallow=_interopRequireDefault(require("react-test-renderer/shallow"));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}/* global expect, jest, document */ /* eslint-disable import/no-extraneous-dependencies */ /* eslint-disable import/no-extraneous-dependencies */ /* eslint-enable import/no-extraneous-dependencies */ /**
|
|
2
2
|
* An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)
|
|
3
3
|
* from `react-dom/test-utils`.
|
|
4
4
|
* @param {function} action
|
|
5
|
-
*/const originalProcessVersions=process.versions;/**
|
|
5
|
+
*/global.IS_REACT_ACT_ENVIRONMENT=true;const originalProcessVersions=process.versions;/**
|
|
6
6
|
* Tricks **react-utils** into thinking the test is running within client-side
|
|
7
7
|
* (browser) environment.
|
|
8
8
|
*/function mockClientSide(){Object.defineProperty(process,"versions",{value:null})}/**
|
|
@@ -20,23 +20,9 @@
|
|
|
20
20
|
*/async function mockTimer(time){_mockdate.default.set(time+Date.now());jest.advanceTimersByTime(time)}/**
|
|
21
21
|
* Mounts `scene` to the DOM, and returns the root scene element.
|
|
22
22
|
* @param {React.ReactNode} scene
|
|
23
|
-
* @return {HTMLElement}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
* @param {HTMLElement} scene
|
|
27
|
-
*/function unmount(scene){(0,_reactDom.unmountComponentAtNode)(scene);scene.remove()}/* OLD STUFF BELOW THIS MARK */ /**
|
|
28
|
-
* Just an alias for
|
|
29
|
-
* [findRenderedDOMComponentWithClass(..)](https://reactjs.org/docs/test-utils.html#findrendereddomcomponentwithclass).
|
|
30
|
-
* @param {object} dom
|
|
31
|
-
* @param {string} className
|
|
32
|
-
* @return {object}
|
|
33
|
-
*/function findInDomByClass(dom,className){return _testUtils.default.findRenderedDOMComponentWithClass(dom,className)}/**
|
|
34
|
-
* Just an alias for
|
|
35
|
-
* [scryRenderedDOMComponentsWithClass(..)](https://reactjs.org/docs/test-utils.html#scryrendereddomcomponentswithclass).
|
|
36
|
-
* @param {object} dom
|
|
37
|
-
* @param {stirng} className
|
|
38
|
-
* @return {array}
|
|
39
|
-
*/function findInDomManyByClass(dom,className){return _testUtils.default.scryRenderedDOMComponentsWithClass(dom,className)}/**
|
|
23
|
+
* @return {HTMLElement} Created container DOM element with destroy() function
|
|
24
|
+
* attached.
|
|
25
|
+
*/function mount(scene){let root;const res=document.createElement("div");document.body.appendChild(res);res.destroy=()=>{(0,_testUtils.act)(()=>root.unmount());res.remove()};(0,_testUtils.act)(()=>{root=(0,_client.createRoot)(res);root.render(scene)});return res}/* OLD STUFF BELOW THIS MARK */ /**
|
|
40
26
|
* Renders provided ReactJS component into JSON representation of the component
|
|
41
27
|
* tree, using [`react-test-renderer`](https://www.npmjs.com/package/react-test-renderer).
|
|
42
28
|
* @param {object} component ReactJS component to render.
|
|
@@ -44,15 +30,7 @@
|
|
|
44
30
|
* @example
|
|
45
31
|
* import { JU } from '@dr.pogodin/react-utils';
|
|
46
32
|
* console.log(JU.render(<div>Example</div>));
|
|
47
|
-
*/function render(component){return _reactTestRenderer.default.create(component).toJSON()}
|
|
48
|
-
// the "renderIntoDocument(..)" function from "react-dom/test-utils" works
|
|
49
|
-
// only with state components, so we have to wrap our ReactJS components into
|
|
50
|
-
// such Wrapper.
|
|
51
|
-
class Wrapper extends _react.Component{componentDidMount(){}render(){const{children}=this.props;return children}}Wrapper.propTypes={children:_propTypes.default.node.isRequired};/**
|
|
52
|
-
* Renders given ReactJS component into DOM, using `react-dom/test-utils`.
|
|
53
|
-
* @param {object} component ReactJS component to render.
|
|
54
|
-
* @return {object} Rendered DOM.
|
|
55
|
-
*/function renderDom(component){return _testUtils.default.renderIntoDocument(/*#__PURE__*/(0,_jsxRuntime.jsx)(Wrapper,{children:component}))}/**
|
|
33
|
+
*/function render(component){return _reactTestRenderer.default.create(component).toJSON()}/**
|
|
56
34
|
* Generates a shallow render of given ReactJS component, using
|
|
57
35
|
* [react-test-renderer/shallow](https://reactjs.org/docs/shallow-renderer.html)
|
|
58
36
|
* and returns the result.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/shared/utils/jest.jsx"],"names":["originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockTimer","time","mockdate","set","Date","now","jest","advanceTimersByTime","mount","scene","res","document","createElement","body","appendChild","
|
|
1
|
+
{"version":3,"sources":["../../../../src/shared/utils/jest.jsx"],"names":["global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockTimer","time","mockdate","set","Date","now","jest","advanceTimersByTime","mount","scene","root","res","document","createElement","body","appendChild","destroy","unmount","remove","render","component","Renderer","create","toJSON","shallowRender","renderer","ShallowRenderer","getRenderOutput","shallowSnapshot","expect","toMatchSnapshot","snapshot","simulate","TU","Simulate"],"mappings":"0iBAGA,0DACA,wCACA,wEAGA,8EACA,4E,o9BATA,mC,CACA,sD,CAMA,sD,CAGA,qD,CAEA;AACA;AACA;AACA;AACA,GAGAA,MAAM,CAACC,wBAAP,CAAkC,IAAlC,CAEA,KAAMC,CAAAA,uBAAuB,CAAGC,OAAO,CAACC,QAAxC,CAEA;AACA;AACA;AACA,GACO,QAASC,CAAAA,cAAT,EAA0B,CAC/BC,MAAM,CAACC,cAAP,CAAsBJ,OAAtB,CAA+B,UAA/B,CAA2C,CAAEK,KAAK,CAAE,IAAT,CAA3C,CACD,CAED;AACA;AACA,GACO,QAASC,CAAAA,gBAAT,EAA4B,CACjCH,MAAM,CAACC,cAAP,CAAsBJ,OAAtB,CAA+B,UAA/B,CAA2C,CACzCK,KAAK,CAAEN,uBADkC,CAEzCQ,QAAQ,CAAE,KAF+B,CAA3C,CAID,CAED;AACA;AACA;AACA;AACA;AACA,GACO,QAASC,CAAAA,WAAT,CAAqBC,IAAI,CAAG,CAA5B,CAA+B,CACpC,KAAMC,CAAAA,CAAC,CAAGD,IAAI,CAACE,QAAL,CAAc,EAAd,EAAkBC,QAAlB,CAA2B,EAA3B,CAA+B,GAA/B,CAAV,CACA,MAAQ,GAAEF,CAAC,CAACG,KAAF,CAAQ,CAAR,CAAW,CAAX,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B,EACA,MAAOK,CAAAA,QAAQ,CAACE,eAAT,EACR,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAASC,CAAAA,eAAT,CAAyBR,SAAzB,CAAoC,CACzC,KAAMT,CAAAA,GAAG,CAAGa,aAAa,CAACJ,SAAD,CAAzB,CACAS,MAAM,CAAClB,GAAD,CAAN,CAAYmB,eAAZ,GACA,MAAOnB,CAAAA,GACR,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAASoB,CAAAA,QAAT,CAAkBX,SAAlB,CAA6B,CAClC,KAAMT,CAAAA,GAAG,CAAGQ,MAAM,CAACC,SAAD,CAAlB,CACAS,MAAM,CAAClB,GAAD,CAAN,CAAYmB,eAAZ,GACA,MAAOnB,CAAAA,GACR,CAEM,KAAMqB,CAAAA,QAAQ,CAAGC,mBAAGC,QAApB,C","sourcesContent":["/* global expect, jest, document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport mockdate from 'mockdate';\nimport { createRoot } from 'react-dom/client';\nimport TU, { act } from 'react-dom/test-utils';\n\n/* eslint-disable import/no-extraneous-dependencies */\nimport Renderer from 'react-test-renderer';\nimport ShallowRenderer from 'react-test-renderer/shallow';\n/* eslint-enable import/no-extraneous-dependencies */\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react-dom/test-utils`.\n * @param {function} action\n */\nexport { act };\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide() {\n Object.defineProperty(process, 'versions', { value: null });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide() {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0) {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time) {\n mockdate.set(time + Date.now());\n jest.advanceTimersByTime(time);\n}\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param {React.ReactNode} scene\n * @return {HTMLElement} Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene) {\n let root;\n const res = document.createElement('div');\n document.body.appendChild(res);\n res.destroy = () => {\n act(() => root.unmount());\n res.remove();\n };\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n/* OLD STUFF BELOW THIS MARK */\n\n/**\n * Renders provided ReactJS component into JSON representation of the component\n * tree, using [`react-test-renderer`](https://www.npmjs.com/package/react-test-renderer).\n * @param {object} component ReactJS component to render.\n * @return {object} JSON representation of the rendered tree.\n * @example\n * import { JU } from '@dr.pogodin/react-utils';\n * console.log(JU.render(<div>Example</div>));\n */\nexport function render(component) {\n return Renderer.create(component).toJSON();\n}\n\n/**\n * Generates a shallow render of given ReactJS component, using\n * [react-test-renderer/shallow](https://reactjs.org/docs/shallow-renderer.html)\n * and returns the result.\n * @param {object} component ReactJS component to render.\n * @return {object} JSON representation of the shallow component's render tree.\n */\nexport function shallowRender(component) {\n const renderer = new ShallowRenderer();\n renderer.render(component);\n return renderer.getRenderOutput();\n}\n\n/**\n * Makes a shallow snapshot test of the given ReactJS component, and also\n * returns JSON representation of the rendered component tree. Under the hood\n * it uses {@link module:JU.shallowRender shallowRender(..)} to generate\n * the render, then executes `expect(RENDER_RESULT).toMatchSnapshot()`,\n * and finally returns the `RENDER_RESULT` to the caller.\n * @param {object} component ReactJS component to render.\n * @return {object} JSON representation of shallow render.\n */\nexport function shallowSnapshot(component) {\n const res = shallowRender(component);\n expect(res).toMatchSnapshot();\n return res;\n}\n\n/**\n * Makes snapshot test of the given ReactJS component, and also returns JSON\n * representation of the rendered component tree. Under the hood, it uses\n * {@link module:JU.render render(..)} to render it, then executes\n * `expect(RENDER_RESULT).toMatchSnapshot()`, and then returns `RENDER_RESULT`.\n * @param {object} component ReactJS component to render.\n * @return {object} JSON render of the component.\n */\nexport function snapshot(component) {\n const res = render(component);\n expect(res).toMatchSnapshot();\n return res;\n}\n\nexport const simulate = TU.Simulate;\n"],"file":"jest.js"}
|
|
@@ -1,14 +1,13 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=splitComponent;var _react=require("react");var _CodeSplit=_interopRequireDefault(require("../components/CodeSplit"))
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=splitComponent;var _react=require("react");var _CodeSplit=_interopRequireDefault(require("../components/CodeSplit"));/* eslint-disable react/jsx-props-no-spreading */ /**
|
|
2
2
|
* Wraps a regular React component into a "code splitting" component,
|
|
3
3
|
* i.e. all code used exclusively by that component and its sub-tree
|
|
4
4
|
* will go into a separate, asynchronously loaded, code chunk for
|
|
5
5
|
* the client-side.
|
|
6
6
|
* @param {object} options
|
|
7
7
|
* @param {string} options.chunkName
|
|
8
|
-
* @param {function} options.
|
|
9
|
-
* @param {React.
|
|
10
|
-
* @
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
return({children=[],...props}={})=>/*#__PURE__*/(0,_react.createElement)(_CodeSplit.default,{...props,chunkName,getClientSide,placeholder,serverSide},...children)}
|
|
8
|
+
* @param {function} options.getComponent
|
|
9
|
+
* @param {React.Element} [options.placeholder]
|
|
10
|
+
* @return {React.ElementType}
|
|
11
|
+
*/function splitComponent({chunkName,getComponent,placeholder}){// eslint-disable-next-line react/prop-types
|
|
12
|
+
return({children,...props})=>/*#__PURE__*/(0,_react.createElement)(_CodeSplit.default,{...props,chunkName,getComponent,placeholder},children)}
|
|
14
13
|
//# sourceMappingURL=splitComponent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/shared/utils/splitComponent.js"],"names":["splitComponent","chunkName","
|
|
1
|
+
{"version":3,"sources":["../../../../src/shared/utils/splitComponent.js"],"names":["splitComponent","chunkName","getComponent","placeholder","children","props","CodeSplit"],"mappings":"wLAEA,4BAEA,0EAJA,iD,CAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACe,QAASA,CAAAA,cAAT,CAAwB,CACrCC,SADqC,CAErCC,YAFqC,CAGrCC,WAHqC,CAAxB,CAIZ,CACD;AACA,MAAO,CAAC,CAAEC,QAAF,CAAY,GAAGC,KAAf,CAAD,gBAA4B,yBACjCC,kBADiC,CAEjC,CACE,GAAGD,KADL,CAEEJ,SAFF,CAGEC,YAHF,CAIEC,WAJF,CAFiC,CAQjCC,QARiC,CAUpC","sourcesContent":["/* eslint-disable react/jsx-props-no-spreading */\n\nimport { createElement } from 'react';\n\nimport CodeSplit from 'components/CodeSplit';\n\n/**\n * Wraps a regular React component into a \"code splitting\" component,\n * i.e. all code used exclusively by that component and its sub-tree\n * will go into a separate, asynchronously loaded, code chunk for\n * the client-side.\n * @param {object} options\n * @param {string} options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent({\n chunkName,\n getComponent,\n placeholder,\n}) {\n // eslint-disable-next-line react/prop-types\n return ({ children, ...props }) => createElement(\n CodeSplit,\n {\n ...props,\n chunkName,\n getComponent,\n placeholder,\n },\n children,\n );\n}\n"],"file":"splitComponent.js"}
|
|
@@ -1,15 +1,4 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _dayjs=_interopRequireDefault(require("dayjs"));/**
|
|
2
|
-
* @category Utilities
|
|
3
|
-
* @module time
|
|
4
|
-
* @desc
|
|
5
|
-
* ```js
|
|
6
|
-
* import { time } from '@dr.pogodin/react-utils';
|
|
7
|
-
* ```
|
|
8
|
-
* Date & time utilities. The `time` export is a convenient alias for
|
|
9
|
-
* [dayjs](https://day.js.org/en/) library, _i.e._ you can use `time`
|
|
10
|
-
* in all ways you would use `dayjs`. It is further extended with
|
|
11
|
-
* the following additional members.
|
|
12
|
-
*/ /**
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _dayjs=_interopRequireDefault(require("dayjs"));var _Barrier=require("./Barrier");/**
|
|
13
2
|
* @static
|
|
14
3
|
* @const SEC_MS
|
|
15
4
|
* @desc One second, expressed in milliseconds (equals 1000 ms).
|
|
@@ -54,13 +43,10 @@
|
|
|
54
43
|
* import { time } from '@dr.pogodin/react-utils';
|
|
55
44
|
* console.log(time.now()); // Prints the current timestamp, e.g. 1618608761000.
|
|
56
45
|
*/_dayjs.default.now=Date.now;/**
|
|
57
|
-
*
|
|
58
|
-
* @func timer
|
|
59
|
-
* @desc Creates a Promise, which resolves after the given timeout.
|
|
46
|
+
* Creates a Promise, which resolves after the given timeout.
|
|
60
47
|
* @param {number} timeout Timeout [ms].
|
|
61
|
-
* @return {
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
|
|
65
|
-
*/_dayjs.default.timer=async function timer(timeout){return new Promise(resolve=>{setTimeout(resolve,timeout)})};var _default=_dayjs.default;exports.default=_default;
|
|
48
|
+
* @return {Barrier} Resolves after the timeout. It has additional
|
|
49
|
+
* .abort() method attached, which cancels the pending timer resolution
|
|
50
|
+
* (without resolving or rejecting the barrier).
|
|
51
|
+
*/_dayjs.default.timer=async function timer(timeout){const res=new _Barrier.Barrier;const id=setTimeout(res.resolve.bind(res),timeout);res.abort=()=>clearTimeout(id);return res};var _default=_dayjs.default;exports.default=_default;
|
|
66
52
|
//# sourceMappingURL=time.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/shared/utils/time.js"],"names":["dayjs","SEC_MS","MIN_MS","HOUR_MS","DAY_MS","YEAR_MS","now","Date","timer","timeout","
|
|
1
|
+
{"version":3,"sources":["../../../../src/shared/utils/time.js"],"names":["dayjs","SEC_MS","MIN_MS","HOUR_MS","DAY_MS","YEAR_MS","now","Date","timer","timeout","res","Barrier","id","setTimeout","resolve","bind","abort","clearTimeout"],"mappings":"gLAAA,oDACA,kCAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACAA,eAAMC,MAAN,CAAe,IAAf,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACAD,eAAME,MAAN,CAAe,GAAKF,eAAMC,MAA1B,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACAD,eAAMG,OAAN,CAAgB,GAAKH,eAAME,MAA3B,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACAF,eAAMI,MAAN,CAAe,GAAKJ,eAAMG,OAA1B,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACAH,eAAMK,OAAN,CAAgB,IAAML,eAAMI,MAA5B,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACAJ,eAAMM,GAAN,CAAYC,IAAI,CAACD,GAAjB,CAEA;AACA;AACA;AACA;AACA;AACA;AACA,GACAN,eAAMQ,KAAN,CAAc,cAAeA,CAAAA,KAAf,CAAqBC,OAArB,CAA8B,CAC1C,KAAMC,CAAAA,GAAG,CAAG,GAAIC,iBAAhB,CACA,KAAMC,CAAAA,EAAE,CAAGC,UAAU,CAACH,GAAG,CAACI,OAAJ,CAAYC,IAAZ,CAAiBL,GAAjB,CAAD,CAAwBD,OAAxB,CAArB,CACAC,GAAG,CAACM,KAAJ,CAAY,IAAMC,YAAY,CAACL,EAAD,CAA9B,CACA,MAAOF,CAAAA,GACR,CALD,C,aAOeV,c","sourcesContent":["import dayjs from 'dayjs';\nimport { Barrier } from './Barrier';\n\n/**\n * @static\n * @const SEC_MS\n * @desc One second, expressed in milliseconds (equals 1000 ms).\n * @example\n * import { time } from '@dr.pogodin/react-utils';\n * console.log(time.SEC_MS); // Prints: 1000\n */\ndayjs.SEC_MS = 1000;\n\n/**\n * @static\n * @const MIN_MS\n * @desc One minute, expressed in milliseconds (equals 60 × `SEC_MS`).\n * @example\n * import { time } from '@dr.pogodin/react-utils';\n * console.log(time.MIN_MS); // Prints: 60000\n */\ndayjs.MIN_MS = 60 * dayjs.SEC_MS;\n\n/**\n * @static\n * @const HOUR_MS\n * @desc One hour, expressed in milliseconds (equals 60 × `MIN_MS`).\n * @example\n * import { time } from '@dr.pogodin/react-utils';\n * console.log(time.HOUR_MS); // Prints: 3600000\n */\ndayjs.HOUR_MS = 60 * dayjs.MIN_MS;\n\n/**\n * @static\n * @const DAY_MS\n * @desc One day, expressed in milliseconds (equals 24 × `HOUR_MS`).\n * @example\n * import { time } from '@dr.pogodin/react-utils';\n * console.log(time.DAY_MS); // Prints: 86400000\n */\ndayjs.DAY_MS = 24 * dayjs.HOUR_MS;\n\n/**\n * @static\n * @const YEAR_MS\n * @desc One year, expressed in milliseconds (equals 365 × `DAY_MS`,\n * thus a normal, non-leap year).\n * @example\n * import { time } from '@dr.pogodin/react-utils';\n * console.log(time.YEAR_MS); // Prints: 31536000000\n */\ndayjs.YEAR_MS = 365 * dayjs.DAY_MS;\n\n/**\n * @static\n * @func now\n * @desc Returns Unix timestamp [ms] (thus, it is just an alias for `Date.now`).\n * @return {number}\n * @example\n * import { time } from '@dr.pogodin/react-utils';\n * console.log(time.now()); // Prints the current timestamp, e.g. 1618608761000.\n */\ndayjs.now = Date.now;\n\n/**\n * Creates a Promise, which resolves after the given timeout.\n * @param {number} timeout Timeout [ms].\n * @return {Barrier} Resolves after the timeout. It has additional\n * .abort() method attached, which cancels the pending timer resolution\n * (without resolving or rejecting the barrier).\n */\ndayjs.timer = async function timer(timeout) {\n const res = new Barrier();\n const id = setTimeout(res.resolve.bind(res), timeout);\n res.abort = () => clearTimeout(id);\n return res;\n};\n\nexport default dayjs;\n"],"file":"time.js"}
|