@dr.pogodin/react-utils 1.47.0-alpha.1 → 1.47.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/build/development/client/getInj.js.map +1 -1
  2. package/build/development/client/index.js.map +1 -1
  3. package/build/development/client/init.js.map +1 -1
  4. package/build/development/index.js +3 -4
  5. package/build/development/index.js.map +1 -1
  6. package/build/development/server/server.js +11 -10
  7. package/build/development/server/server.js.map +1 -1
  8. package/build/development/shared/utils/config.js +5 -6
  9. package/build/development/shared/utils/config.js.map +1 -1
  10. package/build/development/shared/utils/splitComponent.js +18 -22
  11. package/build/development/shared/utils/splitComponent.js.map +1 -1
  12. package/build/production/client/getInj.js.map +1 -1
  13. package/build/production/client/index.js.map +1 -1
  14. package/build/production/client/init.js.map +1 -1
  15. package/build/production/index.js +2 -3
  16. package/build/production/index.js.map +1 -1
  17. package/build/production/server/server.js +2 -4
  18. package/build/production/server/server.js.map +1 -1
  19. package/build/production/shared/utils/config.js +3 -5
  20. package/build/production/shared/utils/config.js.map +1 -1
  21. package/build/production/shared/utils/splitComponent.js +6 -17
  22. package/build/production/shared/utils/splitComponent.js.map +1 -1
  23. package/build/types-code/index.d.ts +2 -2
  24. package/build/web/client/getInj.js +9 -16
  25. package/build/web/client/getInj.js.map +1 -1
  26. package/build/web/client/index.js +14 -21
  27. package/build/web/client/index.js.map +1 -1
  28. package/build/web/client/init.js +2 -4
  29. package/build/web/client/init.js.map +1 -1
  30. package/build/web/index.js +2 -4
  31. package/build/web/index.js.map +1 -1
  32. package/build/web/server/server.js +10 -8
  33. package/build/web/server/server.js.map +1 -1
  34. package/build/web/shared/utils/config.js +4 -6
  35. package/build/web/shared/utils/config.js.map +1 -1
  36. package/build/web/shared/utils/splitComponent.js +17 -20
  37. package/build/web/shared/utils/splitComponent.js.map +1 -1
  38. package/config/jest/default.js +7 -2
  39. package/package.json +9 -8
  40. package/src/index.ts +3 -7
  41. package/src/server/server.ts +10 -10
  42. package/src/shared/utils/config.ts +5 -10
  43. package/src/shared/utils/splitComponent.tsx +17 -20
  44. package/node-entry.js +0 -15
@@ -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 _nodePath=require("node:path");var _nodeUrl=require("node:url");var _cloneDeep=_interopRequireDefault(require("lodash/cloneDeep"));var _mapValues=_interopRequireDefault(require("lodash/mapValues"));var _pick=_interopRequireDefault(require("lodash/pick"));var _compression=_interopRequireDefault(require("compression"));var _cookieParser=_interopRequireDefault(require("cookie-parser"));var _csurf=_interopRequireDefault(require("@dr.pogodin/csurf"));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 _nodePath=require("node:path");var _nodeUrl=require("node:url");var _cloneDeep=_interopRequireDefault(require("lodash/cloneDeep"));var _mapValues=_interopRequireDefault(require("lodash/mapValues"));var _pick=_interopRequireDefault(require("lodash/pick"));var _compression=_interopRequireDefault(require("compression"));var _cookieParser=_interopRequireDefault(require("cookie-parser"));var _csurf=_interopRequireDefault(require("@dr.pogodin/csurf"));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");function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap,n=new WeakMap;return(_interopRequireWildcard=function(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f)}for(const t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(i.get||i.set)?o(f,t,i):f[t]=e[t]);return f})(e,t)}/**
2
2
  * Creation of standard ExpressJS server for ReactJS apps.
3
3
  */// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
4
4
  /**
@@ -45,9 +45,7 @@ server.get("/__service-worker.js",_express.default.static(webpackConfig.output?.
45
45
  // (in dev mode), and app modules are imported in some unfortunate ways.
46
46
  // TODO: Double-check, what is going on here.
47
47
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
48
- if(!global.location){global.location={href:`${(0,_nodeUrl.pathToFileURL)(process.cwd()).href}${_nodePath.sep}`}}/* eslint-disable @typescript-eslint/no-require-imports */const webpack=require("webpack");// TODO: Figure out the exact type for options, don't wanna waste time on it
49
- // right now.
50
- 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 import/no-extraneous-dependencies */server.use(publicPath,_express.default.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use((req,res,next)=>{next((0,_errors.newError)(_errors.ERRORS.NOT_FOUND,_errors.CODES.NOT_FOUND))});let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: Do we need this error handler at all? It actually seems to do
48
+ if(!global.location){global.location={href:`${(0,_nodeUrl.pathToFileURL)(process.cwd()).href}${_nodePath.sep}`}}const{webpack}=await Promise.resolve().then(()=>_interopRequireWildcard(require(/* webpackChunkName: "server-side-code" */"webpack")));const{default:webpackDevMiddleware}=await Promise.resolve().then(()=>_interopRequireWildcard(require(/* webpackChunkName: "server-side-code" */"webpack-dev-middleware")));const{default:webpackHotMiddleware}=await Promise.resolve().then(()=>_interopRequireWildcard(require(/* webpackChunkName: "server-side-code" */"webpack-hot-middleware")));const compiler=webpack(webpackConfig);if(!compiler)throw Error("Internal error");server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable import/no-extraneous-dependencies */server.use(publicPath,_express.default.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use((req,res,next)=>{next((0,_errors.newError)(_errors.ERRORS.NOT_FOUND,_errors.CODES.NOT_FOUND))});let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: Do we need this error handler at all? It actually seems to do
51
49
  // what the default ExpressJS error handler does anyway, see:
52
50
  // https://expressjs.com/en/guide/error-handling.html
53
51
  //
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["_nodePath","require","_nodeUrl","_cloneDeep","_interopRequireDefault","_mapValues","_pick","_compression","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","cookieSignatureSecret","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","getErrorForCode","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport cloneDeep from 'lodash/cloneDeep';\nimport mapValues from 'lodash/mapValues';\nimport pick from 'lodash/pick';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type RequestHandler,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Compiler, Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\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 as string[]).filter((item: string) => 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];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\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 directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => boolean | Promise<boolean>;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) 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 res.redirect(url);\n return;\n }\n 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(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.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: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\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 import/no-extraneous-dependencies */\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 // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n /* eslint-disable @typescript-eslint/no-require-imports */\n const webpack = require('webpack') as (ops: Configuration) => Compiler;\n\n // TODO: Figure out the exact type for options, don't wanna waste time on it\n // right now.\n const webpackDevMiddleware = require('webpack-dev-middleware') as\n (c: Compiler, ops: unknown) => RequestHandler;\n\n const webpackHotMiddleware = require('webpack-hot-middleware') as\n (c: Compiler) => RequestHandler;\n\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 import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\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 server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":"qOAIA,IAAAA,SAAA,CAAAC,OAAA,cACA,IAAAC,QAAA,CAAAD,OAAA,aAEA,IAAAE,UAAA,CAAAC,sBAAA,CAAAH,OAAA,sBACA,IAAAI,UAAA,CAAAD,sBAAA,CAAAH,OAAA,sBACA,IAAAK,KAAA,CAAAF,sBAAA,CAAAH,OAAA,iBAEA,IAAAM,YAAA,CAAAH,sBAAA,CAAAH,OAAA,iBACA,IAAAO,aAAA,CAAAJ,sBAAA,CAAAH,OAAA,mBACA,IAAAQ,MAAA,CAAAL,sBAAA,CAAAH,OAAA,uBAEA,IAAAS,QAAA,CAAAN,sBAAA,CAAAH,OAAA,aAQA,IAAAU,aAAA,CAAAP,sBAAA,CAAAH,OAAA,mBACA,IAAAW,OAAA,CAAAR,sBAAA,CAAAH,OAAA,YACA,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,OAAO,CAACU,MAAM,CAAEyE,GAAG,CAACD,UAAU,CAAG,OAAO,CAAG,OAAO,CAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC,CAErE,GAAI,CAAAC,OAAO,CAAGP,KAAK,CAACO,OAAO,EAAI,GAAAC,uBAAe,EAACN,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAInB,OAAO,CAACwB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDH,OAAO,CAAGZ,cAAM,CAACQ,qBACnB,CAEAnE,GAAG,CAACkE,MAAM,CAACA,MAAM,CAAC,CAAC9C,IAAI,CAACmD,OAAO,CACjC,CAAC,CACH,CAEA,MAAO,CAAA9E,MACT","ignoreList":[]}
1
+ {"version":3,"file":"server.js","names":["_nodePath","require","_nodeUrl","_cloneDeep","_interopRequireDefault","_mapValues","_pick","_compression","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","_interopRequireWildcard","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","cookieSignatureSecret","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","static","path","setHeaders","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","Promise","resolve","then","webpackDevMiddleware","webpackHotMiddleware","compiler","Error","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","getErrorForCode","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport cloneDeep from 'lodash/cloneDeep';\nimport mapValues from 'lodash/mapValues';\nimport pick from 'lodash/pick';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\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 as string[]).filter((item: string) => 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];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\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 directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => boolean | Promise<boolean>;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) 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 res.redirect(url);\n return;\n }\n 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(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.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: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\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 import/no-extraneous-dependencies */\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 // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const { webpack } = await import(/* webpackChunkName: \"server-side-code\" */ 'webpack');\n\n const { default: webpackDevMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-dev-middleware'\n );\n\n const { default: webpackHotMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-hot-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n if (!compiler) throw Error('Internal error');\n\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\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 server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":"qOAIA,IAAAA,SAAA,CAAAC,OAAA,cACA,IAAAC,QAAA,CAAAD,OAAA,aAEA,IAAAE,UAAA,CAAAC,sBAAA,CAAAH,OAAA,sBACA,IAAAI,UAAA,CAAAD,sBAAA,CAAAH,OAAA,sBACA,IAAAK,KAAA,CAAAF,sBAAA,CAAAH,OAAA,iBAEA,IAAAM,YAAA,CAAAH,sBAAA,CAAAH,OAAA,iBACA,IAAAO,aAAA,CAAAJ,sBAAA,CAAAH,OAAA,mBACA,IAAAQ,MAAA,CAAAL,sBAAA,CAAAH,OAAA,uBAEA,IAAAS,QAAA,CAAAN,sBAAA,CAAAH,OAAA,aAOA,IAAAU,aAAA,CAAAP,sBAAA,CAAAH,OAAA,mBACA,IAAAW,OAAA,CAAAR,sBAAA,CAAAH,OAAA,YACA,IAAAY,OAAA,CAAAT,sBAAA,CAAAH,OAAA,YACA,IAAAa,UAAA,CAAAV,sBAAA,CAAAH,OAAA,gBACA,IAAAc,KAAA,CAAAd,OAAA,SAIA,IAAAe,SAAA,CAAAZ,sBAAA,CAAAH,OAAA,gBAKA,IAAAgB,OAAA,CAAAhB,OAAA,mBAIU,SAAAiB,wBAAAC,CAAA,CAAAC,CAAA,wBAAAC,OAAA,KAAAC,CAAA,KAAAD,OAAA,CAAAE,CAAA,KAAAF,OAAA,QAAAH,uBAAA,SAAAA,CAAAC,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nB,CAEArE,GAAG,CAACoE,MAAM,CAACA,MAAM,CAAC,CAAChD,IAAI,CAACqD,OAAO,CACjC,CAAC,CACH,CAEA,MAAO,CAAAhF,MACT","ignoreList":[]}
@@ -1,9 +1,7 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _environmentCheck=require("./isomorphy/environment-check");var _webpack=require("./webpack");/* global document */// TODO: The internal type casting is somewhat messed up here,
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _cookie=require("cookie");var _getInj=_interopRequireDefault(require("../../client/getInj"));var _environmentCheck=require("./isomorphy/environment-check");var _webpack=require("./webpack");/* global document */// TODO: The internal type casting is somewhat messed up here,
2
2
  // to be corrected later.
3
- const config=(_environmentCheck.IS_CLIENT_SIDE// eslint-disable-next-line @typescript-eslint/no-require-imports
4
- ?require("../../client/getInj").default().CONFIG:(0,_webpack.requireWeak)("config"))??{};// The safeguard for "document" is necessary because in non-Node environments,
3
+ const config=(_environmentCheck.IS_CLIENT_SIDE?(0,_getInj.default)().CONFIG:(0,_webpack.requireWeak)("config"))??{};// The safeguard for "document" is necessary because in non-Node environments,
5
4
  // like React Native, IS_CLIENT_SIDE is "true", however "document" and a bunch
6
5
  // of other browser-world features are not available.
7
- if(_environmentCheck.IS_CLIENT_SIDE&&typeof document!=="undefined"){// eslint-disable-next-line @typescript-eslint/no-require-imports
8
- const cookie=require("cookie");config.CSRF=cookie.parse(document.cookie).csrfToken}var _default=exports.default=config;
6
+ if(_environmentCheck.IS_CLIENT_SIDE&&typeof document!=="undefined"){config.CSRF=(0,_cookie.parse)(document.cookie).csrfToken}var _default=exports.default=config;
9
7
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","names":["_environmentCheck","require","_webpack","config","IS_CLIENT_SIDE","default","CONFIG","requireWeak","document","cookie","CSRF","parse","csrfToken","_default","exports"],"sources":["../../../../src/shared/utils/config.ts"],"sourcesContent":["/* global document */\n\nimport type CookieM from 'cookie';\n\nimport { IS_CLIENT_SIDE } from './isomorphy/environment-check';\nimport { requireWeak } from './webpack';\n\n// TODO: The internal type casting is somewhat messed up here,\n// to be corrected later.\nconst config: Record<string, unknown> = (\n IS_CLIENT_SIDE\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n ? (require('client/getInj') as {\n default: () => Record<string, unknown>;\n }).default().CONFIG\n : requireWeak('config')\n) as (Record<string, unknown> | undefined) ?? ({} as Record<string, unknown>);\n\n// The safeguard for \"document\" is necessary because in non-Node environments,\n// like React Native, IS_CLIENT_SIDE is \"true\", however \"document\" and a bunch\n// of other browser-world features are not available.\nif (IS_CLIENT_SIDE && typeof document !== 'undefined') {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const cookie = require('cookie') as typeof CookieM;\n config.CSRF = cookie.parse(document.cookie).csrfToken;\n}\n\nexport default config;\n"],"mappings":"6FAIA,IAAAA,iBAAA,CAAAC,OAAA,kCACA,IAAAC,QAAA,CAAAD,OAAA,cALA,qBAOA;AACA;AACA,KAAM,CAAAE,MAA+B,CAAG,CACtCC,gCACE;AAAA,CACGH,OAAO,sBAAgB,CAAC,CAExBI,OAAO,CAAC,CAAC,CAACC,MAAM,CACjB,GAAAC,oBAAW,EAAC,QAAQ,CAAC,GACoB,CAAC,CAA6B,CAE7E;AACA;AACA;AACA,GAAIH,gCAAc,EAAI,MAAO,CAAAI,QAAQ,GAAK,WAAW,CAAE,CACrD;AACA,KAAM,CAAAC,MAAM,CAAGR,OAAO,CAAC,QAAQ,CAAmB,CAClDE,MAAM,CAACO,IAAI,CAAGD,MAAM,CAACE,KAAK,CAACH,QAAQ,CAACC,MAAM,CAAC,CAACG,SAC9C,KAAAC,QAAA,CAAAC,OAAA,CAAAT,OAAA,CAEeF,MAAM","ignoreList":[]}
1
+ {"version":3,"file":"config.js","names":["_cookie","require","_getInj","_interopRequireDefault","_environmentCheck","_webpack","config","IS_CLIENT_SIDE","clientGetInj","CONFIG","requireWeak","document","CSRF","parse","cookie","csrfToken","_default","exports","default"],"sources":["../../../../src/shared/utils/config.ts"],"sourcesContent":["/* global document */\n\nimport { parse } from 'cookie';\n\nimport clientGetInj from '../../client/getInj';\n\nimport { IS_CLIENT_SIDE } from './isomorphy/environment-check';\nimport { requireWeak } from './webpack';\n\n// TODO: The internal type casting is somewhat messed up here,\n// to be corrected later.\nconst config: Record<string, unknown> = (\n IS_CLIENT_SIDE ? clientGetInj().CONFIG : requireWeak('config')\n) as (Record<string, unknown> | undefined) ?? ({} as Record<string, unknown>);\n\n// The safeguard for \"document\" is necessary because in non-Node environments,\n// like React Native, IS_CLIENT_SIDE is \"true\", however \"document\" and a bunch\n// of other browser-world features are not available.\nif (IS_CLIENT_SIDE && typeof document !== 'undefined') {\n config.CSRF = parse(document.cookie).csrfToken;\n}\n\nexport default config;\n"],"mappings":"gLAEA,IAAAA,OAAA,CAAAC,OAAA,WAEA,IAAAC,OAAA,CAAAC,sBAAA,CAAAF,OAAA,yBAEA,IAAAG,iBAAA,CAAAH,OAAA,kCACA,IAAAI,QAAA,CAAAJ,OAAA,cAPA,qBASA;AACA;AACA,KAAM,CAAAK,MAA+B,CAAG,CACtCC,gCAAc,CAAG,GAAAC,eAAY,EAAC,CAAC,CAACC,MAAM,CAAG,GAAAC,oBAAW,EAAC,QAAQ,CAAC,GACjB,CAAC,CAA6B,CAE7E;AACA;AACA;AACA,GAAIH,gCAAc,EAAI,MAAO,CAAAI,QAAQ,GAAK,WAAW,CAAE,CACrDL,MAAM,CAACM,IAAI,CAAG,GAAAC,aAAK,EAACF,QAAQ,CAACG,MAAM,CAAC,CAACC,SACvC,KAAAC,QAAA,CAAAC,OAAA,CAAAC,OAAA,CAEeZ,MAAM","ignoreList":[]}
@@ -1,15 +1,4 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.bookStyleSheets=bookStyleSheets;exports.default=splitComponent;exports.freeStyleSheets=freeStyleSheets;var _react=require("react");var _jsUtils=require("@dr.pogodin/js-utils");var _globalState=require("./globalState");var _isomorphy=require("./isomorphy");var _jsxRuntime=require("react/jsx-runtime");/* global document */// Note: At the client side we can get chunk groups immediately when loading
2
- // the module; at the server-side we only can get them within React render flow.
3
- // Thus, we set and use the following variable at the client-side, and then when
4
- // needed on the server side, we'll fetch it differently.
5
- let clientChunkGroups;if(_isomorphy.IS_CLIENT_SIDE){// TODO: Rewrite to avoid these overrides of ESLint rules.
6
- /* eslint-disable @typescript-eslint/no-unsafe-assignment,
7
- @typescript-eslint/no-require-imports,
8
- @typescript-eslint/no-unsafe-call,
9
- @typescript-eslint/no-unsafe-member-access */clientChunkGroups=require("../../client/getInj").default().CHUNK_GROUPS??{};/* eslint-enable @typescript-eslint/no-unsafe-assignment,
10
- @typescript-eslint/no-require-imports,
11
- @typescript-eslint/no-unsafe-call,
12
- @typescript-eslint/no-unsafe-member-access */}const refCounts={};function getPublicPath(){return(0,_isomorphy.getBuildInfo)().publicPath}/**
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.bookStyleSheets=bookStyleSheets;exports.default=splitComponent;exports.freeStyleSheets=freeStyleSheets;var _react=require("react");var _jsUtils=require("@dr.pogodin/js-utils");var _globalState=require("./globalState");var _isomorphy=require("./isomorphy");var _jsxRuntime=require("react/jsx-runtime");function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap,n=new WeakMap;return(_interopRequireWildcard=function(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f)}for(const t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(i.get||i.set)?o(f,t,i):f[t]=e[t]);return f})(e,t)}/* global document */function getClientChunkGroups(){if(!_isomorphy.IS_CLIENT_SIDE)return undefined;return(async()=>{const{default:getInj}=await Promise.resolve().then(()=>_interopRequireWildcard(require(/* webpackChunkName: "react-utils-client-side-code" */"../../client/getInj")));return getInj().CHUNK_GROUPS??{}})()}const refCounts={};function getPublicPath(){return(0,_isomorphy.getBuildInfo)().publicPath}/**
13
2
  * Client-side only! Ensures the specified CSS stylesheet is loaded into
14
3
  * the document; loads if it is missing; and does simple reference counting
15
4
  * to facilitate future clean-up.
@@ -44,16 +33,16 @@ const usedChunkNames=new Set;/**
44
33
  * @param {function} options.getComponent
45
34
  * @param {React.Element} [options.placeholder]
46
35
  * @return {React.ElementType}
47
- */function splitComponent({chunkName,getComponent,placeholder}){// On the client side we can check right away if the chunk name is known.
48
- if(_isomorphy.IS_CLIENT_SIDE)assertChunkName(chunkName,clientChunkGroups);// The correct usage of splitComponent() assumes a single call per chunk.
49
- if(usedChunkNames.has(chunkName)){throw Error(`Repeated splitComponent() call for the chunk "${chunkName}"`)}else usedChunkNames.add(chunkName);const LazyComponent=/*#__PURE__*/(0,_react.lazy)(async()=>{const resolved=await getComponent();const Component="default"in resolved?resolved.default:resolved;// This pre-loads necessary stylesheets prior to the first mount of
36
+ */function splitComponent({chunkName,getComponent,placeholder}){// The correct usage of splitComponent() assumes a single call per chunk.
37
+ if(usedChunkNames.has(chunkName)){throw Error(`Repeated splitComponent() call for the chunk "${chunkName}"`)}else usedChunkNames.add(chunkName);const LazyComponent=/*#__PURE__*/(0,_react.lazy)(async()=>{const clientChunkGroups=await getClientChunkGroups();// On the client side we can check right away if the chunk name is known.
38
+ if(_isomorphy.IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");assertChunkName(chunkName,clientChunkGroups)}const resolved=await getComponent();const Component="default"in resolved?resolved.default:resolved;// This pre-loads necessary stylesheets prior to the first mount of
50
39
  // the component (the lazy load function is executed by React one at
51
40
  // the frist mount).
52
- if(_isomorphy.IS_CLIENT_SIDE){await bookStyleSheets(chunkName,clientChunkGroups,false)}const Wrapper=({children,ref,...rest})=>{// On the server side we'll assert the chunk name here,
41
+ if(_isomorphy.IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");await bookStyleSheets(chunkName,clientChunkGroups,false)}const Wrapper=({children,ref,...rest})=>{// On the server side we'll assert the chunk name here,
53
42
  // and also push it to the SSR chunks array.
54
43
  if(_isomorphy.IS_SERVER_SIDE){const{chunkGroups,chunks}=(0,_globalState.getSsrContext)();assertChunkName(chunkName,chunkGroups);if(!chunks.includes(chunkName))chunks.push(chunkName)}// This takes care about stylesheets management every time an instance of
55
44
  // this component is mounted / unmounted.
56
- (0,_react.useInsertionEffect)(()=>{void bookStyleSheets(chunkName,clientChunkGroups,true);return()=>{freeStyleSheets(chunkName,clientChunkGroups)}},[]);return/*#__PURE__*/(0,_jsxRuntime.jsx)(Component// eslint-disable-next-line react/jsx-props-no-spreading
45
+ (0,_react.useInsertionEffect)(()=>{if(!clientChunkGroups)throw Error("Internal error");void bookStyleSheets(chunkName,clientChunkGroups,true);return()=>{freeStyleSheets(chunkName,clientChunkGroups)}},[]);return/*#__PURE__*/(0,_jsxRuntime.jsx)(Component// eslint-disable-next-line react/jsx-props-no-spreading
57
46
  ,{...rest,ref:ref,children:children})};return{default:Wrapper}});const CodeSplit=({children,...rest})=>/*#__PURE__*/(0,_jsxRuntime.jsx)(_react.Suspense,{fallback:placeholder,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(LazyComponent// eslint-disable-next-line react/jsx-props-no-spreading
58
47
  ,{...rest,children:children})});return CodeSplit}
59
48
  //# sourceMappingURL=splitComponent.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"splitComponent.js","names":["_react","require","_jsUtils","_globalState","_isomorphy","_jsxRuntime","clientChunkGroups","IS_CLIENT_SIDE","default","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","resolved","Component","Wrapper","children","ref","rest","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","_jsx","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\n// Note: At the client side we can get chunk groups immediately when loading\n// the module; at the server-side we only can get them within React render flow.\n// Thus, we set and use the following variable at the client-side, and then when\n// needed on the server side, we'll fetch it differently.\nlet clientChunkGroups: ChunkGroupsT;\n\nif (IS_CLIENT_SIDE) {\n // TODO: Rewrite to avoid these overrides of ESLint rules.\n /* eslint-disable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n clientChunkGroups = require('client/getInj').default().CHUNK_GROUPS ?? {};\n /* eslint-enable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) assertChunkName(chunkName, clientChunkGroups);\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":"qLAEA,IAAAA,MAAA,CAAAC,OAAA,UAUA,IAAAC,QAAA,CAAAD,OAAA,yBAEA,IAAAE,YAAA,CAAAF,OAAA,kBAEA,IAAAG,UAAA,CAAAH,OAAA,gBASA,IAAAI,WAAA,CAAAJ,OAAA,sBAzBA,qBAsBA;AACA;AACA;AACA;AACA,GAAI,CAAAK,iBAA+B,CAEnC,GAAIC,yBAAc,CAAE,CAClB;AACA;AACF;AACA;AACA,iDACED,iBAAiB,CAAGL,OAAO,sBAAgB,CAAC,CAACO,OAAO,CAAC,CAAC,CAACC,YAAY,EAAI,CAAC,CAAC,CACzE;AACF;AACA;AACA,iDACA,CAEA,KAAM,CAAAC,SAAiC,CAAG,CAAC,CAAC,CAE5C,QAAS,CAAAC,aAAaA,CAAA,CAAG,CACvB,MAAO,GAAAC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GE,IACY,CAAC,gBAChB,GAAAM,eAAA,EAACE,eAAQ,EAACC,QAAQ,CAAEjB,WAAY,CAAAM,QAAA,cAC9B,GAAAQ,eAAA,EAACb,aACC;AAAA,KACIO,IAAI,CAAAF,QAAA,CAEPA,QAAQ,CACI,CAAC,CACR,CACX,CAED,MAAO,CAAAS,SACT","ignoreList":[]}
1
+ {"version":3,"file":"splitComponent.js","names":["_react","require","_jsUtils","_globalState","_isomorphy","_jsxRuntime","_interopRequireWildcard","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","getClientChunkGroups","IS_CLIENT_SIDE","undefined","getInj","Promise","resolve","then","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","Error","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","asset","endsWith","promise","push","length","allSettled","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","clientChunkGroups","resolved","Component","Wrapper","children","ref","rest","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","_jsx","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\nfunction getClientChunkGroups(): Promise<ChunkGroupsT> | undefined {\n if (!IS_CLIENT_SIDE) return undefined;\n\n return (async () => {\n const { default: getInj } = await import(/* webpackChunkName: \"react-utils-client-side-code\" */ '../../client/getInj');\n return getInj().CHUNK_GROUPS ?? {};\n })();\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const clientChunkGroups = await getClientChunkGroups();\n\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n assertChunkName(chunkName, clientChunkGroups);\n }\n\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":"qLAEA,IAAAA,MAAA,CAAAC,OAAA,UAUA,IAAAC,QAAA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AM,CAACpB,IAAI,CAACR,SAAS,CACxD,CAEA;AACA;AACA,GAAA+B,yBAAkB,EAAC,IAAM,CACvB,GAAI,CAACX,iBAAiB,CAAE,KAAM,CAAA5B,KAAK,CAAC,gBAAgB,CAAC,CACrD,IAAK,CAAAU,eAAe,CAACF,SAAS,CAAEoB,iBAAiB,CAAE,IAAI,CAAC,CACxD,MAAO,IAAM,CACXT,eAAe,CAACX,SAAS,CAAEoB,iBAAiB,CAC9C,CACF,CAAC,CAAE,EAAE,CAAC,CAEN,mBACE,GAAAY,eAAA,EAACV,SACC;AAAA,KACKI,IAAI,CACTD,GAAG,CAAEA,GAAI,CAAAD,QAAA,CAERA,QAAQ,CACA,CAEf,CAAC,CAED,MAAO,CAAEvE,OAAO,CAAEsE,OAAQ,CAC5B,CAAC,CAAC,CAEF,KAAM,CAAAU,SAAmD,CAAGA,CAAC,CAC3DT,QAAQ,CACR,GAAGE,IACY,CAAC,gBAChB,GAAAM,eAAA,EAACE,eAAQ,EAACC,QAAQ,CAAElB,WAAY,CAAAO,QAAA,cAC9B,GAAAQ,eAAA,EAACd,aACC;AAAA,KACIQ,IAAI,CAAAF,QAAA,CAEPA,QAAQ,CACI,CAAC,CACR,CACX,CAED,MAAO,CAAAS,SACT","ignoreList":[]}
@@ -1,8 +1,8 @@
1
1
  import 'styles/global.scss';
2
- import type * as ClientM from './client';
2
+ import clientModule from './client';
3
3
  import type * as ServerFactoryM from './server';
4
4
  declare const server: (typeof ServerFactoryM.default & Omit<typeof ServerFactoryM, "default">) | null;
5
- declare const client: typeof ClientM.default | undefined;
5
+ declare const client: typeof clientModule | undefined;
6
6
  export { type AsyncCollectionT, type AsyncCollectionLoaderT, type AsyncDataEnvelopeT, type AsyncDataLoaderT, type ForceT, type UseAsyncDataOptionsT, type UseAsyncDataResT, type UseGlobalStateResT, type ValueOrInitializerT, getGlobalState, GlobalStateProvider, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState, withGlobalStateType, } from '@dr.pogodin/react-global-state';
7
7
  export * from './shared/components';
8
8
  export { type BeforeRenderResT, type BeforeRenderT, type ConfigT, type ServerSsrContext, type ServerT, } from './server';
@@ -1,21 +1,14 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.default = getInj;
8
- var _forge = _interopRequireDefault(require("node-forge/lib/forge"));
9
- require("node-forge/lib/aes");
10
- var _buildInfo = require("../shared/utils/isomorphy/buildInfo");
11
1
  // Encapsulates retrieval of server-side data injection into HTML template.
12
2
 
13
3
  /* global document */
14
4
 
15
5
  // Note: this way, only required part of "node-forge": AES, and some utils,
16
6
  // is bundled into client-side code.
7
+ import forge from 'node-forge/lib/forge';
17
8
 
18
9
  // eslint-disable-next-line import/no-unassigned-import
10
+ import 'node-forge/lib/aes';
11
+ import { getBuildInfo } from "../shared/utils/isomorphy/buildInfo";
19
12
 
20
13
  // Safeguard is needed here, because the server-side version of Docusaurus docs
21
14
  // is compiled (at least now) with settings suggesting it is a client-side
@@ -24,17 +17,17 @@ let inj = {};
24
17
  const metaElement = typeof document === 'undefined' ? null : document.querySelector('meta[itemprop="drpruinj"]');
25
18
  if (metaElement) {
26
19
  metaElement.remove();
27
- let data = _forge.default.util.decode64(metaElement.content);
20
+ let data = forge.util.decode64(metaElement.content);
28
21
  const {
29
22
  key
30
- } = (0, _buildInfo.getBuildInfo)();
31
- const d = _forge.default.cipher.createDecipher('AES-CBC', key);
23
+ } = getBuildInfo();
24
+ const d = forge.cipher.createDecipher('AES-CBC', key);
32
25
  d.start({
33
26
  iv: data.slice(0, key.length)
34
27
  });
35
- d.update(_forge.default.util.createBuffer(data.slice(key.length)));
28
+ d.update(forge.util.createBuffer(data.slice(key.length)));
36
29
  d.finish();
37
- data = _forge.default.util.decodeUtf8(d.output.data);
30
+ data = forge.util.decodeUtf8(d.output.data);
38
31
 
39
32
  // TODO: Double-check, if there is a safer alternative to parse it?
40
33
  // eslint-disable-next-line no-eval
@@ -48,7 +41,7 @@ if (metaElement) {
48
41
  // Docusaurus examples, etc.
49
42
  inj = {};
50
43
  }
51
- function getInj() {
44
+ export default function getInj() {
52
45
  return inj;
53
46
  }
54
47
  //# sourceMappingURL=getInj.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"getInj.js","names":["_forge","_interopRequireDefault","require","_buildInfo","inj","metaElement","document","querySelector","remove","data","forge","util","decode64","content","key","getBuildInfo","d","cipher","createDecipher","start","iv","slice","length","update","createBuffer","finish","decodeUtf8","output","eval","window","REACT_UTILS_INJECTION","getInj"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\n\n// eslint-disable-next-line import/no-unassigned-import\nimport 'node-forge/lib/aes';\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\n// Safeguard is needed here, because the server-side version of Docusaurus docs\n// is compiled (at least now) with settings suggesting it is a client-side\n// environment, but there is no document.\nlet inj: InjT = {};\n\nconst metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\nif (metaElement) {\n metaElement.remove();\n let data = forge.util.decode64(metaElement.content);\n\n const { key } = getBuildInfo();\n const d = forge.cipher.createDecipher('AES-CBC', key);\n d.start({ iv: data.slice(0, key.length) });\n d.update(forge.util.createBuffer(data.slice(key.length)));\n d.finish();\n\n data = forge.util.decodeUtf8(d.output.data);\n\n // TODO: Double-check, if there is a safer alternative to parse it?\n // eslint-disable-next-line no-eval\n inj = eval(`(${data})`) as InjT;\n} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n inj = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n} else {\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n inj = {};\n}\n\nexport default function getInj(): InjT {\n return inj;\n}\n"],"mappings":";;;;;;;AAMA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AAGAA,OAAA;AAIA,IAAAC,UAAA,GAAAD,OAAA;AAbA;;AAEA;;AAEA;AACA;;AAGA;;AAOA;AACA;AACA;AACA,IAAIE,GAAS,GAAG,CAAC,CAAC;AAElB,MAAMC,WAAmC,GAAG,OAAOC,QAAQ,KAAK,WAAW,GACvE,IAAI,GAAGA,QAAQ,CAACC,aAAa,CAAC,2BAA2B,CAAC;AAE9D,IAAIF,WAAW,EAAE;EACfA,WAAW,CAACG,MAAM,CAAC,CAAC;EACpB,IAAIC,IAAI,GAAGC,cAAK,CAACC,IAAI,CAACC,QAAQ,CAACP,WAAW,CAACQ,OAAO,CAAC;EAEnD,MAAM;IAAEC;EAAI,CAAC,GAAG,IAAAC,uBAAY,EAAC,CAAC;EAC9B,MAAMC,CAAC,GAAGN,cAAK,CAACO,MAAM,CAACC,cAAc,CAAC,SAAS,EAAEJ,GAAG,CAAC;EACrDE,CAAC,CAACG,KAAK,CAAC;IAAEC,EAAE,EAAEX,IAAI,CAACY,KAAK,CAAC,CAAC,EAAEP,GAAG,CAACQ,MAAM;EAAE,CAAC,CAAC;EAC1CN,CAAC,CAACO,MAAM,CAACb,cAAK,CAACC,IAAI,CAACa,YAAY,CAACf,IAAI,CAACY,KAAK,CAACP,GAAG,CAACQ,MAAM,CAAC,CAAC,CAAC;EACzDN,CAAC,CAACS,MAAM,CAAC,CAAC;EAEVhB,IAAI,GAAGC,cAAK,CAACC,IAAI,CAACe,UAAU,CAACV,CAAC,CAACW,MAAM,CAAClB,IAAI,CAAC;;EAE3C;EACA;EACAL,GAAG,GAAGwB,IAAI,CAAC,IAAInB,IAAI,GAAG,CAAS;AACjC,CAAC,MAAM,IAAI,OAAOoB,MAAM,KAAK,WAAW,IAAIA,MAAM,CAACC,qBAAqB,EAAE;EACxE1B,GAAG,GAAGyB,MAAM,CAACC,qBAAqB;EAClC,OAAOD,MAAM,CAACC,qBAAqB;AACrC,CAAC,MAAM;EACL;EACA;EACA;EACA1B,GAAG,GAAG,CAAC,CAAC;AACV;AAEe,SAAS2B,MAAMA,CAAA,EAAS;EACrC,OAAO3B,GAAG;AACZ","ignoreList":[]}
1
+ {"version":3,"file":"getInj.js","names":["forge","getBuildInfo","inj","metaElement","document","querySelector","remove","data","util","decode64","content","key","d","cipher","createDecipher","start","iv","slice","length","update","createBuffer","finish","decodeUtf8","output","eval","window","REACT_UTILS_INJECTION","getInj"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\n\n// eslint-disable-next-line import/no-unassigned-import\nimport 'node-forge/lib/aes';\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\n// Safeguard is needed here, because the server-side version of Docusaurus docs\n// is compiled (at least now) with settings suggesting it is a client-side\n// environment, but there is no document.\nlet inj: InjT = {};\n\nconst metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\nif (metaElement) {\n metaElement.remove();\n let data = forge.util.decode64(metaElement.content);\n\n const { key } = getBuildInfo();\n const d = forge.cipher.createDecipher('AES-CBC', key);\n d.start({ iv: data.slice(0, key.length) });\n d.update(forge.util.createBuffer(data.slice(key.length)));\n d.finish();\n\n data = forge.util.decodeUtf8(d.output.data);\n\n // TODO: Double-check, if there is a safer alternative to parse it?\n // eslint-disable-next-line no-eval\n inj = eval(`(${data})`) as InjT;\n} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n inj = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n} else {\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n inj = {};\n}\n\nexport default function getInj(): InjT {\n return inj;\n}\n"],"mappings":"AAAA;;AAEA;;AAEA;AACA;AACA,OAAOA,KAAK,MAAM,sBAAsB;;AAExC;AACA,OAAO,oBAAoB;AAI3B,SAASC,YAAY;;AAErB;AACA;AACA;AACA,IAAIC,GAAS,GAAG,CAAC,CAAC;AAElB,MAAMC,WAAmC,GAAG,OAAOC,QAAQ,KAAK,WAAW,GACvE,IAAI,GAAGA,QAAQ,CAACC,aAAa,CAAC,2BAA2B,CAAC;AAE9D,IAAIF,WAAW,EAAE;EACfA,WAAW,CAACG,MAAM,CAAC,CAAC;EACpB,IAAIC,IAAI,GAAGP,KAAK,CAACQ,IAAI,CAACC,QAAQ,CAACN,WAAW,CAACO,OAAO,CAAC;EAEnD,MAAM;IAAEC;EAAI,CAAC,GAAGV,YAAY,CAAC,CAAC;EAC9B,MAAMW,CAAC,GAAGZ,KAAK,CAACa,MAAM,CAACC,cAAc,CAAC,SAAS,EAAEH,GAAG,CAAC;EACrDC,CAAC,CAACG,KAAK,CAAC;IAAEC,EAAE,EAAET,IAAI,CAACU,KAAK,CAAC,CAAC,EAAEN,GAAG,CAACO,MAAM;EAAE,CAAC,CAAC;EAC1CN,CAAC,CAACO,MAAM,CAACnB,KAAK,CAACQ,IAAI,CAACY,YAAY,CAACb,IAAI,CAACU,KAAK,CAACN,GAAG,CAACO,MAAM,CAAC,CAAC,CAAC;EACzDN,CAAC,CAACS,MAAM,CAAC,CAAC;EAEVd,IAAI,GAAGP,KAAK,CAACQ,IAAI,CAACc,UAAU,CAACV,CAAC,CAACW,MAAM,CAAChB,IAAI,CAAC;;EAE3C;EACA;EACAL,GAAG,GAAGsB,IAAI,CAAC,IAAIjB,IAAI,GAAG,CAAS;AACjC,CAAC,MAAM,IAAI,OAAOkB,MAAM,KAAK,WAAW,IAAIA,MAAM,CAACC,qBAAqB,EAAE;EACxExB,GAAG,GAAGuB,MAAM,CAACC,qBAAqB;EAClC,OAAOD,MAAM,CAACC,qBAAqB;AACrC,CAAC,MAAM;EACL;EACA;EACA;EACAxB,GAAG,GAAG,CAAC,CAAC;AACV;AAEA,eAAe,SAASyB,MAAMA,CAAA,EAAS;EACrC,OAAOzB,GAAG;AACZ","ignoreList":[]}
@@ -1,38 +1,31 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.default = Launch;
8
- var _client = require("react-dom/client");
9
- var _reactHelmet = require("@dr.pogodin/react-helmet");
10
- var _reactRouter = require("react-router");
11
- var _reactGlobalState = require("@dr.pogodin/react-global-state");
12
- var _getInj = _interopRequireDefault(require("./getInj"));
13
- var _jsxRuntime = require("react/jsx-runtime");
14
1
  // Initialization of client-side code.
15
2
  /* global document */
16
3
 
4
+ import { createRoot, hydrateRoot } from 'react-dom/client';
5
+ import { HelmetProvider } from '@dr.pogodin/react-helmet';
6
+ import { BrowserRouter } from 'react-router';
7
+ import { GlobalStateProvider } from '@dr.pogodin/react-global-state';
8
+ import getInj from "./getInj";
9
+ import { jsx as _jsx } from "react/jsx-runtime";
17
10
  /**
18
11
  * Prepares and launches the app at client side.
19
12
  * @param Application Root application component
20
13
  * @param [options={}] Optional. Additional settings.
21
14
  */
22
- function Launch(Application, options = {}) {
15
+ export default function Launch(Application, options = {}) {
23
16
  const container = document.getElementById('react-view');
24
17
  if (!container) throw Error('Failed to find container for React app');
25
- const scene = /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactGlobalState.GlobalStateProvider, {
26
- initialState: (0, _getInj.default)().ISTATE ?? options.initialState,
27
- children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactRouter.BrowserRouter, {
28
- children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactHelmet.HelmetProvider, {
29
- children: /*#__PURE__*/(0, _jsxRuntime.jsx)(Application, {})
18
+ const scene = /*#__PURE__*/_jsx(GlobalStateProvider, {
19
+ initialState: getInj().ISTATE ?? options.initialState,
20
+ children: /*#__PURE__*/_jsx(BrowserRouter, {
21
+ children: /*#__PURE__*/_jsx(HelmetProvider, {
22
+ children: /*#__PURE__*/_jsx(Application, {})
30
23
  })
31
24
  })
32
25
  });
33
26
  if (options.dontHydrate) {
34
- const root = (0, _client.createRoot)(container);
27
+ const root = createRoot(container);
35
28
  root.render(scene);
36
- } else (0, _client.hydrateRoot)(container, scene);
29
+ } else hydrateRoot(container, scene);
37
30
  }
38
31
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_client","require","_reactHelmet","_reactRouter","_reactGlobalState","_getInj","_interopRequireDefault","_jsxRuntime","Launch","Application","options","container","document","getElementById","Error","scene","jsx","GlobalStateProvider","initialState","getInj","ISTATE","children","BrowserRouter","HelmetProvider","dontHydrate","root","createRoot","render","hydrateRoot"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport type { ComponentType } from 'react';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { BrowserRouter } from 'react-router';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: unknown;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n): void {\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={getInj().ISTATE ?? options.initialState}>\n <BrowserRouter>\n <HelmetProvider>\n <Application />\n </HelmetProvider>\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":";;;;;;;AAIA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,YAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAF,OAAA;AAEA,IAAAG,iBAAA,GAAAH,OAAA;AAEA,IAAAI,OAAA,GAAAC,sBAAA,CAAAL,OAAA;AAA8B,IAAAM,WAAA,GAAAN,OAAA;AAV9B;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACe,SAASO,MAAMA,CAC5BC,WAA0B,EAC1BC,OAAiB,GAAG,CAAC,CAAC,EAChB;EACN,MAAMC,SAAS,GAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC;EACvD,IAAI,CAACF,SAAS,EAAE,MAAMG,KAAK,CAAC,wCAAwC,CAAC;EACrE,MAAMC,KAAK,gBACT,IAAAR,WAAA,CAAAS,GAAA,EAACZ,iBAAA,CAAAa,mBAAmB;IAACC,YAAY,EAAE,IAAAC,eAAM,EAAC,CAAC,CAACC,MAAM,IAAIV,OAAO,CAACQ,YAAa;IAAAG,QAAA,eACzE,IAAAd,WAAA,CAAAS,GAAA,EAACb,YAAA,CAAAmB,aAAa;MAAAD,QAAA,eACZ,IAAAd,WAAA,CAAAS,GAAA,EAACd,YAAA,CAAAqB,cAAc;QAAAF,QAAA,eACb,IAAAd,WAAA,CAAAS,GAAA,EAACP,WAAW,IAAE;MAAC,CACD;IAAC,CACJ;EAAC,CACG,CACtB;EAED,IAAIC,OAAO,CAACc,WAAW,EAAE;IACvB,MAAMC,IAAI,GAAG,IAAAC,kBAAU,EAACf,SAAS,CAAC;IAClCc,IAAI,CAACE,MAAM,CAACZ,KAAK,CAAC;EACpB,CAAC,MAAM,IAAAa,mBAAW,EAACjB,SAAS,EAAEI,KAAK,CAAC;AACtC","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["createRoot","hydrateRoot","HelmetProvider","BrowserRouter","GlobalStateProvider","getInj","jsx","_jsx","Launch","Application","options","container","document","getElementById","Error","scene","initialState","ISTATE","children","dontHydrate","root","render"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport type { ComponentType } from 'react';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { BrowserRouter } from 'react-router';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: unknown;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n): void {\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={getInj().ISTATE ?? options.initialState}>\n <BrowserRouter>\n <HelmetProvider>\n <Application />\n </HelmetProvider>\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":"AAAA;AACA;;AAGA,SAASA,UAAU,EAAEC,WAAW,QAAQ,kBAAkB;AAC1D,SAASC,cAAc,QAAQ,0BAA0B;AACzD,SAASC,aAAa,QAAQ,cAAc;AAE5C,SAASC,mBAAmB,QAAQ,gCAAgC;AAEpE,OAAOC,MAAM;AAAiB,SAAAC,GAAA,IAAAC,IAAA;AAO9B;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,MAAMA,CAC5BC,WAA0B,EAC1BC,OAAiB,GAAG,CAAC,CAAC,EAChB;EACN,MAAMC,SAAS,GAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC;EACvD,IAAI,CAACF,SAAS,EAAE,MAAMG,KAAK,CAAC,wCAAwC,CAAC;EACrE,MAAMC,KAAK,gBACTR,IAAA,CAACH,mBAAmB;IAACY,YAAY,EAAEX,MAAM,CAAC,CAAC,CAACY,MAAM,IAAIP,OAAO,CAACM,YAAa;IAAAE,QAAA,eACzEX,IAAA,CAACJ,aAAa;MAAAe,QAAA,eACZX,IAAA,CAACL,cAAc;QAAAgB,QAAA,eACbX,IAAA,CAACE,WAAW,IAAE;MAAC,CACD;IAAC,CACJ;EAAC,CACG,CACtB;EAED,IAAIC,OAAO,CAACS,WAAW,EAAE;IACvB,MAAMC,IAAI,GAAGpB,UAAU,CAACW,SAAS,CAAC;IAClCS,IAAI,CAACC,MAAM,CAACN,KAAK,CAAC;EACpB,CAAC,MAAMd,WAAW,CAACU,SAAS,EAAEI,KAAK,CAAC;AACtC","ignoreList":[]}
@@ -1,13 +1,11 @@
1
- "use strict";
2
-
3
- var _buildInfo = require("../shared/utils/isomorphy/buildInfo");
4
1
  /**
5
2
  * Initialization of client-side environment.
6
3
  */
7
4
 
8
5
  /* global window */
9
6
 
10
- const buildInfo = (0, _buildInfo.getBuildInfo)();
7
+ import { getBuildInfo } from "../shared/utils/isomorphy/buildInfo";
8
+ const buildInfo = getBuildInfo();
11
9
 
12
10
  // TODO: Should be moved into buildInfo module?
13
11
 
@@ -1 +1 @@
1
- {"version":3,"file":"init.js","names":["_buildInfo","require","buildInfo","getBuildInfo","process","env","NODE_ENV","console","warn","window","__DEV_BUILD_INFO__","BUILD_INFO","useServiceWorker","navigator","addEventListener","reg","serviceWorker","register","log","err"],"sources":["../../../src/client/init.ts"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global window */\n\nimport { type BuildInfoT, getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nconst buildInfo = getBuildInfo();\n\n// TODO: Should be moved into buildInfo module?\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n __DEV_BUILD_INFO__: BuildInfoT | undefined;\n }\n}\n\ndeclare const BUILD_INFO: BuildInfoT | undefined;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.warn('Dev mode: \"BUILD_INFO\" attached to the global \"window\"');\n\n // eslint-disable-next-line no-underscore-dangle\n window.__DEV_BUILD_INFO__ = BUILD_INFO;\n}\n\n/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */\nconst { useServiceWorker } = buildInfo;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', () => {\n void (async () => {\n try {\n // Note: no matter the \"publicPath\", we want to serve the service worker\n // from the web app root, to allow it control any and all pages of the\n // web app (otherwise, it will be restricted to the scope of its path).\n // The server takes it into account.\n const reg = await navigator\n .serviceWorker.register('/__service-worker.js');\n // eslint-disable-next-line no-console\n console.log('SW registered:', reg);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.log('SW registration failed:', err);\n }\n })();\n });\n }\n}\n"],"mappings":";;AAMA,IAAAA,UAAA,GAAAC,OAAA;AANA;AACA;AACA;;AAEA;;AAIA,MAAMC,SAAS,GAAG,IAAAC,uBAAY,EAAC,CAAC;;AAEhC;;AAUA,IAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;EACzC;EACAC,OAAO,CAACC,IAAI,CAAC,wDAAwD,CAAC;;EAEtE;EACAC,MAAM,CAACC,kBAAkB,GAAGC,UAAU;AACxC;;AAEA;AACA,MAAM;EAAEC;AAAiB,CAAC,GAAGV,SAAS;AACtC,IAAIU,gBAAgB,EAAE;EACpB,MAAM;IAAEC;EAAU,CAAC,GAAGJ,MAAM;EAC5B,IAAI,eAAe,IAAII,SAAS,EAAE;IAChCJ,MAAM,CAACK,gBAAgB,CAAC,MAAM,EAAE,MAAM;MACpC,KAAK,CAAC,YAAY;QAChB,IAAI;UACF;UACA;UACA;UACA;UACA,MAAMC,GAAG,GAAG,MAAMF,SAAS,CACxBG,aAAa,CAACC,QAAQ,CAAC,sBAAsB,CAAC;UACjD;UACAV,OAAO,CAACW,GAAG,CAAC,gBAAgB,EAAEH,GAAG,CAAC;QACpC,CAAC,CAAC,OAAOI,GAAG,EAAE;UACZ;UACAZ,OAAO,CAACW,GAAG,CAAC,yBAAyB,EAAEC,GAAG,CAAC;QAC7C;MACF,CAAC,EAAE,CAAC;IACN,CAAC,CAAC;EACJ;AACF","ignoreList":[]}
1
+ {"version":3,"file":"init.js","names":["getBuildInfo","buildInfo","process","env","NODE_ENV","console","warn","window","__DEV_BUILD_INFO__","BUILD_INFO","useServiceWorker","navigator","addEventListener","reg","serviceWorker","register","log","err"],"sources":["../../../src/client/init.ts"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global window */\n\nimport { type BuildInfoT, getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nconst buildInfo = getBuildInfo();\n\n// TODO: Should be moved into buildInfo module?\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n __DEV_BUILD_INFO__: BuildInfoT | undefined;\n }\n}\n\ndeclare const BUILD_INFO: BuildInfoT | undefined;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.warn('Dev mode: \"BUILD_INFO\" attached to the global \"window\"');\n\n // eslint-disable-next-line no-underscore-dangle\n window.__DEV_BUILD_INFO__ = BUILD_INFO;\n}\n\n/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */\nconst { useServiceWorker } = buildInfo;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', () => {\n void (async () => {\n try {\n // Note: no matter the \"publicPath\", we want to serve the service worker\n // from the web app root, to allow it control any and all pages of the\n // web app (otherwise, it will be restricted to the scope of its path).\n // The server takes it into account.\n const reg = await navigator\n .serviceWorker.register('/__service-worker.js');\n // eslint-disable-next-line no-console\n console.log('SW registered:', reg);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.log('SW registration failed:', err);\n }\n })();\n });\n }\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA;;AAEA,SAA0BA,YAAY;AAEtC,MAAMC,SAAS,GAAGD,YAAY,CAAC,CAAC;;AAEhC;;AAUA,IAAIE,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;EACzC;EACAC,OAAO,CAACC,IAAI,CAAC,wDAAwD,CAAC;;EAEtE;EACAC,MAAM,CAACC,kBAAkB,GAAGC,UAAU;AACxC;;AAEA;AACA,MAAM;EAAEC;AAAiB,CAAC,GAAGT,SAAS;AACtC,IAAIS,gBAAgB,EAAE;EACpB,MAAM;IAAEC;EAAU,CAAC,GAAGJ,MAAM;EAC5B,IAAI,eAAe,IAAII,SAAS,EAAE;IAChCJ,MAAM,CAACK,gBAAgB,CAAC,MAAM,EAAE,MAAM;MACpC,KAAK,CAAC,YAAY;QAChB,IAAI;UACF;UACA;UACA;UACA;UACA,MAAMC,GAAG,GAAG,MAAMF,SAAS,CACxBG,aAAa,CAACC,QAAQ,CAAC,sBAAsB,CAAC;UACjD;UACAV,OAAO,CAACW,GAAG,CAAC,gBAAgB,EAAEH,GAAG,CAAC;QACpC,CAAC,CAAC,OAAOI,GAAG,EAAE;UACZ;UACAZ,OAAO,CAACW,GAAG,CAAC,yBAAyB,EAAEC,GAAG,CAAC;QAC7C;MACF,CAAC,EAAE,CAAC;IACN,CAAC,CAAC;EACJ;AACF","ignoreList":[]}
@@ -1,4 +1,5 @@
1
1
  import "./styles/global.scss";
2
+ import clientModule from "./client";
2
3
  import { webpack } from "./shared/utils";
3
4
  // It is a safeguard against multiple instances / versions of the library
4
5
  // being loaded into environment by mistake (e.g. because of different
@@ -14,10 +15,7 @@ if (global.REACT_UTILS_LIBRARY_LOADED) {
14
15
  let dirname = import.meta.url;
15
16
  dirname = dirname.slice(5, dirname.lastIndexOf('/'));
16
17
  const server = webpack.requireWeak('./server', dirname);
17
- const client = server ? undefined
18
-
19
- // eslint-disable-next-line @typescript-eslint/no-require-imports
20
- : require("./client").default;
18
+ const client = server ? undefined : clientModule;
21
19
  export { getGlobalState, GlobalStateProvider, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState, withGlobalStateType } from '@dr.pogodin/react-global-state';
22
20
  export * from "./shared/components";
23
21
  export { assertEmptyObject, config, Barrier, Cached, Emitter, isomorphy, getSsrContext, Semaphore, splitComponent, themed, ThemeProvider, time, webpack, withRetries } from "./shared/utils";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["webpack","global","REACT_UTILS_LIBRARY_LOADED","Error","dirname","import","meta","url","slice","lastIndexOf","server","requireWeak","client","undefined","require","default","getGlobalState","GlobalStateProvider","newAsyncDataEnvelope","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType","assertEmptyObject","config","Barrier","Cached","Emitter","isomorphy","getSsrContext","Semaphore","splitComponent","themed","ThemeProvider","time","withRetries"],"sources":["../../src/index.ts"],"sourcesContent":["import 'styles/global.scss';\n\nimport { webpack } from 'utils';\n\nimport type * as ClientM from './client';\nimport type * as ServerFactoryM from './server';\n\n// It is a safeguard against multiple instances / versions of the library\n// being loaded into environment by mistake (e.g. because of different\n// packages pinning down different exact versions of the lib, thus preventing\n// a proper dedupe and using a single common library version).\nif (global.REACT_UTILS_LIBRARY_LOADED) {\n throw Error('React utils library is already loaded');\n} else global.REACT_UTILS_LIBRARY_LOADED = true;\n\n// TODO: This is a rapid workaround to get rid of __dirname. I guess, later\n// we'll re-implement requireWeak() to accept import.meta.url directly, and\n// this workaround won't be needed.\nlet dirname = import.meta.url;\ndirname = dirname.slice(5, dirname.lastIndexOf('/'));\n\nconst server = webpack.requireWeak<typeof ServerFactoryM>('./server', dirname);\n\nconst client = server\n ? undefined\n\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n : (require('./client') as typeof ClientM).default;\n\nexport {\n type AsyncCollectionT,\n type AsyncCollectionLoaderT,\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type ForceT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateResT,\n type ValueOrInitializerT,\n getGlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n withGlobalStateType,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\n\nexport {\n type BeforeRenderResT,\n type BeforeRenderT,\n type ConfigT,\n type ServerSsrContext,\n type ServerT,\n} from './server';\n\nexport {\n assertEmptyObject,\n config,\n Barrier,\n Cached,\n Emitter,\n isomorphy,\n getSsrContext,\n type Listener,\n type ObjectKey,\n Semaphore,\n splitComponent,\n type Theme,\n themed,\n ThemeProvider,\n time,\n webpack,\n withRetries,\n} from 'utils';\n\nexport { client, server };\n"],"mappings":"AAAA;AAEA,SAASA,OAAO;AAKhB;AACA;AACA;AACA;AACA,IAAIC,MAAM,CAACC,0BAA0B,EAAE;EACrC,MAAMC,KAAK,CAAC,uCAAuC,CAAC;AACtD,CAAC,MAAMF,MAAM,CAACC,0BAA0B,GAAG,IAAI;;AAE/C;AACA;AACA;AACA,IAAIE,OAAO,GAAGC,MAAM,CAACC,IAAI,CAACC,GAAG;AAC7BH,OAAO,GAAGA,OAAO,CAACI,KAAK,CAAC,CAAC,EAAEJ,OAAO,CAACK,WAAW,CAAC,GAAG,CAAC,CAAC;AAEpD,MAAMC,MAAM,GAAGV,OAAO,CAACW,WAAW,CAAwB,UAAU,EAAEP,OAAO,CAAC;AAE9E,MAAMQ,MAAM,GAAGF,MAAM,GACjBG;;AAEF;AAAA,EACGC,OAAO,WAAW,CAAC,CAAoBC,OAAO;AAEnD,SAUEC,cAAc,EACdC,mBAAmB,EACnBC,oBAAoB,EACpBC,kBAAkB,EAClBC,YAAY,EACZC,cAAc,EACdC,mBAAmB,QACd,gCAAgC;AAEvC;AAUA,SACEC,iBAAiB,EACjBC,MAAM,EACNC,OAAO,EACPC,MAAM,EACNC,OAAO,EACPC,SAAS,EACTC,aAAa,EAGbC,SAAS,EACTC,cAAc,EAEdC,MAAM,EACNC,aAAa,EACbC,IAAI,EACJlC,OAAO,EACPmC,WAAW;AAGb,SAASvB,MAAM,EAAEF,MAAM","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["clientModule","webpack","global","REACT_UTILS_LIBRARY_LOADED","Error","dirname","import","meta","url","slice","lastIndexOf","server","requireWeak","client","undefined","getGlobalState","GlobalStateProvider","newAsyncDataEnvelope","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType","assertEmptyObject","config","Barrier","Cached","Emitter","isomorphy","getSsrContext","Semaphore","splitComponent","themed","ThemeProvider","time","withRetries"],"sources":["../../src/index.ts"],"sourcesContent":["import 'styles/global.scss';\n\nimport clientModule from './client';\nimport { webpack } from './shared/utils';\n\nimport type * as ServerFactoryM from './server';\n\n// It is a safeguard against multiple instances / versions of the library\n// being loaded into environment by mistake (e.g. because of different\n// packages pinning down different exact versions of the lib, thus preventing\n// a proper dedupe and using a single common library version).\nif (global.REACT_UTILS_LIBRARY_LOADED) {\n throw Error('React utils library is already loaded');\n} else global.REACT_UTILS_LIBRARY_LOADED = true;\n\n// TODO: This is a rapid workaround to get rid of __dirname. I guess, later\n// we'll re-implement requireWeak() to accept import.meta.url directly, and\n// this workaround won't be needed.\nlet dirname = import.meta.url;\ndirname = dirname.slice(5, dirname.lastIndexOf('/'));\n\nconst server = webpack.requireWeak<typeof ServerFactoryM>('./server', dirname);\n\nconst client = server ? undefined : clientModule;\n\nexport {\n type AsyncCollectionT,\n type AsyncCollectionLoaderT,\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type ForceT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateResT,\n type ValueOrInitializerT,\n getGlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n withGlobalStateType,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\n\nexport {\n type BeforeRenderResT,\n type BeforeRenderT,\n type ConfigT,\n type ServerSsrContext,\n type ServerT,\n} from './server';\n\nexport {\n assertEmptyObject,\n config,\n Barrier,\n Cached,\n Emitter,\n isomorphy,\n getSsrContext,\n type Listener,\n type ObjectKey,\n Semaphore,\n splitComponent,\n type Theme,\n themed,\n ThemeProvider,\n time,\n webpack,\n withRetries,\n} from 'utils';\n\nexport { client, server };\n"],"mappings":"AAAA;AAEA,OAAOA,YAAY;AACnB,SAASC,OAAO;AAIhB;AACA;AACA;AACA;AACA,IAAIC,MAAM,CAACC,0BAA0B,EAAE;EACrC,MAAMC,KAAK,CAAC,uCAAuC,CAAC;AACtD,CAAC,MAAMF,MAAM,CAACC,0BAA0B,GAAG,IAAI;;AAE/C;AACA;AACA;AACA,IAAIE,OAAO,GAAGC,MAAM,CAACC,IAAI,CAACC,GAAG;AAC7BH,OAAO,GAAGA,OAAO,CAACI,KAAK,CAAC,CAAC,EAAEJ,OAAO,CAACK,WAAW,CAAC,GAAG,CAAC,CAAC;AAEpD,MAAMC,MAAM,GAAGV,OAAO,CAACW,WAAW,CAAwB,UAAU,EAAEP,OAAO,CAAC;AAE9E,MAAMQ,MAAM,GAAGF,MAAM,GAAGG,SAAS,GAAGd,YAAY;AAEhD,SAUEe,cAAc,EACdC,mBAAmB,EACnBC,oBAAoB,EACpBC,kBAAkB,EAClBC,YAAY,EACZC,cAAc,EACdC,mBAAmB,QACd,gCAAgC;AAEvC;AAUA,SACEC,iBAAiB,EACjBC,MAAM,EACNC,OAAO,EACPC,MAAM,EACNC,OAAO,EACPC,SAAS,EACTC,aAAa,EAGbC,SAAS,EACTC,cAAc,EAEdC,MAAM,EACNC,aAAa,EACbC,IAAI,EACJhC,OAAO,EACPiC,WAAW;AAGb,SAASrB,MAAM,EAAEF,MAAM","ignoreList":[]}
@@ -165,15 +165,17 @@ export default async function factory(webpackConfig, options) {
165
165
  href: `${pathToFileURL(process.cwd()).href}${sep}`
166
166
  };
167
167
  }
168
-
169
- /* eslint-disable @typescript-eslint/no-require-imports */
170
- const webpack = require('webpack');
171
-
172
- // TODO: Figure out the exact type for options, don't wanna waste time on it
173
- // right now.
174
- const webpackDevMiddleware = require('webpack-dev-middleware');
175
- const webpackHotMiddleware = require('webpack-hot-middleware');
168
+ const {
169
+ webpack
170
+ } = await import(/* webpackChunkName: "server-side-code" */'webpack');
171
+ const {
172
+ default: webpackDevMiddleware
173
+ } = await import(/* webpackChunkName: "server-side-code" */'webpack-dev-middleware');
174
+ const {
175
+ default: webpackHotMiddleware
176
+ } = await import(/* webpackChunkName: "server-side-code" */'webpack-hot-middleware');
176
177
  const compiler = webpack(webpackConfig);
178
+ if (!compiler) throw Error('Internal error');
177
179
  server.use(webpackDevMiddleware(compiler, {
178
180
  publicPath,
179
181
  serverSideRender: true