@dr.pogodin/react-utils 1.12.9 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/build/development/index.js +1 -11
  2. package/build/development/index.js.map +1 -1
  3. package/build/development/server/server.js +18 -1
  4. package/build/development/server/server.js.map +1 -1
  5. package/build/development/shared/components/CodeSplit/ClientSide.js +12 -6
  6. package/build/development/shared/components/CodeSplit/ClientSide.js.map +1 -1
  7. package/build/development/shared/components/CodeSplit/ServerSide.js +19 -46
  8. package/build/development/shared/components/CodeSplit/ServerSide.js.map +1 -1
  9. package/build/development/shared/components/CodeSplit/index.js +6 -10
  10. package/build/development/shared/components/CodeSplit/index.js.map +1 -1
  11. package/build/development/shared/components/index.js +0 -8
  12. package/build/development/shared/components/index.js.map +1 -1
  13. package/build/development/shared/utils/Semaphore.js +44 -0
  14. package/build/development/shared/utils/Semaphore.js.map +1 -0
  15. package/build/development/shared/utils/config.js +1 -3
  16. package/build/development/shared/utils/config.js.map +1 -1
  17. package/build/development/shared/utils/index.js +31 -9
  18. package/build/development/shared/utils/index.js.map +1 -1
  19. package/build/development/shared/utils/splitComponent.js +43 -0
  20. package/build/development/shared/utils/splitComponent.js.map +1 -0
  21. package/build/development/shared/utils/webpack.js +26 -39
  22. package/build/development/shared/utils/webpack.js.map +1 -1
  23. package/build/development/web.bundle.js +46 -16
  24. package/build/production/index.js +1 -2
  25. package/build/production/index.js.map +1 -1
  26. package/build/production/server/server.js +7 -3
  27. package/build/production/server/server.js.map +1 -1
  28. package/build/production/shared/components/CodeSplit/ClientSide.js +6 -5
  29. package/build/production/shared/components/CodeSplit/ClientSide.js.map +1 -1
  30. package/build/production/shared/components/CodeSplit/ServerSide.js +9 -15
  31. package/build/production/shared/components/CodeSplit/ServerSide.js.map +1 -1
  32. package/build/production/shared/components/CodeSplit/index.js +5 -2
  33. package/build/production/shared/components/CodeSplit/index.js.map +1 -1
  34. package/build/production/shared/components/index.js +1 -1
  35. package/build/production/shared/components/index.js.map +1 -1
  36. package/build/production/shared/utils/Semaphore.js +5 -0
  37. package/build/production/shared/utils/Semaphore.js.map +1 -0
  38. package/build/production/shared/utils/config.js +1 -1
  39. package/build/production/shared/utils/config.js.map +1 -1
  40. package/build/production/shared/utils/index.js +5 -3
  41. package/build/production/shared/utils/index.js.map +1 -1
  42. package/build/production/shared/utils/splitComponent.js +14 -0
  43. package/build/production/shared/utils/splitComponent.js.map +1 -0
  44. package/build/production/shared/utils/webpack.js +4 -27
  45. package/build/production/shared/utils/webpack.js.map +1 -1
  46. package/build/production/web.bundle.js +1 -1
  47. package/build/production/web.bundle.js.map +1 -1
  48. package/config/babel/node-ssr.js +2 -4
  49. package/package.json +24 -26
@@ -1,4 +1,4 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=factory;exports.getDefaultCspSettings=getDefaultCspSettings;var _lodash=require("lodash");var _compression=_interopRequireDefault(require("compression"));var _cookieParser=_interopRequireDefault(require("cookie-parser"));var _express=_interopRequireDefault(require("express"));var _serveFavicon=_interopRequireDefault(require("serve-favicon"));var _helmet=_interopRequireDefault(require("helmet"));var _morgan=_interopRequireDefault(require("morgan"));var _requestIp=_interopRequireDefault(require("request-ip"));var _uuid=require("uuid");var _renderer=_interopRequireDefault(require("./renderer"));var _errors=require("./utils/errors");/**
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=factory;exports.getDefaultCspSettings=getDefaultCspSettings;var _path=require("path");var _url=require("url");var _lodash=require("lodash");var _compression=_interopRequireDefault(require("compression"));var _cookieParser=_interopRequireDefault(require("cookie-parser"));var _express=_interopRequireDefault(require("express"));var _serveFavicon=_interopRequireDefault(require("serve-favicon"));var _helmet=_interopRequireDefault(require("helmet"));var _morgan=_interopRequireDefault(require("morgan"));var _requestIp=_interopRequireDefault(require("request-ip"));var _uuid=require("uuid");var _renderer=_interopRequireDefault(require("./renderer"));var _errors=require("./utils/errors");/**
2
2
  * Creation of standard ExpressJS server for ReactJS apps.
3
3
  */ /**
4
4
  * Default Content Security Policy settings.
@@ -26,13 +26,17 @@ delete defaultCspSettings.directives["upgrade-insecure-requests"];/**
26
26
  * }} A deep copy of default CSP settings object used by `react-utils`,
27
27
  * with the exception of `nonce-xxx` clause in `script-src` directive,
28
28
  * which is added dynamically for each request.
29
- */function getDefaultCspSettings(){return(0,_lodash.cloneDeep)(defaultCspSettings)}async function factory(webpackConfig,options){const rendererOps=(0,_lodash.pick)(options,["Application","beforeRender","favicon","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=(0,_renderer.default)(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=(0,_express.default)();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server)}server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;return res.redirect(url)}return next()})}server.use((0,_compression.default)());server.use((0,_helmet.default)({contentSecurityPolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{req.nonce=(0,_uuid.v4)();// TODO: This is deprecated, but it is kept for now for backward
29
+ */function getDefaultCspSettings(){return(0,_lodash.cloneDeep)(defaultCspSettings)}async function factory(webpackConfig,options){const rendererOps=(0,_lodash.pick)(options,["Application","beforeRender","favicon","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=(0,_renderer.default)(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=(0,_express.default)();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server)}server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;return res.redirect(url)}return next()})}server.use((0,_compression.default)());server.use((0,_helmet.default)({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{req.nonce=(0,_uuid.v4)();// TODO: This is deprecated, but it is kept for now for backward
30
30
  // compatibility. Should be removed sometime later.
31
31
  req.cspNonce=req.nonce;// The deep clone is necessary here to ensure that default value can't be
32
32
  // mutated during request processing.
33
33
  let cspSettings=(0,_lodash.cloneDeep)(defaultCspSettings);cspSettings.directives["script-src"].push(`'nonce-${req.nonce}'`);if(options.cspSettingsHook){cspSettings=options.cspSettingsHook(cspSettings,req)}_helmet.default.contentSecurityPolicy(cspSettings)(req,res,next)})}if(options.favicon){server.use((0,_serveFavicon.default)(options.favicon))}server.use("/robots.txt",(req,res)=>res.send("User-agent: *\nDisallow:"));server.use(_express.default.json({limit:"300kb"}));server.use(_express.default.urlencoded({extended:false}));server.use((0,_cookieParser.default)());server.use(_requestIp.default.mw());_morgan.default.token("ip",req=>req.clientIp);const FORMAT=":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";server.use((0,_morgan.default)(FORMAT,{stream:{write:options.logger.info.bind(options.logger)}}));/* Ensures no caching for the service worker script. */server.use(`${publicPath}service-worker.js`,(req,res,next)=>{res.header("Cache-Control","no-cache");next()});/* Setup of Hot Module Reloading for development environment.
34
34
  * These dependencies are not used, nor installed for production use,
35
- * hence we should violate some import-related lint rules. */ /* eslint-disable global-require */ /* eslint-disable import/no-extraneous-dependencies */ /* eslint-disable import/no-unresolved */if(options.devMode){const webpack=require("webpack");const webpackDevMiddleware=require("webpack-dev-middleware");const webpackHotMiddleware=require("webpack-hot-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable global-require */ /* eslint-enable import/no-extraneous-dependencies */ /* eslint-enable import/no-unresolved */server.use(publicPath,_express.default.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use(()=>(0,_errors.fail)(_errors.ERRORS.NOT_FOUND,_errors.CODES.NOT_FOUND));let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: It is better to move the default error handler definition
35
+ * hence we should violate some import-related lint rules. */ /* eslint-disable global-require */ /* eslint-disable import/no-extraneous-dependencies */ /* eslint-disable import/no-unresolved */if(options.devMode){// This is a workaround for SASS bug:
36
+ // https://github.com/dart-lang/sdk/issues/27979
37
+ // which manifests itself sometimes when webpack dev middleware is used
38
+ // (in dev mode), and app modules are imported in some unfortunate ways.
39
+ if(!global.location){global.location={href:`${(0,_url.pathToFileURL)(process.cwd()).href}${_path.sep}`}}const webpack=require("webpack");const webpackDevMiddleware=require("webpack-dev-middleware");const webpackHotMiddleware=require("webpack-hot-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable global-require */ /* eslint-enable import/no-extraneous-dependencies */ /* eslint-enable import/no-unresolved */server.use(publicPath,_express.default.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use(()=>(0,_errors.fail)(_errors.ERRORS.NOT_FOUND,_errors.CODES.NOT_FOUND));let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: It is better to move the default error handler definition
36
40
  // to a stand-alone function at top-level, but the use of options.logger
37
41
  // prevents to do it without some extra refactoring. Should be done sometime
38
42
  // though.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/server/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","noCsp","nonce","cspNonce","cspSettings","cspSettingsHook","favicon","send","express","json","limit","urlencoded","extended","requestIp","mw","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","header","devMode","webpack","require","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","static","path","onExpressJsSetup","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","status","INTERNAL_SERVER_ERROR","serverSide","log","message","process","env","NODE_ENV"],"mappings":"qOAIA,8BAMA,gEACA,mEACA,wDACA,mEACA,sDACA,sDACA,6DACA,0BAEA,4DAEA,sCArBA;AACA;AACA,G,CA0BA;AACA;AACA;AACA,GACA,KAAMA,CAAAA,kBAAkB,CAAG,CACzBC,UAAU,CAAE,sBACVC,gBAAOC,qBAAP,CAA6BC,oBAA7B,EADU,CAGV;AACA;AACA;AACA;AACCC,KAAD,EAAWA,KAAK,CAACC,MAAN,CAAcC,IAAD,EAAUA,IAAI,GAAK,QAAhC,CAPD,CADa,CAA3B,CAWAP,kBAAkB,CAACC,UAAnB,CAA8B,WAA9B,EAA6C,CAC3C,QAD2C,CAG3C;AACA;AACA,uBAL2C,CAA7C,CAOAD,kBAAkB,CAACC,UAAnB,CAA8B,YAA9B,EAA4CO,IAA5C,CAAiD,eAAjD,EAEA;AACA;AACA;AACA,MAAOR,CAAAA,kBAAkB,CAACC,UAAnB,CAA8B,2BAA9B,CAAP,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAASQ,CAAAA,qBAAT,EAAiC,CACtC,MAAO,sBAAUT,kBAAV,CACR,CAEc,cAAeU,CAAAA,OAAf,CAAuBC,aAAvB,CAAsCC,OAAtC,CAA+C,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,CACA,GAAIvD,OAAO,CAACwD,oBAAZ,CAAkC,CAChCD,6BAA6B,CAAG,KAAMvD,CAAAA,OAAO,CAACwD,oBAAR,CAA6BnD,MAA7B,CACvC,CAED,oBACA,GAAI,CAACkD,6BAAL,CAAoC,CAClC;AACA;AACA;AACA;AACA,mCACAlD,MAAM,CAACI,GAAP,CAAW,CAACgD,KAAD,CAAQ/C,GAAR,CAAaC,GAAb,CAAkBC,IAAlB,GAA2B,CACtC,kCACE,KAAM8C,CAAAA,MAAM,CAAGD,KAAK,CAACC,MAAN,EAAgBJ,cAAMK,qBAArC,CACA,KAAMC,CAAAA,UAAU,CAAGF,MAAM,EAAIJ,cAAMK,qBAAnC,CAEA;AACA3D,OAAO,CAACO,MAAR,CAAesD,GAAf,CAAmBD,UAAU,CAAG,OAAH,CAAa,OAA1C,CAAmDH,KAAnD,EAEA,GAAIK,CAAAA,OAAO,CAAGL,KAAK,CAACK,OAAN,EAAiB,4BAAgBJ,MAAhB,CAA/B,CACA,GAAIE,UAAU,EAAIG,OAAO,CAACC,GAAR,CAAYC,QAAZ,GAAyB,YAA3C,CAAyD,CACvDH,OAAO,CAAGV,eAAOO,qBAClB,CAEDhD,GAAG,CAAC+C,MAAJ,CAAWA,MAAX,EAAmBjC,IAAnB,CAAwBqC,OAAxB,CACD,CAdD,CAeD,CAED,MAAOzD,CAAAA,MACR","sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport express from 'express';\nimport favicon from 'serve-favicon';\nimport helmet from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport rendererFactory from './renderer';\n\nimport {\n CODES,\n ERRORS,\n fail,\n getErrorForCode,\n} from './utils/errors';\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => array.filter((item) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\ndefaultCspSettings.directives['script-src'].push(\"'unsafe-eval'\");\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings() {\n return cloneDeep(defaultCspSettings);\n}\n\nexport default async function factory(webpackConfig, options) {\n const rendererOps = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output;\n\n const server = express();\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n return res.redirect(url);\n }\n return next();\n });\n }\n\n server.use(compression());\n server.use(helmet({ contentSecurityPolicy: false }));\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 const webpack = require('webpack');\n const webpackDevMiddleware = require('webpack-dev-middleware');\n const webpackHotMiddleware = require('webpack-hot-middleware');\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable global-require */\n /* eslint-enable import/no-extraneous-dependencies */\n /* eslint-enable import/no-unresolved */\n\n server.use(publicPath, express.static(webpackConfig.output.path));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use(() => fail(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n /* eslint-disable no-unused-vars */\n server.use((error, req, res, next) => {\n /* eslint-enable no-unused-vars */\n const status = error.status || CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger.log(serverSide ? 'error' : 'debug', error);\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"file":"server.js"}
1
+ {"version":3,"sources":["../../../src/server/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"],"mappings":"qOAIA,0BACA,wBAE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ACA;AACA;AACA;AACA,mCACA3D,MAAM,CAACI,GAAP,CAAW,CAACyD,KAAD,CAAQxD,GAAR,CAAaC,GAAb,CAAkBC,IAAlB,GAA2B,CACtC,kCACE,KAAMuD,CAAAA,MAAM,CAAGD,KAAK,CAACC,MAAN,EAAgBJ,cAAMK,qBAArC,CACA,KAAMC,CAAAA,UAAU,CAAGF,MAAM,EAAIJ,cAAMK,qBAAnC,CAEA;AACApE,OAAO,CAACO,MAAR,CAAe+D,GAAf,CAAmBD,UAAU,CAAG,OAAH,CAAa,OAA1C,CAAmDH,KAAnD,EAEA,GAAIK,CAAAA,OAAO,CAAGL,KAAK,CAACK,OAAN,EAAiB,4BAAgBJ,MAAhB,CAA/B,CACA,GAAIE,UAAU,EAAIpB,OAAO,CAACuB,GAAR,CAAYC,QAAZ,GAAyB,YAA3C,CAAyD,CACvDF,OAAO,CAAGV,eAAOO,qBAClB,CAEDzD,GAAG,CAACwD,MAAJ,CAAWA,MAAX,EAAmBvC,IAAnB,CAAwB2C,OAAxB,CACD,CAdD,CAeD,CAED,MAAOlE,CAAAA,MACR","sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport express from 'express';\nimport favicon from 'serve-favicon';\nimport helmet from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport rendererFactory from './renderer';\n\nimport {\n CODES,\n ERRORS,\n fail,\n getErrorForCode,\n} from './utils/errors';\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => array.filter((item) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\ndefaultCspSettings.directives['script-src'].push(\"'unsafe-eval'\");\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings() {\n return cloneDeep(defaultCspSettings);\n}\n\nexport default async function factory(webpackConfig, options) {\n const rendererOps = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output;\n\n const server = express();\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n return res.redirect(url);\n }\n return next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use((req, res, next) => {\n req.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req.cspNonce = req.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings = cloneDeep(defaultCspSettings);\n cspSettings.directives['script-src'].push(`'nonce-${req.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n });\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => res.send('User-agent: *\\nDisallow:'));\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n loggerMiddleware.token('ip', (req) => req.clientIp);\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n write: options.logger.info.bind(options.logger),\n },\n }));\n\n /* Ensures no caching for the service worker script. */\n server.use(`${publicPath}service-worker.js`, (req, res, next) => {\n res.header('Cache-Control', 'no-cache');\n next();\n });\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable global-require */\n /* eslint-disable import/no-extraneous-dependencies */\n /* eslint-disable import/no-unresolved */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n };\n }\n\n const webpack = require('webpack');\n const webpackDevMiddleware = require('webpack-dev-middleware');\n const webpackHotMiddleware = require('webpack-hot-middleware');\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable global-require */\n /* eslint-enable import/no-extraneous-dependencies */\n /* eslint-enable import/no-unresolved */\n\n server.use(publicPath, express.static(webpackConfig.output.path));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use(() => fail(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n /* eslint-disable no-unused-vars */\n server.use((error, req, res, next) => {\n /* eslint-enable no-unused-vars */\n const status = error.status || CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger.log(serverSide ? 'error' : 'debug', error);\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"file":"server.js"}
@@ -1,14 +1,15 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=ClientSide;var _react=require("react");var _reactGlobalState=require("@dr.pogodin/react-global-state");var _utils=require("../../utils");var _isomorphy=require("../../utils/isomorphy");var _time=_interopRequireDefault(require("../../utils/time"));var _jsxRuntime=require("react/jsx-runtime");/**
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=ClientSide;var _react=require("react");var _reactGlobalState=require("@dr.pogodin/react-global-state");var _Barrier=require("../../utils/Barrier");var _isomorphy=require("../../utils/isomorphy");var _time=_interopRequireDefault(require("../../utils/time"));var _jsxRuntime=require("react/jsx-runtime");/**
2
2
  * Client-side implementation of a split code chunk.
3
- */ /* global document, window */ /* eslint-disable react/jsx-props-no-spreading */function ClientSide({chunkName,getComponentAsync,placeholder,...rest}){const{current:heap}=(0,_react.useRef)({pendingStyles:[],renderInitialized:false,stylesInitialized:false});// publicPath from buildInfo does not have a trailing slash at the end.
3
+ */ /* global document, window */ /* eslint-disable react/jsx-props-no-spreading */function ClientSide({chunkName,children,getClientSide,placeholder,// Not used in <ClientSide>, but should not go into "...rest" either.
4
+ serverSide,...rest}){const{current:heap}=(0,_react.useRef)({pendingStyles:[],renderInitialized:false,stylesInitialized:false});// publicPath from buildInfo does not have a trailing slash at the end.
4
5
  const{publicPath}=(0,_isomorphy.getBuildInfo)();// This code block initiates style loading as soon as possible; it collects
5
6
  // into heap.pendingStyles all style load promises; and heap.stylesInitialized
6
7
  // flag remains set until the styles are teared down upon unmounting.
7
- if(!heap.stylesInitialized){heap.stylesInitialized=true;window.CHUNK_GROUPS[chunkName].forEach(asset=>{if(!asset.endsWith(".css"))return;const path=`${publicPath}/${asset}`;let link=document.querySelector(`link[href="${path}"]`);if(!link){link=document.createElement("link");link.setAttribute("href",path);link.setAttribute("rel","stylesheet");const barrier=(0,_utils.newBarrier)();link.onload=barrier.resolve;heap.pendingStyles.push(barrier);const head=document.querySelector("head");head.appendChild(link)}if(!link.dependants)link.dependants=new Set([chunkName]);else link.dependants.add(chunkName)})}// Async loading of React component necessary to render the chunk.
8
- const{data}=(0,_reactGlobalState.useAsyncData)(`dr_pogodin_react_utils___split_components.${chunkName}`,getComponentAsync,{maxage:_time.default.YEAR_MS});const createRender=()=>{const Scene=data.default||data;return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{"data-chunk-name":chunkName,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(Scene,{...rest})})};const[render,setRender]=(0,_react.useState)(()=>{// No need to await anything, we can render the final component right away.
8
+ if(!heap.stylesInitialized){heap.stylesInitialized=true;window.CHUNK_GROUPS[chunkName].forEach(asset=>{if(!asset.endsWith(".css"))return;const path=`${publicPath}/${asset}`;let link=document.querySelector(`link[href="${path}"]`);if(!link){link=document.createElement("link");link.setAttribute("href",path);link.setAttribute("rel","stylesheet");const barrier=(0,_Barrier.newBarrier)();link.onload=barrier.resolve;heap.pendingStyles.push(barrier);const head=document.querySelector("head");head.appendChild(link)}if(!link.dependants)link.dependants=new Set([chunkName]);else link.dependants.add(chunkName)})}// Async loading of React component necessary to render the chunk.
9
+ const{data}=(0,_reactGlobalState.useAsyncData)(`dr_pogodin_react_utils___split_components.${chunkName}`,getClientSide,{maxage:_time.default.YEAR_MS});const createRender=()=>{const Scene=data.default||data;return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{"data-chunk-name":chunkName,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(Scene,{...rest,children:children})})};const[render,setRender]=(0,_react.useState)(()=>{// No need to await anything, we can render the final component right away.
9
10
  if(data&&!heap.pendingStyles.length){heap.renderInitialized=true;return createRender()}// Try to reuse the markup rendered during SSR.
10
11
  const node=document.querySelector(`[data-chunk-name=${chunkName}]`);if(node){return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{/* eslint-disable react/no-danger */dangerouslySetInnerHTML:{__html:node.innerHTML||""}/* eslint-disable react/no-danger */,"data-chunk-name":chunkName})}// Else render placeholder, or empty div.
11
- const Scene=placeholder||(()=>null);return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{children:/*#__PURE__*/(0,_jsxRuntime.jsx)(Scene,{})})});// At this point, if we have data, the absense of heap.renderInitialized flag
12
+ const Scene=placeholder||(()=>null);return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{children:/*#__PURE__*/(0,_jsxRuntime.jsx)(Scene,{...rest,children:children})})});// At this point, if we have data, the absense of heap.renderInitialized flag
12
13
  // means we have to await styles loading; once it is done, and if we are still
13
14
  // mounted, we can set the final render.
14
15
  if(data&&!heap.renderInitialized){heap.renderInitialized=true;Promise.all(heap.pendingStyles).then(()=>{if(heap.stylesInitialized)setRender(createRender())})}// This effectively fires only once, just before the component unmounts.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/shared/components/CodeSplit/ClientSide.jsx"],"names":["ClientSide","chunkName","getComponentAsync","placeholder","rest","current","heap","pendingStyles","renderInitialized","stylesInitialized","publicPath","window","CHUNK_GROUPS","forEach","asset","endsWith","path","link","document","querySelector","createElement","setAttribute","barrier","onload","resolve","push","head","appendChild","dependants","Set","add","data","maxage","time","YEAR_MS","createRender","Scene","default","render","setRender","length","node","__html","innerHTML","Promise","all","then","item","delete","size","removeChild"],"mappings":"oLAMA,4BAEA,gEAEA,kCACA,gDACA,8D,6CAZA;AACA;AACA,G,CACA,6B,CACA,iDAUe,QAASA,CAAAA,UAAT,CAAoB,CACjCC,SADiC,CAEjCC,iBAFiC,CAGjCC,WAHiC,CAIjC,GAAGC,IAJ8B,CAApB,CAKZ,CACD,KAAM,CAAEC,OAAO,CAAEC,IAAX,EAAoB,kBAAO,CAC/BC,aAAa,CAAE,EADgB,CAE/BC,iBAAiB,CAAE,KAFY,CAG/BC,iBAAiB,CAAE,KAHY,CAAP,CAA1B,CAMA;AACA,KAAM,CAAEC,UAAF,EAAiB,6BAAvB,CAEA;AACA;AACA;AACA,GAAI,CAACJ,IAAI,CAACG,iBAAV,CAA6B,CAC3BH,IAAI,CAACG,iBAAL,CAAyB,IAAzB,CACAE,MAAM,CAACC,YAAP,CAAoBX,SAApB,EAA+BY,OAA/B,CAAwCC,KAAD,EAAW,CAChD,GAAI,CAACA,KAAK,CAACC,QAAN,CAAe,MAAf,CAAL,CAA6B,OAC7B,KAAMC,CAAAA,IAAI,CAAI,GAAEN,UAAW,IAAGI,KAAM,EAApC,CACA,GAAIG,CAAAA,IAAI,CAAGC,QAAQ,CAACC,aAAT,CAAwB,cAAaH,IAAK,IAA1C,CAAX,CACA,GAAI,CAACC,IAAL,CAAW,CACTA,IAAI,CAAGC,QAAQ,CAACE,aAAT,CAAuB,MAA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AZ,CAAkBI,UAAlB,CAZH,EAcA,MAAO4B,CAAAA,MACR","sourcesContent":["/**\n * Client-side implementation of a split code chunk.\n */\n/* global document, window */\n/* eslint-disable react/jsx-props-no-spreading */\n\nimport { useEffect, useRef, useState } from 'react';\n\nimport { useAsyncData } from '@dr.pogodin/react-global-state';\n\nimport { newBarrier } from 'utils';\nimport { getBuildInfo } from 'utils/isomorphy';\nimport time from 'utils/time';\n\nexport default function ClientSide({\n chunkName,\n getComponentAsync,\n placeholder,\n ...rest\n}) {\n const { current: heap } = useRef({\n pendingStyles: [],\n renderInitialized: false,\n stylesInitialized: false,\n });\n\n // publicPath from buildInfo does not have a trailing slash at the end.\n const { publicPath } = getBuildInfo();\n\n // This code block initiates style loading as soon as possible; it collects\n // into heap.pendingStyles all style load promises; and heap.stylesInitialized\n // flag remains set until the styles are teared down upon unmounting.\n if (!heap.stylesInitialized) {\n heap.stylesInitialized = true;\n window.CHUNK_GROUPS[chunkName].forEach((asset) => {\n if (!asset.endsWith('.css')) return;\n const path = `${publicPath}/${asset}`;\n let link = document.querySelector(`link[href=\"${path}\"]`);\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('href', path);\n link.setAttribute('rel', 'stylesheet');\n\n const barrier = newBarrier();\n link.onload = barrier.resolve;\n heap.pendingStyles.push(barrier);\n\n const head = document.querySelector('head');\n head.appendChild(link);\n }\n if (!link.dependants) link.dependants = new Set([chunkName]);\n else link.dependants.add(chunkName);\n });\n }\n\n // Async loading of React component necessary to render the chunk.\n const { data } = useAsyncData(\n `dr_pogodin_react_utils___split_components.${chunkName}`,\n getComponentAsync,\n { maxage: time.YEAR_MS },\n );\n\n const createRender = () => {\n const Scene = data.default || data;\n return <div data-chunk-name={chunkName}><Scene {...rest} /></div>;\n };\n\n const [render, setRender] = useState(() => {\n // No need to await anything, we can render the final component right away.\n if (data && !heap.pendingStyles.length) {\n heap.renderInitialized = true;\n return createRender();\n }\n\n // Try to reuse the markup rendered during SSR.\n const node = document.querySelector(`[data-chunk-name=${chunkName}]`);\n if (node) {\n return (\n <div\n /* eslint-disable react/no-danger */\n dangerouslySetInnerHTML={{ __html: node.innerHTML || '' }}\n /* eslint-disable react/no-danger */\n data-chunk-name={chunkName}\n />\n );\n }\n\n // Else render placeholder, or empty div.\n const Scene = placeholder || (() => null);\n return <div><Scene /></div>;\n });\n\n // At this point, if we have data, the absense of heap.renderInitialized flag\n // means we have to await styles loading; once it is done, and if we are still\n // mounted, we can set the final render.\n if (data && !heap.renderInitialized) {\n heap.renderInitialized = true;\n Promise.all(heap.pendingStyles).then(() => {\n if (heap.stylesInitialized) setRender(createRender());\n });\n }\n\n // This effectively fires only once, just before the component unmounts.\n useEffect(() => () => {\n heap.stylesInitialized = false;\n window.CHUNK_GROUPS[chunkName].forEach((item) => {\n if (!item.endsWith('.css')) return;\n const path = `${publicPath}/${item}`;\n const link = document.querySelector(`link[href=\"${path}\"]`);\n link.dependants.delete(chunkName);\n if (!link.dependants.size) {\n const head = document.querySelector('head');\n head.removeChild(link);\n }\n });\n }, [chunkName, heap, publicPath]);\n\n return render;\n}\n"],"file":"ClientSide.js"}
1
+ {"version":3,"sources":["../../../../../src/shared/components/CodeSplit/ClientSide.jsx"],"names":["ClientSide","chunkName","children","getClientSide","placeholder","serverSide","rest","current","heap","pendingStyles","renderInitialized","stylesInitialized","publicPath","window","CHUNK_GROUPS","forEach","asset","endsWith","path","link","document","querySelector","createElement","setAttribute","barrier","onload","resolve","push","head","appendChild","dependants","Set","add","data","maxage","time","YEAR_MS","createRender","Scene","default","render","setRender","length","node","__html","innerHTML","Promise","all","then","item","delete","size","removeChild"],"mappings":"oLAMA,4BAEA,gEAEA,4CACA,gDACA,8D,6CAZA;AACA;AACA,G,CACA,6B,CACA,iDAUe,QAASA,CAAAA,UAAT,CAAoB,CACjCC,SADiC,CAEjCC,QAFiC,CAGjCC,aAHiC,CAIjCC,WAJiC,CAMjC;AACAC,UAPiC,CASjC,GAAGC,IAT8B,CAApB,CAUZ,CACD,KAA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AACJ,YAAY,EAAb,CACtC,CAFD,CAGD,CAED;AACA,qBAAU,IAAM,IAAM,CACpB7B,IAAI,CAACG,iBAAL,CAAyB,KAAzB,CACAE,MAAM,CAACC,YAAP,CAAoBb,SAApB,EAA+Bc,OAA/B,CAAwCkC,IAAD,EAAU,CAC/C,GAAI,CAACA,IAAI,CAAChC,QAAL,CAAc,MAAd,CAAL,CAA4B,OAC5B,KAAMC,CAAAA,IAAI,CAAI,GAAEN,UAAW,IAAGqC,IAAK,EAAnC,CACA,KAAM9B,CAAAA,IAAI,CAAGC,QAAQ,CAACC,aAAT,CAAwB,cAAaH,IAAK,IAA1C,CAAb,CACAC,IAAI,CAACW,UAAL,CAAgBoB,MAAhB,CAAuBjD,SAAvB,EACA,GAAI,CAACkB,IAAI,CAACW,UAAL,CAAgBqB,IAArB,CAA2B,CACzB,KAAMvB,CAAAA,IAAI,CAAGR,QAAQ,CAACC,aAAT,CAAuB,MAAvB,CAAb,CACAO,IAAI,CAACwB,WAAL,CAAiBjC,IAAjB,CACD,CACF,CATD,CAUD,CAZD,CAYG,CAAClB,SAAD,CAAYO,IAAZ,CAAkBI,UAAlB,CAZH,EAcA,MAAO4B,CAAAA,MACR","sourcesContent":["/**\n * Client-side implementation of a split code chunk.\n */\n/* global document, window */\n/* eslint-disable react/jsx-props-no-spreading */\n\nimport { useEffect, useRef, useState } from 'react';\n\nimport { useAsyncData } from '@dr.pogodin/react-global-state';\n\nimport { newBarrier } from 'utils/Barrier';\nimport { getBuildInfo } from 'utils/isomorphy';\nimport time from 'utils/time';\n\nexport default function ClientSide({\n chunkName,\n children,\n getClientSide,\n placeholder,\n\n // Not used in <ClientSide>, but should not go into \"...rest\" either.\n serverSide,\n\n ...rest\n}) {\n const { current: heap } = useRef({\n pendingStyles: [],\n renderInitialized: false,\n stylesInitialized: false,\n });\n\n // publicPath from buildInfo does not have a trailing slash at the end.\n const { publicPath } = getBuildInfo();\n\n // This code block initiates style loading as soon as possible; it collects\n // into heap.pendingStyles all style load promises; and heap.stylesInitialized\n // flag remains set until the styles are teared down upon unmounting.\n if (!heap.stylesInitialized) {\n heap.stylesInitialized = true;\n window.CHUNK_GROUPS[chunkName].forEach((asset) => {\n if (!asset.endsWith('.css')) return;\n const path = `${publicPath}/${asset}`;\n let link = document.querySelector(`link[href=\"${path}\"]`);\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('href', path);\n link.setAttribute('rel', 'stylesheet');\n\n const barrier = newBarrier();\n link.onload = barrier.resolve;\n heap.pendingStyles.push(barrier);\n\n const head = document.querySelector('head');\n head.appendChild(link);\n }\n if (!link.dependants) link.dependants = new Set([chunkName]);\n else link.dependants.add(chunkName);\n });\n }\n\n // Async loading of React component necessary to render the chunk.\n const { data } = useAsyncData(\n `dr_pogodin_react_utils___split_components.${chunkName}`,\n getClientSide,\n { maxage: time.YEAR_MS },\n );\n\n const createRender = () => {\n const Scene = data.default || data;\n return (\n <div data-chunk-name={chunkName}>\n <Scene {...rest}>\n {children}\n </Scene>\n </div>\n );\n };\n\n const [render, setRender] = useState(() => {\n // No need to await anything, we can render the final component right away.\n if (data && !heap.pendingStyles.length) {\n heap.renderInitialized = true;\n return createRender();\n }\n\n // Try to reuse the markup rendered during SSR.\n const node = document.querySelector(`[data-chunk-name=${chunkName}]`);\n if (node) {\n return (\n <div\n /* eslint-disable react/no-danger */\n dangerouslySetInnerHTML={{ __html: node.innerHTML || '' }}\n /* eslint-disable react/no-danger */\n data-chunk-name={chunkName}\n />\n );\n }\n\n // Else render placeholder, or empty div.\n const Scene = placeholder || (() => null);\n return <div><Scene {...rest}>{children}</Scene></div>;\n });\n\n // At this point, if we have data, the absense of heap.renderInitialized flag\n // means we have to await styles loading; once it is done, and if we are still\n // mounted, we can set the final render.\n if (data && !heap.renderInitialized) {\n heap.renderInitialized = true;\n Promise.all(heap.pendingStyles).then(() => {\n if (heap.stylesInitialized) setRender(createRender());\n });\n }\n\n // This effectively fires only once, just before the component unmounts.\n useEffect(() => () => {\n heap.stylesInitialized = false;\n window.CHUNK_GROUPS[chunkName].forEach((item) => {\n if (!item.endsWith('.css')) return;\n const path = `${publicPath}/${item}`;\n const link = document.querySelector(`link[href=\"${path}\"]`);\n link.dependants.delete(chunkName);\n if (!link.dependants.size) {\n const head = document.querySelector('head');\n head.removeChild(link);\n }\n });\n }, [chunkName, heap, publicPath]);\n\n return render;\n}\n"],"file":"ClientSide.js"}
@@ -1,24 +1,18 @@
1
1
  "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=ServerSide;var _server=_interopRequireDefault(require("react-dom/server"));var _propTypes=_interopRequireDefault(require("prop-types"));var _reactGlobalState=require("@dr.pogodin/react-global-state");var _reactRouterDom=require("react-router-dom");var _server2=require("react-router-dom/server");var _jsxRuntime=require("react/jsx-runtime");/**
2
2
  * Server-side implementation.
3
- */ /* eslint-disable react/jsx-props-no-spreading */ /**
4
- * A specially wrapped `require()`, which is passed as an argument into
5
- * the optional `getComponentServer` prop of <{@link CodeSplit}> component.
6
- * @param {string} base Path resolution base, you want to pass in `__dirname`
7
- * value from the host module using `<CodeSplit>`.
8
- * @param {string} path The path of module to require.
9
- * @return {object} Required module.
10
- */function resolveRequire(base,path){// NOTE: A part of code here attempts to correctly load ES6 modules
11
- // transformed by Babel; namely if required module has "default" field,
12
- // all other fields (presumed to be named exports) are attached to
13
- // the "default".
14
- const p=require.resolve(path,{paths:[base]});/* eslint-disable global-require, import/no-dynamic-require */const{default:def,...named}=require(p);/* eslint-enable global-require, import/no-dynamic-require */if(!def)return named;Object.entries(named).forEach(([key,value])=>{if(def[key])throw Error("Conflict between default and named exports");def[key]=value});return def}function ServerSide({chunkName,getComponentAsync,getComponentServer,placeholder,...rest}){/* 1. The component, or its placeholder is rendered into HTML string.
3
+ */ /* eslint-disable react/jsx-props-no-spreading */function ServerSide({chunkName,getClientSide,serverSide,placeholder,children,...rest}){/* 1. The component, or its placeholder is rendered into HTML string.
15
4
  * The component is wrapped into <GlobalStateProvider>, and <StaticRouter>
16
5
  * to ensure that global state, and react router will work inside
17
6
  * the component, if present there. Also, if no server-side (sync) way
18
7
  * to load the component is provider, `useAsyncData(..)` is used to
19
- * attempt to load and use the component via SSR mechanics. */let Scene;if(getComponentServer)Scene=getComponentServer(resolveRequire);else{// In this case we are sure the condition won't change during the rendering
8
+ * attempt to load and use the component via SSR mechanics. */let Scene;if(serverSide)Scene=serverSide;else{// In this case we are sure the condition won't change during the rendering
20
9
  // loop, thus we can ignore the rule.
21
- /* eslint-disable react-hooks/rules-of-hooks */const{data}=(0,_reactGlobalState.useAsyncData)(`dr_pogodin_react_utils___split_components.${chunkName}`,getComponentAsync);Scene=data?data.default||data:placeholder||(()=>null);/* eslint-enable react-hooks/rules-of-hooks */}const globalState=(0,_reactGlobalState.getGlobalState)();const{pathname}=(0,_reactRouterDom.useResolvedPath)("");const html=_server.default.renderToString(/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactGlobalState.GlobalStateProvider,{stateProxy:globalState,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_server2.StaticRouter,{basename:pathname,location:globalState.ssrContext.req.url,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(Scene,{...rest})})}));/* 2. `chunks` array is used to record CSS chunks to inject. */const{chunks}=globalState.ssrContext;if(chunks.includes(chunkName)){throw new Error(`CodeSplit: chunk name clash for (${chunkName})`)}else chunks.push(chunkName);/* The result is rendered using the container with `dangerouslySetInnerHTML`
10
+ /* eslint-disable react-hooks/rules-of-hooks */const{data}=(0,_reactGlobalState.useAsyncData)(`dr_pogodin_react_utils___split_components.${chunkName}`,getClientSide);Scene=data?data.default||data:placeholder||(()=>null);/* eslint-enable react-hooks/rules-of-hooks */}const globalState=(0,_reactGlobalState.getGlobalState)();const{pathname}=(0,_reactRouterDom.useResolvedPath)("");const html=_server.default.renderToString(/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactGlobalState.GlobalStateProvider,{stateProxy:globalState,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_server2.StaticRouter,{basename:pathname,location:globalState.ssrContext.req.url,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(Scene,{...rest,children:children})})}));/* 2. `chunks` array is used to record CSS chunks to inject. */const{chunks}=globalState.ssrContext;if(chunks.includes(chunkName)){throw new Error(`CodeSplit: chunk name clash for (${chunkName})`)}else chunks.push(chunkName);/* The result is rendered using the container with `dangerouslySetInnerHTML`
22
11
  * to allow reproduce the same rendering result at the client side, even prior
23
- * to the async loading of the split code. */ /* eslint-disable react/no-danger */return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{dangerouslySetInnerHTML:{__html:html},"data-chunk-name":chunkName});/* eslint-enable react/no-danger */}ServerSide.propTypes={chunkName:_propTypes.default.string.isRequired,getComponentAsync:_propTypes.default.func,getComponentServer:_propTypes.default.func,placeholder:_propTypes.default.elementType};ServerSide.defaultProps={getComponentAsync:null,getComponentServer:null,placeholder:null};
12
+ * to the async loading of the split code. */ /* eslint-disable react/no-danger */return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{dangerouslySetInnerHTML:{__html:html},"data-chunk-name":chunkName});/* eslint-enable react/no-danger */}ServerSide.propTypes={children:_propTypes.default.node,chunkName:_propTypes.default.string.isRequired,// Note: it is not strictly required by <ServerSide> component per se,
13
+ // as it is expected that in most cases "serverSide" prop should be provided,
14
+ // however "getClientSide" prop is still used as a fallback at the server side
15
+ // and also it is required by the parent splitComponent() function, so no harm
16
+ // to declare it as required here.
17
+ getClientSide:_propTypes.default.func.isRequired,placeholder:_propTypes.default.elementType,serverSide:_propTypes.default.elementType};ServerSide.defaultProps={children:undefined,placeholder:null,serverSide:undefined};
24
18
  //# sourceMappingURL=ServerSide.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/shared/components/CodeSplit/ServerSide.jsx"],"names":["resolveRequire","base","path","p","require","resolve","paths","default","def","named","Object","entries","forEach","key","value","Error","ServerSide","chunkName","getComponentAsync","getComponentServer","placeholder","rest","Scene","data","globalState","pathname","html","ReactDom","renderToString","ssrContext","req","url","chunks","includes","push","__html","propTypes","PT","string","isRequired","func","elementType","defaultProps"],"mappings":"oLAKA,gEACA,6DAEA,gEAMA,gDACA,gD,6CAfA;AACA;AACA,G,CACA,iD,CAcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAASA,CAAAA,cAAT,CAAwBC,IAAxB,CAA8BC,IAA9B,CAAoC,CAClC;AACA;AACA;AACA;AACA,KAAMC,CAAAA,CAAC,CAAGC,OAAO,CAACC,OAAR,CAAgBH,IAAhB,CAAsB,CAAEI,KAAK,CAAE,CAACL,IAAD,CAAT,CAAtB,CAAV,CACA,8DACA,KAAM,CAAEM,OAAO,CAAEC,GAAX,CAAgB,GAAGC,KAAnB,EAA6BL,OAAO,CAACD,CAAD,CAA1C,CACA,6DACA,GAAI,CAACK,GAAL,CAAU,MAAOC,CAAAA,KAAP,CAEVC,MAAM,CAACC,OAAP,CAAeF,KAAf,EAAsBG,OAAtB,CAA8B,CAAC,CAACC,GAAD,CAAMC,KAAN,CAAD,GAAkB,CAC9C,GAAIN,GAAG,CAACK,GAAD,CAAP,CAAc,KAAME,CAAAA,KAAK,CAAC,4CAAD,CAAX,CACdP,GAAG,CAACK,GAAD,CAAH,CAAWC,KACZ,CAHD,EAIA,MAAON,CAAAA,GACR,CAEc,QAASQ,CAAAA,UAAT,CAAoB,CACjCC,SADiC,CAEjCC,iBAFiC,CAGjCC,kBAHiC,CAIjCC,WAJiC,CAKjC,GAAGC,IAL8B,CAApB,CAMZ,CACD;AACF;AACA;AACA;AACA;AACA,mEACE,GAAIC,CAAAA,KAAJ,CACA,GAAIH,kBAAJ,CAAwBG,KAAK,CAAGH,kBAAkB,CAACnB,cAAD,CAA1B,CAAxB,IACK,CACH;AACA;AACA,+CACA,KAAM,CAAEuB,IAAF,EAAW,mCACd,6CAA4CN,SAAU,EADxC,CAEfC,iBAFe,CAAjB,CAIAI,KAAK,CAAGC,IAAI,CAAIA,IAAI,CAAChB,OAAL,EAAgBgB,IAApB,CAA6BH,WAAW,GAAK,IAAM,IAAX,CAApD,CACA,8CACD,CAED,KAAMI,CAAAA,WAAW,CAAG,sCAApB,CACA,KAAM,CAAEC,QAAF,EAAe,oCAAgB,EAAhB,CAArB,CACA,KAAMC,CAAAA,IAAI,CAAGC,gBAASC,cAAT,cACX,oBAAC,qCAAD,EAAqB,UAAU,CAAEJ,WAAjC,uBACE,oBAAC,qBAAD,EACE,QAAQ,CAAEC,QADZ,CAEE,QAAQ,CAAED,WAAW,CAACK,UAAZ,CAAuBC,GAAvB,CAA2BC,GAFvC,uBAIE,oBAAC,KAAD,KAAWV,IAAX,EAJF,EADF,EADW,CAAb,CAWA,+DACA,KAAM,CAAEW,MAAF,EAAaR,WAAW,CAACK,UAA/B,CACA,GAAIG,MAAM,CAACC,QAAP,CAAgBhB,SAAhB,CAAJ,CAAgC,CAC9B,KAAM,IAAIF,CAAAA,KAAJ,CAAW,oCAAmCE,SAAU,GAAxD,CACP,CAFD,IAEOe,CAAAA,MAAM,CAACE,IAAP,CAAYjB,SAAZ,EAEP;AACF;AACA,+CA1CG,CA2CD,oCACA,mBACE,2BACE,uBAAuB,CAAE,CAAEkB,MAAM,CAAET,IAAV,CAD3B,CAEE,kBAAiBT,SAFnB,EADF,CAMA,mCACD,CAEDD,UAAU,CAACoB,SAAX,CAAuB,CACrBnB,SAAS,CAAEoB,mBAAGC,MAAH,CAAUC,UADA,CAErBrB,iBAAiB,CAAEmB,mBAAGG,IAFD,CAGrBrB,kBAAkB,CAAEkB,mBAAGG,IAHF,CAIrBpB,WAAW,CAAEiB,mBAAGI,WAJK,CAAvB,CAOAzB,UAAU,CAAC0B,YAAX,CAA0B,CACxBxB,iBAAiB,CAAE,IADK,CAExBC,kBAAkB,CAAE,IAFI,CAGxBC,WAAW,CAAE,IAHW,CAA1B","sourcesContent":["/**\n * Server-side implementation.\n */\n/* eslint-disable react/jsx-props-no-spreading */\n\nimport ReactDom from 'react-dom/server';\nimport PT from 'prop-types';\n\nimport {\n getGlobalState,\n GlobalStateProvider,\n useAsyncData,\n} from '@dr.pogodin/react-global-state';\n\nimport { useResolvedPath } from 'react-router-dom';\nimport { StaticRouter } from 'react-router-dom/server';\n\n/**\n * A specially wrapped `require()`, which is passed as an argument into\n * the optional `getComponentServer` prop of <{@link CodeSplit}> component.\n * @param {string} base Path resolution base, you want to pass in `__dirname`\n * value from the host module using `<CodeSplit>`.\n * @param {string} path The path of module to require.\n * @return {object} Required module.\n */\nfunction resolveRequire(base, path) {\n // NOTE: A part of code here attempts to correctly load ES6 modules\n // transformed by Babel; namely if required module has \"default\" field,\n // all other fields (presumed to be named exports) are attached to\n // the \"default\".\n const p = require.resolve(path, { paths: [base] });\n /* eslint-disable global-require, import/no-dynamic-require */\n const { default: def, ...named } = require(p);\n /* eslint-enable global-require, import/no-dynamic-require */\n if (!def) return named;\n\n Object.entries(named).forEach(([key, value]) => {\n if (def[key]) throw Error('Conflict between default and named exports');\n def[key] = value;\n });\n return def;\n}\n\nexport default function ServerSide({\n chunkName,\n getComponentAsync,\n getComponentServer,\n placeholder,\n ...rest\n}) {\n /* 1. The component, or its placeholder is rendered into HTML string.\n * The component is wrapped into <GlobalStateProvider>, and <StaticRouter>\n * to ensure that global state, and react router will work inside\n * the component, if present there. Also, if no server-side (sync) way\n * to load the component is provider, `useAsyncData(..)` is used to\n * attempt to load and use the component via SSR mechanics. */\n let Scene;\n if (getComponentServer) Scene = getComponentServer(resolveRequire);\n else {\n // In this case we are sure the condition won't change during the rendering\n // loop, thus we can ignore the rule.\n /* eslint-disable react-hooks/rules-of-hooks */\n const { data } = useAsyncData(\n `dr_pogodin_react_utils___split_components.${chunkName}`,\n getComponentAsync,\n );\n Scene = data ? (data.default || data) : (placeholder || (() => null));\n /* eslint-enable react-hooks/rules-of-hooks */\n }\n\n const globalState = getGlobalState();\n const { pathname } = useResolvedPath('');\n const html = ReactDom.renderToString((\n <GlobalStateProvider stateProxy={globalState}>\n <StaticRouter\n basename={pathname}\n location={globalState.ssrContext.req.url}\n >\n <Scene {...rest} />\n </StaticRouter>\n </GlobalStateProvider>\n ));\n\n /* 2. `chunks` array is used to record CSS chunks to inject. */\n const { chunks } = globalState.ssrContext;\n if (chunks.includes(chunkName)) {\n throw new Error(`CodeSplit: chunk name clash for (${chunkName})`);\n } else chunks.push(chunkName);\n\n /* The result is rendered using the container with `dangerouslySetInnerHTML`\n * to allow reproduce the same rendering result at the client side, even prior\n * to the async loading of the split code. */\n /* eslint-disable react/no-danger */\n return (\n <div\n dangerouslySetInnerHTML={{ __html: html }}\n data-chunk-name={chunkName}\n />\n );\n /* eslint-enable react/no-danger */\n}\n\nServerSide.propTypes = {\n chunkName: PT.string.isRequired,\n getComponentAsync: PT.func,\n getComponentServer: PT.func,\n placeholder: PT.elementType,\n};\n\nServerSide.defaultProps = {\n getComponentAsync: null,\n getComponentServer: null,\n placeholder: null,\n};\n"],"file":"ServerSide.js"}
1
+ {"version":3,"sources":["../../../../../src/shared/components/CodeSplit/ServerSide.jsx"],"names":["ServerSide","chunkName","getClientSide","serverSide","placeholder","children","rest","Scene","data","default","globalState","pathname","html","ReactDom","renderToString","ssrContext","req","url","chunks","includes","Error","push","__html","propTypes","PT","node","string","isRequired","func","elementType","defaultProps","undefined"],"mappings":"oLAKA,gEACA,6DAEA,gEAMA,gDACA,gD,6CAfA;AACA;AACA,G,CACA,iDAce,QAASA,CAAAA,UAAT,CAAoB,CACjCC,SADiC,CAEjCC,aAFiC,CAGjCC,UAHiC,CAIjCC,WAJiC,CAKjCC,QALiC,CAMjC,GAAGC,IAN8B,CAApB,CAOZ,CACD;AACF;AACA;AACA;AACA;AACA,mEACE,GAAIC,CAAAA,KAAJ,CACA,GAAIJ,UAAJ,CAAgBI,KAAK,CAAGJ,UAAR,CAAhB,IACK,CACH;AACA;AACA,+CACA,KAAM,CAAEK,IAAF,EAAW,mCACd,6CAA4CP,SAAU,EADxC,CAEfC,aAFe,CAAjB,CAIAK,KAAK,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,UAAU,CAAE4B,SAHY,CAA1B","sourcesContent":["/**\n * Server-side implementation.\n */\n/* eslint-disable react/jsx-props-no-spreading */\n\nimport ReactDom from 'react-dom/server';\nimport PT from 'prop-types';\n\nimport {\n getGlobalState,\n GlobalStateProvider,\n useAsyncData,\n} from '@dr.pogodin/react-global-state';\n\nimport { useResolvedPath } from 'react-router-dom';\nimport { StaticRouter } from 'react-router-dom/server';\n\nexport default function ServerSide({\n chunkName,\n getClientSide,\n serverSide,\n placeholder,\n children,\n ...rest\n}) {\n /* 1. The component, or its placeholder is rendered into HTML string.\n * The component is wrapped into <GlobalStateProvider>, and <StaticRouter>\n * to ensure that global state, and react router will work inside\n * the component, if present there. Also, if no server-side (sync) way\n * to load the component is provider, `useAsyncData(..)` is used to\n * attempt to load and use the component via SSR mechanics. */\n let Scene;\n if (serverSide) Scene = serverSide;\n else {\n // In this case we are sure the condition won't change during the rendering\n // loop, thus we can ignore the rule.\n /* eslint-disable react-hooks/rules-of-hooks */\n const { data } = useAsyncData(\n `dr_pogodin_react_utils___split_components.${chunkName}`,\n getClientSide,\n );\n Scene = data ? (data.default || data) : (placeholder || (() => null));\n /* eslint-enable react-hooks/rules-of-hooks */\n }\n\n const globalState = getGlobalState();\n const { pathname } = useResolvedPath('');\n const html = ReactDom.renderToString((\n <GlobalStateProvider stateProxy={globalState}>\n <StaticRouter\n basename={pathname}\n location={globalState.ssrContext.req.url}\n >\n <Scene {...rest}>\n {children}\n </Scene>\n </StaticRouter>\n </GlobalStateProvider>\n ));\n\n /* 2. `chunks` array is used to record CSS chunks to inject. */\n const { chunks } = globalState.ssrContext;\n if (chunks.includes(chunkName)) {\n throw new Error(`CodeSplit: chunk name clash for (${chunkName})`);\n } else chunks.push(chunkName);\n\n /* The result is rendered using the container with `dangerouslySetInnerHTML`\n * to allow reproduce the same rendering result at the client side, even prior\n * to the async loading of the split code. */\n /* eslint-disable react/no-danger */\n return (\n <div\n dangerouslySetInnerHTML={{ __html: html }}\n data-chunk-name={chunkName}\n />\n );\n /* eslint-enable react/no-danger */\n}\n\nServerSide.propTypes = {\n children: PT.node,\n chunkName: PT.string.isRequired,\n\n // Note: it is not strictly required by <ServerSide> component per se,\n // as it is expected that in most cases \"serverSide\" prop should be provided,\n // however \"getClientSide\" prop is still used as a fallback at the server side\n // and also it is required by the parent splitComponent() function, so no harm\n // to declare it as required here.\n getClientSide: PT.func.isRequired,\n\n placeholder: PT.elementType,\n serverSide: PT.elementType,\n};\n\nServerSide.defaultProps = {\n children: undefined,\n placeholder: null,\n serverSide: undefined,\n};\n"],"file":"ServerSide.js"}
@@ -1,3 +1,6 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _utils=require("../../utils");var _ClientSide=_interopRequireDefault(require("./ClientSide"));let Component;// eslint-disable-line import/no-mutable-exports
2
- try{Component=_utils.isomorphy.IS_SERVER_SIDE&&_utils.webpack.requireWeak(`${__dirname}/ServerSide`)}catch(error){Component=undefined}if(!Component)Component=_ClientSide.default;var _default=Component;exports.default=_default;
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _webpack=require("../../utils/webpack");var _ClientSide=_interopRequireDefault(require("./ClientSide"));// This module exposes client- or server-side version of the <CodeSplit>
2
+ // component, depending on the environment. That component is used internally
3
+ // to implement the code splitting. Library users should use splitComponent()
4
+ // function to use the code splitting (see "utils/splitComponent.js").
5
+ var _default=(0,_webpack.requireWeak)("./ServerSide",__dirname)||_ClientSide.default;exports.default=_default;
3
6
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/shared/components/CodeSplit/index.js"],"names":["Component","isomorphy","IS_SERVER_SIDE","webpack","requireWeak","__dirname","error","undefined","ClientSide"],"mappings":"gLAAA,kCAEA,gEAEA,GAAIA,CAAAA,SAAJ,CAAe;AAEf,GAAI,CACFA,SAAS,CAAGC,iBAAUC,cAAV,EACPC,eAAQC,WAAR,CAAqB,GAAEC,SAAU,aAAjC,CACN,CAAC,MAAOC,KAAP,CAAc,CACdN,SAAS,CAAGO,SACb,CAED,GAAI,CAACP,SAAL,CAAgBA,SAAS,CAAGQ,mBAAZ,C,aAEDR,S","sourcesContent":["import { isomorphy, webpack } from 'utils';\n\nimport ClientSide from './ClientSide';\n\nlet Component; // eslint-disable-line import/no-mutable-exports\n\ntry {\n Component = isomorphy.IS_SERVER_SIDE\n && webpack.requireWeak(`${__dirname}/ServerSide`);\n} catch (error) {\n Component = undefined;\n}\n\nif (!Component) Component = ClientSide;\n\nexport default Component;\n"],"file":"index.js"}
1
+ {"version":3,"sources":["../../../../../src/shared/components/CodeSplit/index.jsx"],"names":["__dirname","ClientSide"],"mappings":"gLAKA,4CACA,gEANA;AACA;AACA;AACA;aAKe,wCAA4BA,SAA5B,GAA0CC,mB","sourcesContent":["// This module exposes client- or server-side version of the <CodeSplit>\n// component, depending on the environment. That component is used internally\n// to implement the code splitting. Library users should use splitComponent()\n// function to use the code splitting (see \"utils/splitComponent.js\").\n\nimport { requireWeak } from 'utils/webpack';\nimport ClientSide from './ClientSide';\n\nexport default requireWeak('./ServerSide', __dirname) || ClientSide;\n"],"file":"index.js"}
@@ -1,2 +1,2 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"BaseModal",{enumerable:true,get:function(){return _Modal.BaseModal}});Object.defineProperty(exports,"Button",{enumerable:true,get:function(){return _Button.default}});Object.defineProperty(exports,"Checkbox",{enumerable:true,get:function(){return _Checkbox.default}});Object.defineProperty(exports,"CodeSplit",{enumerable:true,get:function(){return _CodeSplit.default}});Object.defineProperty(exports,"Dropdown",{enumerable:true,get:function(){return _Dropdown.default}});Object.defineProperty(exports,"Input",{enumerable:true,get:function(){return _Input.default}});Object.defineProperty(exports,"Link",{enumerable:true,get:function(){return _Link.default}});Object.defineProperty(exports,"MetaTags",{enumerable:true,get:function(){return _MetaTags.default}});Object.defineProperty(exports,"Modal",{enumerable:true,get:function(){return _Modal.default}});Object.defineProperty(exports,"NavLink",{enumerable:true,get:function(){return _NavLink.default}});Object.defineProperty(exports,"PageLayout",{enumerable:true,get:function(){return _PageLayout.default}});Object.defineProperty(exports,"ScalableRect",{enumerable:true,get:function(){return _ScalableRect.default}});Object.defineProperty(exports,"Throbber",{enumerable:true,get:function(){return _Throbber.default}});Object.defineProperty(exports,"WithTooltip",{enumerable:true,get:function(){return _WithTooltip.default}});Object.defineProperty(exports,"YouTubeVideo",{enumerable:true,get:function(){return _YouTubeVideo.default}});Object.defineProperty(exports,"client",{enumerable:true,get:function(){return _client.default}});var _Button=_interopRequireDefault(require("./Button"));var _Checkbox=_interopRequireDefault(require("./Checkbox"));var _client=_interopRequireDefault(require("../../client"));var _CodeSplit=_interopRequireDefault(require("./CodeSplit"));var _Dropdown=_interopRequireDefault(require("./Dropdown"));var _Input=_interopRequireDefault(require("./Input"));var _Link=_interopRequireDefault(require("./Link"));var _PageLayout=_interopRequireDefault(require("./PageLayout"));var _MetaTags=_interopRequireDefault(require("./MetaTags"));var _Modal=_interopRequireWildcard(require("./Modal"));var _NavLink=_interopRequireDefault(require("./NavLink"));var _ScalableRect=_interopRequireDefault(require("./ScalableRect"));var _Throbber=_interopRequireDefault(require("./Throbber"));var _WithTooltip=_interopRequireDefault(require("./WithTooltip"));var _YouTubeVideo=_interopRequireDefault(require("./YouTubeVideo"));function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap;var cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj.default=obj;if(cache){cache.set(obj,newObj)}return newObj}
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"BaseModal",{enumerable:true,get:function(){return _Modal.BaseModal}});Object.defineProperty(exports,"Button",{enumerable:true,get:function(){return _Button.default}});Object.defineProperty(exports,"Checkbox",{enumerable:true,get:function(){return _Checkbox.default}});Object.defineProperty(exports,"Dropdown",{enumerable:true,get:function(){return _Dropdown.default}});Object.defineProperty(exports,"Input",{enumerable:true,get:function(){return _Input.default}});Object.defineProperty(exports,"Link",{enumerable:true,get:function(){return _Link.default}});Object.defineProperty(exports,"MetaTags",{enumerable:true,get:function(){return _MetaTags.default}});Object.defineProperty(exports,"Modal",{enumerable:true,get:function(){return _Modal.default}});Object.defineProperty(exports,"NavLink",{enumerable:true,get:function(){return _NavLink.default}});Object.defineProperty(exports,"PageLayout",{enumerable:true,get:function(){return _PageLayout.default}});Object.defineProperty(exports,"ScalableRect",{enumerable:true,get:function(){return _ScalableRect.default}});Object.defineProperty(exports,"Throbber",{enumerable:true,get:function(){return _Throbber.default}});Object.defineProperty(exports,"WithTooltip",{enumerable:true,get:function(){return _WithTooltip.default}});Object.defineProperty(exports,"YouTubeVideo",{enumerable:true,get:function(){return _YouTubeVideo.default}});Object.defineProperty(exports,"client",{enumerable:true,get:function(){return _client.default}});var _Button=_interopRequireDefault(require("./Button"));var _Checkbox=_interopRequireDefault(require("./Checkbox"));var _client=_interopRequireDefault(require("../../client"));var _Dropdown=_interopRequireDefault(require("./Dropdown"));var _Input=_interopRequireDefault(require("./Input"));var _Link=_interopRequireDefault(require("./Link"));var _PageLayout=_interopRequireDefault(require("./PageLayout"));var _MetaTags=_interopRequireDefault(require("./MetaTags"));var _Modal=_interopRequireWildcard(require("./Modal"));var _NavLink=_interopRequireDefault(require("./NavLink"));var _ScalableRect=_interopRequireDefault(require("./ScalableRect"));var _Throbber=_interopRequireDefault(require("./Throbber"));var _WithTooltip=_interopRequireDefault(require("./WithTooltip"));var _YouTubeVideo=_interopRequireDefault(require("./YouTubeVideo"));function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap;var cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj.default=obj;if(cache){cache.set(obj,newObj)}return newObj}
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/shared/components/index.js"],"names":[],"mappings":"uuDAIA,wDACA,4DACA,4DACA,8DACA,4DACA,sDACA,oDACA,gEACA,4DACA,uDACA,0DACA,oEACA,4DACA,kEACA,oE","sourcesContent":["/**\n * Just an aggregation of all exported components into a single module.\n */\n\nexport { default as Button } from 'components/Button';\nexport { default as Checkbox } from 'components/Checkbox';\nexport { default as client } from 'client';\nexport { default as CodeSplit } from './CodeSplit';\nexport { default as Dropdown } from 'components/Dropdown';\nexport { default as Input } from 'components/Input';\nexport { default as Link } from 'components/Link';\nexport { default as PageLayout } from 'components/PageLayout';\nexport { default as MetaTags } from 'components/MetaTags';\nexport { default as Modal, BaseModal } from 'components/Modal';\nexport { default as NavLink } from 'components/NavLink';\nexport { default as ScalableRect } from 'components/ScalableRect';\nexport { default as Throbber } from 'components/Throbber';\nexport { default as WithTooltip } from 'components/WithTooltip';\nexport { default as YouTubeVideo } from 'components/YouTubeVideo';\n"],"file":"index.js"}
1
+ {"version":3,"sources":["../../../../src/shared/components/index.js"],"names":[],"mappings":"goDAIA,wDACA,4DACA,4DACA,4DACA,sDACA,oDACA,gEACA,4DACA,uDACA,0DACA,oEACA,4DACA,kEACA,oE","sourcesContent":["/**\n * Just an aggregation of all exported components into a single module.\n */\n\nexport { default as Button } from 'components/Button';\nexport { default as Checkbox } from 'components/Checkbox';\nexport { default as client } from 'client';\nexport { default as Dropdown } from 'components/Dropdown';\nexport { default as Input } from 'components/Input';\nexport { default as Link } from 'components/Link';\nexport { default as PageLayout } from 'components/PageLayout';\nexport { default as MetaTags } from 'components/MetaTags';\nexport { default as Modal, BaseModal } from 'components/Modal';\nexport { default as NavLink } from 'components/NavLink';\nexport { default as ScalableRect } from 'components/ScalableRect';\nexport { default as Throbber } from 'components/Throbber';\nexport { default as WithTooltip } from 'components/WithTooltip';\nexport { default as YouTubeVideo } from 'components/YouTubeVideo';\n"],"file":"index.js"}
@@ -0,0 +1,5 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _Barrier=require("./Barrier");/**
2
+ * Implements a simple semaphore for async code logic.
3
+ */class Semaphore{#barrier;#ready;constructor(ready=false){this.#ready=ready}get ready(){return this.#ready}setReady(ready){this.#ready=ready;if(this.#barrier){this.#barrier.resolve();this.#barrier=undefined}}async waitReady(){while(!this.#ready){if(!this.#barrier)this.#barrier=(0,_Barrier.newBarrier)();await this.#barrier;// eslint-disable-line no-await-in-loop
4
+ }}}exports.default=Semaphore;
5
+ //# sourceMappingURL=Semaphore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/shared/utils/Semaphore.js"],"names":["Semaphore","barrier","ready","constructor","setReady","resolve","undefined","waitReady"],"mappings":"6FAAA,kCAEA;AACA;AACA,GACe,KAAMA,CAAAA,SAAU,CAC7B,CAACC,OAAD,CAEA,CAACC,KAAD,CAEAC,WAAW,CAACD,KAAK,CAAG,KAAT,CAAgB,CACzB,KAAK,CAACA,KAAN,CAAcA,KACf,CAEQ,GAALA,CAAAA,KAAK,EAAG,CAAE,MAAO,MAAK,CAACA,KAAQ,CAEnCE,QAAQ,CAACF,KAAD,CAAQ,CACd,KAAK,CAACA,KAAN,CAAcA,KAAd,CACA,GAAI,KAAK,CAACD,OAAV,CAAmB,CACjB,KAAK,CAACA,OAAN,CAAcI,OAAd,GACA,KAAK,CAACJ,OAAN,CAAgBK,SACjB,CACF,CAEc,KAATC,CAAAA,SAAS,EAAG,CAChB,MAAO,CAAC,KAAK,CAACL,KAAd,CAAqB,CACnB,GAAI,CAAC,KAAK,CAACD,OAAX,CAAoB,KAAK,CAACA,OAAN,CAAgB,yBAAhB,CACpB,KAAM,MAAK,CAACA,OAAZ,CAAqB;AACtB,CACF,CAxB4B,C","sourcesContent":["import { newBarrier } from './Barrier';\n\n/**\n * Implements a simple semaphore for async code logic.\n */\nexport default class Semaphore {\n #barrier;\n\n #ready;\n\n constructor(ready = false) {\n this.#ready = ready;\n }\n\n get ready() { return this.#ready; }\n\n setReady(ready) {\n this.#ready = ready;\n if (this.#barrier) {\n this.#barrier.resolve();\n this.#barrier = undefined;\n }\n }\n\n async waitReady() {\n while (!this.#ready) {\n if (!this.#barrier) this.#barrier = newBarrier();\n await this.#barrier; // eslint-disable-line no-await-in-loop\n }\n }\n}\n"],"file":"Semaphore.js"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _isomorphy=require("./isomorphy");var _webpack=require("./webpack");/* global window */ /* eslint-disable global-require */var _default=_isomorphy.IS_CLIENT_SIDE?window.CONFIG:(0,_webpack.requireWeak)("config");/* eslint-enable global-require */exports.default=_default;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _webpack=require("./webpack");/* global window */ /* eslint-disable global-require */var _default=(0,_webpack.requireWeak)("config")||window.CONFIG;/* eslint-enable global-require */exports.default=_default;
2
2
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/shared/utils/config.js"],"names":["IS_CLIENT_SIDE","window","CONFIG"],"mappings":"6FAEA,sCACA,kCAHA,mB,CAKA,mC,aACeA,0BAAiBC,MAAM,CAACC,MAAxB,CAAiC,yBAAY,QAAZ,C,CAChD,kC","sourcesContent":["/* global window */\n\nimport { IS_CLIENT_SIDE } from './isomorphy';\nimport { requireWeak } from './webpack';\n\n/* eslint-disable global-require */\nexport default IS_CLIENT_SIDE ? window.CONFIG : requireWeak('config');\n/* eslint-enable global-require */\n"],"file":"config.js"}
1
+ {"version":3,"sources":["../../../../src/shared/utils/config.js"],"names":["window","CONFIG"],"mappings":"6FAEA,kCAFA,mB,CAIA,mC,aACe,yBAAY,QAAZ,GAAyBA,MAAM,CAACC,M,CAC/C,kC","sourcesContent":["/* global window */\n\nimport { requireWeak } from './webpack';\n\n/* eslint-disable global-require */\nexport default requireWeak('config') || window.CONFIG;\n/* eslint-enable global-require */\n"],"file":"config.js"}
@@ -1,5 +1,7 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={withRetries:true,JU:true,themed:true,ThemeProvider:true,config:true,isomorphy:true,time:true,webpack:true,Emitter:true};Object.defineProperty(exports,"Emitter",{enumerable:true,get:function(){return _Emitter.default}});exports.JU=void 0;Object.defineProperty(exports,"ThemeProvider",{enumerable:true,get:function(){return _reactThemes.ThemeProvider}});Object.defineProperty(exports,"config",{enumerable:true,get:function(){return _config.default}});exports.isomorphy=void 0;Object.defineProperty(exports,"themed",{enumerable:true,get:function(){return _reactThemes.default}});Object.defineProperty(exports,"time",{enumerable:true,get:function(){return _time.default}});exports.webpack=void 0;exports.withRetries=withRetries;var _reactThemes=_interopRequireWildcard(require("@dr.pogodin/react-themes"));var _config=_interopRequireDefault(require("./config"));var isomorphy=_interopRequireWildcard(require("./isomorphy"));exports.isomorphy=isomorphy;var _time=_interopRequireDefault(require("./time"));var webpack=_interopRequireWildcard(require("./webpack"));exports.webpack=webpack;var _Barrier=require("./Barrier");Object.keys(_Barrier).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===_Barrier[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _Barrier[key]}})});var _Emitter=_interopRequireDefault(require("./Emitter"));function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap;var cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj.default=obj;if(cache){cache.set(obj,newObj)}return newObj}_reactThemes.default.COMPOSE=_reactThemes.COMPOSE;_reactThemes.default.PRIORITY=_reactThemes.PRIORITY;let JU=null;// eslint-disable-line import/no-mutable-exports
2
- exports.JU=JU;if(isomorphy.IS_SERVER_SIDE&&(process.env.NODE_CONFIG_ENV||process.env.NODE_ENV)!=="production"){/* eslint-disable global-require */const path=webpack.requireWeak("path");exports.JU=JU=webpack.requireWeak(path.resolve(__dirname,"./jest"));/* eslint-enable global-require */}/**
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={withRetries:true,JU:true,themed:true,ThemeProvider:true,config:true,isomorphy:true,time:true,webpack:true,Emitter:true,Semaphore:true,splitComponent:true};Object.defineProperty(exports,"Emitter",{enumerable:true,get:function(){return _Emitter.default}});exports.JU=void 0;Object.defineProperty(exports,"Semaphore",{enumerable:true,get:function(){return _Semaphore.default}});Object.defineProperty(exports,"ThemeProvider",{enumerable:true,get:function(){return _reactThemes.ThemeProvider}});Object.defineProperty(exports,"config",{enumerable:true,get:function(){return _config.default}});exports.isomorphy=void 0;Object.defineProperty(exports,"splitComponent",{enumerable:true,get:function(){return _splitComponent.default}});Object.defineProperty(exports,"themed",{enumerable:true,get:function(){return _reactThemes.default}});Object.defineProperty(exports,"time",{enumerable:true,get:function(){return _time.default}});exports.webpack=void 0;exports.withRetries=withRetries;var _reactThemes=_interopRequireWildcard(require("@dr.pogodin/react-themes"));var _config=_interopRequireDefault(require("./config"));var isomorphy=_interopRequireWildcard(require("./isomorphy"));exports.isomorphy=isomorphy;var _time=_interopRequireDefault(require("./time"));var webpack=_interopRequireWildcard(require("./webpack"));exports.webpack=webpack;var _Barrier=require("./Barrier");Object.keys(_Barrier).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===_Barrier[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _Barrier[key]}})});var _Emitter=_interopRequireDefault(require("./Emitter"));var _Semaphore=_interopRequireDefault(require("./Semaphore"));var _splitComponent=_interopRequireDefault(require("./splitComponent"));function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap;var cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj.default=obj;if(cache){cache.set(obj,newObj)}return newObj}_reactThemes.default.COMPOSE=_reactThemes.COMPOSE;_reactThemes.default.PRIORITY=_reactThemes.PRIORITY;// Note: it should be done this way, as in some environments
2
+ // "process" might not exist, and process.env.NODE_CONFIG_ENV
3
+ // not injected by Webpack.
4
+ let NODE_CONFIG_ENV;try{NODE_CONFIG_ENV=process.env.NODE_CONFIG_ENV}catch{/* noop */}const env=NODE_CONFIG_ENV||process.env.NODE_ENV;const JU=env!=="production"&&webpack.requireWeak("./jest",__dirname);/**
3
5
  * @category Utilities
4
6
  * @global
5
7
  * @func withRetries
@@ -33,5 +35,5 @@ exports.JU=JU;if(isomorphy.IS_SERVER_SIDE&&(process.env.NODE_CONFIG_ENV||process
33
35
  * withRetries(sampleAction).then(console.log);
34
36
  * // It will print 'success' after one second, once the second attempt
35
37
  * // is performed.
36
- */async function withRetries(action,maxRetries=5,interval=1000){/* eslint-disable no-await-in-loop */for(let n=1;;++n){try{return await action()}catch(error){if(n<maxRetries)await _time.default.timer(interval);else throw error}}/* eslint-enable no-await-in-loop */}
38
+ */exports.JU=JU;async function withRetries(action,maxRetries=5,interval=1000){/* eslint-disable no-await-in-loop */for(let n=1;;++n){try{return await action()}catch(error){if(n<maxRetries)await _time.default.timer(interval);else throw error}}/* eslint-enable no-await-in-loop */}
37
39
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/shared/utils/index.js"],"names":["themed","COMPOSE","PRIORITY","JU","isomorphy","IS_SERVER_SIDE","process","env","NODE_CONFIG_ENV","NODE_ENV","path","webpack","requireWeak","resolve","__dirname","withRetries","action","maxRetries","interval","n","error","time","timer"],"mappings":"+3BAAA,8EAMA,wDACA,8D,4BACA,oDACA,0D,wBAEA,gVACA,0D,o9BAEAA,qBAAOC,OAAP,CAAiBA,oBAAjB,CACAD,qBAAOE,QAAP,CAAkBA,qBAAlB,CAEA,GAAIC,CAAAA,EAAE,CAAG,IAAT,CAAe;cACf,GAAIC,SAAS,CAACC,cAAV,EACC,CAACC,OAAO,CAACC,GAAR,CAAYC,eAAZ,EAA+BF,OAAO,CAACC,GAAR,CAAYE,QAA5C,IAA0D,YAD/D,CAEE,CACA,mCACA,KAAMC,CAAAA,IAAI,CAAGC,OAAO,CAACC,WAAR,CAAoB,MAApB,CAAb,CACA,WAAAT,EAAE,CAAGQ,OAAO,CAACC,WAAR,CAAoBF,IAAI,CAACG,OAAL,CAAaC,SAAb,CAAwB,QAAxB,CAApB,CAAL,CACA,kCACD,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,cAAeC,CAAAA,WAAf,CAA2BC,MAA3B,CAAmCC,UAAU,CAAG,CAAhD,CAAmDC,QAAQ,CAAG,IAA9D,CAAoE,CACzE,qCACA,IAAK,GAAIC,CAAAA,CAAC,CAAG,CAAb,EAAkB,EAAEA,CAApB,CAAuB,CACrB,GAAI,CACF,MAAO,MAAMH,CAAAA,MAAM,EACpB,CAAC,MAAOI,KAAP,CAAc,CACd,GAAID,CAAC,CAAGF,UAAR,CAAoB,KAAMI,eAAKC,KAAL,CAAWJ,QAAX,CAAN,CAApB,IACK,MAAME,CAAAA,KACZ,CACF,CACD,oCACD","sourcesContent":["import themed, {\n COMPOSE,\n PRIORITY,\n ThemeProvider,\n} from '@dr.pogodin/react-themes';\n\nimport config from './config';\nimport * as isomorphy from './isomorphy';\nimport time from './time';\nimport * as webpack from './webpack';\n\nexport * from './Barrier';\nexport { default as Emitter } from './Emitter';\n\nthemed.COMPOSE = COMPOSE;\nthemed.PRIORITY = PRIORITY;\n\nlet JU = null; // eslint-disable-line import/no-mutable-exports\nif (isomorphy.IS_SERVER_SIDE\n && (process.env.NODE_CONFIG_ENV || process.env.NODE_ENV) !== 'production'\n) {\n /* eslint-disable global-require */\n const path = webpack.requireWeak('path');\n JU = webpack.requireWeak(path.resolve(__dirname, './jest'));\n /* eslint-enable global-require */\n}\n\n/**\n * @category Utilities\n * @global\n * @func withRetries\n * @desc\n * ```js\n * import { withRetries } from '@dr.pogodin/react-utils';\n * ```\n * Attempts to perform given asynchronous `action` up to `maxRetries` times,\n * with the given `interval` between attempts. If any attempt is successful,\n * the result is returned immediately, with no further attempts done;\n * otherwise, if all attempts fail, the result Promise rejects after the last\n * attempt.\n * @param {function} action\n * @param {number} [maxRetries=5] Optional. Maximum number of retries. Defaults\n * to 5 attempts.\n * @param {number} [interval=1000] Optional. Interval between retries [ms].\n * Defaults to 1 second.\n * @return {Promise} Resolves to the result of successful operation, or\n * rejects with the error from the latst failed attempt.\n * @example\n * import { withRetries } from '@dr.pogodin/react-utils';\n *\n * let firstCall = true;\n *\n * function sampleAction() {\n * if (!firstCall) return 'success';\n * firstCall = false;\n * throw Error('The first call to this method fails');\n * }\n *\n * withRetries(sampleAction).then(console.log);\n * // It will print 'success' after one second, once the second attempt\n * // is performed.\n */\nexport async function withRetries(action, maxRetries = 5, interval = 1000) {\n /* eslint-disable no-await-in-loop */\n for (let n = 1; ; ++n) {\n try {\n return await action();\n } catch (error) {\n if (n < maxRetries) await time.timer(interval);\n else throw error;\n }\n }\n /* eslint-enable no-await-in-loop */\n}\n\nexport {\n config,\n isomorphy,\n JU,\n themed,\n ThemeProvider,\n time,\n webpack,\n};\n"],"file":"index.js"}
1
+ {"version":3,"sources":["../../../../src/shared/utils/index.js"],"names":["themed","COMPOSE","PRIORITY","NODE_CONFIG_ENV","process","env","NODE_ENV","JU","webpack","requireWeak","__dirname","withRetries","action","maxRetries","interval","n","error","time","timer"],"mappings":"0nCAAA,8EAMA,wDACA,8D,4BACA,oDACA,0D,wBAEA,gVACA,0DACA,8DACA,wE,o9BAEAA,qBAAOC,OAAP,CAAiBA,oBAAjB,CACAD,qBAAOE,QAAP,CAAkBA,qBAAlB,CAEA;AACA;AACA;AACA,GAAIC,CAAAA,eAAJ,CACA,GAAI,CACFA,eAAe,CAAGC,OAAO,CAACC,GAAR,CAAYF,eAC/B,CAAC,KAAM,CAAE,UAAY,CAEtB,KAAME,CAAAA,GAAG,CAAGF,eAAe,EAAIC,OAAO,CAACC,GAAR,CAAYC,QAA3C,CACA,KAAMC,CAAAA,EAAE,CAAGF,GAAG,GAAK,YAAR,EAAwBG,OAAO,CAACC,WAAR,UAA8BC,SAA9B,CAAnC,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,cACO,cAAeC,CAAAA,WAAf,CAA2BC,MAA3B,CAAmCC,UAAU,CAAG,CAAhD,CAAmDC,QAAQ,CAAG,IAA9D,CAAoE,CACzE,qCACA,IAAK,GAAIC,CAAAA,CAAC,CAAG,CAAb,EAAkB,EAAEA,CAApB,CAAuB,CACrB,GAAI,CACF,MAAO,MAAMH,CAAAA,MAAM,EACpB,CAAC,MAAOI,KAAP,CAAc,CACd,GAAID,CAAC,CAAGF,UAAR,CAAoB,KAAMI,eAAKC,KAAL,CAAWJ,QAAX,CAAN,CAApB,IACK,MAAME,CAAAA,KACZ,CACF,CACD,oCACD","sourcesContent":["import themed, {\n COMPOSE,\n PRIORITY,\n ThemeProvider,\n} from '@dr.pogodin/react-themes';\n\nimport config from './config';\nimport * as isomorphy from './isomorphy';\nimport time from './time';\nimport * as webpack from './webpack';\n\nexport * from './Barrier';\nexport { default as Emitter } from './Emitter';\nexport { default as Semaphore } from './Semaphore';\nexport { default as splitComponent } from './splitComponent';\n\nthemed.COMPOSE = COMPOSE;\nthemed.PRIORITY = PRIORITY;\n\n// Note: it should be done this way, as in some environments\n// \"process\" might not exist, and process.env.NODE_CONFIG_ENV\n// not injected by Webpack.\nlet NODE_CONFIG_ENV;\ntry {\n NODE_CONFIG_ENV = process.env.NODE_CONFIG_ENV;\n} catch { /* noop */ }\n\nconst env = NODE_CONFIG_ENV || process.env.NODE_ENV;\nconst JU = env !== 'production' && webpack.requireWeak('./jest', __dirname);\n\n/**\n * @category Utilities\n * @global\n * @func withRetries\n * @desc\n * ```js\n * import { withRetries } from '@dr.pogodin/react-utils';\n * ```\n * Attempts to perform given asynchronous `action` up to `maxRetries` times,\n * with the given `interval` between attempts. If any attempt is successful,\n * the result is returned immediately, with no further attempts done;\n * otherwise, if all attempts fail, the result Promise rejects after the last\n * attempt.\n * @param {function} action\n * @param {number} [maxRetries=5] Optional. Maximum number of retries. Defaults\n * to 5 attempts.\n * @param {number} [interval=1000] Optional. Interval between retries [ms].\n * Defaults to 1 second.\n * @return {Promise} Resolves to the result of successful operation, or\n * rejects with the error from the latst failed attempt.\n * @example\n * import { withRetries } from '@dr.pogodin/react-utils';\n *\n * let firstCall = true;\n *\n * function sampleAction() {\n * if (!firstCall) return 'success';\n * firstCall = false;\n * throw Error('The first call to this method fails');\n * }\n *\n * withRetries(sampleAction).then(console.log);\n * // It will print 'success' after one second, once the second attempt\n * // is performed.\n */\nexport async function withRetries(action, maxRetries = 5, interval = 1000) {\n /* eslint-disable no-await-in-loop */\n for (let n = 1; ; ++n) {\n try {\n return await action();\n } catch (error) {\n if (n < maxRetries) await time.timer(interval);\n else throw error;\n }\n }\n /* eslint-enable no-await-in-loop */\n}\n\nexport {\n config,\n isomorphy,\n JU,\n themed,\n ThemeProvider,\n time,\n webpack,\n};\n"],"file":"index.js"}
@@ -0,0 +1,14 @@
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=splitComponent;var _react=require("react");var _CodeSplit=_interopRequireDefault(require("../components/CodeSplit"));/**
2
+ * Wraps a regular React component into a "code splitting" component,
3
+ * i.e. all code used exclusively by that component and its sub-tree
4
+ * will go into a separate, asynchronously loaded, code chunk for
5
+ * the client-side.
6
+ * @param {object} options
7
+ * @param {string} options.chunkName
8
+ * @param {function} options.getClientSide
9
+ * @param {React.ElementType} [options.placeholder]
10
+ * @param {React.ElementType} [options.serverSide]
11
+ * @returns {React.ElementType}
12
+ */function splitComponent({chunkName,getClientSide,placeholder,serverSide}){// eslint-disable-next-line react/prop-types
13
+ return({children=[],...props})=>/*#__PURE__*/(0,_react.createElement)(_CodeSplit.default,{...props,chunkName,getClientSide,placeholder,serverSide},...children)}
14
+ //# sourceMappingURL=splitComponent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/shared/utils/splitComponent.js"],"names":["splitComponent","chunkName","getClientSide","placeholder","serverSide","children","props","CodeSplit"],"mappings":"wLAAA,4BACA,0EAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACe,QAASA,CAAAA,cAAT,CAAwB,CACrCC,SADqC,CAErCC,aAFqC,CAGrCC,WAHqC,CAIrCC,UAJqC,CAAxB,CAKZ,CACD;AACA,MAAO,CAAC,CAAEC,QAAQ,CAAG,EAAb,CAAiB,GAAGC,KAApB,CAAD,gBAAiC,yBACtCC,kBADsC,CAEtC,CACE,GAAGD,KADL,CAEEL,SAFF,CAGEC,aAHF,CAIEC,WAJF,CAKEC,UALF,CAFsC,CAStC,GAAGC,QATmC,CAWzC","sourcesContent":["import { createElement } from 'react';\nimport CodeSplit from 'components/CodeSplit';\n\n/**\n * Wraps a regular React component into a \"code splitting\" component,\n * i.e. all code used exclusively by that component and its sub-tree\n * will go into a separate, asynchronously loaded, code chunk for\n * the client-side.\n * @param {object} options\n * @param {string} options.chunkName\n * @param {function} options.getClientSide\n * @param {React.ElementType} [options.placeholder]\n * @param {React.ElementType} [options.serverSide]\n * @returns {React.ElementType}\n */\nexport default function splitComponent({\n chunkName,\n getClientSide,\n placeholder,\n serverSide,\n}) {\n // eslint-disable-next-line react/prop-types\n return ({ children = [], ...props }) => createElement(\n CodeSplit,\n {\n ...props,\n chunkName,\n getClientSide,\n placeholder,\n serverSide,\n },\n ...children,\n );\n}\n"],"file":"splitComponent.js"}
@@ -1,33 +1,10 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireWeak=requireWeak;exports.resolveWeak=resolveWeak;/**
2
- * @category Utilities
3
- * @module webpack
4
- * @desc
5
- * ```js
6
- * import { webpack } from '@dr.pogodin/react-utils';
7
- * ```
8
- * Webpack-related utilities.
9
- */ /**
10
- * ```js
11
- * import { webpack } from '@dr.pogodin/react-utils';
12
- * const { requireWeak } = webpack;
13
- * ```
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireWeak=requireWeak;exports.resolveWeak=resolveWeak;var _isomorphy=require("./isomorphy");/**
14
2
  * Requires the specified module without including it into the bundle during
15
- * Webpack build. This function should be executed only server-side.
16
- *
17
- * WARNING: Beware to pass in relative paths: they will be resolved relative
18
- * to the library distribution function, this is not what you want in most of
19
- * cases. To convert a relative path to the absolute one, do in the caller code
20
- * ```
21
- * import path from 'path';
22
- * const p = path.resolve(__dirname, './relative/path');
23
- * const module = requireWeak(p);
24
- * ```
25
- * In case you use an absolute path that relies on Babel module resolver,
26
- * pass it through resolveWeak function below.
27
- *
3
+ * Webpack build.
28
4
  * @param {string} modulePath
5
+ * @param {string} [basePath]
29
6
  * @return {object} Required module.
30
- */function requireWeak(modulePath){/* eslint-disable no-eval */const{default:def,...named}=eval("require")(modulePath);/* eslint-enable no-eval */if(!def)return named;Object.entries(named).forEach(([key,value])=>{if(def[key])throw Error("Conflict between default and named exports");def[key]=value});return def}/**
7
+ */function requireWeak(modulePath,basePath){if(_isomorphy.IS_CLIENT_SIDE)return null;try{/* eslint-disable no-eval */const{resolve}=eval("require")("path");const path=basePath?resolve(basePath,modulePath):modulePath;const{default:def,...named}=eval("require")(path);/* eslint-enable no-eval */if(!def)return named;Object.entries(named).forEach(([key,value])=>{if(def[key])throw Error("Conflict between default and named exports");def[key]=value});return def}catch{return null}}/**
31
8
  * Resolves specified module path with help of Babel's module resolver.
32
9
  * Yes, the function itself just returns its argument to the caller, but Babel
33
10
  * is configured to resolve the first argument of resolveWeak(..) function, thus
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/shared/utils/webpack.js"],"names":["requireWeak","modulePath","default","def","named","eval","Object","entries","forEach","key","value","Error","resolveWeak"],"mappings":"sIAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAASA,CAAAA,WAAT,CAAqBC,UAArB,CAAiC,CACtC,4BACA,KAAM,CAAEC,OAAO,CAAEC,GAAX,CAAgB,GAAGC,KAAnB,EAA6BC,IAAI,CAAC,SAAD,CAAJ,CAAgBJ,UAAhB,CAAnC,CACA,2BAEA,GAAI,CAACE,GAAL,CAAU,MAAOC,CAAAA,KAAP,CAEVE,MAAM,CAACC,OAAP,CAAeH,KAAf,EAAsBI,OAAtB,CAA8B,CAAC,CAACC,GAAD,CAAMC,KAAN,CAAD,GAAkB,CAC9C,GAAIP,GAAG,CAACM,GAAD,CAAP,CAAc,KAAME,CAAAA,KAAK,CAAC,4CAAD,CAAX,CACdR,GAAG,CAACM,GAAD,CAAH,CAAWC,KACZ,CAHD,EAIA,MAAOP,CAAAA,GACR,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAASS,CAAAA,WAAT,CAAqBX,UAArB,CAAiC,CACtC,MAAOA,CAAAA,UACR","sourcesContent":["/**\n * @category Utilities\n * @module webpack\n * @desc\n * ```js\n * import { webpack } from '@dr.pogodin/react-utils';\n * ```\n * Webpack-related utilities.\n */\n\n/**\n * ```js\n * import { webpack } from '@dr.pogodin/react-utils';\n * const { requireWeak } = webpack;\n * ```\n * Requires the specified module without including it into the bundle during\n * Webpack build. This function should be executed only server-side.\n *\n * WARNING: Beware to pass in relative paths: they will be resolved relative\n * to the library distribution function, this is not what you want in most of\n * cases. To convert a relative path to the absolute one, do in the caller code\n * ```\n * import path from 'path';\n * const p = path.resolve(__dirname, './relative/path');\n * const module = requireWeak(p);\n * ```\n * In case you use an absolute path that relies on Babel module resolver,\n * pass it through resolveWeak function below.\n *\n * @param {string} modulePath\n * @return {object} Required module.\n */\nexport function requireWeak(modulePath) {\n /* eslint-disable no-eval */\n const { default: def, ...named } = eval('require')(modulePath);\n /* eslint-enable no-eval */\n\n if (!def) return named;\n\n Object.entries(named).forEach(([key, value]) => {\n if (def[key]) throw Error('Conflict between default and named exports');\n def[key] = value;\n });\n return def;\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath) {\n return modulePath;\n}\n"],"file":"webpack.js"}
1
+ {"version":3,"sources":["../../../../src/shared/utils/webpack.js"],"names":["requireWeak","modulePath","basePath","IS_CLIENT_SIDE","resolve","eval","path","default","def","named","Object","entries","forEach","key","value","Error","resolveWeak"],"mappings":"sIAAA,sCAEA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAASA,CAAAA,WAAT,CAAqBC,UAArB,CAAiCC,QAAjC,CAA2C,CAChD,GAAIC,yBAAJ,CAAoB,MAAO,KAAP,CAEpB,GAAI,CACF,4BACA,KAAM,CAAEC,OAAF,EAAcC,IAAI,CAAC,SAAD,CAAJ,CAAgB,MAAhB,CAApB,CACA,KAAMC,CAAAA,IAAI,CAAGJ,QAAQ,CAAGE,OAAO,CAACF,QAAD,CAAWD,UAAX,CAAV,CAAmCA,UAAxD,CACA,KAAM,CAAEM,OAAO,CAAEC,GAAX,CAAgB,GAAGC,KAAnB,EAA6BJ,IAAI,CAAC,SAAD,CAAJ,CAAgBC,IAAhB,CAAnC,CACA,2BAEA,GAAI,CAACE,GAAL,CAAU,MAAOC,CAAAA,KAAP,CAEVC,MAAM,CAACC,OAAP,CAAeF,KAAf,EAAsBG,OAAtB,CAA8B,CAAC,CAACC,GAAD,CAAMC,KAAN,CAAD,GAAkB,CAC9C,GAAIN,GAAG,CAACK,GAAD,CAAP,CAAc,KAAME,CAAAA,KAAK,CAAC,4CAAD,CAAX,CACdP,GAAG,CAACK,GAAD,CAAH,CAAWC,KACZ,CAHD,EAIA,MAAON,CAAAA,GACR,CAAC,KAAM,CACN,MAAO,KACR,CACF,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAASQ,CAAAA,WAAT,CAAqBf,UAArB,CAAiC,CACtC,MAAOA,CAAAA,UACR","sourcesContent":["import { IS_CLIENT_SIDE } from './isomorphy';\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param {string} modulePath\n * @param {string} [basePath]\n * @return {object} Required module.\n */\nexport function requireWeak(modulePath, basePath) {\n if (IS_CLIENT_SIDE) return null;\n\n try {\n /* eslint-disable no-eval */\n const { resolve } = eval('require')('path');\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n const { default: def, ...named } = eval('require')(path);\n /* eslint-enable no-eval */\n\n if (!def) return named;\n\n Object.entries(named).forEach(([key, value]) => {\n if (def[key]) throw Error('Conflict between default and named exports');\n def[key] = value;\n });\n return def;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath) {\n return modulePath;\n}\n"],"file":"webpack.js"}