@dr.pogodin/react-utils 1.8.5 → 1.10.0
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/bin/build.js +0 -129
- package/bin/release.sh +1 -1
- package/bin/setup.js +0 -44
- package/build/development/client/index.js +0 -6
- package/build/development/client/index.js.map +1 -1
- package/build/development/client/init.js +3 -1
- package/build/development/client/init.js.map +1 -1
- package/build/development/index.js +14 -19
- package/build/development/index.js.map +1 -1
- package/build/development/server/index.js +1 -51
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +10 -4
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +1 -1
- package/build/development/server/utils/errors.js +3 -3
- package/build/development/shared/components/Button/index.js +7 -42
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +7 -14
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/CodeSplit/index.js +9 -66
- package/build/development/shared/components/CodeSplit/index.js.map +1 -1
- package/build/development/shared/components/Dropdown/index.js +9 -35
- package/build/development/shared/components/Dropdown/index.js.map +1 -1
- package/build/development/shared/components/GenericLink/index.js +1 -23
- package/build/development/shared/components/GenericLink/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +6 -19
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/MetaTags.js +0 -21
- package/build/development/shared/components/MetaTags.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +5 -39
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/NavLink.js +0 -10
- package/build/development/shared/components/NavLink.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js +6 -31
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/ScalableRect/index.js +2 -8
- package/build/development/shared/components/ScalableRect/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js +10 -22
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +7 -13
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +9 -15
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/index.js +18 -18
- package/build/development/shared/components/index.js.map +1 -1
- package/build/development/shared/utils/config.js +0 -22
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/index.js +11 -29
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/isomorphy.js +3 -44
- package/build/development/shared/utils/isomorphy.js.map +1 -1
- package/build/development/shared/utils/jest.js +12 -126
- package/build/development/shared/utils/jest.js.map +1 -1
- package/build/development/shared/utils/url.js +1 -1
- package/build/development/shared/utils/webpack.js +0 -4
- package/build/development/shared/utils/webpack.js.map +1 -1
- package/build/development/style.css +149 -149
- package/build/development/web.bundle.js +33 -33
- package/build/production/client/index.js +0 -6
- package/build/production/client/index.js.map +1 -1
- package/build/production/client/init.js +2 -1
- package/build/production/client/init.js.map +1 -1
- package/build/production/index.js +2 -11
- package/build/production/index.js.map +1 -1
- package/build/production/server/index.js +1 -49
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +2 -2
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +1 -1
- package/build/production/server/utils/errors.js +1 -1
- package/build/production/shared/components/Button/index.js +2 -37
- package/build/production/shared/components/Button/index.js.map +1 -1
- package/build/production/shared/components/Checkbox/index.js +2 -9
- package/build/production/shared/components/Checkbox/index.js.map +1 -1
- package/build/production/shared/components/CodeSplit/index.js +2 -65
- package/build/production/shared/components/CodeSplit/index.js.map +1 -1
- package/build/production/shared/components/Dropdown/index.js +2 -24
- package/build/production/shared/components/Dropdown/index.js.map +1 -1
- package/build/production/shared/components/GenericLink/index.js +1 -23
- package/build/production/shared/components/GenericLink/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +2 -13
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/MetaTags.js +0 -21
- package/build/production/shared/components/MetaTags.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +2 -34
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/NavLink.js +1 -10
- package/build/production/shared/components/NavLink.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js +2 -25
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/ScalableRect/index.js +1 -7
- package/build/production/shared/components/ScalableRect/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js +2 -13
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +1 -7
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +1 -7
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/index.js +1 -1
- package/build/production/shared/components/index.js.map +1 -1
- package/build/production/shared/utils/config.js +1 -21
- package/build/production/shared/utils/config.js.map +1 -1
- package/build/production/shared/utils/index.js +1 -20
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/isomorphy.js +1 -40
- package/build/production/shared/utils/isomorphy.js.map +1 -1
- package/build/production/shared/utils/jest.js +2 -112
- package/build/production/shared/utils/jest.js.map +1 -1
- package/build/production/shared/utils/url.js +1 -1
- package/build/production/shared/utils/webpack.js +0 -4
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/production/style.css +1 -1
- package/build/production/style.css.map +1 -1
- package/build/production/web.bundle.js +1 -1
- package/build/production/web.bundle.js.map +1 -1
- package/config/babel/node-ssr.js +1 -8
- package/config/babel/webpack.js +1 -8
- package/config/jest/default.js +0 -34
- package/config/shared/utils.js +9 -100
- package/config/stylelint/default.js +2 -19
- package/config/webpack/app-base.js +3 -6
- package/config/webpack/app-development.js +0 -23
- package/config/webpack/app-production.js +0 -20
- package/config/webpack/lib-base.js +3 -66
- package/config/webpack/lib-development.js +0 -10
- package/config/webpack/lib-production.js +0 -9
- package/index.js +21 -10
- package/package.json +34 -36
- package/src/index.js +6 -61
- package/src/styles/_mixins/fonts.scss +4 -4
- package/src/styles/mixins.scss +1 -1
- package/build/development/styles/global-docs.js +0 -29
- package/build/development/styles/global-docs.js.map +0 -1
- package/build/development/styles/mixins.js +0 -103
- package/build/development/styles/mixins.js.map +0 -1
- package/build/production/styles/global-docs.js +0 -28
- package/build/production/styles/global-docs.js.map +0 -1
- package/build/production/styles/mixins.js +0 -101
- package/build/production/styles/mixins.js.map +0 -1
- package/config/eslint/docs.js +0 -40
- package/config/jsdoc/config.js +0 -34
- package/src/README.md +0 -130
|
@@ -1,11 +1,5 @@
|
|
|
1
1
|
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=Launch;var _reactGlobalState=require("@dr.pogodin/react-global-state");var _reactDom=_interopRequireDefault(require("react-dom"));var _reactRouterDom=require("react-router-dom");var _jsxRuntime=require("react/jsx-runtime");// Initialization of client-side code.
|
|
2
2
|
/* global document, window */ /**
|
|
3
|
-
* @category Utilities
|
|
4
|
-
* @func client
|
|
5
|
-
* @desc
|
|
6
|
-
* ```js
|
|
7
|
-
* import { client } from '@dr.pogodin/react-utils';
|
|
8
|
-
* ```
|
|
9
3
|
* Prepares and launches the app at client side.
|
|
10
4
|
* @param {object} Application Root application component
|
|
11
5
|
*/function Launch(Application){_reactDom.default.hydrate(/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactGlobalState.GlobalStateProvider,{initialState:window.ISTATE,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactRouterDom.BrowserRouter,{children:/*#__PURE__*/(0,_jsxRuntime.jsx)(Application,{})})}),document.getElementById("react-view"))}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/client/index.jsx"],"names":["Launch","Application","ReactDom","hydrate","window","ISTATE","document","getElementById"],"mappings":"gLAGA,gEAEA,2DACA,gD,6CANA;AACA,6B,CAOA;AACA;AACA;AACA
|
|
1
|
+
{"version":3,"sources":["../../../src/client/index.jsx"],"names":["Launch","Application","ReactDom","hydrate","window","ISTATE","document","getElementById"],"mappings":"gLAGA,gEAEA,2DACA,gD,6CANA;AACA,6B,CAOA;AACA;AACA;AACA,GACe,QAASA,CAAAA,MAAT,CAAgBC,WAAhB,CAA6B,CAC1CC,kBAASC,OAAT,cACE,oBAAC,qCAAD,EAAqB,YAAY,CAAEC,MAAM,CAACC,MAA1C,uBACE,oBAAC,6BAAD,wBACE,oBAAC,WAAD,IADF,EADF,EADF,CAMGC,QAAQ,CAACC,cAAT,CAAwB,YAAxB,CANH,CAOD","sourcesContent":["// Initialization of client-side code.\n/* global document, window */\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport ReactDom from 'react-dom';\nimport { BrowserRouter } from 'react-router-dom';\n\n/**\n * Prepares and launches the app at client side.\n * @param {object} Application Root application component\n */\nexport default function Launch(Application) {\n ReactDom.hydrate((\n <GlobalStateProvider initialState={window.ISTATE}>\n <BrowserRouter>\n <Application />\n </BrowserRouter>\n </GlobalStateProvider>\n ), document.getElementById('react-view'));\n}\n"],"file":"index.js"}
|
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
// is bundled into client-side code.
|
|
5
5
|
/* `BUILD_INFO` is always injected by Webpack build, but this check is needed
|
|
6
6
|
* to adopt the code for usage in tests. */if(typeof BUILD_INFO!=="undefined"){window.TRU_BUILD_INFO=BUILD_INFO}/* Removes data injection script out of the document.
|
|
7
|
-
* The if block is here for test purposes. */if(!window.TRU_KEEP_INJ_SCRIPT){var block=document.querySelector("script[id=\"inj\"]");if(block)document.getElementsByTagName("body")[0].removeChild(block)}/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */ /* eslint-disable no-console */var useServiceWorker=window.TRU_BUILD_INFO.useServiceWorker;if(useServiceWorker){var _window=window,navigator=_window.navigator;if("serviceWorker"in navigator){window.addEventListener("load",/*#__PURE__*/(0,_asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee(){var reg;return _regenerator.default.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.prev=0;_context.next=3;return navigator.serviceWorker.register("/__service-worker.js");case 3:reg=_context.sent;console.log("SW registered:",reg);_context.next=10;break;case 7:_context.prev=7;_context.t0=_context["catch"](0);console.log("SW registration failed:",_context.t0);case 10:case"end":return _context.stop();}}},_callee,null,[[0,7]])})))}}/* eslint-enable no-console */ /* Decodes data injected at the server side. */if(window.INJ){var key=window.TRU_BUILD_INFO.key;var data=_forge.default.util.decode64(window.INJ);var decipher=_forge.default.cipher.createDecipher("AES-CBC",key);decipher.start({iv:data.slice(0,32)});decipher.update(_forge.default.util.createBuffer(data.slice(32)));decipher.finish();data=
|
|
7
|
+
* The if block is here for test purposes. */if(!window.TRU_KEEP_INJ_SCRIPT){var block=document.querySelector("script[id=\"inj\"]");if(block)document.getElementsByTagName("body")[0].removeChild(block)}/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */ /* eslint-disable no-console */var useServiceWorker=window.TRU_BUILD_INFO.useServiceWorker;if(useServiceWorker){var _window=window,navigator=_window.navigator;if("serviceWorker"in navigator){window.addEventListener("load",/*#__PURE__*/(0,_asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee(){var reg;return _regenerator.default.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.prev=0;_context.next=3;return navigator.serviceWorker.register("/__service-worker.js");case 3:reg=_context.sent;console.log("SW registered:",reg);_context.next=10;break;case 7:_context.prev=7;_context.t0=_context["catch"](0);console.log("SW registration failed:",_context.t0);case 10:case"end":return _context.stop();}}},_callee,null,[[0,7]])})))}}/* eslint-enable no-console */ /* Decodes data injected at the server side. */if(window.INJ){var key=window.TRU_BUILD_INFO.key;var data=_forge.default.util.decode64(window.INJ);var decipher=_forge.default.cipher.createDecipher("AES-CBC",key);decipher.start({iv:data.slice(0,32)});decipher.update(_forge.default.util.createBuffer(data.slice(32)));decipher.finish();data=_forge.default.util.decodeUtf8(decipher.output.data);data=eval("(".concat(data,")"));// eslint-disable-line no-eval
|
|
8
|
+
window.CHUNK_GROUPS=data.CHUNK_GROUPS;window.CONFIG=data.CONFIG;window.ISTATE=data.ISTATE}else{// This is possible when the client-side bundle is launched as a stand-alone
|
|
8
9
|
// precompiled website, rather than served by react-utils' based server.
|
|
9
10
|
window.CHUNK_GROUPS={};window.CONFIG={}}
|
|
10
11
|
//# sourceMappingURL=init.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/client/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","
|
|
1
|
+
{"version":3,"sources":["../../../src/client/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"],"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,W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B,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","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"],"file":"init.js"}
|
|
@@ -1,12 +1,3 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={server:true,_:true,api:true,PT:true,getGlobalState:true,GlobalStateProvider:true,useAsyncCollection:true,useAsyncData:true,useGlobalState:true};Object.defineProperty(exports,"
|
|
2
|
-
exports.server=server;if(_utils.isomorphy.IS_SERVER_SIDE){const path=_utils.webpack.requireWeak("path");exports.server=server=_utils.webpack.requireWeak(path.resolve(__dirname,"./server"))}
|
|
3
|
-
* @category Utilities
|
|
4
|
-
* @module _
|
|
5
|
-
* @desc
|
|
6
|
-
* ```js
|
|
7
|
-
* import { _ } from '@dr.pogodin/react-utils';
|
|
8
|
-
* ```
|
|
9
|
-
* `_` is just an alias for [lodash](https://lodash.com/docs) library,
|
|
10
|
-
* which provides various generic JS helpers.
|
|
11
|
-
*/
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={server:true,_: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,"_",{enumerable:true,get:function(){return _lodash.default}});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 _lodash=_interopRequireDefault(require("lodash"));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}let server=null;// eslint-disable-line import/no-mutable-exports
|
|
2
|
+
exports.server=server;if(_utils.isomorphy.IS_SERVER_SIDE){try{const path=_utils.webpack.requireWeak("path");exports.server=server=_utils.webpack.requireWeak(path.resolve(__dirname,"./server"))}catch(error){exports.server=server=null}}
|
|
12
3
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.js"],"names":["server","isomorphy","IS_SERVER_SIDE","path","webpack","requireWeak","resolve","__dirname"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/index.js"],"names":["server","isomorphy","IS_SERVER_SIDE","path","webpack","requireWeak","resolve","__dirname","error"],"mappings":"4oCAEA,qCAyBA,wSAbA,sDACA,oD,sEAGA,gEAQA,sW,o9BAtBA,GAAIA,CAAAA,MAAM,CAAG,IAAb,CAAmB;sBACnB,GAAIC,iBAAUC,cAAd,CAA8B,CAC5B,GAAI,CACF,KAAMC,CAAAA,IAAI,CAAGC,eAAQC,WAAR,CAAoB,MAApB,CAAb,CACA,eAAAL,MAAM,CAAGI,eAAQC,WAAR,CAAoBF,IAAI,CAACG,OAAL,CAAaC,SAAb,CAAwB,UAAxB,CAApB,CACV,CAAC,MAAOC,KAAP,CAAc,CACd,eAAAR,MAAM,CAAG,IACV,CACF","sourcesContent":["import 'styles/global.scss';\n\nimport { isomorphy, webpack } from 'utils';\n\nlet server = null; // eslint-disable-line import/no-mutable-exports\nif (isomorphy.IS_SERVER_SIDE) {\n try {\n const path = webpack.requireWeak('path');\n server = webpack.requireWeak(path.resolve(__dirname, './server'));\n } catch (error) {\n server = null;\n }\n}\n\nexport { default as _ } from 'lodash';\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"],"file":"index.js"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={getDefaultCspSettings:true};Object.defineProperty(exports,"getDefaultCspSettings",{enumerable:true,get:function(){return _server.getDefaultCspSettings}});
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={getDefaultCspSettings:true};exports.default=void 0;Object.defineProperty(exports,"getDefaultCspSettings",{enumerable:true,get:function(){return _server.getDefaultCspSettings}});require("source-map-support/register");var _lodash=_interopRequireDefault(require("lodash"));var _http=_interopRequireDefault(require("http"));var _https=_interopRequireDefault(require("https"));require("raf/polyfill");var _winston=_interopRequireDefault(require("winston"));var _server=_interopRequireWildcard(require("./server"));var _renderer=require("./renderer");var _utils=require("./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]}})});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}/* Polyfill required by ReactJS. */ // Various default settings of server factory (launch() function).
|
|
2
2
|
const DEFAULT_MAX_SSR_ROUNDS=10;const DEFAULT_SSR_TIMEOUT=1000;/**
|
|
3
3
|
* Normalizes a port into a number, string, or false.
|
|
4
4
|
* TODO: Drop this function?
|
|
@@ -6,54 +6,6 @@ const DEFAULT_MAX_SSR_ROUNDS=10;const DEFAULT_SSR_TIMEOUT=1000;/**
|
|
|
6
6
|
* @param {String} value Port name or number.
|
|
7
7
|
* @return Port number (Number), name (String), or false.
|
|
8
8
|
*/function normalizePort(value){const port=_lodash.default.toNumber(value);if(_lodash.default.isFinite(port))return port;/* port number */if(!_lodash.default.isNumber(port))return value;/* named pipe */return false}/**
|
|
9
|
-
* @category Utilities
|
|
10
|
-
* @callback BeforeRenderHook
|
|
11
|
-
* @desc A hook for {@link server}'s `beforeRender` option.
|
|
12
|
-
* @param {object} req Incoming ExpressJS HTTP request, with some extra
|
|
13
|
-
* fields attached:
|
|
14
|
-
* - `.nonce: string` – CSP nonce for `<script>` tags, which should be
|
|
15
|
-
* added to the tags injected into the page to allow them to work.
|
|
16
|
-
* @param {object} config Application config that server wants to
|
|
17
|
-
* inject into generated HTML template.
|
|
18
|
-
* @return {Promise<{
|
|
19
|
-
* configToInject: object,
|
|
20
|
-
* extraScript: Array<object|string>,
|
|
21
|
-
* initialState: object
|
|
22
|
-
* }>} `Promise` resolving to the object with fields:
|
|
23
|
-
* - `[configToInject]` (_Object_) – Optional. The actual config object
|
|
24
|
-
* to inject into the generated page. If not provided, the `config` provided as
|
|
25
|
-
* argument will be injected as is.
|
|
26
|
-
* - `[extraScripts]` (_Array of Objects and/or Strings_) – Optional.
|
|
27
|
-
* Additional scripts to inject into the generated page. Each script given
|
|
28
|
-
* as a string will be injected as is in the end of generated document's
|
|
29
|
-
* `<body>`, just before the main application bundle. Each script given as
|
|
30
|
-
* an object is expected to have two fields: `code` holding the actual code
|
|
31
|
-
* to inject, and `location` specifying where to inject that `code`. The valid
|
|
32
|
-
* locations are exposed via the `server.SCRIPT_LOCATIONS` object. The scripts
|
|
33
|
-
* intended for the same location are injected in the order
|
|
34
|
-
* they are listed in the `extraScript` array.
|
|
35
|
-
* - `[initialState]` (_Object_) – Optional. Initial value of the global
|
|
36
|
-
* state.
|
|
37
|
-
*
|
|
38
|
-
* `server.SCRIPT_LOCATIONS`
|
|
39
|
-
* - `server.SCRIPT_LOCATIONS.BODY_OPEN` – Right after the opening
|
|
40
|
-
* `<body>`
|
|
41
|
-
* tag.
|
|
42
|
-
* - `server.SCRIPT_LOCATIONS.DEFAULT` – In the end of `<body>` block, just
|
|
43
|
-
* before the main application bundle.
|
|
44
|
-
* - `server.SCRIPT_LOCATIONS.HEAD_OPEN` – Right after the opening
|
|
45
|
-
* `<head>` tag.
|
|
46
|
-
*/ /**
|
|
47
|
-
* @category Utilities
|
|
48
|
-
* @func server
|
|
49
|
-
* @desc
|
|
50
|
-
* ```js
|
|
51
|
-
* import { server } from '@dr.pogodin/react-utils`;
|
|
52
|
-
* import webpackConfig from 'path/to/your/webpack.config';
|
|
53
|
-
* server(webpackConfig);
|
|
54
|
-
* // Web server is up, running, and serving the app specified by the provided
|
|
55
|
-
* // Webpack config.
|
|
56
|
-
* ```
|
|
57
9
|
* Creates and launches web-server for ReactJS application. Allows zero
|
|
58
10
|
* or detailed configuration, supports server-side rendering,
|
|
59
11
|
* and development tools, including Hot Module Reloading (HMR).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/server/index.js"],"names":["DEFAULT_MAX_SSR_ROUNDS","DEFAULT_SSR_TIMEOUT","normalizePort","value","port","_","toNumber","isFinite","isNumber","launch","webpackConfig","options","ops","cloneDeep","process","env","PORT","defaults","httpsRedirect","maxSsrRounds","ssrTimeout","staticCacheSize","isUndefined","logger","format","transports","winston","createLogger","level","defaultLoggerLogLevel","combine","splat","timestamp","colorize","printf","message","stack","rest","res","Object","keys","length","JSON","stringify","Console","expressServer","httpServer","https","createServer","cert","key","http","on","error","syscall","bind","isString","code","exit","addr","address","info","NODE_ENV","listen","SCRIPT_LOCATIONS"],"mappings":"4VAAA,uCAEA,sDACA,kDACA,oDAGA,wBAEA,wDAEA,yDACA,oCAGA,sU,o9BATA,mC,CAWA;AACA,KAAMA,CAAAA,sBAAsB,CAAG,EAA/B,CACA,KAAMC,CAAAA,mBAAmB,CAAG,IAA5B,CAEA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAASC,CAAAA,aAAT,CAAuBC,KAAvB,CAA8B,CAC5B,KAAMC,CAAAA,IAAI,CAAGC,gBAAEC,QAAF,CAAWH,KAAX,CAAb,CACA,GAAIE,gBAAEE,QAAF,CAAWH,IAAX,CAAJ,CAAsB,MAAOA,CAAAA,IAAP,CAAa,iBACnC,GAAI,CAACC,gBAAEG,QAAF,CAAWJ,IAAX,CAAL,CAAuB,MAAOD,CAAAA,KAAP,CAAc,gBACrC,MAAO,MACR,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A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zC,OAAO,CAAC4C,IAAR,CAAa,CAAb,EACA,MACF,QACE,KAAML,CAAAA,KAAN,CAVJ,CAYD,CAjBD,EAmBA,iDACAP,UAAU,CAACM,EAAX,CAAc,WAAd,CAA2B,IAAM,CAC/B,KAAMO,CAAAA,IAAI,CAAGb,UAAU,CAACc,OAAX,EAAb,CACA,KAAML,CAAAA,IAAI,CAAGlD,gBAAEmD,QAAF,CAAWG,IAAX,EAAoB,QAAOA,IAAK,EAAhC,CAAqC,QAAOA,IAAI,CAACvD,IAAK,EAAnE,CACAQ,GAAG,CAACW,MAAJ,CAAWsC,IAAX,CAAiB,uBAAsBN,IAAK,OAC1CzC,OAAO,CAACC,GAAR,CAAY+C,QAAS,OADvB,CAED,CALD,EAOAhB,UAAU,CAACiB,MAAX,CAAkBnD,GAAG,CAACR,IAAtB,EAEA,MAAO,CACLyC,aADK,CAELC,UAFK,CAIR,CAEDrC,MAAM,CAACuD,gBAAP,CAA0BA,0BAA1B,C,aAEevD,M","sourcesContent":["import 'source-map-support/register';\n\nimport _ from 'lodash';\nimport http from 'http';\nimport https from 'https';\n\n/* Polyfill required by ReactJS. */\nimport 'raf/polyfill';\n\nimport winston from 'winston';\n\nimport serverFactory from './server';\nimport { SCRIPT_LOCATIONS } from './renderer';\n\nexport { getDefaultCspSettings } from './server';\nexport * from './utils';\n\n// Various default settings of server factory (launch() function).\nconst DEFAULT_MAX_SSR_ROUNDS = 10;\nconst DEFAULT_SSR_TIMEOUT = 1000;\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @ignore\n * @param {String} value Port name or number.\n * @return Port number (Number), name (String), or false.\n */\nfunction normalizePort(value) {\n const port = _.toNumber(value);\n if (_.isFinite(port)) return port; /* port number */\n if (!_.isNumber(port)) return value; /* named pipe */\n return false;\n}\n\n/**\n * @category Utilities\n * @callback BeforeRenderHook\n * @desc A hook for {@link server}'s `beforeRender` option.\n * @param {object} req Incoming ExpressJS HTTP request, with some extra\n * fields attached:\n * - `.nonce: string` – CSP nonce for `<script>` tags, which should be\n * added to the tags injected into the page to allow them to work.\n * @param {object} config Application config that server wants to\n * inject into generated HTML template.\n * @return {Promise<{\n * configToInject: object,\n * extraScript: Array<object|string>,\n * initialState: object\n * }>} `Promise` resolving to the object with fields:\n * - `[configToInject]` (_Object_) – Optional. The actual config object\n * to inject into the generated page. If not provided, the `config` provided as\n * argument will be injected as is.\n * - `[extraScripts]` (_Array of Objects and/or Strings_) – Optional.\n * Additional scripts to inject into the generated page. Each script given\n * as a string will be injected as is in the end of generated document's\n * `<body>`, just before the main application bundle. Each script given as\n * an object is expected to have two fields: `code` holding the actual code\n * to inject, and `location` specifying where to inject that `code`. The valid\n * locations are exposed via the `server.SCRIPT_LOCATIONS` object. The scripts\n * intended for the same location are injected in the order\n * they are listed in the `extraScript` array.\n * - `[initialState]` (_Object_) – Optional. Initial value of the global\n * state.\n *\n * `server.SCRIPT_LOCATIONS`\n * - `server.SCRIPT_LOCATIONS.BODY_OPEN` – Right after the opening\n * `<body>`\n * tag.\n * - `server.SCRIPT_LOCATIONS.DEFAULT` – In the end of `<body>` block, just\n * before the main application bundle.\n * - `server.SCRIPT_LOCATIONS.HEAD_OPEN` – Right after the opening\n * `<head>` tag.\n*/\n\n/**\n * @category Utilities\n * @func server\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils`;\n * import webpackConfig from 'path/to/your/webpack.config';\n * server(webpackConfig);\n * // Web server is up, running, and serving the app specified by the provided\n * // Webpack config.\n * ```\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * See {@link module:ReactGlobalState ReactGlobalState} for some additional\n * notes related to SSR, access to incoming requests during SSR, _etc._\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\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 {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` ⇒ `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel=info] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\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` – the cache key for the response;\n * - `maxage?: number` – the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\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 * @return {Promise<{ expressServer: object, httpServer: object }>} Resolves to\n * an object with created Express and HTTP servers.\n */\nasync function launch(webpackConfig, options) {\n /* Options normalization. */\n const ops = options ? _.cloneDeep(options) : {};\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n _.defaults(ops, {\n httpsRedirect: true,\n maxSsrRounds: DEFAULT_MAX_SSR_ROUNDS,\n ssrTimeout: DEFAULT_SSR_TIMEOUT,\n });\n if (!ops.staticCacheSize) ops.staticCacheSize = 1.e7;\n\n if (_.isUndefined(ops.logger)) {\n const { format, transports } = winston;\n ops.logger = winston.createLogger({\n level: ops.defaultLoggerLogLevel || 'info',\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp}):\\t${message}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack}`;\n return res;\n },\n ),\n ),\n transports: [new transports.Console()],\n });\n }\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer);\n } else httpServer = http.createServer(expressServer);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error) => {\n if (error.syscall !== 'listen') throw error;\n const bind = _.isString(ops.port) ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch (error.code) {\n case 'EACCES':\n ops.logger.error(`${bind} requires elevated privileges`);\n process.exit(1);\n break;\n case 'EADDRINUSE':\n ops.logger.error(`${bind} is already in use`);\n process.exit(1);\n break;\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address();\n const bind = _.isString(addr) ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n\nlaunch.SCRIPT_LOCATIONS = SCRIPT_LOCATIONS;\n\nexport default launch;\n"],"file":"index.js"}
|
|
1
|
+
{"version":3,"sources":["../../../src/server/index.js"],"names":["DEFAULT_MAX_SSR_ROUNDS","DEFAULT_SSR_TIMEOUT","normalizePort","value","port","_","toNumber","isFinite","isNumber","launch","webpackConfig","options","ops","cloneDeep","process","env","PORT","defaults","httpsRedirect","maxSsrRounds","ssrTimeout","staticCacheSize","isUndefined","logger","format","transports","winston","createLogger","level","defaultLoggerLogLevel","combine","splat","timestamp","colorize","printf","message","stack","rest","res","Object","keys","length","JSON","stringify","Console","expressServer","httpServer","https","createServer","cert","key","http","on","error","syscall","bind","isString","code","exit","addr","address","info","NODE_ENV","listen","SCRIPT_LOCATIONS"],"mappings":"4VAAA,uCAEA,sDACA,kDACA,oDAGA,wBAEA,wDAEA,yDACA,oCAGA,sU,o9BATA,mC,CAWA;AACA,KAAMA,CAAAA,sBAAsB,CAAG,EAA/B,CACA,KAAMC,CAAAA,mBAAmB,CAAG,IAA5B,CAEA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAASC,CAAAA,aAAT,CAAuBC,KAAvB,CAA8B,CAC5B,KAAMC,CAAAA,IAAI,CAAGC,gBAAEC,QAAF,CAAWH,KAAX,CAAb,CACA,GAAIE,gBAAEE,QAAF,CAAWH,IAAX,CAAJ,CAAsB,MAAOA,CAAAA,IAAP,CAAa,iBACnC,GAAI,CAACC,gBAAEG,QAAF,CAAWJ,IAAX,CAAL,CAAuB,MAAOD,CAAAA,KAAP,CAAc,gBACrC,MAAO,MACR,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,cAAeM,CAAAA,MAAf,CAAsBC,aAAtB,CAAqCC,OAArC,CAA8C,CAC5C,4BACA,KAAMC,CAAAA,GAAG,CAAGD,OAAO,CAAGN,gBAAEQ,SAAF,CAAYF,OAAZ,CAAH,CAA0B,EAA7C,CACAC,GAAG,CAACR,IAAJ,CAAWF,aAAa,CAACU,GAAG,CAACR,IAAJ,EAAYU,OAAO,CAACC,GAAR,CAAYC,IAAxB,EAAgC,IAAjC,CAAxB,CACAX,gBAAEY,QAAF,CAAWL,GAAX,CAAgB,CACdM,aAAa,CAAE,IADD,CAEdC,YAAY,CAAEnB,sBAFA,CAGdoB,UAAU,CAAEnB,mBAHE,CAAhB,EAKA,GAAI,CAACW,GAAG,CAACS,eAAT,CAA0BT,GAAG,CAACS,eAAJ,CAAsB,IAAtB,CAE1B,GAAIhB,gBAAEiB,WAAF,CAAcV,GAAG,CAACW,MAAlB,CAAJ,CAA+B,CA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b,CAEP,4CACAC,UAAU,CAACM,EAAX,CAAc,OAAd,CAAwBC,KAAD,EAAW,CAChC,GAAIA,KAAK,CAACC,OAAN,GAAkB,QAAtB,CAAgC,KAAMD,CAAAA,KAAN,CAChC,KAAME,CAAAA,IAAI,CAAGlD,gBAAEmD,QAAF,CAAW5C,GAAG,CAACR,IAAf,EAAwB,QAAOQ,GAAG,CAACR,IAAK,EAAxC,CAA6C,QAAOQ,GAAG,CAACR,IAAK,EAA1E,CAEA,6DACA,OAAQiD,KAAK,CAACI,IAAd,EACE,IAAK,QAAL,CACE7C,GAAG,CAACW,MAAJ,CAAW8B,KAAX,CAAkB,GAAEE,IAAK,+BAAzB,EACAzC,OAAO,CAAC4C,IAAR,CAAa,CAAb,EACA,MACF,IAAK,YAAL,CACE9C,GAAG,CAACW,MAAJ,CAAW8B,KAAX,CAAkB,GAAEE,IAAK,oBAAzB,EACAzC,OAAO,CAAC4C,IAAR,CAAa,CAAb,EACA,MACF,QACE,KAAML,CAAAA,KAAN,CAVJ,CAYD,CAjBD,EAmBA,iDACAP,UAAU,CAACM,EAAX,CAAc,WAAd,CAA2B,IAAM,CAC/B,KAAMO,CAAAA,IAAI,CAAGb,UAAU,CAACc,OAAX,EAAb,CACA,KAAML,CAAAA,IAAI,CAAGlD,gBAAEmD,QAAF,CAAWG,IAAX,EAAoB,QAAOA,IAAK,EAAhC,CAAqC,QAAOA,IAAI,CAACvD,IAAK,EAAnE,CACAQ,GAAG,CAACW,MAAJ,CAAWsC,IAAX,CAAiB,uBAAsBN,IAAK,OAC1CzC,OAAO,CAACC,GAAR,CAAY+C,QAAS,OADvB,CAED,CALD,EAOAhB,UAAU,CAACiB,MAAX,CAAkBnD,GAAG,CAACR,IAAtB,EAEA,MAAO,CACLyC,aADK,CAELC,UAFK,CAIR,CAEDrC,MAAM,CAACuD,gBAAP,CAA0BA,0BAA1B,C,aAEevD,M","sourcesContent":["import 'source-map-support/register';\n\nimport _ from 'lodash';\nimport http from 'http';\nimport https from 'https';\n\n/* Polyfill required by ReactJS. */\nimport 'raf/polyfill';\n\nimport winston from 'winston';\n\nimport serverFactory from './server';\nimport { SCRIPT_LOCATIONS } from './renderer';\n\nexport { getDefaultCspSettings } from './server';\nexport * from './utils';\n\n// Various default settings of server factory (launch() function).\nconst DEFAULT_MAX_SSR_ROUNDS = 10;\nconst DEFAULT_SSR_TIMEOUT = 1000;\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @ignore\n * @param {String} value Port name or number.\n * @return Port number (Number), name (String), or false.\n */\nfunction normalizePort(value) {\n const port = _.toNumber(value);\n if (_.isFinite(port)) return port; /* port number */\n if (!_.isNumber(port)) return value; /* named pipe */\n return false;\n}\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * See {@link module:ReactGlobalState ReactGlobalState} for some additional\n * notes related to SSR, access to incoming requests during SSR, _etc._\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\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 {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` ⇒ `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel=info] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\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` – the cache key for the response;\n * - `maxage?: number` – the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\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 * @return {Promise<{ expressServer: object, httpServer: object }>} Resolves to\n * an object with created Express and HTTP servers.\n */\nasync function launch(webpackConfig, options) {\n /* Options normalization. */\n const ops = options ? _.cloneDeep(options) : {};\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n _.defaults(ops, {\n httpsRedirect: true,\n maxSsrRounds: DEFAULT_MAX_SSR_ROUNDS,\n ssrTimeout: DEFAULT_SSR_TIMEOUT,\n });\n if (!ops.staticCacheSize) ops.staticCacheSize = 1.e7;\n\n if (_.isUndefined(ops.logger)) {\n const { format, transports } = winston;\n ops.logger = winston.createLogger({\n level: ops.defaultLoggerLogLevel || 'info',\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp}):\\t${message}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack}`;\n return res;\n },\n ),\n ),\n transports: [new transports.Console()],\n });\n }\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer);\n } else httpServer = http.createServer(expressServer);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error) => {\n if (error.syscall !== 'listen') throw error;\n const bind = _.isString(ops.port) ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch (error.code) {\n case 'EACCES':\n ops.logger.error(`${bind} requires elevated privileges`);\n process.exit(1);\n break;\n case 'EADDRINUSE':\n ops.logger.error(`${bind} is already in use`);\n process.exit(1);\n break;\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address();\n const bind = _.isString(addr) ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n\nlaunch.SCRIPT_LOCATIONS = SCRIPT_LOCATIONS;\n\nexport default launch;\n"],"file":"index.js"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.
|
|
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=_interopRequireDefault(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=_interopRequireDefault(require("react-dom/server"));var _reactHelmet=require("react-helmet");var _reactRouterDom=require("react-router-dom");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=_lodash.default.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
|
|
@@ -55,7 +55,7 @@ chunks:[]};if(App){let markup;const ssrStart=Date.now();for(let round=0;round<op
|
|
|
55
55
|
* Keep in mind, that this encryption is no way secure: as the JS bundle
|
|
56
56
|
* contains decryption key and is able to decode it at the client side.
|
|
57
57
|
* Hovewer, for a number of reasons, encryption of injected data is still
|
|
58
|
-
* better than injection of a plain text. */delete ssrContext.state.dr_pogodin_react_utils___split_components;
|
|
58
|
+
* 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,
|
|
59
59
|
// because unlike all other chunks they are not managed by <CodeSplit>
|
|
60
60
|
// component, thus they are not added to the ssrContext.chunks
|
|
61
61
|
// automatically. Actually, names of these entry chunks should be
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/server/renderer.jsx"],"names":["sanitizedConfig","_","omit","config","SCRIPT_LOCATIONS","BODY_OPEN","DEFAULT","HEAD_OPEN","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","err","prepareCipher","key","Promise","reject","forge","random","getBytes","iv","cipher","createCipher","start","isBrotliAcceptable","req","acceptable","get","ops","split","i","length","type","priority","trim","parseFloat","factory","webpackConfig","options","buildInfo","global","TRU_BUILD_INFO","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","staticCacheSize","CHUNK_GROUPS","defaults","clone","beforeRender","next","cacheRef","data","noCsp","set","send","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","initialState","all","helmet","App","Application","ssrContext","state","cloneDeep","chunks","markup","ssrStart","Date","now","round","maxSsrRounds","ReactDOM","renderToString","dirty","timeout","ssrTimeout","ok","race","allSettled","pending","time","timer","then","Helmet","renderStatic","chunkGroups","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","dr_pogodin_react_utils___split_components","update","util","createBuffer","stringify","CONFIG","ISTATE","finish","INJ","encode64","status","chunkSet","Set","forEach","chunk","asset","add","styleChunkString","scriptChunkString","endsWith","bodyOpenExtraScripts","defaultExtraScripts","headOpenExtraScripts","filter","script","isObject","location","code","join","isString","faviconLink","favicon","title","meta","buffer"],"mappings":"+PAIA,gEAEA,sDACA,sDACA,6DACA,8CACA,kDACA,0BAEA,gEACA,yCACA,gDAEA,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MAAM,CAACsE,IAAP,CAAY/E,QAAZ,EAAH,CAA4B,EAAG;AACnD;AACA,cAAcnB,YAAa;AAC3B,cAAckF,gBAAiB;AAC/B,cAAca,WAAY;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAcV,oBAAoB,EAAI,EAAG;AACzC,mCAAmCxD,GAAG,EAAI,EAAG;AAC7C;AACA;AACA;AACA,gBAAgBpC,OAAO,CAACoB,KAAR,CAAgB,EAAhB,CAAsB,UAASjC,GAAG,CAAC0C,KAAM,GAAG;AAC5D;AACA,4BAA4BmD,GAAI;AAChC;AACA,cAAcU,iBAAkB;AAChC,cAAcG,mBAAmB,EAAI,EAAG;AACxC;AACA,gBA7BM,CA+BAxH,GAAG,CAACiD,IAAJ,CAASE,IAAT,EAEA,GAAIN,QAAJ,CAAc,CACZ,yBAAeM,IAAf,CAAqB,CAACD,KAAD,CAAQmF,MAAR,GAAmB,CACtC,GAAInF,KAAJ,CAAW,KAAMA,CAAAA,KAAN,CACXmF,MAAM,CAAC7E,KAAP,CAAe1C,GAAG,CAAC0C,KAAnB,CAA0B;AAC1BpB,KAAK,CAAC+E,GAAN,CAAUkB,MAAV,CAAkBxF,QAAQ,CAAC1C,GAA3B,CACD,CAJD,CAKD,CACF,CAAC,MAAO+C,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 _ from 'lodash';\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';\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 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\n context={ssrContext}\n location={req.url}\n >\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 cipher.update(forge.util.createBuffer(JSON.stringify({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject || sanitizedConfig,\n ISTATE: ssrContext.state,\n }), '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","_","omit","config","SCRIPT_LOCATIONS","BODY_OPEN","DEFAULT","HEAD_OPEN","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","err","prepareCipher","key","Promise","reject","forge","random","getBytes","iv","cipher","createCipher","start","isBrotliAcceptable","req","acceptable","get","ops","split","i","length","type","priority","trim","parseFloat","factory","webpackConfig","options","buildInfo","global","TRU_BUILD_INFO","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","staticCacheSize","CHUNK_GROUPS","defaults","clone","beforeRender","next","cacheRef","data","noCsp","set","send","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","initialState","all","helmet","App","Application","ssrContext","state","cloneDeep","chunks","markup","ssrStart","Date","now","round","maxSsrRounds","ReactDOM","renderToString","dirty","timeout","ssrTimeout","ok","race","allSettled","pending","time","timer","then","Helmet","renderStatic","chunkGroups","webpackStats","locals","mapValues","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","isObject","location","code","join","isString","faviconLink","favicon","title","meta","buffer"],"mappings":"+PAIA,gEAEA,sDACA,sDACA,6DACA,8CACA,kDACA,0BAEA,gEACA,yCACA,gDACA,iFAEA,kEAEA,sD,6CApBA;AACA;AACA,GAoBA,KAAMA,CAAAA,eAAe,CAAGC,gBAAEC,IAAF,CAAOC,eAAP,CAAe,QAAf,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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G,IAHH,EAIpBC,IAJoB,CAIf,EAJe,CAKxB,CAED,KAAME,CAAAA,WAAW,CAAGlH,GAAG,CAACmH,OAAJ,CAClB,sDADkB,CAEhB,EAFJ,CAIA,KAAMjF,CAAAA,IAAI,CAAI;AACpB;AACA;AACA,cAAcwE,oBAAoB,EAAI,EAAG;AACzC,cAAc7D,MAAM,CAAGA,MAAM,CAACuE,KAAP,CAAahF,QAAb,EAAH,CAA6B,EAAG;AACpD,cAAcS,MAAM,CAAGA,MAAM,CAACwE,IAAP,CAAYjF,QAAZ,EAAH,CAA4B,EAAG;AACnD;AACA,cAAcnB,YAAa;AAC3B,cAAcoF,gBAAiB;AAC/B,cAAca,WAAY;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAcV,oBAAoB,EAAI,EAAG;AACzC,mCAAmC1D,GAAG,EAAI,EAAG;AAC7C;AACA;AACA;AACA,gBAAgBpC,OAAO,CAACoB,KAAR,CAAgB,EAAhB,CAAsB,UAASjC,GAAG,CAAC0C,KAAM,GAAG;AAC5D;AACA,4BAA4BqD,GAAI;AAChC;AACA,cAAcU,iBAAkB;AAChC,cAAcG,mBAAmB,EAAI,EAAG;AACxC;AACA,gBA7BM,CA+BA1H,GAAG,CAACiD,IAAJ,CAASE,IAAT,EAEA,GAAIN,QAAJ,CAAc,CACZ,yBAAeM,IAAf,CAAqB,CAACD,KAAD,CAAQqF,MAAR,GAAmB,CACtC,GAAIrF,KAAJ,CAAW,KAAMA,CAAAA,KAAN,CACXqF,MAAM,CAAC/E,KAAP,CAAe1C,GAAG,CAAC0C,KAAnB,CAA0B;AAC1BpB,KAAK,CAACiF,GAAN,CAAUkB,MAAV,CAAkB1F,QAAQ,CAAC1C,GAA3B,CACD,CAJD,CAKD,CACF,CAAC,MAAO+C,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 _ from 'lodash';\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';\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 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\n context={ssrContext}\n location={req.url}\n >\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,4 +1,4 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=factory;exports.getDefaultCspSettings=getDefaultCspSettings;var _lodash=require("lodash");var _compression=_interopRequireDefault(require("compression"));var _cookieParser=_interopRequireDefault(require("cookie-parser"));var _express=_interopRequireDefault(require("express"));var _serveFavicon=_interopRequireDefault(require("serve-favicon"));var _helmet=_interopRequireDefault(require("helmet"));var _morgan=_interopRequireDefault(require("morgan"));var _requestIp=_interopRequireDefault(require("request-ip"));var _uuid=require("uuid");var _renderer=_interopRequireDefault(require("./renderer"));var _errors=require("./utils/errors");/**
|
|
2
2
|
* Creation of standard ExpressJS server for ReactJS apps.
|
|
3
3
|
*/ /**
|
|
4
4
|
* Default Content Security Policy settings.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"CODES",{enumerable:true,get:function(){return _httpStatusCodes.StatusCodes}});Object.defineProperty(exports,"ERRORS",{enumerable:true,get:function(){return _httpStatusCodes.ReasonPhrases}});exports.assert=assert;exports.fail=fail;Object.defineProperty(exports,"getErrorForCode",{enumerable:true,get:function(){return _httpStatusCodes.getReasonPhrase}});Object.defineProperty(exports,"joi",{enumerable:true,get:function(){return _joi.default}});exports.newError=newError;var _httpStatusCodes=require("http-status-codes");var _joi=_interopRequireDefault(require("joi"));/**
|
|
2
2
|
* @category Utilities
|
|
3
3
|
* @module server/errors
|
|
4
4
|
* @desc
|
|
@@ -1,31 +1,13 @@
|
|
|
1
1
|
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types"));var _Link=_interopRequireDefault(require("../Link"));var _utils=require("../../utils");var _jsxRuntime=require("react/jsx-runtime");// The <Button> component implements a standard button / button-like link.
|
|
2
|
-
var defaultTheme={"context":"
|
|
3
|
-
*
|
|
4
|
-
* @typedef {object} ButtonTheme {@link Button} component theme: a map of CSS
|
|
2
|
+
var defaultTheme={"context":"_33qmle","ad":"JqF7SX","hoc":"_6uVxU-","button":"_2629gm","active":"_2qX90D","disabled":"_24vuTm"};function BaseButton({active,children,disabled,enforceA,onClick,onMouseDown,openNewTab,replace,theme,to}){let className=theme.button;if(active&&theme.active)className+=` ${theme.active}`;if(disabled){if(theme.disabled)className+=` ${theme.disabled}`;return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{className:className,children:children})}if(to){return/*#__PURE__*/(0,_jsxRuntime.jsx)(_Link.default,{className:className,enforceA:enforceA,onClick:onClick,onMouseDown:onMouseDown,openNewTab:openNewTab,replace:replace,to:to,children:children})}return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{className:className,onClick:onClick,onKeyPress:onClick,onMouseDown:onMouseDown,role:"button",tabIndex:0,children:children})}/**
|
|
3
|
+
* Button component theme: a map of CSS
|
|
5
4
|
* class names to append to button elements:
|
|
6
5
|
* @prop {string} [active] to the root element of active button.
|
|
7
6
|
* @prop {string} [button] to the root element of any button.
|
|
8
7
|
* @prop {string} [disabled] to the root element of disabled button.
|
|
9
8
|
*/const ThemedButton=(0,_utils.themed)("Button",["active","button","disabled"],defaultTheme)(BaseButton);/**
|
|
10
|
-
* @category Components
|
|
11
|
-
* @func Button
|
|
12
|
-
* @desc
|
|
13
|
-
* ```js
|
|
14
|
-
* import { Button } from '@dr.pogodin/react-utils';
|
|
15
|
-
* ```
|
|
16
9
|
* Implements themeable buttons, and button-line links (elements which look
|
|
17
10
|
* like buttons, but behave as links) in the same uniform manner.
|
|
18
|
-
*
|
|
19
|
-
* Under the hood, a `<Button>` instance is rendered as:
|
|
20
|
-
* 1. `<div>` when the button is disabled. It helps to ensure exactly
|
|
21
|
-
* the same style of disabled buttons and button-like links.
|
|
22
|
-
* 2. `<Link>` when `to` property is set.
|
|
23
|
-
* This takes care about internal and external links.
|
|
24
|
-
* 3. `<div>` element, otherwise. `<Link>` component could also play the button
|
|
25
|
-
* role, but is more efficient to use `<div>` in this case.
|
|
26
|
-
*
|
|
27
|
-
* **Children:** Component children, if any, are rendered as button content.
|
|
28
|
-
*
|
|
29
11
|
* @param {object} [props] Component props.
|
|
30
12
|
* @param {boolean} [props.active] Set `true` to render the button as
|
|
31
13
|
* active, even if it is not active otherwise.
|
|
@@ -48,22 +30,5 @@ var defaultTheme={"context":"_1orYrC","ad":"_14A3nZ","hoc":"_5EzTm9","button":"_
|
|
|
48
30
|
* or URL.
|
|
49
31
|
* @param {...any} [props....]
|
|
50
32
|
* [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)
|
|
51
|
-
*
|
|
52
|
-
* @example
|
|
53
|
-
* import React from 'react';
|
|
54
|
-
* import { Button } from '@dr.pogodin/react-utils';
|
|
55
|
-
*
|
|
56
|
-
* export default function ButtonDemo() {
|
|
57
|
-
* return (
|
|
58
|
-
* <div>
|
|
59
|
-
* <Button onClick={() => alert('Button Clicked')}>Button</Button>
|
|
60
|
-
* <Button to="https://dr.pogodin.studio" openNewTab>
|
|
61
|
-
* Button-Like Link
|
|
62
|
-
* </Button>
|
|
63
|
-
* <Button disabled>Disabled Button</Button>
|
|
64
|
-
* <Button active>Forced-Active Button</Button>
|
|
65
|
-
* </div>
|
|
66
|
-
* );
|
|
67
|
-
* }
|
|
68
33
|
*/BaseButton.defaultProps={active:false,children:undefined,disabled:false,enforceA:false,onClick:undefined,onMouseDown:undefined,openNewTab:false,replace:false,to:undefined};BaseButton.propTypes={active:_propTypes.default.bool,children:_propTypes.default.node,disabled:_propTypes.default.bool,enforceA:_propTypes.default.bool,onClick:_propTypes.default.func,onMouseDown:_propTypes.default.func,openNewTab:_propTypes.default.bool,replace:_propTypes.default.bool,theme:ThemedButton.themeType.isRequired,to:_propTypes.default.oneOfType([_propTypes.default.object,_propTypes.default.string])};var _default=ThemedButton;exports.default=_default;
|
|
69
34
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/shared/components/Button/index.jsx"],"names":["BaseButton","active","children","disabled","enforceA","onClick","onMouseDown","openNewTab","replace","theme","to","className","button","ThemedButton","defaultTheme","defaultProps","undefined","propTypes","PT","bool","node","func","themeType","isRequired","oneOfType","object","string"],"mappings":"gLAEA,6DAEA,qDAEA,kC,6CANA;gIAUA,QAASA,CAAAA,UAAT,CAAoB,CAClBC,MADkB,CAElBC,QAFkB,CAGlBC,QAHkB,CAIlBC,QAJkB,CAKlBC,OALkB,CAMlBC,WANkB,CAOlBC,UAPkB,CAQlBC,OARkB,CASlBC,KATkB,CAUlBC,EAVkB,CAApB,CAWG,CACD,GAAIC,CAAAA,SAAS,CAAGF,KAAK,CAACG,MAAtB,CACA,GAAIX,MAAM,EAAIQ,KAAK,CAACR,MAApB,CAA4BU,SAAS,EAAK,IAAGF,KAAK,CAACR,MAAO,EAA9B,CAC5B,GAAIE,QAAJ,CAAc,CACZ,GAAIM,KAAK,CAACN,QAAV,CAAoBQ,SAAS,EAAK,IAAGF,KAAK,CAACN,QAAS,EAAhC,CACpB,mBACE,2BAAK,SAAS,CAAEQ,SAAhB,UACGT,QADH,EAIH,CACD,GAAIQ,EAAJ,CAAQ,CACN,mBACE,oBAAC,aAAD,EACE,SAAS,CAAEC,SADb,CAEE,QAAQ,CAAEP,QAFZ,CAGE,OAAO,CAAEC,OAHX,CAIE,WAAW,CAAEC,WAJf,CAKE,UAAU,CAAEC,UALd,CAME,OAAO,CAAEC,OANX,CAOE,EAAE,CAAEE,EAPN,UASGR,QATH,EAYH,CACD,mBACE,2BACE,SAAS,CAAES,SADb,CAEE,OAAO,CAAEN,OAFX,CAGE,UAAU,CAAEA,OAHd,CAIE,WAAW,CAAEC,WAJf,CAKE,IAAI,CAAC,QALP,CAME,QAAQ,CAAE,CANZ,UAQGJ,QARH,EAWH,CAED;AACA;AACA;AACA;AACA;AACA;AACA
|
|
1
|
+
{"version":3,"sources":["../../../../../src/shared/components/Button/index.jsx"],"names":["BaseButton","active","children","disabled","enforceA","onClick","onMouseDown","openNewTab","replace","theme","to","className","button","ThemedButton","defaultTheme","defaultProps","undefined","propTypes","PT","bool","node","func","themeType","isRequired","oneOfType","object","string"],"mappings":"gLAEA,6DAEA,qDAEA,kC,6CANA;gIAUA,QAASA,CAAAA,UAAT,CAAoB,CAClBC,MADkB,CAElBC,QAFkB,CAGlBC,QAHkB,CAIlBC,QAJkB,CAKlBC,OALkB,CAMlBC,WANkB,CAOlBC,UAPkB,CAQlBC,OARkB,CASlBC,KATkB,CAUlBC,EAVkB,CAApB,CAWG,CACD,GAAIC,CAAAA,SAAS,CAAGF,KAAK,CAACG,MAAtB,CACA,GAAIX,MAAM,EAAIQ,KAAK,CAACR,MAApB,CAA4BU,SAAS,EAAK,IAAGF,KAAK,CAACR,MAAO,EAA9B,CAC5B,GAAIE,QAAJ,CAAc,CACZ,GAAIM,KAAK,CAACN,QAAV,CAAoBQ,SAAS,EAAK,IAAGF,KAAK,CAACN,QAAS,EAAhC,CACpB,mBACE,2BAAK,SAAS,CAAEQ,SAAhB,UACGT,QADH,EAIH,CACD,GAAIQ,EAAJ,CAAQ,CACN,mBACE,oBAAC,aAAD,EACE,SAAS,CAAEC,SADb,CAEE,QAAQ,CAAEP,QAFZ,CAGE,OAAO,CAAEC,OAHX,CAIE,WAAW,CAAEC,WAJf,CAKE,UAAU,CAAEC,UALd,CAME,OAAO,CAAEC,OANX,CAOE,EAAE,CAAEE,EAPN,UASGR,QATH,EAYH,CACD,mBACE,2BACE,SAAS,CAAES,SADb,CAEE,OAAO,CAAEN,OAFX,CAGE,UAAU,CAAEA,OAHd,CAIE,WAAW,CAAEC,WAJf,CAKE,IAAI,CAAC,QALP,CAME,QAAQ,CAAE,CANZ,UAQGJ,QARH,EAWH,CAED;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAMW,CAAAA,YAAY,CAAG,kBAAO,QAAP,CAAiB,CACpC,QADoC,CAEpC,QAFoC,CAGpC,UAHoC,CAAjB,CAIlBC,YAJkB,EAIJd,UAJI,CAArB,CAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACAA,UAAU,CAACe,YAAX,CAA0B,CACxBd,MAAM,CAAE,KADgB,CAExBC,QAAQ,CAAEc,SAFc,CAGxBb,QAAQ,CAAE,KAHc,CAIxBC,QAAQ,CAAE,KAJc,CAKxBC,OAAO,CAAEW,SALe,CAMxBV,WAAW,CAAEU,SANW,CAOxBT,UAAU,CAAE,KAPY,CAQxBC,OAAO,CAAE,KARe,CASxBE,EAAE,CAAEM,SAToB,CAA1B,CAYAhB,UAAU,CAACiB,SAAX,CAAuB,CACrBhB,MAAM,CAAEiB,mBAAGC,IADU,CAErBjB,QAAQ,CAAEgB,mBAAGE,IAFQ,CAGrBjB,QAAQ,CAAEe,mBAAGC,IAHQ,CAIrBf,QAAQ,CAAEc,mBAAGC,IAJQ,CAKrBd,OAAO,CAAEa,mBAAGG,IALS,CAMrBf,WAAW,CAAEY,mBAAGG,IANK,CAOrBd,UAAU,CAAEW,mBAAGC,IAPM,CAQrBX,OAAO,CAAEU,mBAAGC,IARS,CASrBV,KAAK,CAAEI,YAAY,CAACS,SAAb,CAAuBC,UATT,CAUrBb,EAAE,CAAEQ,mBAAGM,SAAH,CAAa,CAACN,mBAAGO,MAAJ,CAAYP,mBAAGQ,MAAf,CAAb,CAViB,CAAvB,C,aAaeb,Y","sourcesContent":["// The <Button> component implements a standard button / button-like link.\n\nimport PT from 'prop-types';\n\nimport Link from 'components/Link';\n\nimport { themed } from 'utils';\n\nimport defaultTheme from './style.scss';\n\nfunction BaseButton({\n active,\n children,\n disabled,\n enforceA,\n onClick,\n onMouseDown,\n openNewTab,\n replace,\n theme,\n to,\n}) {\n let className = theme.button;\n if (active && theme.active) className += ` ${theme.active}`;\n if (disabled) {\n if (theme.disabled) className += ` ${theme.disabled}`;\n return (\n <div className={className}>\n {children}\n </div>\n );\n }\n if (to) {\n return (\n <Link\n className={className}\n enforceA={enforceA}\n onClick={onClick}\n onMouseDown={onMouseDown}\n openNewTab={openNewTab}\n replace={replace}\n to={to}\n >\n {children}\n </Link>\n );\n }\n return (\n <div\n className={className}\n onClick={onClick}\n onKeyPress={onClick}\n onMouseDown={onMouseDown}\n role=\"button\"\n tabIndex={0}\n >\n {children}\n </div>\n );\n}\n\n/**\n * Button component theme: a map of CSS\n * class names to append to button elements:\n * @prop {string} [active] to the root element of active button.\n * @prop {string} [button] to the root element of any button.\n * @prop {string} [disabled] to the root element of disabled button.\n */\nconst ThemedButton = themed('Button', [\n 'active',\n 'button',\n 'disabled',\n], defaultTheme)(BaseButton);\n\n/**\n * Implements themeable buttons, and button-line links (elements which look\n * like buttons, but behave as links) in the same uniform manner.\n * @param {object} [props] Component props.\n * @param {boolean} [props.active] Set `true` to render the button as\n * active, even if it is not active otherwise.\n * @param {boolean} [props.disabled] Set `true` to disable the button.\n * @param {boolean} [props.enforceA] When the button is rendered as `<Link>`\n * component, this prop enforces it to be rendered as a simple `<a>` element\n * (external link), rather than the React router's internal link.\n * See `<Link>` documentation to learn when links are rendered as `<a>`\n * by default.\n * @param {function} [props.onClick] Click event handler.\n * @param {function} [props.onMouseDown] Mouse down event handler.\n * @param {boolean} [props.openNewTab] Set `true` to open link in the new tab.\n * @param {boolean} [props.replace] When the button is rendered as\n * `<Link>`, and the target URL is internal, this property tells that\n * the new route should replace the last record in the browser's history,\n * rather than to be pushed as a new entry into the history stack.\n * @param {ButtonTheme} [props.theme] _Ad hoc_ button theme.\n * @param {object|string} [props.to] If specified, the button will be rendered\n * as `<Link>` (if not disabled), and it will point to the specified location\n * or URL.\n * @param {...any} [props....]\n * [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nBaseButton.defaultProps = {\n active: false,\n children: undefined,\n disabled: false,\n enforceA: false,\n onClick: undefined,\n onMouseDown: undefined,\n openNewTab: false,\n replace: false,\n to: undefined,\n};\n\nBaseButton.propTypes = {\n active: PT.bool,\n children: PT.node,\n disabled: PT.bool,\n enforceA: PT.bool,\n onClick: PT.func,\n onMouseDown: PT.func,\n openNewTab: PT.bool,\n replace: PT.bool,\n theme: ThemedButton.themeType.isRequired,\n to: PT.oneOfType([PT.object, PT.string]),\n};\n\nexport default ThemedButton;\n"],"file":"index.js"}
|
|
@@ -1,17 +1,10 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types"));var _utils=require("../../utils");var _jsxRuntime=require("react/jsx-runtime");var defaultTheme={"context":"
|
|
2
|
-
*
|
|
3
|
-
* @typedef {object} CheckboxTheme {@link Checkbox} component theme: a map of
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _propTypes=_interopRequireDefault(require("prop-types"));var _utils=require("../../utils");var _jsxRuntime=require("react/jsx-runtime");var defaultTheme={"context":"_3elv1W","ad":"_38el0G","hoc":"_285jVN","checkbox":"_1OUp4C","container":"_32kN_q","label":"_26M9Hw"};function Checkbox({checked,label,onChange,theme}){return/*#__PURE__*/(0,_jsxRuntime.jsxs)("div",{className:theme.container,children:[label===undefined?null:/*#__PURE__*/(0,_jsxRuntime.jsx)("p",{className:theme.label,children:label}),/*#__PURE__*/(0,_jsxRuntime.jsx)("input",{checked:checked,className:theme.checkbox,onChange:onChange,type:"checkbox"})]})}/**
|
|
2
|
+
* Checkbox component theme: a map of
|
|
4
3
|
* CSS classes to append to its elements:
|
|
5
4
|
* @prop {string} [checkbox] to the underlying checkbox `<input>` element.
|
|
6
5
|
* @prop {string} [container] to the root checkbox element.
|
|
7
6
|
* @prop {string} [label] to the checkbox label element.
|
|
8
7
|
*/const ThemedCheckbox=(0,_utils.themed)("Checkbox",["checkbox","container","label"],defaultTheme)(Checkbox);/**
|
|
9
|
-
* @category Components
|
|
10
|
-
* @func Checkbox
|
|
11
|
-
* @desc
|
|
12
|
-
* ```js
|
|
13
|
-
* import { Checkbox } from '@dr.pogodin/react-utils';
|
|
14
|
-
* ```
|
|
15
8
|
* The `<Checkbox>` component implements themeable checkboxes.
|
|
16
9
|
* @param {object} [props] Component properties.
|
|
17
10
|
* @param {boolean} [props.checked] Checkbox value.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/shared/components/Checkbox/index.jsx"],"names":["Checkbox","checked","label","onChange","theme","container","undefined","checkbox","ThemedCheckbox","defaultTheme","propTypes","PT","bool","string","func","themeType","isRequired","defaultProps"],"mappings":"gLAAA,6DAEA,kC,
|
|
1
|
+
{"version":3,"sources":["../../../../../src/shared/components/Checkbox/index.jsx"],"names":["Checkbox","checked","label","onChange","theme","container","undefined","checkbox","ThemedCheckbox","defaultTheme","propTypes","PT","bool","string","func","themeType","isRequired","defaultProps"],"mappings":"gLAAA,6DAEA,kC,gLAIA,QAASA,CAAAA,QAAT,CAAkB,CAChBC,OADgB,CAEhBC,KAFgB,CAGhBC,QAHgB,CAIhBC,KAJgB,CAAlB,CAKG,CACD,mBACE,4BAAK,SAAS,CAAEA,KAAK,CAACC,SAAtB,WACIH,KAAK,GAAKI,SAAV,CAAsB,IAAtB,cAA6B,yBAAG,SAAS,CAAEF,KAAK,CAACF,KAApB,UAA4BA,KAA5B,EADjC,cAEE,6BACE,OAAO,CAAED,OADX,CAEE,SAAS,CAAEG,KAAK,CAACG,QAFnB,CAGE,QAAQ,CAAEJ,QAHZ,CAIE,IAAI,CAAC,UAJP,EAFF,GAUH,CAED;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAMK,CAAAA,cAAc,CAAG,kBAAO,UAAP,CAAmB,CACxC,UADwC,CAExC,WAFwC,CAGxC,OAHwC,CAAnB,CAIpBC,YAJoB,EAINT,QAJM,CAAvB,CAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACAA,QAAQ,CAACU,SAAT,CAAqB,CACnBT,OAAO,CAAEU,mBAAGC,IADO,CAEnBV,KAAK,CAAES,mBAAGE,MAFS,CAGnBV,QAAQ,CAAEQ,mBAAGG,IAHM,CAInBV,KAAK,CAAEI,cAAc,CAACO,SAAf,CAAyBC,UAJb,CAArB,CAOAhB,QAAQ,CAACiB,YAAT,CAAwB,CACtBhB,OAAO,CAAEK,SADa,CAEtBJ,KAAK,CAAEI,SAFe,CAGtBH,QAAQ,CAAEG,SAHY,CAAxB,C,aAMeE,c","sourcesContent":["import PT from 'prop-types';\n\nimport { themed } from 'utils';\n\nimport defaultTheme from './theme.scss';\n\nfunction Checkbox({\n checked,\n label,\n onChange,\n theme,\n}) {\n return (\n <div className={theme.container}>\n { label === undefined ? null : <p className={theme.label}>{label}</p> }\n <input\n checked={checked}\n className={theme.checkbox}\n onChange={onChange}\n type=\"checkbox\"\n />\n </div>\n );\n}\n\n/**\n * Checkbox component theme: a map of\n * CSS classes to append to its elements:\n * @prop {string} [checkbox] to the underlying checkbox `<input>` element.\n * @prop {string} [container] to the root checkbox element.\n * @prop {string} [label] to the checkbox label element.\n */\nconst ThemedCheckbox = themed('Checkbox', [\n 'checkbox',\n 'container',\n 'label',\n], defaultTheme)(Checkbox);\n\n/**\n * The `<Checkbox>` component implements themeable checkboxes.\n * @param {object} [props] Component properties.\n * @param {boolean} [props.checked] Checkbox value.\n * @param {string} [props.label] Checkbox label.\n * @param {function} [props.onChange] State change handler.\n * @param {CheckboxTheme} [props.theme] _Ad hoc_ theme.\n * @param {...any} [props....]\n * [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties).\n */\nCheckbox.propTypes = {\n checked: PT.bool,\n label: PT.string,\n onChange: PT.func,\n theme: ThemedCheckbox.themeType.isRequired,\n};\n\nCheckbox.defaultProps = {\n checked: undefined,\n label: undefined,\n onChange: undefined,\n};\n\nexport default ThemedCheckbox;\n"],"file":"index.js"}
|