@dr.pogodin/react-utils 1.47.0-alpha.5 → 1.47.0-alpha.7

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 (65) hide show
  1. package/build/development/client/getInj.js +11 -0
  2. package/build/development/client/getInj.js.map +1 -1
  3. package/build/development/server/renderer.js +20 -0
  4. package/build/development/server/renderer.js.map +1 -1
  5. package/build/development/server/server.js +6 -0
  6. package/build/development/server/server.js.map +1 -1
  7. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +6 -0
  8. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  9. package/build/development/shared/components/selectors/CustomDropdown/index.js +4 -0
  10. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  11. package/build/development/shared/components/selectors/NativeDropdown/index.js +6 -0
  12. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  13. package/build/development/shared/components/selectors/Switch/index.js +2 -0
  14. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  15. package/build/development/shared/utils/jest/E2eSsrEnv.js +4 -0
  16. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  17. package/build/development/shared/utils/splitComponent.js +18 -0
  18. package/build/development/shared/utils/splitComponent.js.map +1 -1
  19. package/build/development/shared/utils/webpack.js +4 -0
  20. package/build/development/shared/utils/webpack.js.map +1 -1
  21. package/build/production/client/getInj.js +1 -1
  22. package/build/production/client/getInj.js.map +1 -1
  23. package/build/production/server/renderer.js +1 -1
  24. package/build/production/server/renderer.js.map +1 -1
  25. package/build/production/server/server.js +1 -1
  26. package/build/production/server/server.js.map +1 -1
  27. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  28. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  29. package/build/production/shared/components/selectors/CustomDropdown/index.js +1 -1
  30. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  31. package/build/production/shared/components/selectors/NativeDropdown/index.js +1 -1
  32. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  33. package/build/production/shared/components/selectors/Switch/index.js +1 -1
  34. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  35. package/build/production/shared/utils/jest/E2eSsrEnv.js +1 -1
  36. package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  37. package/build/production/shared/utils/splitComponent.js +1 -1
  38. package/build/production/shared/utils/splitComponent.js.map +1 -1
  39. package/build/production/shared/utils/webpack.js +1 -1
  40. package/build/production/shared/utils/webpack.js.map +1 -1
  41. package/build/web/client/getInj.js +7 -0
  42. package/build/web/client/getInj.js.map +1 -1
  43. package/build/web/server/renderer.js +10 -0
  44. package/build/web/server/renderer.js.map +1 -1
  45. package/build/web/server/server.js +3 -0
  46. package/build/web/server/server.js.map +1 -1
  47. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +3 -0
  48. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  49. package/build/web/shared/components/selectors/CustomDropdown/index.js +2 -0
  50. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  51. package/build/web/shared/components/selectors/NativeDropdown/index.js +3 -0
  52. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  53. package/build/web/shared/components/selectors/Switch/index.js +1 -0
  54. package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
  55. package/build/web/shared/utils/jest/E2eSsrEnv.js +2 -0
  56. package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  57. package/build/web/shared/utils/splitComponent.js +9 -0
  58. package/build/web/shared/utils/splitComponent.js.map +1 -1
  59. package/build/web/shared/utils/webpack.js +2 -0
  60. package/build/web/shared/utils/webpack.js.map +1 -1
  61. package/config/babel/node-ssr.js +7 -1
  62. package/config/babel/webpack.js +3 -1
  63. package/config/webpack/app-base.js +4 -7
  64. package/config/webpack/app-development.js +2 -3
  65. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"E2eSsrEnv.js","names":["path","defaults","set","register","JsdomEnv","Volume","createFsFromVolume","webpack","ssrFactory","setBuildInfo","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","require","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","renderer","status","markup","ssrRequest","cookie","send","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","dirname","testPath","withSsr","root","process","cwd","envName","babelEnv","extensions","setup","cache","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\nimport path from 'node:path';\n\nimport type { Request, Response } from 'express';\n\nimport { defaults, set } from 'lodash-es';\n\nimport type { ReactNode } from 'react';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration } from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport ssrFactory from 'server/renderer';\n\nimport { setBuildInfo } from '../isomorphy/buildInfo';\n\nfunction noop() {\n // NOOP\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n let factory = require(path.resolve(this.rootDir, factoryPath)) as\n (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n if (!compiler) throw Error('Failed to construct Webpack compiler');\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n // TODO: This sure can be replaced by a dynamic import().\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n const module = require(p) as NodeJS.Module;\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\n register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n await super.teardown();\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA,OAAOA,IAAI,MAAM,WAAW;AAI5B,SAASC,QAAQ,EAAEC,GAAG,QAAQ,WAAW;AAIzC;AACA;AACA;AACA,OAAOC,QAAQ,MAAM,qCAAqC;AAE1D,OAAOC,QAAQ,MAAM,wBAAwB;AAC7C,SAASC,MAAM,EAAEC,kBAAkB,QAAQ,OAAO;AAClD,OAAOC,OAAO,MAA8B,SAAS;AACrD;AAAA,OAOOC,UAAU;AAAA,SAERC,YAAY;AAErB,SAASC,IAAIA,CAAA,EAAG;EACd;AAAA;AAGF,eAAe,MAAMC,SAAS,SAASP,QAAQ,CAAC;EAa9C;AACF;AACA;AACA;EACUQ,iBAAiBA,CAAA,EAAG;IAC1B,MAAMC,aAAa,GAAG,IAAI,CAACC,OAAO,CAAC,wBAAwB,CAAW;IAEtE,MAAMC,OAAO,GAAIF,aAAa,GAAGG,IAAI,CAACC,KAAK,CAACJ,aAAa,CAAC,GAAG,CAAC,CACvC;IAEvBZ,QAAQ,CAACc,OAAO,EAAE;MAChBG,OAAO,EAAE,IAAI,CAACC,UAAU;MACxBC,EAAE,EAAE,IAAI,CAACC,MAAM,CAACC;IAClB,CAAC,CAAC;IAEF,MAAMC,WAAW,GAAG,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,EAAkB;IAC3B,MAAM,KAAK,CAACA,KAAK,CAAC,CAAC;IACnB,MAAM,IAAI,CAAC3D,UAAU,CAAC,CAAC;;IAEvB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACAR,OAAO,CAACoE,KAAK,GAAG,CAAC,CAAC;IAClBpF,YAAY,CAACqF,SAAS,EAAE,IAAI,CAAC;IAE7B,IAAI,IAAI,CAACT,OAAO,EAAE,MAAM,IAAI,CAACpC,MAAM,CAAC,CAAC;IACrC,IAAI,CAAC5B,MAAM,CAAC0E,6BAA6B,GAAG,IAAI;EAClD;EAEA,MAAMC,QAAQA,CAAA,EAAkB;IAC9B,OAAO,IAAI,CAAC3E,MAAM,CAAC0E,6BAA6B;;IAEhD;IACA;IACA;IACA;IACA;IACA;IACAE,MAAM,CAACC,IAAI,CAACzE,OAAO,CAACoE,KAAK,CAAC,CAACM,OAAO,CAAEC,GAAG,IAAK;MAC1C,OAAO3E,OAAO,CAACoE,KAAK,CAACO,GAAG,CAAC;IAC3B,CAAC,CAAC;IACFjG,QAAQ,CAACkG,MAAM,CAAC,CAAC;IACjB,MAAM,KAAK,CAACL,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
1
+ {"version":3,"file":"E2eSsrEnv.js","names":["path","defaults","set","register","JsdomEnv","Volume","createFsFromVolume","webpack","ssrFactory","setBuildInfo","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","require","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","renderer","status","markup","ssrRequest","cookie","send","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","dirname","testPath","withSsr","root","process","cwd","envName","babelEnv","extensions","setup","cache","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\nimport path from 'node:path';\n\nimport type { Request, Response } from 'express';\n\nimport { defaults, set } from 'lodash-es';\n\nimport type { ReactNode } from 'react';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration } from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport ssrFactory from 'server/renderer';\n\nimport { setBuildInfo } from '../isomorphy/buildInfo';\n\nfunction noop() {\n // NOOP\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n let factory = require(path.resolve(this.rootDir, factoryPath)) as\n (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n if (!compiler) throw Error('Failed to construct Webpack compiler');\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n // TODO: This sure can be replaced by a dynamic import().\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n const module = require(p) as NodeJS.Module;\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\n register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n await super.teardown();\n }\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;A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BAA6B;;IAEhD;IACA;IACA;IACA;IACA;IACA;IACAE,MAAM,CAACC,IAAI,CAACzE,OAAO,CAACoE,KAAK,CAAC,CAACM,OAAO,CAAEC,GAAG,IAAK;MAC1C,OAAO3E,OAAO,CAACoE,KAAK,CAACO,GAAG,CAAC;IAC3B,CAAC,CAAC;IACFjG,QAAQ,CAACkG,MAAM,CAAC,CAAC;IACjB,MAAM,KAAK,CAACL,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
@@ -1,3 +1,21 @@
1
+ import "core-js/modules/es.array.push.js";
2
+ import "core-js/modules/es.iterator.constructor.js";
3
+ import "core-js/modules/es.set.difference.v2.js";
4
+ import "core-js/modules/es.set.intersection.v2.js";
5
+ import "core-js/modules/es.set.is-disjoint-from.v2.js";
6
+ import "core-js/modules/es.set.is-subset-of.v2.js";
7
+ import "core-js/modules/es.set.is-superset-of.v2.js";
8
+ import "core-js/modules/es.set.symmetric-difference.v2.js";
9
+ import "core-js/modules/es.set.union.v2.js";
10
+ import "core-js/modules/es.array.push.js";
11
+ import "core-js/modules/es.iterator.constructor.js";
12
+ import "core-js/modules/es.set.difference.v2.js";
13
+ import "core-js/modules/es.set.intersection.v2.js";
14
+ import "core-js/modules/es.set.is-disjoint-from.v2.js";
15
+ import "core-js/modules/es.set.is-subset-of.v2.js";
16
+ import "core-js/modules/es.set.is-superset-of.v2.js";
17
+ import "core-js/modules/es.set.symmetric-difference.v2.js";
18
+ import "core-js/modules/es.set.union.v2.js";
1
19
  /* global document */
2
20
 
3
21
  import { Suspense, lazy, useInsertionEffect } from 'react';
@@ -1 +1 @@
1
- {"version":3,"file":"splitComponent.js","names":["Suspense","lazy","useInsertionEffect","Barrier","getSsrContext","IS_CLIENT_SIDE","IS_SERVER_SIDE","getBuildInfo","jsx","_jsx","getClientChunkGroups","undefined","default","getInj","inj","CHUNK_GROUPS","refCounts","getPublicPath","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","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","clientChunkGroups","resolved","Component","Wrapper","children","ref","rest","chunks","includes","CodeSplit","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\n const inj = await getInj();\n return inj.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\ntype GenericComponentPropsT = {\n children?: ReactNode;\n ref?: RefObject<unknown>;\n\n // NOTE: This is necessary, as without it this type (with only optional\n // fields) will be conisdered as \"weak\" by TypeScript, and it will be\n // a error to assign to it any type that does not use \"children\", or \"ref\".\n [propName: string]: unknown;\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 GenericComponentPropsT,\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":"AAAA;;AAEA,SAKEA,QAAQ,EACRC,IAAI,EACJC,kBAAkB,QACb,OAAO;AAEd,SAASC,OAAO,QAAQ,sBAAsB;AAAA,SAElBC,aAAa;AAAA,SAGvCC,cAAc,EACdC,cAAc,EACdC,YAAY;AACO,SAAAC,GAAA,IAAAC,IAAA;AAErB,SAASC,oBAAoBA,CAAA,EAAsC;EACjE,IAAI,CAACL,cAAc,EAAE,OAAOM,SAAS;EAErC,OAAO,CAAC,YAAY;IAClB,MAAM;MAAEC,OAAO,EAAEC;IAAO,CAAC,GAAG,MAAM,MAAM,CAAC,2EAA4E,CAAC;IAEtH,MAAMC,GAAG,GAAG,MAAMD,MAAM,CAAC,CAAC;IAC1B,OAAOC,GAAG,CAACC,YAAY,I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C,EAAE,EAAE,CAAC;MAEN,oBACE1D,IAAA,CAAC4D;MACC;MAAA;QAAA,GACKI,IAAI;QACTD,GAAG,EAAEA,GAAI;QAAAD,QAAA,EAERA;MAAQ,CACA,CAAC;IAEhB,CAAC;IAED,OAAO;MAAE3D,OAAO,EAAE0D;IAAQ,CAAC;EAC7B,CAAC,CAAC;EAEF,MAAMM,SAAmD,GAAGA,CAAC;IAC3DL,QAAQ;IACR,GAAGE;EACY,CAAC,kBAChBhE,IAAA,CAACT,QAAQ;IAAC6E,QAAQ,EAAEZ,WAAY;IAAAM,QAAA,eAC9B9D,IAAA,CAACyD;IACC;IAAA;MAAA,GACIO,IAAI;MAAAF,QAAA,EAEPA;IAAQ,CACI;EAAC,CACR,CACX;EAED,OAAOK,SAAS;AAClB","ignoreList":[]}
1
+ {"version":3,"file":"splitComponent.js","names":["Suspense","lazy","useInsertionEffect","Barrier","getSsrContext","IS_CLIENT_SIDE","IS_SERVER_SIDE","getBuildInfo","jsx","_jsx","getClientChunkGroups","undefined","default","getInj","inj","CHUNK_GROUPS","refCounts","getPublicPath","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","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","clientChunkGroups","resolved","Component","Wrapper","children","ref","rest","chunks","includes","CodeSplit","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\n const inj = await getInj();\n return inj.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\ntype GenericComponentPropsT = {\n children?: ReactNode;\n ref?: RefObject<unknown>;\n\n // NOTE: This is necessary, as without it this type (with only optional\n // fields) will be conisdered as \"weak\" by TypeScript, and it will be\n // a error to assign to it any type that does not use \"children\", or \"ref\".\n [propName: string]: unknown;\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 GenericComponentPropsT,\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":";;;;;;;;;;;;;;;;;;AAAA;;AAEA,SAKEA,QAAQ,EACRC,IAAI,EACJC,kBAAkB,QACb,OAAO;AAEd,SAASC,OAAO,QAAQ,sBAAsB;AAAA,SAElBC,aAAa;AAAA,SAGvCC,cAAc,EACdC,cAAc,EACdC,YAAY;AACO,SAAAC,GAAA,IAAAC,IAAA;AAErB,SAASC,oBAAoBA,CAAA,EAAsC;EACjE,IAAI,CAACL,cAAc,EAAE,OAAOM,SAAS;EAErC,OAAO,CAAC,YAAY;IAClB,MAAM;MAAEC,OAAO,EAAEC;IAAO,CAAC,GAAG,MAAM,MAAM,CAAC,2EAA4E,CAAC;IAEtH,MAAMC,GAAG,GAAG,MAAMD,MAAM,CAAC,CAAC;IAC1B,OAAOC,GAAG,CAACC,YAAY,IAAI,CAAC,CAAC;EAC/B,CAAC,EAAE,CAAC;AACN;AAEA,MAAMC,SAAiC,GAAG,CAAC,CAAC;AAE5C,SAASC,aAAaA,CAAA,EAAG;EACvB,OAAOV,YAAY,CAAC,CAAC,CAACW,UAAU;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,cAAcA,CACrBC,IAAY,EACZC,YAAyB,EACzBC,QAAiB,EACU;EAC3B,IAAIC,GAA8B;EAClC,MAAMC,IAAI,GAAG,GAAGP,aAAa,CAAC,CAAC,IAAIG,IAAI,EAAE;EACzC,MAAMK,QAAQ,GAAG,GAAGC,QAAQ,CAACC,QAAQ,CAACC,MAAM,GAAGJ,IAAI,EAAE;EAErD,IAAI,CAACH,Y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K,SAAS;AAClB","ignoreList":[]}
@@ -1,3 +1,7 @@
1
+ import "core-js/modules/es.iterator.constructor.js";
2
+ import "core-js/modules/es.iterator.for-each.js";
3
+ import "core-js/modules/es.iterator.constructor.js";
4
+ import "core-js/modules/es.iterator.for-each.js";
1
5
  // eslint-disable-next-line import/enforce-node-protocol-usage
2
6
  import { createRequire } from 'module';
3
7
  import { IS_CLIENT_SIDE, IS_SERVER_SIDE } from "./isomorphy/index.js";
@@ -1 +1 @@
1
- {"version":3,"file":"webpack.js","names":["createRequire","IS_CLIENT_SIDE","IS_SERVER_SIDE","require","import","meta","url","requireWeak","modulePath","basePathOrOptions","basePath","ops","resolve","path","module","default","def","named","res","Object","entries","forEach","name","value","assigned","undefined","Error","resolveWeak"],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import type PathNS from 'node:path';\n\n// eslint-disable-next-line import/enforce-node-protocol-usage\nimport { createRequire } from 'module';\n\nimport { IS_CLIENT_SIDE, IS_SERVER_SIDE } from './isomorphy';\n\ntype RequireWeakOptionsT = {\n basePath?: string;\n};\n\ntype RequireWeakResT<T> = T extends { default: infer D }\n ? (D extends null | undefined ? T : D & Omit<T, 'default'>)\n : T;\n\nlet require: ((url: string) => unknown) | undefined;\n\nif (IS_SERVER_SIDE) require = createRequire(import.meta.url);\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak<T extends object>(\n modulePath: string,\n\n // TODO: For now `basePath` can be provided directly as a string here,\n // for backward compatibility. Deprecate it in future, if any other\n // breaking changes are done for requireWeak().\n basePathOrOptions?: string | RequireWeakOptionsT,\n): RequireWeakResT<T> | null {\n if (IS_CLIENT_SIDE) return null;\n\n let basePath: string | undefined;\n let ops: RequireWeakOptionsT;\n if (typeof basePathOrOptions === 'string') {\n basePath = basePathOrOptions;\n } else {\n ops = basePathOrOptions ?? {};\n ({ basePath } = ops);\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { resolve } = require!('node:path') as typeof PathNS;\n\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n\n const module = require!(path) as T;\n\n if (!('default' in module) || !module.default) return module as RequireWeakResT<T>;\n\n const { default: def, ...named } = module;\n\n const res = def as RequireWeakResT<T>;\n\n Object.entries(named).forEach(([name, value]) => {\n const assigned = res[name as keyof RequireWeakResT<T>];\n if (assigned === undefined) {\n (res[name as keyof RequireWeakResT<T>] as unknown) = value;\n } else if (assigned !== value) {\n throw Error('Conflict between default and named exports');\n }\n });\n return res;\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":"AAEA;AACA,SAASA,aAAa,QAAQ,QAAQ;AAAA,SAE7BC,cAAc,EAAEC,cAAc;AAUvC,IAAIC,OAA+C;AAEnD,IAAID,cAAc,EAAEC,OAAO,GAAGH,aAAa,CAACI,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC;;AAE5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,WAAWA,CACzBC,UAAkB;AAElB;AACA;AACA;AACAC,iBAAgD,EACrB;EAC3B,IAAIR,cAAc,EAAE,OAAO,IAAI;EAE/B,IAAIS,QAA4B;EAChC,IAAIC,GAAwB;EAC5B,IAAI,OAAOF,iBAAiB,KAAK,QAAQ,EAAE;IACzCC,QAAQ,GAAGD,iBAAiB;EAC9B,CAAC,MAAM;IACLE,GAAG,GAAGF,iBAAiB,IAAI,CAAC,CAAC;IAC7B,CAAC;MAAEC;IAAS,CAAC,GAAGC,GAAG;EACrB;;EAEA;EACA,MAAM;IAAEC;EAAQ,CAAC,GAAGT,OAAO,CAAE,WAAW,CAAkB;EAE1D,MAAMU,IAAI,GAAGH,QAAQ,GAAGE,OAAO,CAACF,QAAQ,EAAEF,UAAU,CAAC,GAAGA,UAAU;EAElE,MAAMM,MAAM,GAAGX,OAAO,CAAEU,IAAI,CAAM;EAElC,IAAI,EAAE,SAAS,IAAIC,MAAM,CAAC,IAAI,CAACA,MAAM,CAACC,OAAO,EAAE,OAAOD,MAAM;EAE5D,MAAM;IAAEC,OAAO,EAAEC,GAAG;IAAE,GAAGC;EAAM,CAAC,GAAGH,MAAM;EAEzC,MAAMI,GAAG,GAAGF,GAAyB;EAErCG,MAAM,CAACC,OAAO,CAACH,KAAK,CAAC,CAACI,OAAO,CAAC,CAAC,CAACC,IAAI,EAAEC,KAAK,CAAC,KAAK;IAC/C,MAAMC,QAAQ,GAAGN,GAAG,CAACI,IAAI,CAA6B;IACtD,IAAIE,QAAQ,KAAKC,SAAS,EAAE;MACzBP,GAAG,CAACI,IAAI,CAA6B,GAAeC,KAAK;IAC5D,CAAC,MAAM,IAAIC,QAAQ,KAAKD,KAAK,EAAE;MAC7B,MAAMG,KAAK,CAAC,4CAA4C,CAAC;IAC3D;EACF,CAAC,CAAC;EACF,OAAOR,GAAG;AACZ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASS,WAAWA,CAACnB,UAAkB,EAAU;EACtD,OAAOA,UAAU;AACnB","ignoreList":[]}
1
+ {"version":3,"file":"webpack.js","names":["createRequire","IS_CLIENT_SIDE","IS_SERVER_SIDE","require","import","meta","url","requireWeak","modulePath","basePathOrOptions","basePath","ops","resolve","path","module","default","def","named","res","Object","entries","forEach","name","value","assigned","undefined","Error","resolveWeak"],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import type PathNS from 'node:path';\n\n// eslint-disable-next-line import/enforce-node-protocol-usage\nimport { createRequire } from 'module';\n\nimport { IS_CLIENT_SIDE, IS_SERVER_SIDE } from './isomorphy';\n\ntype RequireWeakOptionsT = {\n basePath?: string;\n};\n\ntype RequireWeakResT<T> = T extends { default: infer D }\n ? (D extends null | undefined ? T : D & Omit<T, 'default'>)\n : T;\n\nlet require: ((url: string) => unknown) | undefined;\n\nif (IS_SERVER_SIDE) require = createRequire(import.meta.url);\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak<T extends object>(\n modulePath: string,\n\n // TODO: For now `basePath` can be provided directly as a string here,\n // for backward compatibility. Deprecate it in future, if any other\n // breaking changes are done for requireWeak().\n basePathOrOptions?: string | RequireWeakOptionsT,\n): RequireWeakResT<T> | null {\n if (IS_CLIENT_SIDE) return null;\n\n let basePath: string | undefined;\n let ops: RequireWeakOptionsT;\n if (typeof basePathOrOptions === 'string') {\n basePath = basePathOrOptions;\n } else {\n ops = basePathOrOptions ?? {};\n ({ basePath } = ops);\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { resolve } = require!('node:path') as typeof PathNS;\n\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n\n const module = require!(path) as T;\n\n if (!('default' in module) || !module.default) return module as RequireWeakResT<T>;\n\n const { default: def, ...named } = module;\n\n const res = def as RequireWeakResT<T>;\n\n Object.entries(named).forEach(([name, value]) => {\n const assigned = res[name as keyof RequireWeakResT<T>];\n if (assigned === undefined) {\n (res[name as keyof RequireWeakResT<T>] as unknown) = value;\n } else if (assigned !== value) {\n throw Error('Conflict between default and named exports');\n }\n });\n return res;\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":";;;;AAEA;AACA,SAASA,aAAa,QAAQ,QAAQ;AAAA,SAE7BC,cAAc,EAAEC,cAAc;AAUvC,IAAIC,OAA+C;AAEnD,IAAID,cAAc,EAAEC,OAAO,GAAGH,aAAa,CAACI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;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASS,WAAWA,CAACnB,UAAkB,EAAU;EACtD,OAAOA,UAAU;AACnB","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- // Encapsulates retrieval of server-side data injection into HTML template.
1
+ import"core-js/modules/es.array-buffer.detached.js";import"core-js/modules/es.array-buffer.transfer.js";import"core-js/modules/es.array-buffer.transfer-to-fixed-length.js";import"core-js/modules/es.array-buffer.detached.js";import"core-js/modules/es.array-buffer.transfer.js";import"core-js/modules/es.array-buffer.transfer-to-fixed-length.js";import"core-js/modules/es.typed-array.to-reversed.js";import"core-js/modules/es.typed-array.to-sorted.js";import"core-js/modules/es.typed-array.with.js";import"core-js/modules/web.dom-exception.stack.js";// Encapsulates retrieval of server-side data injection into HTML template.
2
2
  /* global document */import{getBuildInfo}from"../shared/utils/isomorphy/buildInfo.js";let inj;export default function getInj(){inj??=(async()=>{const metaElement=typeof document==="undefined"?null:document.querySelector("meta[itemprop=\"drpruinj\"]");if(metaElement){metaElement.remove();// NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be
3
3
  // preferred, but it is not supported by older environments yet.
4
4
  const data=atob(metaElement.content);// TODO: Our current handling of this encryption / decryption follows
@@ -1 +1 @@
1
- {"version":3,"file":"getInj.js","names":["getBuildInfo","inj","getInj","metaElement","document","querySelector","remove","data","atob","content","key","code","x","charCodeAt","dataBuffer","Uint8Array","from","slice","ivBuffer","keyBuffer","cKey","window","crypto","subtle","importKey","name","buffer","decrypt","iv","decoder","TextDecoder","res","eval","decode","REACT_UTILS_INJECTION"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nlet inj: InjT | Promise<InjT> | undefined;\n\nexport default function getInj(): InjT | Promise<InjT> {\n inj ??= (async () => {\n const metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\n if (metaElement) {\n metaElement.remove();\n\n // NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be\n // preferred, but it is not supported by older environments yet.\n const data = atob(metaElement.content);\n\n // TODO: Our current handling of this encryption / decryption follows\n // a legacy approach, and can be enhanced by using Crypto features.\n // Though, this is not strictly intended to be secure (it is more\n // to obfurscate injected data, rather than really keeping them\n // secure), thus it is fine like this for now.\n const { key } = getBuildInfo();\n\n const code = (x: string) => x.charCodeAt(0);\n const dataBuffer = Uint8Array.from(data.slice(16), code);\n const ivBuffer = Uint8Array.from(data.slice(0, 16), code);\n const keyBuffer = Uint8Array.from(atob(key), code);\n\n const cKey = await window.crypto.subtle.importKey(\n 'raw',\n keyBuffer,\n { name: 'AES-CBC' },\n false,\n ['decrypt'],\n );\n\n const buffer = await window.crypto.subtle.decrypt({\n iv: ivBuffer,\n name: 'AES-CBC',\n }, cKey, dataBuffer);\n\n const decoder = new TextDecoder();\n\n // eslint-disable-next-line no-eval\n const res = eval(`(${decoder.decode(buffer)})`) as InjT;\n\n // NOTE: This is important, to be able to return the injection\n // synchronously once it is initialized.\n inj = res;\n\n return res;\n } else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n const res = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n return res;\n }\n\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 return {};\n })();\n\n return inj;\n}\n"],"mappings":"AAAA;AAEA,4BAISA,YAAY,8CAErB,GAAI,CAAAC,GAAqC,CAEzC,cAAe,SAAS,CAAAC,MAAMA,CAAA,CAAyB,CACrDD,GAAG,GAAK,CAAC,SAAY,CACnB,KAAM,CAAAE,WAAmC,CAAG,MAAO,CAAAC,QAAQ,GAAK,WAAW,CACvE,IAAI,CAAGA,QAAQ,CAACC,aAAa,CAAC,6BAA2B,CAAC,CA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T,CAAC,IAAM,IAAI,MAAO,CAAAV,MAAM,GAAK,WAAW,EAAIA,MAAM,CAACa,qBAAqB,CAAE,CACxE,KAAM,CAAAH,GAAG,CAAGV,MAAM,CAACa,qBAAqB,CACxC,MAAO,CAAAb,MAAM,CAACa,qBAAqB,CACnC,MAAO,CAAAH,GACT,CAEA;AACA;AACA;AACA,MAAO,CAAC,CACV,CAAC,EAAE,CAAC,CAEJ,MAAO,CAAA9B,GACT","ignoreList":[]}
1
+ {"version":3,"file":"getInj.js","names":["getBuildInfo","inj","getInj","metaElement","document","querySelector","remove","data","atob","content","key","code","x","charCodeAt","dataBuffer","Uint8Array","from","slice","ivBuffer","keyBuffer","cKey","window","crypto","subtle","importKey","name","buffer","decrypt","iv","decoder","TextDecoder","res","eval","decode","REACT_UTILS_INJECTION"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nlet inj: InjT | Promise<InjT> | undefined;\n\nexport default function getInj(): InjT | Promise<InjT> {\n inj ??= (async () => {\n const metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\n if (metaElement) {\n metaElement.remove();\n\n // NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be\n // preferred, but it is not supported by older environments yet.\n const data = atob(metaElement.content);\n\n // TODO: Our current handling of this encryption / decryption follows\n // a legacy approach, and can be enhanced by using Crypto features.\n // Though, this is not strictly intended to be secure (it is more\n // to obfurscate injected data, rather than really keeping them\n // secure), thus it is fine like this for now.\n const { key } = getBuildInfo();\n\n const code = (x: string) => x.charCodeAt(0);\n const dataBuffer = Uint8Array.from(data.slice(16), code);\n const ivBuffer = Uint8Array.from(data.slice(0, 16), code);\n const keyBuffer = Uint8Array.from(atob(key), code);\n\n const cKey = await window.crypto.subtle.importKey(\n 'raw',\n keyBuffer,\n { name: 'AES-CBC' },\n false,\n ['decrypt'],\n );\n\n const buffer = await window.crypto.subtle.decrypt({\n iv: ivBuffer,\n name: 'AES-CBC',\n }, cKey, dataBuffer);\n\n const decoder = new TextDecoder();\n\n // eslint-disable-next-line no-eval\n const res = eval(`(${decoder.decode(buffer)})`) as InjT;\n\n // NOTE: This is important, to be able to return the injection\n // synchronously once it is initialized.\n inj = res;\n\n return res;\n } else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n const res = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n return res;\n }\n\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 return {};\n })();\n\n return inj;\n}\n"],"mappings":"oiBAAA;AAEA,4BAISA,YAAY,8CAErB,GAAI,CAAAC,GAAqC,CAEzC,cAAe,SAAS,CAAAC,MAAMA,CAAA,CAAyB,CACrDD,GAAG,GAAK,CAAC,SAAY,CACnB,KAAM,CAAAE,WAAmC,CAAG,MAAO,CAAAC,QAAQ,GAAK,WAAW,CACvE,IAAI,CAAGA,QAAQ,CAACC,aAAa,CAAC,6BAA2B,CAAC,CAE9D,GAAIF,WAAW,CAAE,CACfA,WAAW,CAACG,MAAM,CAAC,CAAC,CAEpB;AACA;AACA,KAAM,CAAAC,IAAI,CAAGC,IAAI,CAACL,WAAW,CAACM,OAAO,CAAC,CAEtC;AACA;AACA;AACA;AACA;AACA,KAAM,CAAEC,GAAI,CAAC,CAAGV,YAAY,CAAC,CAAC,CAE9B,KAAM,CAAAW,IAAI,CAAIC,CAAS,EAAKA,CAAC,CAACC,UAAU,CAAC,CAAC,CAAC,CAC3C,KAAM,CAAAC,UAAU,CAAGC,UAAU,CAACC,IAAI,CAACT,IAAI,CAACU,KAAK,CAAC,EAAE,CAAC,CAAEN,IAAI,CAAC,CACxD,KAAM,CAAAO,QAAQ,CAAGH,UAAU,CAACC,IAAI,CAACT,IAAI,CAACU,KAAK,CAAC,CAAC,CAAE,EAAE,CAAC,CAAEN,IAAI,CAAC,CACzD,KAAM,CAAAQ,SAAS,CAAGJ,UAAU,CAACC,IAAI,CAACR,IAAI,CAACE,GAAG,CAAC,CAAEC,IAAI,CAAC,CAElD,KAAM,CAAAS,IAAI,CAAG,KAAM,CAAAC,MAAM,CAACC,MAAM,CAACC,MAAM,CAACC,SAAS,CAC/C,KAAK,CACLL,SAAS,CACT,CAAEM,IAAI,CAAE,SAAU,CAAC,CACnB,KAAK,CACL,CAAC,SAAS,CACZ,CAAC,CAED,KAAM,CAAAC,MAAM,CAAG,KAAM,CAAAL,MAAM,CAACC,MAAM,CAACC,MAAM,CAACI,OAAO,CAAC,CAChDC,EAAE,CAAEV,QAAQ,CACZO,IAAI,CAAE,SACR,CAAC,CAAEL,IAAI,CAAEN,UAAU,CAAC,CAEpB,KAAM,CAAAe,OAAO,CAAG,GAAI,CAAAC,WAAa,CAEjC;AACA,KAAM,CAAAC,GAAG,CAAGC,IAAI,CAAC,IAAIH,OAAO,CAACI,MAAM,CAACP,MAAM,CAAC,GAAG,CAAS,CAEvD;AACA;AACAzB,GAAG,CAAG8B,GAAG,CAET,MAAO,CAAAA,GACT,CAAC,IAAM,IAAI,MAAO,CAAAV,MAAM,GAAK,WAAW,EAAIA,MAAM,CAACa,qBAAqB,CAAE,CACxE,KAAM,CAAAH,GAAG,CAAGV,MAAM,CAACa,qBAAqB,CACxC,MAAO,CAAAb,MAAM,CAACa,qBAAqB,CACnC,MAAO,CAAAH,GACT,CAEA;AACA;AACA;AACA,MAAO,CAAC,CACV,CAAC,EAAE,CAAC,CAEJ,MAAO,CAAA9B,GACT","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- /**
1
+ import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterator.map.js";import"core-js/modules/es.set.difference.v2.js";import"core-js/modules/es.set.intersection.v2.js";import"core-js/modules/es.set.is-disjoint-from.v2.js";import"core-js/modules/es.set.is-subset-of.v2.js";import"core-js/modules/es.set.is-superset-of.v2.js";import"core-js/modules/es.set.symmetric-difference.v2.js";import"core-js/modules/es.set.union.v2.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterator.map.js";import"core-js/modules/es.set.difference.v2.js";import"core-js/modules/es.set.intersection.v2.js";import"core-js/modules/es.set.is-disjoint-from.v2.js";import"core-js/modules/es.set.is-subset-of.v2.js";import"core-js/modules/es.set.is-superset-of.v2.js";import"core-js/modules/es.set.symmetric-difference.v2.js";import"core-js/modules/es.set.union.v2.js";/**
2
2
  * ExpressJS middleware for server-side rendering of a ReactJS app.
3
3
  */import{Buffer}from"node:buffer";import{createCipheriv,randomBytes}from"node:crypto";import fs from"node:fs";import path from"node:path";import{Writable}from"node:stream";import{brotliCompress,brotliDecompress}from"node:zlib";import winston from"winston";import{GlobalStateProvider,SsrContext}from"@dr.pogodin/react-global-state";import{timer}from"@dr.pogodin/js-utils";import{cloneDeep,defaults,get,mapValues}from"lodash-es";import config from"config";import{prerenderToNodeStream}from"react-dom/static";import{HelmetProvider}from"@dr.pogodin/react-helmet";import{StaticRouter}from"react-router";import serializeJs from"serialize-javascript";import{setBuildInfo}from"../shared/utils/isomorphy/buildInfo.js";import Cache from"./Cache.js";// @ts-expect-error "Property 'SECRET' does not exist on type 'IConfig'."
4
4
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -1 +1 @@
1
- {"version":3,"file":"renderer.js","names":["Buffer","createCipheriv","randomBytes","fs","path","Writable","brotliCompress","brotliDecompress","winston","GlobalStateProvider","SsrContext","timer","cloneDeep","defaults","get","mapValues","config","prerenderToNodeStream","HelmetProvider","StaticRouter","serializeJs","setBuildInfo","Cache","jsx","_jsx","SECRET","sanitizedConfig","SCRIPT_LOCATIONS","ServerSsrContext","chunks","status","constructor","req","chunkGroups","initialState","getBuildInfo","context","url","resolve","JSON","parse","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","iv","cipher","from","isBrotliAcceptable","acceptable","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","beforeRender","Promise","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","helmet","webpackStats","locals","toJson","all","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","reject","helmetContext","state","children","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","logMsg","log","redirectTo","redirect","ready","pipe","destroy","write","chunk","_","payload","CONFIG","ISTATE","ignoreFunction","unsafe","INJ","concat","update","final","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { type Cipheriv, createCipheriv, randomBytes } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport type { Request, RequestHandler } from 'express';\nimport type { ComponentType } from 'react';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\n\nimport {\n cloneDeep,\n defaults,\n get,\n mapValues,\n} from 'lodash-es';\n\nimport config from 'config';\n\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { type HelmetDataContext, HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\n\nimport Cache from './Cache';\n\n// @ts-expect-error \"Property 'SECRET' does not exist on type 'IConfig'.\"\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst { SECRET, ...sanitizedConfig } = config;\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (level: string, message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LeveledLogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nexport class ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n redirectTo?: string;\n\n req: Request;\n\n status: number = 200;\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) ?? ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8')) as BuildInfoT;\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8')) as Record<string, string[]>;\n } catch {\n // TODO: Should we message the error here somehow?\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random, Base64-encoded key is expected).\n * @return Returns a tuple of:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string): [cipher: Cipheriv, iv: Buffer] {\n const iv = randomBytes(16);\n const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);\n return [cipher, iv];\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param req\n */\nexport function isBrotliAcceptable(req: Request): boolean {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (const op of ops) {\n const [type, priority] = op.trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<string | ScriptT> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (const script of scripts) {\n if (typeof script === 'string') {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (script.location in res) res[script.location] += script.code;\n else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}): winston.Logger {\n const { format, transports } = winston;\n return winston.createLogger({\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\n transports: [new transports.Console()],\n });\n}\n\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: unknown;\n};\n\nexport type BeforeRenderT = (\n req: Request,\n config: ConfigT,\n) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n staticCacheSize?: number;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults({ ...options }, {\n beforeRender: async () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context!);\n setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath as string}manifest.json\">` : '';\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface BufferWithNonce extends ArrayBuffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n // TODO: Look at it later.\n // eslint-disable-next-line complexity\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n\n // TODO: It should be implemented more careful.\n h = h.replace(regex, (req as unknown as {\n nonce: string;\n }).nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const brr = ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT);\n const { configToInject, extraScripts, initialState } = await brr;\n\n const [cipher, iv] = prepareCipher(buildInfo.key);\n\n let helmet: HelmetDataContext['helmet'];\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats') as Stats | undefined;\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name)\n ?? [],\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: NodeJS.ReadableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n rejectArg(arg as Error);\n };\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n const helmetContext = {} as HelmetDataContext;\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\n const timeout = ops.ssrTimeout! + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject ?? sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n\n const INJ = Buffer.concat([\n iv,\n cipher.update(payload, 'utf8'),\n cipher.final(),\n ]).toString('base64');\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath as string}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath as string}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon\n ? '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet?.title.toString() ?? ''}\n ${helmet?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmet?.link.toString() ?? ''}${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n const b = buffer as unknown as BufferWithNonce;\n b.nonce = (req as unknown as {\n nonce: string;\n }).nonce;\n cache!.add({ buffer: b, status }, cacheRef.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":"AAAA;AACA;AACA,GAEA,OAASA,MAAM,KAAQ,aAAa,CACpC,OAAwBC,cAAc,CAAEC,WAAW,KAAQ,aAAa,CACxE,MAAO,CAAAC,EAAE,KAAM,SAAS,CACxB,MAAO,CAAAC,IAAI,KAAM,WAAW,CAC5B,OAASC,QAAQ,KAAQ,aAAa,CACtC,OAASC,cAAc,CAAEC,gBAAgB,KAAQ,WAAW,CAK5D,MAAO,CAAAC,OAAO,KAAM,SAAS,CAE7B,OAASC,mBAAmB,CAAEC,UAAU,KAAQ,gCAAgC,CAChF,OAASC,KAAK,KAAQ,sBAAsB,CAE5C,OACEC,SAAS,CACTC,QAAQ,CACRC,GAAG,CACHC,SAAS,KACJ,WAAW,CAElB,MAAO,CAAAC,MAAM,KAAM,QAAQ,CAE3B,OAASC,qBAAqB,KAAQ,kBAAkB,CACxD,OAAiCC,cAAc,KAAQ,0BAA0B,CACjF,OAASC,YAAY,KAAQ,cAAc,CAC3C,MAAO,CAAAC,WAAW,KAAM,sBAAsB,QACpBC,YAAY,oDAI/B,CAAAC,KAAK,kBAEZ;AACA;AAAA,OAAAC,GAAA,IAAAC,IAAA,yBACA,KAAM,CAAEC,MAAM,CAAE,GAAGC,eAAgB,CAAC,CAAGV,MAAM,CAE7C;AACA;AACA;AACA;AAMA;AAMA;AASA,UAAY,CAAAW,gBAAgB,uBAAhBA,gBAAgB,EAAhBA,gBAAgB,0BAAhBA,gBAAgB,sBAAhBA,gBAAgB,gCAAhB,CAAAA,gBAAgB,MAM5B,MAAO,MAAM,CAAAC,gBAAgB,QACnB,CAAAlB,UACuB,CAG/BmB,MAAM,CAAa,EAAE,CAMrBC,MAAM,CAAW,GAAG,CAEpBC,WAAWA,CACTC,GAAY,CACZC,WAAyB,CACzBC,Y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M,CAAC,CAEtC,GAAIgF,QAAQ,EAAIhF,MAAM,CAAG,GAAG,CAAE,CAC5B;AACA;AACA,KAAM,IAAI,CAAA6D,OAAO,CAAO,CAACwB,IAAI,CAAEC,MAAM,GAAK,CACxC9G,cAAc,CAACgH,IAAI,CAAE,CAACD,KAAK,CAAEL,MAAM,GAAK,CACtC,GAAIK,KAAK,CAAED,MAAM,CAACC,KAAK,CAAC,CAAC,IACpB,CACH,KAAM,CAAAoF,CAAC,CAAGzF,MAAoC,CAC9CyF,CAAC,CAAC9E,KAAK,CAAI3F,GAAG,CAEX2F,KAAK,CACRpB,KAAK,CAAEwF,GAAG,CAAC,CAAE/E,MAAM,CAAEyF,CAAC,CAAE3K,MAAO,CAAC,CAAEgF,QAAQ,CAAChE,GAAG,CAAEkE,MAAM,CAAC5B,MAAM,CAAC,CAC9D+B,IAAI,CAAC,CACP,CACF,CAAC,CACH,CAAC,CACH,CAEA;AACA;AACA;AACAvE,GAAG,CAACsE,IAAI,CAACI,IAAI,CACf,CAAE,MAAOD,KAAK,CAAE,CACdX,IAAI,CAACW,KAAK,CACZ,CACF,CACF","ignoreList":[]}
1
+ {"version":3,"file":"renderer.js","names":["Buffer","createCipheriv","randomBytes","fs","path","Writable","brotliCompress","brotliDecompress","winston","GlobalStateProvider","SsrContext","timer","cloneDeep","defaults","get","mapValues","config","prerenderToNodeStream","HelmetProvider","StaticRouter","serializeJs","setBuildInfo","Cache","jsx","_jsx","SECRET","sanitizedConfig","SCRIPT_LOCATIONS","ServerSsrContext","chunks","status","constructor","req","chunkGroups","initialState","getBuildInfo","context","url","resolve","JSON","parse","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","iv","cipher","from","isBrotliAcceptable","acceptable","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","beforeRender","Promise","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","helmet","webpackStats","locals","toJson","all","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","reject","helmetContext","state","children","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","logMsg","log","redirectTo","redirect","ready","pipe","destroy","write","chunk","_","payload","CONFIG","ISTATE","ignoreFunction","unsafe","INJ","concat","update","final","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { type Cipheriv, createCipheriv, randomBytes } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport type { Request, RequestHandler } from 'express';\nimport type { ComponentType } from 'react';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\n\nimport {\n cloneDeep,\n defaults,\n get,\n mapValues,\n} from 'lodash-es';\n\nimport config from 'config';\n\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { type HelmetDataContext, HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\n\nimport Cache from './Cache';\n\n// @ts-expect-error \"Property 'SECRET' does not exist on type 'IConfig'.\"\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst { SECRET, ...sanitizedConfig } = config;\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (level: string, message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LeveledLogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nexport class ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n redirectTo?: string;\n\n req: Request;\n\n status: number = 200;\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) ?? ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8')) as BuildInfoT;\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8')) as Record<string, string[]>;\n } catch {\n // TODO: Should we message the error here somehow?\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random, Base64-encoded key is expected).\n * @return Returns a tuple of:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string): [cipher: Cipheriv, iv: Buffer] {\n const iv = randomBytes(16);\n const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);\n return [cipher, iv];\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param req\n */\nexport function isBrotliAcceptable(req: Request): boolean {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (const op of ops) {\n const [type, priority] = op.trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<string | ScriptT> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (const script of scripts) {\n if (typeof script === 'string') {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (script.location in res) res[script.location] += script.code;\n else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}): winston.Logger {\n const { format, transports } = winston;\n return winston.createLogger({\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\n transports: [new transports.Console()],\n });\n}\n\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: unknown;\n};\n\nexport type BeforeRenderT = (\n req: Request,\n config: ConfigT,\n) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n staticCacheSize?: number;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults({ ...options }, {\n beforeRender: async () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context!);\n setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath as string}manifest.json\">` : '';\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface BufferWithNonce extends ArrayBuffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n // TODO: Look at it later.\n // eslint-disable-next-line complexity\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n\n // TODO: It should be implemented more careful.\n h = h.replace(regex, (req as unknown as {\n nonce: string;\n }).nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const brr = ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT);\n const { configToInject, extraScripts, initialState } = await brr;\n\n const [cipher, iv] = prepareCipher(buildInfo.key);\n\n let helmet: HelmetDataContext['helmet'];\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats') as Stats | undefined;\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name)\n ?? [],\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: NodeJS.ReadableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n rejectArg(arg as Error);\n };\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n const helmetContext = {} as HelmetDataContext;\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\n const timeout = ops.ssrTimeout! + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject ?? sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n\n const INJ = Buffer.concat([\n iv,\n cipher.update(payload, 'utf8'),\n cipher.final(),\n ]).toString('base64');\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath as string}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath as string}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon\n ? '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet?.title.toString() ?? ''}\n ${helmet?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmet?.link.toString() ?? ''}${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n const b = buffer as unknown as BufferWithNonce;\n b.nonce = (req as unknown as {\n nonce: string;\n }).nonce;\n cache!.add({ buffer: b, status }, cacheRef.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":"k+BAAA;AACA;AACA,GAEA,OAASA,MAAM,KAAQ,aAAa,CACpC,OAAw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AAK,CACtC,GAAIK,KAAK,CAAED,MAAM,CAACC,KAAK,CAAC,CAAC,IACpB,CACH,KAAM,CAAAoF,CAAC,CAAGzF,MAAoC,CAC9CyF,CAAC,CAAC9E,KAAK,CAAI3F,GAAG,CAEX2F,KAAK,CACRpB,KAAK,CAAEwF,GAAG,CAAC,CAAE/E,MAAM,CAAEyF,CAAC,CAAE3K,MAAO,CAAC,CAAEgF,QAAQ,CAAChE,GAAG,CAAEkE,MAAM,CAAC5B,MAAM,CAAC,CAC9D+B,IAAI,CAAC,CACP,CACF,CAAC,CACH,CAAC,CACH,CAEA;AACA;AACA;AACAvE,GAAG,CAACsE,IAAI,CAACI,IAAI,CACf,CAAE,MAAOD,KAAK,CAAE,CACdX,IAAI,CAACW,KAAK,CACZ,CACF,CACF","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- /**
1
+ import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";/**
2
2
  * Creation of standard ExpressJS server for ReactJS apps.
3
3
  */import{sep}from"node:path";import{pathToFileURL}from"node:url";import{cloneDeep,mapValues,pick}from"lodash-es";import compression from"compression";import cookieParser from"cookie-parser";import csrf from"@dr.pogodin/csurf";import express from"express";import favicon from"serve-favicon";import helmet from"helmet";import loggerMiddleware from"morgan";import requestIp from"request-ip";import{v4 as uuid}from"uuid";import rendererFactory from"./renderer.js";import{CODES,ERRORS,getErrorForCode,newError}from"./utils/errors.js";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
4
4
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["sep","pathToFileURL","cloneDeep","mapValues","pick","compression","cookieParser","csrf","express","favicon","helmet","loggerMiddleware","requestIp","v4","uuid","rendererFactory","CODES","ERRORS","getErrorForCode","newError","defaultCspSettings","directives","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","cspNonce","cspSettings","cspSettingsHook","send","json","limit","urlencoded","extended","cookieSignatureSecret","mw","cookie","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","process","cwd","default","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","Error","serverSideRender","onExpressJsSetup","NOT_FOUND","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","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, mapValues, pick } from 'lodash-es';\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 { default: 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":"AAAA;AACA;AACA,GAEA,OAASA,GAAG,KAAQ,WAAW,CAC/B,OAASC,aAAa,KAAQ,UAAU,CAExC,OAASC,SAAS,CAAEC,SAAS,CAAEC,IAAI,KAAQ,WAAW,CAEtD,MAAO,CAAAC,WAAW,KAAM,aAAa,CACrC,MAAO,CAAAC,YAAY,KAAM,eAAe,CACxC,MAAO,CAAAC,IAAI,KAAM,mBAAmB,CAEpC,MAAO,CAAAC,OAAO,KAKP,SAAS,CAEhB,MAAO,CAAAC,OAAO,KAAM,eAAe,CACnC,MAAO,CAAAC,MAAM,KAA8B,QAAQ,CACnD,MAAO,CAAAC,gBAAgB,KAAM,QAAQ,CACrC,MAAO,CAAAC,SAAS,KAAM,YAAY,CAClC,OAASC,EAAE,GAAI,CAAAC,IAAI,KAAQ,MAAM,OAI1B,CAAAC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EJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC,CAErE,GAAI,CAAAC,OAAO,CAAGP,KAAK,CAACO,OAAO,EAAIrF,eAAe,CAACgF,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAIjB,OAAO,CAACqB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDF,OAAO,CAAGtF,MAAM,CAACkF,qBACnB,CAEAzD,GAAG,CAACwD,MAAM,CAACA,MAAM,CAAC,CAACvC,IAAI,CAAC4C,OAAO,CACjC,CAAC,CACH,CAEA,MAAO,CAAAnE,MACT","ignoreList":[]}
1
+ {"version":3,"file":"server.js","names":["sep","pathToFileURL","cloneDeep","mapValues","pick","compression","cookieParser","csrf","express","favicon","helmet","loggerMiddleware","requestIp","v4","uuid","rendererFactory","CODES","ERRORS","getErrorForCode","newError","defaultCspSettings","directives","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","cspNonce","cspSettings","cspSettingsHook","send","json","limit","urlencoded","extended","cookieSignatureSecret","mw","cookie","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","process","cwd","default","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","Error","serverSideRender","onExpressJsSetup","NOT_FOUND","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","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, mapValues, pick } from 'lodash-es';\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 { default: 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_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ChCD,6BAA6B,CAAG,KAAM,CAAA/D,OAAO,CAACgE,oBAAoB,CAAC3D,MAAM,CAC3E,CAEA,oBACA,GAAI,CAAC0D,6BAA6B,CAAE,CAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA1D,MAAM,CAACI,GAAG,CAAC,CACTwD,KAEC,CACDvD,GAAY,CACZC,GAAa,CACbC,IAAkB,GACf,CACH;AACA;AACA,GAAID,GAAG,CAACuD,WAAW,CAAE,CACnBtD,IAAI,CAACqD,KAAK,CAAC,CACX,MACF,CAEA,KAAM,CAAAE,MAAM,CAAGF,KAAK,CAACE,MAAM,EAAIlF,KAAK,CAACmF,qBAAqB,CAC1D,KAAM,CAAAC,UAAU,CAAGF,MAAM,EAAKlF,KAAK,CAACmF,qBAAgC,CAEpE;AACApE,OAAO,CAACO,MAAM,CAAE+D,GAAG,CAACD,UAAU,CAAG,OAAO,CAAG,OAAO,CAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC,CAErE,GAAI,CAAAC,OAAO,CAAGP,KAAK,CAACO,OAAO,EAAIrF,eAAe,CAACgF,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAIjB,OAAO,CAACqB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDF,OAAO,CAAGtF,MAAM,CAACkF,qBACnB,CAEAzD,GAAG,CAACwD,MAAM,CAACA,MAAM,CAAC,CAACvC,IAAI,CAAC4C,OAAO,CACjC,CAAC,CACH,CAEA,MAAO,CAAAnE,MACT","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- import{useImperativeHandle,useRef}from"react";import{BaseModal}from"../../../Modal/index.js";import{optionValueName}from"../../common.js";const S={"overlay":"ntZ5My"};import{jsx as _jsx}from"react/jsx-runtime";export function areEqual(a,b){return a?.left===b?.left&&a?.top===b?.top&&a?.width===b?.width}const Options=({containerClass,containerStyle,filter,onCancel,onChange,optionClass,options,ref})=>{const opsRef=useRef(null);useImperativeHandle(ref,()=>({measure:()=>{const e=opsRef.current?.parentElement;if(!e)return undefined;const rect=opsRef.current.getBoundingClientRect();const style=window.getComputedStyle(e);const mBottom=parseFloat(style.marginBottom);const mTop=parseFloat(style.marginTop);rect.height+=mBottom+mTop;return rect}}),[]);const optionNodes=[];for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);optionNodes.push(/*#__PURE__*/_jsx("div",{className:optionClass,onClick:e=>{onChange(iValue);e.stopPropagation()},onKeyDown:e=>{if(e.key==="Enter"){onChange(iValue);e.stopPropagation()}},role:"button",tabIndex:0,children:iName},iValue))}}return/*#__PURE__*/_jsx(BaseModal// Closes the dropdown (cancels the selection) on any page scrolling attempt.
1
+ import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";import{useImperativeHandle,useRef}from"react";import{BaseModal}from"../../../Modal/index.js";import{optionValueName}from"../../common.js";const S={"overlay":"ntZ5My"};import{jsx as _jsx}from"react/jsx-runtime";export function areEqual(a,b){return a?.left===b?.left&&a?.top===b?.top&&a?.width===b?.width}const Options=({containerClass,containerStyle,filter,onCancel,onChange,optionClass,options,ref})=>{const opsRef=useRef(null);useImperativeHandle(ref,()=>({measure:()=>{const e=opsRef.current?.parentElement;if(!e)return undefined;const rect=opsRef.current.getBoundingClientRect();const style=window.getComputedStyle(e);const mBottom=parseFloat(style.marginBottom);const mTop=parseFloat(style.marginTop);rect.height+=mBottom+mTop;return rect}}),[]);const optionNodes=[];for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);optionNodes.push(/*#__PURE__*/_jsx("div",{className:optionClass,onClick:e=>{onChange(iValue);e.stopPropagation()},onKeyDown:e=>{if(e.key==="Enter"){onChange(iValue);e.stopPropagation()}},role:"button",tabIndex:0,children:iName},iValue))}}return/*#__PURE__*/_jsx(BaseModal// Closes the dropdown (cancels the selection) on any page scrolling attempt.
2
2
  // This is the same native <select> elements do on scrolling, and at least for
3
3
  // now we have no reason to deal with complications needed to support open
4
4
  // dropdowns during the scrolling (that would need to re-position it in