@dr.pogodin/react-utils 1.17.5 → 1.17.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/development/client/index.js.map +1 -1
- package/build/development/client/init.js.map +1 -1
- package/build/development/index.js.map +1 -1
- package/build/development/server/index.js +6 -31
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +64 -3
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +1 -1
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/errors.js.map +1 -1
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/CodeSplit/index.js.map +1 -1
- package/build/development/shared/components/Dropdown/index.js.map +1 -1
- package/build/development/shared/components/GenericLink/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/MetaTags.js.map +1 -1
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/ScalableRect/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/utils/Semaphore.js.map +1 -1
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js +9 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/time.js.map +1 -1
- package/build/production/client/index.js.map +1 -1
- package/build/production/client/init.js.map +1 -1
- package/build/production/index.js.map +1 -1
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/index.js +3 -3
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +11 -3
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +1 -1
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/errors.js.map +1 -1
- package/build/production/shared/components/Button/index.js.map +1 -1
- package/build/production/shared/components/Checkbox/index.js.map +1 -1
- package/build/production/shared/components/CodeSplit/index.js.map +1 -1
- package/build/production/shared/components/Dropdown/index.js.map +1 -1
- package/build/production/shared/components/GenericLink/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Link.js.map +1 -1
- package/build/production/shared/components/MetaTags.js.map +1 -1
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/NavLink.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/ScalableRect/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/utils/Barrier.js.map +1 -1
- package/build/production/shared/utils/Emitter.js.map +1 -1
- package/build/production/shared/utils/Semaphore.js.map +1 -1
- package/build/production/shared/utils/config.js.map +1 -1
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/isomorphy.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +2 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/time.js.map +1 -1
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/package.json +20 -20
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Launch","Application","options","container","document","getElementById","scene","window","ISTATE","dontHydrate","root","render"],"sources":["../../../src/client/index.jsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document, window */\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { BrowserRouter } from 'react-router-dom';\n\n/**\n * Prepares and launches the app at client side.\n * @param {object} Application Root application component\n * @param {object} [options={}] Optional. Additional settings.\n */\nexport default function Launch(Application, options = {}) {\n const container = document.getElementById('react-view');\n const scene = (\n <GlobalStateProvider initialState={window.ISTATE}>\n <BrowserRouter>\n <Application />\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":";;;;;;;AAGA;;AAEA;;AACA;;;;AANA;;AACA;;AAOA;AACA;AACA;AACA;AACA;AACe,SAASA,MAAT,CAAgBC,WAAhB,EAA2C;EAAA,IAAdC,OAAc,uEAAJ,EAAI;EACxD,IAAMC,SAAS,GAAGC,QAAQ,CAACC,cAAT,CAAwB,YAAxB,CAAlB;EACA,IAAMC,KAAK,gBACT,qBAAC,qCAAD;IAAqB,YAAY,EAAEC,MAAM,CAACC,MAA1C;IAAA,uBACE,qBAAC,6BAAD;MAAA,uBACE,qBAAC,WAAD;IADF;EADF,EADF;;EAQA,IAAIN,OAAO,CAACO,WAAZ,EAAyB;IACvB,IAAMC,IAAI,GAAG,
|
|
1
|
+
{"version":3,"file":"index.js","names":["Launch","Application","options","container","document","getElementById","scene","window","ISTATE","dontHydrate","root","createRoot","render","hydrateRoot"],"sources":["../../../src/client/index.jsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document, window */\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { BrowserRouter } from 'react-router-dom';\n\n/**\n * Prepares and launches the app at client side.\n * @param {object} Application Root application component\n * @param {object} [options={}] Optional. Additional settings.\n */\nexport default function Launch(Application, options = {}) {\n const container = document.getElementById('react-view');\n const scene = (\n <GlobalStateProvider initialState={window.ISTATE}>\n <BrowserRouter>\n <Application />\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":";;;;;;;AAGA;;AAEA;;AACA;;;;AANA;;AACA;;AAOA;AACA;AACA;AACA;AACA;AACe,SAASA,MAAT,CAAgBC,WAAhB,EAA2C;EAAA,IAAdC,OAAc,uEAAJ,EAAI;EACxD,IAAMC,SAAS,GAAGC,QAAQ,CAACC,cAAT,CAAwB,YAAxB,CAAlB;EACA,IAAMC,KAAK,gBACT,qBAAC,qCAAD;IAAqB,YAAY,EAAEC,MAAM,CAACC,MAA1C;IAAA,uBACE,qBAAC,6BAAD;MAAA,uBACE,qBAAC,WAAD;IADF;EADF,EADF;;EAQA,IAAIN,OAAO,CAACO,WAAZ,EAAyB;IACvB,IAAMC,IAAI,GAAG,IAAAC,kBAAA,EAAWR,SAAX,CAAb;IACAO,IAAI,CAACE,MAAL,CAAYN,KAAZ;EACD,CAHD,MAGO,IAAAO,mBAAA,EAAYV,SAAZ,EAAuBG,KAAvB;AACR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.js","names":["BUILD_INFO","window","TRU_BUILD_INFO","TRU_KEEP_INJ_SCRIPT","block","document","querySelector","getElementsByTagName","removeChild","publicPath","useServiceWorker","navigator","addEventListener","serviceWorker","register","reg","console","log","INJ","key","data","forge","util","decode64","decipher","cipher","createDecipher","start","iv","slice","update","createBuffer","finish","decodeUtf8","output","eval","CHUNK_GROUPS","CONFIG","ISTATE"],"sources":["../../../src/client/init.js"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global BUILD_INFO, document, window */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\nimport 'node-forge/lib/aes';\n\n/* `BUILD_INFO` is always injected by Webpack build, but this check is needed\n * to adopt the code for usage in tests. */\nif (typeof BUILD_INFO !== 'undefined') {\n window.TRU_BUILD_INFO = BUILD_INFO;\n}\n\n/* Removes data injection script out of the document.\n * The if block is here for test purposes. */\nif (!window.TRU_KEEP_INJ_SCRIPT) {\n const block = document.querySelector('script[id=\"inj\"]');\n if (block) document.getElementsByTagName('body')[0].removeChild(block);\n}\n\n/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */\n/* eslint-disable no-console */\nconst { publicPath, useServiceWorker } = window.TRU_BUILD_INFO;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', async () => {\n try {\n const reg = await navigator\n .serviceWorker.register(`${publicPath}/__service-worker.js`);\n console.log('SW registered:', reg);\n } catch (err) {\n console.log('SW registration failed:', err);\n }\n });\n }\n}\n/* eslint-enable no-console */\n\n/* Decodes data injected at the server side. */\nif (window.INJ) {\n const { key } = window.TRU_BUILD_INFO;\n let data = forge.util.decode64(window.INJ);\n const decipher = forge.cipher.createDecipher('AES-CBC', key);\n decipher.start({ iv: data.slice(0, 32) });\n decipher.update(forge.util.createBuffer(data.slice(32)));\n decipher.finish();\n\n data = forge.util.decodeUtf8(decipher.output.data);\n data = eval(`(${data})`); // eslint-disable-line no-eval\n\n window.CHUNK_GROUPS = data.CHUNK_GROUPS;\n window.CONFIG = data.CONFIG;\n window.ISTATE = data.ISTATE;\n} else {\n // This is possible when the client-side bundle is launched as a stand-alone\n // precompiled website, rather than served by react-utils' based server.\n window.CHUNK_GROUPS = {};\n window.CONFIG = {};\n}\n"],"mappings":";;;;;;;;AAQA;;AACA;;AATA;AACA;AACA;;AAEA;AAEA;AACA;;AAIA;AACA;AACA,IAAI,OAAOA,UAAP,KAAsB,WAA1B,EAAuC;EACrCC,MAAM,CAACC,cAAP,GAAwBF,UAAxB;AACD;AAED;AACA;;;AACA,IAAI,CAACC,MAAM,CAACE,mBAAZ,EAAiC;EAC/B,IAAMC,KAAK,GAAGC,QAAQ,CAACC,aAAT,CAAuB,kBAAvB,CAAd;EACA,IAAIF,KAAJ,EAAWC,QAAQ,CAACE,oBAAT,CAA8B,MAA9B,EAAsC,CAAtC,EAAyCC,WAAzC,CAAqDJ,KAArD;AACZ;AAED;;AACA;;;AACA,4BAAyCH,MAAM,CAACC,cAAhD;AAAA,IAAQO,UAAR,yBAAQA,UAAR;AAAA,IAAoBC,gBAApB,yBAAoBA,gBAApB;;AACA,IAAIA,gBAAJ,EAAsB;EACpB,cAAsBT,MAAtB;EAAA,IAAQU,SAAR,WAAQA,SAAR;;EACA,IAAI,mBAAmBA,SAAvB,EAAkC;IAChCV,MAAM,CAACW,gBAAP,CAAwB,MAAxB,uFAAgC;MAAA;MAAA;QAAA;UAAA;YAAA;cAAA;cAAA;cAAA,OAEVD,SAAS,CACxBE,aADe,CACDC,QADC,WACWL,UADX,0BAFU;;YAAA;cAEtBM,GAFsB;cAI5BC,OAAO,CAACC,GAAR,CAAY,gBAAZ,EAA8BF,GAA9B;cAJ4B;cAAA;;YAAA;cAAA;cAAA;cAM5BC,OAAO,CAACC,GAAR,CAAY,yBAAZ;;YAN4B;YAAA;cAAA;UAAA;QAAA;MAAA;IAAA,CAAhC;EASD;AACF;AACD;;AAEA;;;AACA,IAAIhB,MAAM,CAACiB,GAAX,EAAgB;EACd,IAAQC,GAAR,GAAgBlB,MAAM,CAACC,cAAvB,CAAQiB,GAAR;;EACA,IAAIC,IAAI,GAAGC,
|
|
1
|
+
{"version":3,"file":"init.js","names":["BUILD_INFO","window","TRU_BUILD_INFO","TRU_KEEP_INJ_SCRIPT","block","document","querySelector","getElementsByTagName","removeChild","publicPath","useServiceWorker","navigator","addEventListener","serviceWorker","register","reg","console","log","INJ","key","data","forge","util","decode64","decipher","cipher","createDecipher","start","iv","slice","update","createBuffer","finish","decodeUtf8","output","eval","CHUNK_GROUPS","CONFIG","ISTATE"],"sources":["../../../src/client/init.js"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global BUILD_INFO, document, window */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\nimport 'node-forge/lib/aes';\n\n/* `BUILD_INFO` is always injected by Webpack build, but this check is needed\n * to adopt the code for usage in tests. */\nif (typeof BUILD_INFO !== 'undefined') {\n window.TRU_BUILD_INFO = BUILD_INFO;\n}\n\n/* Removes data injection script out of the document.\n * The if block is here for test purposes. */\nif (!window.TRU_KEEP_INJ_SCRIPT) {\n const block = document.querySelector('script[id=\"inj\"]');\n if (block) document.getElementsByTagName('body')[0].removeChild(block);\n}\n\n/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */\n/* eslint-disable no-console */\nconst { publicPath, useServiceWorker } = window.TRU_BUILD_INFO;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', async () => {\n try {\n const reg = await navigator\n .serviceWorker.register(`${publicPath}/__service-worker.js`);\n console.log('SW registered:', reg);\n } catch (err) {\n console.log('SW registration failed:', err);\n }\n });\n }\n}\n/* eslint-enable no-console */\n\n/* Decodes data injected at the server side. */\nif (window.INJ) {\n const { key } = window.TRU_BUILD_INFO;\n let data = forge.util.decode64(window.INJ);\n const decipher = forge.cipher.createDecipher('AES-CBC', key);\n decipher.start({ iv: data.slice(0, 32) });\n decipher.update(forge.util.createBuffer(data.slice(32)));\n decipher.finish();\n\n data = forge.util.decodeUtf8(decipher.output.data);\n data = eval(`(${data})`); // eslint-disable-line no-eval\n\n window.CHUNK_GROUPS = data.CHUNK_GROUPS;\n window.CONFIG = data.CONFIG;\n window.ISTATE = data.ISTATE;\n} else {\n // This is possible when the client-side bundle is launched as a stand-alone\n // precompiled website, rather than served by react-utils' based server.\n window.CHUNK_GROUPS = {};\n window.CONFIG = {};\n}\n"],"mappings":";;;;;;;;AAQA;;AACA;;AATA;AACA;AACA;;AAEA;AAEA;AACA;;AAIA;AACA;AACA,IAAI,OAAOA,UAAP,KAAsB,WAA1B,EAAu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IAAEC,EAAE,EAAER,IAAI,CAACS,KAAL,CAAW,CAAX,EAAc,EAAd;EAAN,CAAf;EACAL,QAAQ,CAACM,MAAT,CAAgBT,cAAA,CAAMC,IAAN,CAAWS,YAAX,CAAwBX,IAAI,CAACS,KAAL,CAAW,EAAX,CAAxB,CAAhB;EACAL,QAAQ,CAACQ,MAAT;EAEAZ,IAAI,GAAGC,cAAA,CAAMC,IAAN,CAAWW,UAAX,CAAsBT,QAAQ,CAACU,MAAT,CAAgBd,IAAtC,CAAP;EACAA,IAAI,GAAGe,IAAI,YAAKf,IAAL,OAAX,CATc,CASY;;EAE1BnB,MAAM,CAACmC,YAAP,GAAsBhB,IAAI,CAACgB,YAA3B;EACAnC,MAAM,CAACoC,MAAP,GAAgBjB,IAAI,CAACiB,MAArB;EACApC,MAAM,CAACqC,MAAP,GAAgBlB,IAAI,CAACkB,MAArB;AACD,CAdD,MAcO;EACL;EACA;EACArC,MAAM,CAACmC,YAAP,GAAsB,EAAtB;EACAnC,MAAM,CAACoC,MAAP,GAAgB,EAAhB;AACD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["server","webpack","requireWeak","__dirname"],"sources":["../../src/index.js"],"sourcesContent":["import 'styles/global.scss';\n\nimport { webpack } from 'utils';\n\nconst server = webpack.requireWeak('./server', __dirname);\n\nexport { default as api } from 'axios';\nexport * as PT from 'prop-types';\n\nexport {\n getGlobalState,\n getSsrContext,\n GlobalStateProvider,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\nexport * from 'utils';\n\nexport { server };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA;;AAiBA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AAbA;;;;;;AAGA;;AASA;;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;;;;;AAdA,MAAMA,MAAM,GAAGC,
|
|
1
|
+
{"version":3,"file":"index.js","names":["server","webpack","requireWeak","__dirname"],"sources":["../../src/index.js"],"sourcesContent":["import 'styles/global.scss';\n\nimport { webpack } from 'utils';\n\nconst server = webpack.requireWeak('./server', __dirname);\n\nexport { default as api } from 'axios';\nexport * as PT from 'prop-types';\n\nexport {\n getGlobalState,\n getSsrContext,\n GlobalStateProvider,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\nexport * from 'utils';\n\nexport { server };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA;;AAiBA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AAbA;;;;;;AAGA;;AASA;;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;;;;;AAdA,MAAMA,MAAM,GAAGC,cAAA,CAAQC,WAAR,aAAgCC,SAAhC,CAAf"}
|
|
@@ -26,8 +26,6 @@ var _https = _interopRequireDefault(require("https"));
|
|
|
26
26
|
|
|
27
27
|
require("raf/polyfill");
|
|
28
28
|
|
|
29
|
-
var _winston = _interopRequireDefault(require("winston"));
|
|
30
|
-
|
|
31
29
|
var _server = _interopRequireWildcard(require("./server"));
|
|
32
30
|
|
|
33
31
|
var _renderer = require("./renderer");
|
|
@@ -143,7 +141,7 @@ function normalizePort(value) {
|
|
|
143
141
|
* of `.beforeRender` hook.
|
|
144
142
|
* - `upgradeInsecureRequests` directive is removed in development mode,
|
|
145
143
|
* to simplify local testing with http requests.
|
|
146
|
-
* @param {string} [options.defaultLoggerLogLevel=info] Log level for
|
|
144
|
+
* @param {string} [options.defaultLoggerLogLevel='info'] Log level for
|
|
147
145
|
* the default logger, which is created if no `logger` option provided.
|
|
148
146
|
* @param {boolean} [options.devMode] Pass in `true` to start the server in
|
|
149
147
|
* development mode.
|
|
@@ -198,30 +196,9 @@ async function launch(webpackConfig, options) {
|
|
|
198
196
|
httpsRedirect: true
|
|
199
197
|
});
|
|
200
198
|
|
|
201
|
-
if (
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
transports
|
|
205
|
-
} = _winston.default;
|
|
206
|
-
ops.logger = _winston.default.createLogger({
|
|
207
|
-
level: ops.defaultLoggerLogLevel || 'info',
|
|
208
|
-
format: format.combine(format.splat(), format.timestamp(), format.colorize(), format.printf(({
|
|
209
|
-
level,
|
|
210
|
-
message,
|
|
211
|
-
timestamp,
|
|
212
|
-
stack,
|
|
213
|
-
...rest
|
|
214
|
-
}) => {
|
|
215
|
-
let res = `${level}\t(at ${timestamp}):\t${message}`;
|
|
216
|
-
|
|
217
|
-
if (Object.keys(rest).length) {
|
|
218
|
-
res += `\n${JSON.stringify(rest, null, 2)}`;
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
if (stack) res += `\n${stack}`;
|
|
222
|
-
return res;
|
|
223
|
-
})),
|
|
224
|
-
transports: [new transports.Console()]
|
|
199
|
+
if (ops.logger === undefined) {
|
|
200
|
+
ops.logger = (0, _renderer.newDefaultLogger)({
|
|
201
|
+
defaultLogLevel: ops.defaultLoggerLogLevel
|
|
225
202
|
});
|
|
226
203
|
}
|
|
227
204
|
/* Creates servers, resolves and sets the port. */
|
|
@@ -247,13 +224,11 @@ async function launch(webpackConfig, options) {
|
|
|
247
224
|
switch (error.code) {
|
|
248
225
|
case 'EACCES':
|
|
249
226
|
ops.logger.error(`${bind} requires elevated privileges`);
|
|
250
|
-
process.exit(1);
|
|
251
|
-
break;
|
|
227
|
+
return process.exit(1);
|
|
252
228
|
|
|
253
229
|
case 'EADDRINUSE':
|
|
254
230
|
ops.logger.error(`${bind} is already in use`);
|
|
255
|
-
process.exit(1);
|
|
256
|
-
break;
|
|
231
|
+
return process.exit(1);
|
|
257
232
|
|
|
258
233
|
default:
|
|
259
234
|
throw error;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["normalizePort","value","port","launch","webpackConfig","options","ops","process","env","PORT","httpsRedirect","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","code","exit","addr","address","info","NODE_ENV","listen","SCRIPT_LOCATIONS"],"sources":["../../../src/server/index.js"],"sourcesContent":["import 'source-map-support/register';\n\nimport {\n cloneDeep,\n defaults,\n isFinite,\n isNumber,\n isUndefined,\n isString,\n toNumber,\n} from 'lodash';\n\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/**\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 * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\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, { httpsRedirect: true });\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"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;;AAEA;;AAUA;;AACA;;AAGA;;AAEA;;AAEA;;AACA;;AAGA;;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;;;;;AATA;;AAWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,aAAT,CAAuBC,KAAvB,EAA8B;EAC5B,MAAMC,IAAI,GAAG,sBAASD,KAAT,CAAb;EACA,IAAI,sBAASC,IAAT,CAAJ,EAAoB,OAAOA,IAAP;EAAa;;EACjC,IAAI,CAAC,sBAASA,IAAT,CAAL,EAAqB,OAAOD,KAAP;EAAc;;EACnC,OAAO,KAAP;AACD;AAED;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;AACA;;;AACA,eAAeE,MAAf,CAAsBC,aAAtB,EAAqCC,OAArC,EAA8C;EAC5C;EACA,MAAMC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vB;EAED,CALD;EAOAf,UAAU,CAACgB,MAAX,CAAkB5C,GAAG,CAACJ,IAAtB;EAEA,OAAO;IACL+B,aADK;IAELC;EAFK,CAAP;AAID;;AAED/B,MAAM,CAACgD,gBAAP,GAA0BA,0BAA1B;eAEehD,M"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["normalizePort","value","port","toNumber","isFinite","isNumber","launch","webpackConfig","options","ops","cloneDeep","process","env","PORT","defaults","httpsRedirect","logger","undefined","newDefaultLogger","defaultLogLevel","defaultLoggerLogLevel","expressServer","serverFactory","httpServer","https","createServer","cert","key","http","on","error","syscall","bind","isString","code","exit","addr","address","info","NODE_ENV","listen","SCRIPT_LOCATIONS"],"sources":["../../../src/server/index.js"],"sourcesContent":["import 'source-map-support/register';\n\nimport {\n cloneDeep,\n defaults,\n isFinite,\n isNumber,\n isString,\n toNumber,\n} from 'lodash';\n\nimport http from 'http';\nimport https from 'https';\n\n/* Polyfill required by ReactJS. */\nimport 'raf/polyfill';\n\nimport serverFactory from './server';\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nexport { getDefaultCspSettings } from './server';\nexport * from './utils';\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 * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\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, { httpsRedirect: true });\n\n if (ops.logger === undefined) {\n ops.logger = newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\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 return process.exit(1);\n case 'EADDRINUSE':\n ops.logger.error(`${bind} is already in use`);\n return process.exit(1);\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"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;;AAEA;;AASA;;AACA;;AAGA;;AAEA;;AACA;;AAGA;;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;;;;;AAPA;;AASA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,aAAT,CAAuBC,KAAvB,EAA8B;EAC5B,MAAMC,IAAI,GAAG,IAAAC,gBAAA,EAASF,KAAT,CAAb;EACA,IAAI,IAAAG,gBAAA,EAASF,IAAT,CAAJ,EAAoB,OAAOA,IAAP;EAAa;;EACjC,IAAI,CAAC,IAAAG,gBAAA,EAASH,IAAT,CAAL,EAAqB,OAAOD,KAAP;EAAc;;EACnC,OAAO,KAAP;AACD;AAED;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;AACA;;;AACA,eAAeK,MAAf,CAAsBC,aAAtB,EAAqCC,OAArC,EAA8C;EAC5C;EACA,MAAMC,GAAG,GAAGD,OAAO,GAAG,IAAAE,iBAAA,EAAUF,OAAV,CAAH,GAAwB,EAA3C;EACAC,GAAG,CAACP,IAAJ,GAAWF,aAAa,CAACS,GAAG,CAACP,IAAJ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B;QACA,OAAOrB,OAAO,CAACwB,IAAR,CAAa,CAAb,CAAP;;MACF;QACE,MAAML,KAAN;IARJ;EAUD,CAfD;EAiBA;;EACAP,UAAU,CAACM,EAAX,CAAc,WAAd,EAA2B,MAAM;IAC/B,MAAMO,IAAI,GAAGb,UAAU,CAACc,OAAX,EAAb;IACA,MAAML,IAAI,GAAG,IAAAC,gBAAA,EAASG,IAAT,IAAkB,QAAOA,IAAK,EAA9B,GAAmC,QAAOA,IAAI,CAAClC,IAAK,EAAjE;IACAO,GAAG,CAACO,MAAJ,CAAWsB,IAAX,CAAiB,uBAAsBN,IAAK,OAC1CrB,OAAO,CAACC,GAAR,CAAY2B,QAAS,OADvB;EAED,CALD;EAOAhB,UAAU,CAACiB,MAAX,CAAkB/B,GAAG,CAACP,IAAtB;EAEA,OAAO;IACLmB,aADK;IAELE;EAFK,CAAP;AAID;;AAEDjB,MAAM,CAACmC,gBAAP,GAA0BA,0BAA1B;eAEenC,M"}
|
|
@@ -8,6 +8,7 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
8
8
|
exports.SCRIPT_LOCATIONS = void 0;
|
|
9
9
|
exports.default = factory;
|
|
10
10
|
exports.isBrotliAcceptable = isBrotliAcceptable;
|
|
11
|
+
exports.newDefaultLogger = newDefaultLogger;
|
|
11
12
|
|
|
12
13
|
var _stream = require("stream");
|
|
13
14
|
|
|
@@ -35,6 +36,8 @@ var _serializeJavascript = _interopRequireDefault(require("serialize-javascript"
|
|
|
35
36
|
|
|
36
37
|
var _time = _interopRequireDefault(require("../shared/utils/time"));
|
|
37
38
|
|
|
39
|
+
var _winston = _interopRequireDefault(require("winston"));
|
|
40
|
+
|
|
38
41
|
var _Cache = _interopRequireDefault(require("./Cache"));
|
|
39
42
|
|
|
40
43
|
var _jsxRuntime = require("react/jsx-runtime");
|
|
@@ -181,6 +184,42 @@ function groupExtraScripts(scripts = []) {
|
|
|
181
184
|
|
|
182
185
|
return res;
|
|
183
186
|
}
|
|
187
|
+
/**
|
|
188
|
+
* Creates a new default (Winston) logger.
|
|
189
|
+
* @param {object} [options={}]
|
|
190
|
+
* @param {string} [options.defaultLogLevel='info']
|
|
191
|
+
* @return {object}
|
|
192
|
+
*/
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
function newDefaultLogger({
|
|
196
|
+
defaultLogLevel = 'info'
|
|
197
|
+
} = {}) {
|
|
198
|
+
const {
|
|
199
|
+
format,
|
|
200
|
+
transports
|
|
201
|
+
} = _winston.default;
|
|
202
|
+
return _winston.default.createLogger({
|
|
203
|
+
level: defaultLogLevel,
|
|
204
|
+
format: format.combine(format.splat(), format.timestamp(), format.colorize(), format.printf(({
|
|
205
|
+
level,
|
|
206
|
+
message,
|
|
207
|
+
timestamp,
|
|
208
|
+
stack,
|
|
209
|
+
...rest
|
|
210
|
+
}) => {
|
|
211
|
+
let res = `${level}\t(at ${timestamp}):\t${message}`;
|
|
212
|
+
|
|
213
|
+
if (Object.keys(rest).length) {
|
|
214
|
+
res += `\n${JSON.stringify(rest, null, 2)}`;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
if (stack) res += `\n${stack}`;
|
|
218
|
+
return res;
|
|
219
|
+
})),
|
|
220
|
+
transports: [new transports.Console()]
|
|
221
|
+
});
|
|
222
|
+
}
|
|
184
223
|
/**
|
|
185
224
|
* Creates the middleware.
|
|
186
225
|
* @param {object} webpackConfig
|
|
@@ -220,7 +259,16 @@ function factory(webpackConfig, options) {
|
|
|
220
259
|
maxSsrRounds: 10,
|
|
221
260
|
ssrTimeout: 1000,
|
|
222
261
|
staticCacheSize: 1.e7
|
|
223
|
-
});
|
|
262
|
+
}); // Note: in normal use the default logger is created and set in the root
|
|
263
|
+
// server function, and this initialization is for testing uses, where
|
|
264
|
+
// renderer is imported directly.
|
|
265
|
+
|
|
266
|
+
if (ops.logger === undefined) {
|
|
267
|
+
ops.logger = newDefaultLogger({
|
|
268
|
+
defaultLogLevel: ops.defaultLoggerLogLevel
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
224
272
|
const buildInfo = ops.buildInfo || getBuildInfo(webpackConfig.context);
|
|
225
273
|
global.TRU_BUILD_INFO = buildInfo; // publicPath from webpack.output has a trailing slash at the end.
|
|
226
274
|
|
|
@@ -324,13 +372,26 @@ function factory(webpackConfig, options) {
|
|
|
324
372
|
for (let round = 0; round < ops.maxSsrRounds; ++round) {
|
|
325
373
|
stream = await renderPass(); // eslint-disable-line no-await-in-loop
|
|
326
374
|
|
|
327
|
-
if (!ssrContext.dirty)
|
|
375
|
+
if (!ssrContext.dirty) {
|
|
376
|
+
ops.logger.info(`SSR completed in ${round + 1} rounds`);
|
|
377
|
+
break;
|
|
378
|
+
}
|
|
328
379
|
/* eslint-disable no-await-in-loop */
|
|
329
380
|
|
|
381
|
+
|
|
330
382
|
const timeout = ops.ssrTimeout + ssrStart - Date.now();
|
|
331
383
|
const ok = timeout > 0 && (await Promise.race([Promise.allSettled(ssrContext.pending), _time.default.timer(timeout).then(() => false)]));
|
|
332
|
-
|
|
384
|
+
|
|
385
|
+
if (!ok) {
|
|
386
|
+
ops.logger.warn(`SSR timed out (${ops.ssrTimeout}sec)`);
|
|
387
|
+
break;
|
|
388
|
+
}
|
|
333
389
|
/* eslint-enable no-await-in-loop */
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
if (round + 1 === ops.maxSsrRounds) {
|
|
393
|
+
ops.logger.warn(`SSR reached max number of rounds ${ops.maxSsrRounds}`);
|
|
394
|
+
}
|
|
334
395
|
}
|
|
335
396
|
|
|
336
397
|
App = '';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.js","names":["sanitizedConfig","config","SCRIPT_LOCATIONS","BODY_OPEN","DEFAULT","HEAD_OPEN","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","err","prepareCipher","key","Promise","reject","forge","random","getBytes","iv","cipher","createCipher","start","isBrotliAcceptable","req","acceptable","get","ops","split","i","length","type","priority","trim","parseFloat","groupExtraScripts","scripts","script","code","location","undefined","Error","factory","webpackConfig","options","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","buildInfo","global","TRU_BUILD_INFO","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cacheRef","data","buffer","status","noCsp","send","done","failed","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","initialState","all","helmet","App","Application","ssrContext","state","chunks","stream","ssrStart","Date","now","renderPass","pipeableStream","onAllReady","onError","round","dirty","timeout","ok","race","allSettled","pending","time","timer","then","pipe","Writable","write","chunk","_","Helmet","renderStatic","chunkGroups","webpackStats","locals","toJson","namedChunkGroups","item","assets","map","name","dr_pogodin_react_utils___split_components","payload","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta"],"sources":["../../../src/server/renderer.jsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Writable } from 'stream';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport {\n clone,\n cloneDeep,\n defaults,\n isString,\n get,\n mapValues,\n omit,\n} from 'lodash';\n\nimport config from 'config';\nimport forge from 'node-forge';\nimport fs from 'fs';\nimport path from 'path';\nimport { brotliCompress, brotliDecompress } from 'zlib';\n\nimport { renderToPipeableStream } from 'react-dom/server';\nimport { Helmet } from 'react-helmet';\nimport { StaticRouter } from 'react-router-dom/server';\nimport serializeJs from 'serialize-javascript';\n\nimport time from 'utils/time';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\nexport const SCRIPT_LOCATIONS = {\n BODY_OPEN: 'BODY_OPEN',\n DEFAULT: 'DEFAULT',\n HEAD_OPEN: 'HEAD_OPEN',\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @ignore\n * @param {String} context Webpack context path used during the build.\n * @return {Object} Resolves to the build-time information.\n */\nfunction getBuildInfo(context) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url));\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @ignore\n * @param {string} buildDir\n * @return {object}\n */\nfunction readChunkGroupsJson(buildDir) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url));\n } catch (err) {\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @ignore\n * @param {String} key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return {Promise} Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key) {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param {object} req\n * @return {boolean}\n * @ignore\n */\nexport function isBrotliAcceptable(req) {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (let i = 0; i < ops.length; ++i) {\n const [type, priority] = ops[i].trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (let i = 0; i < scripts.length; ++i) {\n const script = scripts[i];\n if (isString(script)) {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (res[script.location] !== undefined) {\n res[script.location] += script.code;\n } else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates the middleware.\n * @param {object} webpackConfig\n * @param {object} options Additional options:\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {object} [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param {boolean} [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param {boolean} [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` – 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 * @return {function} Created middleware.\n */\nexport default function factory(webpackConfig, options) {\n const ops = defaults(clone(options), {\n beforeRender: () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n const buildInfo = ops.buildInfo || getBuildInfo(webpackConfig.context);\n global.TRU_BUILD_INFO = buildInfo;\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath}manifest.json\">` : '';\n\n const cache = ops.staticCacheController\n ? new Cache(ops.staticCacheSize) : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath);\n\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n let cacheRef;\n if (cache) {\n cacheRef = ops.staticCacheController(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n h = h.replace(regex, req.nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n ops.beforeRender(req, sanitizedConfig),\n prepareCipher(buildInfo.key),\n ]);\n\n let helmet;\n\n /* Optional server-side rendering. */\n let App = ops.Application;\n const ssrContext = {\n req,\n state: cloneDeep(initialState || {}),\n\n // Array of chunk names encountered during the rendering.\n chunks: [],\n };\n let stream;\n if (App) {\n const ssrStart = Date.now();\n\n const renderPass = async () => {\n ssrContext.chunks = [];\n return new Promise((resolve, reject) => {\n const pipeableStream = renderToPipeableStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <App />\n </StaticRouter>\n </GlobalStateProvider>,\n {\n onAllReady: () => resolve(pipeableStream),\n onError: reject,\n },\n );\n });\n };\n\n for (let round = 0; round < ops.maxSsrRounds; ++round) {\n stream = await renderPass(); // eslint-disable-line no-await-in-loop\n\n if (!ssrContext.dirty) break;\n\n /* eslint-disable no-await-in-loop */\n const timeout = ops.ssrTimeout + ssrStart - Date.now();\n const ok = timeout > 0 && await Promise.race([\n Promise.allSettled(ssrContext.pending),\n time.timer(timeout).then(() => false),\n ]);\n if (!ok) break;\n /* eslint-enable no-await-in-loop */\n }\n\n App = '';\n stream.pipe(new Writable({\n write: (chunk, _, done) => {\n App += chunk.toString();\n done();\n },\n }));\n\n /* This takes care about server-side rendering of page title and meta tags\n * (still demands injection into HTML template, which happens below). */\n helmet = Helmet.renderStatic();\n }\n\n let chunkGroups;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets.map(({ name }) => name),\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n delete ssrContext.state.dr_pogodin_react_utils___split_components;\n\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject || sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n const chunkSet = new Set();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon ? (\n '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n ) : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet ? helmet.title.toString() : ''}\n ${helmet ? helmet.meta.toString() : ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${App || ''}</div>\n <script\n id=\"inj\"\n type=\"application/javascript\"\n ${ops.noCsp ? '' : `nonce=\"${req.nonce}\"`}\n >\n window.INJ=\"${INJ}\"\n </script>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n res.send(html);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n buffer.nonce = req.nonce; // eslint-disable-line no-param-reassign\n cache.add({ buffer, status }, cacheRef.key);\n done();\n }\n });\n });\n }\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;AAIA;;AAEA;;AAEA;;AAUA;;AACA;;AACA;;AACA;;AACA;;AAEA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;;;AA/BA;AACA;AACA;AA+BA,MAAMA,eAAe,GAAG,kBAAKC,eAAL,EAAa,QAAb,CAAxB;AAEO,MAAMC,gBAAgB,GAAG;EAC9BC,SAAS,EAAE,WADmB;EAE9BC,OAAO,EAAE,SAFqB;EAG9BC,SAAS,EAAE;AAHmB,CAAzB;AAMP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AACA,SAASC,YAAT,CAAsBC,OAAtB,EAA+B;EAC7B,MAAMC,GAAG,GAAGC,cAAKC,OAAL,CAAaH,OAAb,EAAsB,aAAtB,CAAZ;;EACA,OAAOI,IAAI,CAACC,KAAL,CAAWC,YAAGC,YAAH,CAAgBN,GAAhB,CAAX,CAAP;AACD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACA,SAASO,mBAAT,CAA6BC,QAA7B,EAAuC;EACrC,MAAMR,GAAG,GAAGC,cAAKC,OAAL,CAAaM,QAAb,EAAuB,uBAAvB,CAAZ;;EACA,IAAIC,GAAJ;;EACA,IAAI;IACFA,GAAG,GAAGN,IAAI,CAACC,KAAL,CAAWC,YAAGC,YAAH,CAAgBN,GAAhB,CAAX,CAAN;EACD,CAFD,CAEE,OAAOU,GAAP,EAAY;IACZ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;IACD;EACF,CAjPD;AAkPD"}
|
|
1
|
+
{"version":3,"file":"renderer.js","names":["sanitizedConfig","omit","config","SCRIPT_LOCATIONS","BODY_OPEN","DEFAULT","HEAD_OPEN","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","err","prepareCipher","key","Promise","reject","forge","random","getBytes","iv","cipher","createCipher","start","isBrotliAcceptable","req","acceptable","get","ops","split","i","length","type","priority","trim","parseFloat","groupExtraScripts","scripts","script","isString","code","location","undefined","Error","newDefaultLogger","defaultLogLevel","format","transports","winston","createLogger","level","combine","splat","timestamp","colorize","printf","message","stack","rest","Object","keys","stringify","Console","factory","webpackConfig","options","defaults","clone","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","global","TRU_BUILD_INFO","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cacheRef","data","buffer","status","noCsp","send","done","failed","brotliDecompress","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","initialState","all","helmet","App","Application","ssrContext","state","cloneDeep","chunks","stream","ssrStart","Date","now","renderPass","pipeableStream","renderToPipeableStream","onAllReady","onError","round","dirty","info","timeout","ok","race","allSettled","pending","time","timer","then","warn","pipe","Writable","write","chunk","_","Helmet","renderStatic","chunkGroups","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","dr_pogodin_react_utils___split_components","payload","serializeJs","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","brotliCompress"],"sources":["../../../src/server/renderer.jsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Writable } from 'stream';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport {\n clone,\n cloneDeep,\n defaults,\n isString,\n get,\n mapValues,\n omit,\n} from 'lodash';\n\nimport config from 'config';\nimport forge from 'node-forge';\nimport fs from 'fs';\nimport path from 'path';\nimport { brotliCompress, brotliDecompress } from 'zlib';\n\nimport { renderToPipeableStream } from 'react-dom/server';\nimport { Helmet } from 'react-helmet';\nimport { StaticRouter } from 'react-router-dom/server';\nimport serializeJs from 'serialize-javascript';\nimport time from 'utils/time';\nimport winston from 'winston';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\nexport const SCRIPT_LOCATIONS = {\n BODY_OPEN: 'BODY_OPEN',\n DEFAULT: 'DEFAULT',\n HEAD_OPEN: 'HEAD_OPEN',\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @ignore\n * @param {String} context Webpack context path used during the build.\n * @return {Object} Resolves to the build-time information.\n */\nfunction getBuildInfo(context) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url));\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @ignore\n * @param {string} buildDir\n * @return {object}\n */\nfunction readChunkGroupsJson(buildDir) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url));\n } catch (err) {\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @ignore\n * @param {String} key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return {Promise} Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key) {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param {object} req\n * @return {boolean}\n * @ignore\n */\nexport function isBrotliAcceptable(req) {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (let i = 0; i < ops.length; ++i) {\n const [type, priority] = ops[i].trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (let i = 0; i < scripts.length; ++i) {\n const script = scripts[i];\n if (isString(script)) {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (res[script.location] !== undefined) {\n res[script.location] += script.code;\n } else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}) {\n const { format, transports } = winston;\n return winston.createLogger({\n level: defaultLogLevel,\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp}):\\t${message}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack}`;\n return res;\n },\n ),\n ),\n transports: [new transports.Console()],\n });\n}\n\n/**\n * Creates the middleware.\n * @param {object} webpackConfig\n * @param {object} options Additional options:\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {object} [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param {boolean} [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param {boolean} [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` – 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 * @return {function} Created middleware.\n */\nexport default function factory(webpackConfig, options) {\n const ops = defaults(clone(options), {\n beforeRender: () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n if (ops.logger === undefined) {\n ops.logger = newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n }\n\n const buildInfo = ops.buildInfo || getBuildInfo(webpackConfig.context);\n global.TRU_BUILD_INFO = buildInfo;\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath}manifest.json\">` : '';\n\n const cache = ops.staticCacheController\n ? new Cache(ops.staticCacheSize) : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath);\n\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n let cacheRef;\n if (cache) {\n cacheRef = ops.staticCacheController(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n h = h.replace(regex, req.nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n ops.beforeRender(req, sanitizedConfig),\n prepareCipher(buildInfo.key),\n ]);\n\n let helmet;\n\n /* Optional server-side rendering. */\n let App = ops.Application;\n const ssrContext = {\n req,\n state: cloneDeep(initialState || {}),\n\n // Array of chunk names encountered during the rendering.\n chunks: [],\n };\n let stream;\n if (App) {\n const ssrStart = Date.now();\n\n const renderPass = async () => {\n ssrContext.chunks = [];\n return new Promise((resolve, reject) => {\n const pipeableStream = renderToPipeableStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <App />\n </StaticRouter>\n </GlobalStateProvider>,\n {\n onAllReady: () => resolve(pipeableStream),\n onError: reject,\n },\n );\n });\n };\n\n for (let round = 0; round < ops.maxSsrRounds; ++round) {\n stream = await renderPass(); // eslint-disable-line no-await-in-loop\n\n if (!ssrContext.dirty) {\n ops.logger.info(`SSR completed in ${round + 1} rounds`);\n break;\n }\n\n /* eslint-disable no-await-in-loop */\n const timeout = ops.ssrTimeout + ssrStart - Date.now();\n const ok = timeout > 0 && await Promise.race([\n Promise.allSettled(ssrContext.pending),\n time.timer(timeout).then(() => false),\n ]);\n if (!ok) {\n ops.logger.warn(`SSR timed out (${ops.ssrTimeout}sec)`);\n break;\n }\n /* eslint-enable no-await-in-loop */\n\n if (round + 1 === ops.maxSsrRounds) {\n ops.logger.warn(\n `SSR reached max number of rounds ${ops.maxSsrRounds}`,\n );\n }\n }\n\n App = '';\n stream.pipe(new Writable({\n write: (chunk, _, done) => {\n App += chunk.toString();\n done();\n },\n }));\n\n /* This takes care about server-side rendering of page title and meta tags\n * (still demands injection into HTML template, which happens below). */\n helmet = Helmet.renderStatic();\n }\n\n let chunkGroups;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets.map(({ name }) => name),\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n delete ssrContext.state.dr_pogodin_react_utils___split_components;\n\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject || sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n const chunkSet = new Set();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon ? (\n '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n ) : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet ? helmet.title.toString() : ''}\n ${helmet ? helmet.meta.toString() : ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${App || ''}</div>\n <script\n id=\"inj\"\n type=\"application/javascript\"\n ${ops.noCsp ? '' : `nonce=\"${req.nonce}\"`}\n >\n window.INJ=\"${INJ}\"\n </script>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n res.send(html);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n buffer.nonce = req.nonce; // eslint-disable-line no-param-reassign\n cache.add({ buffer, status }, cacheRef.key);\n done();\n }\n });\n });\n }\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;AAIA;;AAEA;;AAEA;;AAUA;;AACA;;AACA;;AACA;;AACA;;AAEA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA;;;;AA/BA;AACA;AACA;AA+BA,MAAMA,eAAe,GAAG,IAAAC,YAAA,EAAKC,eAAL,EAAa,QAAb,CAAxB;AAEO,MAAMC,gBAAgB,GAAG;EAC9BC,SAAS,EAAE,WADmB;EAE9BC,OAAO,EAAE,SAFqB;EAG9BC,SAAS,EAAE;AAHmB,CAAzB;AAMP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AACA,SAASC,YAAT,CAAsBC,OAAtB,EAA+B;EAC7B,MAAMC,GAAG,GAAGC,aAAA,CAAKC,OAAL,CAAaH,OAAb,EAAsB,aAAtB,CAAZ;;EACA,OAAOI,IAAI,CAACC,KAAL,CAAWC,WAAA,CAAGC,YAAH,CAAgBN,GAAhB,CAAX,CAAP;AACD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACA,SAASO,mBAAT,CAA6BC,QAA7B,EAAuC;EACrC,MAAMR,GAAG,GAAGC,aAAA,CAAKC,OAAL,CAAaM,QAAb,EAAuB,uBAAvB,CAAZ;;EACA,IAAIC,GAAJ;;EACA,IAAI;IACFA,GAAG,GAAGN,IAAI,CAACC,KAAL,CAAWC,WAAA,CAAGC,YAAH,CAAgBN,GAAhB,CAAX,CAAN;EACD,CAFD,C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E,IAAD,EAAOC,MAAP,KAAkB;UAClC,IAAAqF,oBAAA,EAAelF,IAAf,EAAqB,CAACD,KAAD,EAAQP,MAAR,KAAmB;YACtC,IAAIO,KAAJ,EAAWF,MAAM,CAACE,KAAD,CAAN,CAAX,KACK;cACHP,MAAM,CAACa,KAAP,GAAe9E,GAAG,CAAC8E,KAAnB,CADG,CACuB;;cAC1BrB,KAAK,CAACyF,GAAN,CAAU;gBAAEjF,MAAF;gBAAUC;cAAV,CAAV,EAA8BH,QAAQ,CAAC1E,GAAvC;cACAgF,IAAI;YACL;UACF,CAPD;QAQD,CATK,CAAN;MAUD;IACF,CAzPD,CAyPE,OAAOG,KAAP,EAAc;MACdX,IAAI,CAACW,KAAD,CAAJ;IACD;EACF,CA7PD;AA8PD"}
|
|
@@ -78,7 +78,7 @@ function getDefaultCspSettings() {
|
|
|
78
78
|
}
|
|
79
79
|
|
|
80
80
|
async function factory(webpackConfig, options) {
|
|
81
|
-
const rendererOps = (0, _lodash.pick)(options, ['Application', 'beforeRender', 'favicon', 'maxSsrRounds', 'noCsp', 'ssrTimeout', 'staticCacheController', 'staticCacheSize']);
|
|
81
|
+
const rendererOps = (0, _lodash.pick)(options, ['Application', 'beforeRender', 'favicon', 'logger', 'maxSsrRounds', 'noCsp', 'ssrTimeout', 'staticCacheController', 'staticCacheSize']);
|
|
82
82
|
const renderer = (0, _renderer.default)(webpackConfig, rendererOps);
|
|
83
83
|
const {
|
|
84
84
|
publicPath
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":["defaultCspSettings","directives","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","nonce","cspNonce","cspSettings","cspSettingsHook","favicon","send","express","json","limit","urlencoded","extended","requestIp","mw","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","header","devMode","global","location","href","process","cwd","sep","webpack","require","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","static","path","onExpressJsSetup","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","status","INTERNAL_SERVER_ERROR","serverSide","log","message","env","NODE_ENV"],"sources":["../../../src/server/server.js"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport express from 'express';\nimport favicon from 'serve-favicon';\nimport helmet from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport rendererFactory from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => array.filter((item) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\ndefaultCspSettings.directives['script-src'].push(\"'unsafe-eval'\");\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings() {\n return cloneDeep(defaultCspSettings);\n}\n\nexport default async function factory(webpackConfig, options) {\n const rendererOps = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output;\n\n const server = express();\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n return res.redirect(url);\n }\n return next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use((req, res, next) => {\n req.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req.cspNonce = req.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings = cloneDeep(defaultCspSettings);\n cspSettings.directives['script-src'].push(`'nonce-${req.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n });\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => res.send('User-agent: *\\nDisallow:'));\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n loggerMiddleware.token('ip', (req) => req.clientIp);\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n write: options.logger.info.bind(options.logger),\n },\n }));\n\n /* Ensures no caching for the service worker script. */\n server.use(`${publicPath}service-worker.js`, (req, res, next) => {\n res.header('Cache-Control', 'no-cache');\n next();\n });\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable global-require */\n /* eslint-disable import/no-extraneous-dependencies */\n /* eslint-disable import/no-unresolved */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n };\n }\n\n const webpack = require('webpack');\n const webpackDevMiddleware = require('webpack-dev-middleware');\n const webpackHotMiddleware = require('webpack-hot-middleware');\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable global-require */\n /* eslint-enable import/no-extraneous-dependencies */\n /* eslint-enable import/no-unresolved */\n\n server.use(publicPath, express.static(webpackConfig.output.path));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n /* eslint-disable no-unused-vars */\n server.use((error, req, res, next) => {\n /* eslint-enable no-unused-vars */\n const status = error.status || CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger.log(serverSide ? 'error' : 'debug', error);\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":";;;;;;;;;;AAIA;;AACA;;AAEA;;AAMA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AAxBA;AACA;AACA;;AA6BA;AACA;AACA;AACA;AACA,MAAMA,kBAAkB,GAAG;EACzBC,UAAU,EAAE,uBACVC,gBAAOC,qBAAP,CAA6BC,oBAA7B,EADU,EAGV;EACA;EACA;EACA;EACCC,KAAD,IAAWA,KAAK,CAACC,MAAN,CAAcC,IAAD,IAAUA,IAAI,KAAK,QAAhC,CAPD;AADa,CAA3B;AAWAP,kBAAkB,CAACC,UAAnB,CAA8B,WAA9B,IAA6C,CAC3C,QAD2C,EAG3C;AACA;AACA,uBAL2C,CAA7C;AAOAD,kBAAkB,CAACC,UAAnB,CAA8B,YAA9B,EAA4CO,IAA5C,CAAiD,eAAjD,E,CAEA;AACA;AACA;;AACA,OAAOR,kBAAkB,CAACC,UAAnB,CAA8B,2BAA9B,CAAP;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACO,SAASQ,qBAAT,GAAiC;EACtC,OAAO,uBAAUT,kBAAV,CAAP;AACD;;AAEc,eAAeU,OAAf,CAAuBC,aAAvB,EAAsCC,OAAtC,EAA+C;EAC5D,MAAMC,WAAW,GAAG,kBAAKD,OAAL,EAAc,CAChC,aADgC,EAEhC,cAFgC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EAEA;;EACAG,MAAM,CAACI,GAAP,CAAW,CAACC,GAAD,EAAMC,GAAN,EAAWC,IAAX,KAAoB;IAC7BA,IAAI,CAAC,sBAASiD,eAAOC,SAAhB,EAA2BC,cAAMD,SAAjC,CAAD,CAAJ;EACD,CAFD;EAIA,IAAIE,6BAAJ;;EACA,IAAIhE,OAAO,CAACiE,oBAAZ,EAAkC;IAChCD,6BAA6B,GAAG,MAAMhE,OAAO,CAACiE,oBAAR,CAA6B5D,MAA7B,CAAtC;EACD;EAED;;;EACA,IAAI,CAAC2D,6BAAL,EAAoC;IAClC;IACA;IACA;IACA;;IACA;IACA3D,MAAM,CAACI,GAAP,CAAW,CAACyD,KAAD,EAAQxD,GAAR,EAAaC,GAAb,EAAkBC,IAAlB,KAA2B;MACtC;MACE,MAAMuD,MAAM,GAAGD,KAAK,CAACC,MAAN,IAAgBJ,cAAMK,qBAArC;MACA,MAAMC,UAAU,GAAGF,MAAM,IAAIJ,cAAMK,qBAAnC,CAHoC,CAKpC;;MACApE,OAAO,CAACO,MAAR,CAAe+D,GAAf,CAAmBD,UAAU,GAAG,OAAH,GAAa,OAA1C,EAAmDH,KAAnD;MAEA,IAAIK,OAAO,GAAGL,KAAK,CAACK,OAAN,IAAiB,6BAAgBJ,MAAhB,CAA/B;;MACA,IAAIE,UAAU,IAAIpB,OAAO,CAACuB,GAAR,CAAYC,QAAZ,KAAyB,YAA3C,EAAyD;QACvDF,OAAO,GAAGV,eAAOO,qBAAjB;MACD;;MAEDzD,GAAG,CAACwD,MAAJ,CAAWA,MAAX,EAAmBvC,IAAnB,CAAwB2C,OAAxB;IACD,CAdD;EAeD;;EAED,OAAOlE,MAAP;AACD"}
|
|
1
|
+
{"version":3,"file":"server.js","names":["defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","requestIp","mw","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","header","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","require","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","static","path","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","status","INTERNAL_SERVER_ERROR","serverSide","log","message","getErrorForCode","env","NODE_ENV"],"sources":["../../../src/server/server.js"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport express from 'express';\nimport favicon from 'serve-favicon';\nimport helmet from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport rendererFactory from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => array.filter((item) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\ndefaultCspSettings.directives['script-src'].push(\"'unsafe-eval'\");\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings() {\n return cloneDeep(defaultCspSettings);\n}\n\nexport default async function factory(webpackConfig, options) {\n const rendererOps = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output;\n\n const server = express();\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n return res.redirect(url);\n }\n return next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use((req, res, next) => {\n req.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req.cspNonce = req.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings = cloneDeep(defaultCspSettings);\n cspSettings.directives['script-src'].push(`'nonce-${req.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n });\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => res.send('User-agent: *\\nDisallow:'));\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n loggerMiddleware.token('ip', (req) => req.clientIp);\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n write: options.logger.info.bind(options.logger),\n },\n }));\n\n /* Ensures no caching for the service worker script. */\n server.use(`${publicPath}service-worker.js`, (req, res, next) => {\n res.header('Cache-Control', 'no-cache');\n next();\n });\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable global-require */\n /* eslint-disable import/no-extraneous-dependencies */\n /* eslint-disable import/no-unresolved */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n };\n }\n\n const webpack = require('webpack');\n const webpackDevMiddleware = require('webpack-dev-middleware');\n const webpackHotMiddleware = require('webpack-hot-middleware');\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable global-require */\n /* eslint-enable import/no-extraneous-dependencies */\n /* eslint-enable import/no-unresolved */\n\n server.use(publicPath, express.static(webpackConfig.output.path));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n /* eslint-disable no-unused-vars */\n server.use((error, req, res, next) => {\n /* eslint-enable no-unused-vars */\n const status = error.status || CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger.log(serverSide ? 'error' : 'debug', error);\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":";;;;;;;;;;AAIA;;AACA;;AAEA;;AAMA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AAxBA;AACA;AACA;;AA6BA;AACA;AACA;AACA;AACA,MAAMA,kBAAkB,GAAG;EACzBC,UAAU,EAAE,IAAAC,iBAAA,EACVC,eAAA,CAAOC,qBAAP,CAA6BC,oBAA7B,EADU,EAGV;EACA;EACA;EACA;EACCC,KAAD,IAAWA,KAAK,CAACC,MAAN,CAAcC,IAAD,IAAUA,IAAI,KAAK,QAAhC,CAPD;AADa,CAA3B;AAWAR,kBAAkB,CAACC,UAAnB,CAA8B,WAA9B,IAA6C,CAC3C,QAD2C,EAG3C;AACA;AACA,uBAL2C,CAA7C;AAOAD,kBAAkB,CAACC,UAAnB,CAA8B,YAA9B,EAA4CQ,IAA5C,CAAiD,eAAjD,E,CAEA;AACA;AACA;;AACA,OAAOT,kBAAkB,CAACC,UAAnB,CAA8B,2BAA9B,CAAP;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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A,EAAgBL,MAAhB,CAA/B;;MACA,IAAIE,UAAU,IAAIrB,OAAO,CAACyB,GAAR,CAAYC,QAAZ,KAAyB,YAA3C,EAAyD;QACvDH,OAAO,GAAGV,cAAA,CAAOO,qBAAjB;MACD;;MAED7D,GAAG,CAAC4D,MAAJ,CAAWA,MAAX,EAAmBzC,IAAnB,CAAwB6C,OAAxB;IACD,CAdD;EAeD;;EAED,OAAOvE,MAAP;AACD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":["newError","message","statusCode","CODES","INTERNAL_SERVER_ERROR","error","Error","status","fail","assert","value","schema","BAD_REQUEST","validate","abortEarly","concat"],"sources":["../../../../src/server/utils/errors.js"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport joi from 'joi';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n/**\n * @static\n * @const joi\n * @desc An alias for [Joi library](https://joi.dev/api/?v=17.4.0),\n * which provides tooling for HTTP request validation. You can use it in any\n * way you would use that library import.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { joi } = server.errors;\n * const requestBodySchema = joi.object({\n * sampleKey: joi.string().max(16).required(),\n * });\n */\nexport { joi };\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(message, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n const error = new Error(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { fail } = server.errors;\n * ```\n * Throws an error with given message and HTTP status code.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP error code. Defaults to 500 (Internal\n * Server Error).\n * @throws {Error}\n */\nexport function fail(message, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n throw newError(message, statusCode);\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { assert } = server.errors;\n * ```\n * Validates a value using given Joi schema, and throws an error with given\n * message and HTTP status code in case of the validation failure.\n * @param {any} value\n * @param {object} schema\n * @param {string} [message] Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 400 (Bad\n * Request).\n * @throws {Error}\n */\nexport function assert(\n value,\n schema,\n message = '',\n statusCode = CODES.BAD_REQUEST,\n) {\n const { error } = schema.validate(value, { abortEarly: false });\n if (error) {\n fail(message.concat(message ? '\\n' : '', error.message), statusCode);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA;;AAMA;;AAjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,QAAT,CAAkBC,OAAlB,EAA2BC,UAAU,GAAGC,
|
|
1
|
+
{"version":3,"file":"errors.js","names":["newError","message","statusCode","CODES","INTERNAL_SERVER_ERROR","error","Error","status","fail","assert","value","schema","BAD_REQUEST","validate","abortEarly","concat"],"sources":["../../../../src/server/utils/errors.js"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport joi from 'joi';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n/**\n * @static\n * @const joi\n * @desc An alias for [Joi library](https://joi.dev/api/?v=17.4.0),\n * which provides tooling for HTTP request validation. You can use it in any\n * way you would use that library import.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { joi } = server.errors;\n * const requestBodySchema = joi.object({\n * sampleKey: joi.string().max(16).required(),\n * });\n */\nexport { joi };\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(message, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n const error = new Error(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { fail } = server.errors;\n * ```\n * Throws an error with given message and HTTP status code.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP error code. Defaults to 500 (Internal\n * Server Error).\n * @throws {Error}\n */\nexport function fail(message, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n throw newError(message, statusCode);\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { assert } = server.errors;\n * ```\n * Validates a value using given Joi schema, and throws an error with given\n * message and HTTP status code in case of the validation failure.\n * @param {any} value\n * @param {object} schema\n * @param {string} [message] Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 400 (Bad\n * Request).\n * @throws {Error}\n */\nexport function assert(\n value,\n schema,\n message = '',\n statusCode = CODES.BAD_REQUEST,\n) {\n const { error } = schema.validate(value, { abortEarly: false });\n if (error) {\n fail(message.concat(message ? '\\n' : '', error.message), statusCode);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA;;AAMA;;AAjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,QAAT,CAAkBC,OAAlB,EAA2BC,UAAU,GAAGC,4BAAA,CAAMC,qBAA9C,EAAqE;EAC1E,MAAMC,KAAK,GAAG,IAAIC,KAAJ,CAAUL,OAAV,CAAd;EACAI,KAAK,CAACE,MAAN,GAAeL,UAAf;EACA,OAAOG,KAAP;AACD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACO,SAASG,IAAT,CAAcP,OAAd,EAAuBC,UAAU,GAAGC,4BAAA,CAAMC,qBAA1C,EAAiE;EACtE,MAAMJ,QAAQ,CAACC,OAAD,EAAUC,UAAV,CAAd;AACD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACO,SAASO,MAAT,CACLC,KADK,EAELC,MAFK,EAGLV,OAAO,GAAG,EAHL,EAILC,UAAU,GAAGC,4BAAA,CAAMS,WAJd,EAKL;EACA,MAAM;IAAEP;EAAF,IAAYM,MAAM,CAACE,QAAP,CAAgBH,KAAhB,EAAuB;IAAEI,UAAU,EAAE;EAAd,CAAvB,CAAlB;;EACA,IAAIT,KAAJ,EAAW;IACTG,IAAI,CAACP,OAAO,CAACc,MAAR,CAAed,OAAO,GAAG,IAAH,GAAU,EAAhC,EAAoCI,KAAK,CAACJ,OAA1C,CAAD,EAAqDC,UAArD,CAAJ;EACD;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","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"],"sources":["../../../../../src/shared/components/Button/index.jsx"],"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"],"mappings":";;;;;;;;;AAEA;;AAEA;;AAEA;;;;AANA;;;;;;;;;;AAUA,SAASA,UAAT,CAAoB;EAClBC,MADkB;EAElBC,QAFkB;EAGlBC,QAHkB;EAIlBC,QAJkB;EAKlBC,OALkB;EAMlBC,WANkB;EAOlBC,UAPkB;EAQlBC,OARkB;EASlBC,KATkB;EAUlBC;AAVkB,CAApB,EAWG;EACD,IAAIC,SAAS,GAAGF,KAAK,CAACG,MAAtB;EACA,IAAIX,MAAM,IAAIQ,KAAK,CAACR,MAApB,EAA4BU,SAAS,IAAK,IAAGF,KAAK,CAACR,MAAO,EAA9B;;EAC5B,IAAIE,QAAJ,EAAc;IACZ,IAAIM,KAAK,CAACN,QAAV,EAAoBQ,SAAS,IAAK,IAAGF,KAAK,CAACN,QAAS,EAAhC;IACpB,oBACE;MAAK,SAAS,EAAEQ,SAAhB;MAAA,UACGT;IADH,EADF;EAKD;;EACD,IAAIQ,EAAJ,EAAQ;IACN,oBACE,qBAAC,aAAD;MACE,SAAS,EAAEC,SADb;MAEE,QAAQ,EAAEP,QAFZ;MAGE,OAAO,EAAEC,OAHX;MAIE,WAAW,EAAEC,WAJf;MAKE,UAAU,EAAEC,UALd;MAME,OAAO,EAAEC,OANX;MAOE,EAAE,EAAEE,EAPN;MAAA,UASGR;IATH,EADF;EAaD;;EACD,oBACE;IACE,SAAS,EAAES,SADb;IAEE,OAAO,EAAEN,OAFX;IAGE,UAAU,EAAEA,OAHd;IAIE,WAAW,EAAEC,WAJf;IAKE,IAAI,EAAC,QALP;IAME,QAAQ,EAAE,CANZ;IAAA,UAQGJ;EARH,EADF;AAYD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;;;AACA,MAAMW,YAAY,GAAG,
|
|
1
|
+
{"version":3,"file":"index.js","names":["BaseButton","active","children","disabled","enforceA","onClick","onMouseDown","openNewTab","replace","theme","to","className","button","ThemedButton","themed","defaultTheme","defaultProps","undefined","propTypes","PT","bool","node","func","themeType","isRequired","oneOfType","object","string"],"sources":["../../../../../src/shared/components/Button/index.jsx"],"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"],"mappings":";;;;;;;;;AAEA;;AAEA;;AAEA;;;;AANA;;;;;;;;;;AAUA,SAASA,UAAT,CAAoB;EAClBC,MADkB;EAElBC,QAFkB;EAGlBC,QAHkB;EAIlBC,QAJkB;EAKlBC,OALkB;EAMlBC,WANkB;EAOlBC,UAPkB;EAQlBC,OARkB;EASlBC,KATkB;EAUlBC;AAVkB,CAApB,EAWG;EACD,IAAIC,SAAS,GAAGF,KAAK,CAACG,MAAtB;EACA,IAAIX,MAAM,IAAIQ,KAAK,CAACR,MAApB,EAA4BU,SAAS,IAAK,IAAGF,KAAK,CAACR,MAAO,EAA9B;;EAC5B,IAAIE,QAAJ,EAAc;IACZ,IAAIM,KAAK,CAACN,QAAV,EAAoBQ,SAAS,IAAK,IAAGF,KAAK,CAACN,QAAS,EAAhC;IACpB,oBACE;MAAK,SAAS,EAAEQ,SAAhB;MAAA,UACGT;IADH,EADF;EAKD;;EACD,IAAIQ,EAAJ,EAAQ;IACN,oBACE,qBAAC,aAAD;MACE,SAAS,EAAEC,SADb;MAEE,QAAQ,EAAEP,QAFZ;MAGE,OAAO,EAAEC,OAHX;MAIE,WAAW,EAAEC,WAJf;MAKE,UAAU,EAAEC,UALd;MAME,OAAO,EAAEC,OANX;MAOE,EAAE,EAAEE,EAPN;MAAA,UASGR;IATH,EADF;EAaD;;EACD,oBACE;IACE,SAAS,EAAES,SADb;IAEE,OAAO,EAAEN,OAFX;IAGE,UAAU,EAAEA,OAHd;IAIE,WAAW,EAAEC,WAJf;IAKE,IAAI,EAAC,QALP;IAME,QAAQ,EA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