@dr.pogodin/react-utils 1.57.1 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/build/development/server/Cache.js +7 -7
  2. package/build/development/server/Cache.js.map +1 -1
  3. package/build/development/server/index.js +6 -3
  4. package/build/development/server/index.js.map +1 -1
  5. package/build/development/server/renderer.js +18 -7
  6. package/build/development/server/renderer.js.map +1 -1
  7. package/build/development/server/server.js +12 -6
  8. package/build/development/server/server.js.map +1 -1
  9. package/build/development/server/utils/errors.js +10 -10
  10. package/build/development/server/utils/errors.js.map +1 -1
  11. package/build/development/shared/components/Button/index.js +1 -1
  12. package/build/development/shared/components/Button/index.js.map +1 -1
  13. package/build/development/shared/components/Checkbox/index.js +5 -5
  14. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  15. package/build/development/shared/components/Input/index.js +3 -3
  16. package/build/development/shared/components/Input/index.js.map +1 -1
  17. package/build/development/shared/components/Modal/index.js +3 -0
  18. package/build/development/shared/components/Modal/index.js.map +1 -1
  19. package/build/development/shared/components/TextArea/index.js +3 -3
  20. package/build/development/shared/components/TextArea/index.js.map +1 -1
  21. package/build/development/shared/components/WithTooltip/Tooltip.js +2 -2
  22. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  23. package/build/development/shared/components/WithTooltip/index.js +3 -1
  24. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  25. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +4 -1
  26. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  27. package/build/development/shared/components/selectors/CustomDropdown/index.js +7 -4
  28. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  29. package/build/development/shared/components/selectors/NativeDropdown/index.js +3 -3
  30. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  31. package/build/development/shared/components/selectors/Switch/index.js +2 -2
  32. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  33. package/build/development/shared/utils/config.js.map +1 -1
  34. package/build/development/shared/utils/jest/E2eSsrEnv/index.js +7 -6
  35. package/build/development/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
  36. package/build/development/shared/utils/jest/index.js +2 -1
  37. package/build/development/shared/utils/jest/index.js.map +1 -1
  38. package/build/development/shared/utils/splitComponent.js +10 -8
  39. package/build/development/shared/utils/splitComponent.js.map +1 -1
  40. package/build/development/shared/utils/webpack.js +2 -1
  41. package/build/development/shared/utils/webpack.js.map +1 -1
  42. package/build/production/server/Cache.js +3 -3
  43. package/build/production/server/Cache.js.map +1 -1
  44. package/build/production/server/index.js +1 -1
  45. package/build/production/server/index.js.map +1 -1
  46. package/build/production/server/renderer.js +9 -9
  47. package/build/production/server/renderer.js.map +1 -1
  48. package/build/production/server/server.js +6 -6
  49. package/build/production/server/server.js.map +1 -1
  50. package/build/production/server/utils/errors.js +1 -1
  51. package/build/production/server/utils/errors.js.map +1 -1
  52. package/build/production/shared/components/Button/index.js +1 -1
  53. package/build/production/shared/components/Button/index.js.map +1 -1
  54. package/build/production/shared/components/Checkbox/index.js +1 -1
  55. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  56. package/build/production/shared/components/Input/index.js +1 -1
  57. package/build/production/shared/components/Input/index.js.map +1 -1
  58. package/build/production/shared/components/Modal/index.js +1 -1
  59. package/build/production/shared/components/Modal/index.js.map +1 -1
  60. package/build/production/shared/components/TextArea/index.js +1 -1
  61. package/build/production/shared/components/TextArea/index.js.map +1 -1
  62. package/build/production/shared/components/WithTooltip/Tooltip.js +1 -1
  63. package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
  64. package/build/production/shared/components/WithTooltip/index.js +2 -2
  65. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  66. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  67. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  68. package/build/production/shared/components/selectors/CustomDropdown/index.js +1 -1
  69. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  70. package/build/production/shared/components/selectors/NativeDropdown/index.js +2 -2
  71. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  72. package/build/production/shared/components/selectors/Switch/index.js +1 -1
  73. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  74. package/build/production/shared/utils/config.js.map +1 -1
  75. package/build/production/shared/utils/jest/E2eSsrEnv/index.js +2 -2
  76. package/build/production/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
  77. package/build/production/shared/utils/jest/index.js +2 -2
  78. package/build/production/shared/utils/jest/index.js.map +1 -1
  79. package/build/production/shared/utils/splitComponent.js +3 -3
  80. package/build/production/shared/utils/splitComponent.js.map +1 -1
  81. package/build/production/shared/utils/webpack.js +3 -2
  82. package/build/production/shared/utils/webpack.js.map +1 -1
  83. package/build/types-code/shared/utils/config.d.ts +1 -1
  84. package/build/web/server/Cache.js +3 -3
  85. package/build/web/server/Cache.js.map +1 -1
  86. package/build/web/server/index.js +1 -1
  87. package/build/web/server/index.js.map +1 -1
  88. package/build/web/server/renderer.js +9 -9
  89. package/build/web/server/renderer.js.map +1 -1
  90. package/build/web/server/server.js +6 -6
  91. package/build/web/server/server.js.map +1 -1
  92. package/build/web/server/utils/errors.js +1 -1
  93. package/build/web/server/utils/errors.js.map +1 -1
  94. package/build/web/shared/components/Button/index.js +1 -1
  95. package/build/web/shared/components/Button/index.js.map +1 -1
  96. package/build/web/shared/components/Checkbox/index.js +1 -1
  97. package/build/web/shared/components/Checkbox/index.js.map +1 -1
  98. package/build/web/shared/components/Input/index.js +1 -1
  99. package/build/web/shared/components/Input/index.js.map +1 -1
  100. package/build/web/shared/components/Modal/index.js +1 -1
  101. package/build/web/shared/components/Modal/index.js.map +1 -1
  102. package/build/web/shared/components/TextArea/index.js +1 -1
  103. package/build/web/shared/components/TextArea/index.js.map +1 -1
  104. package/build/web/shared/components/WithTooltip/Tooltip.js +1 -1
  105. package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -1
  106. package/build/web/shared/components/WithTooltip/index.js +2 -2
  107. package/build/web/shared/components/WithTooltip/index.js.map +1 -1
  108. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  109. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  110. package/build/web/shared/components/selectors/CustomDropdown/index.js +1 -1
  111. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  112. package/build/web/shared/components/selectors/NativeDropdown/index.js +2 -2
  113. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  114. package/build/web/shared/components/selectors/Switch/index.js +1 -1
  115. package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
  116. package/build/web/shared/utils/config.js.map +1 -1
  117. package/build/web/shared/utils/jest/E2eSsrEnv/index.js +2 -2
  118. package/build/web/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
  119. package/build/web/shared/utils/jest/index.js +2 -2
  120. package/build/web/shared/utils/jest/index.js.map +1 -1
  121. package/build/web/shared/utils/splitComponent.js +3 -3
  122. package/build/web/shared/utils/splitComponent.js.map +1 -1
  123. package/build/web/shared/utils/webpack.js +3 -2
  124. package/build/web/shared/utils/webpack.js.map +1 -1
  125. package/config/babel/webpack.js +6 -1
  126. package/package.json +19 -19
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/index.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\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 */\n\nimport { fork } from 'node:child_process';\nimport { access } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration, type Stats } from 'webpack';\n\nimport register, { revert } from '@babel/register';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport { deduceChunkGroups } from 'server/renderer';\n\nimport type { LaunchT, ResultT } from './ssr';\n\nasync function findModule(module: string): Promise<string> {\n try {\n const res = `${module}.ts`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n try {\n const res = `${module}.js`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n throw Error(`Module \"${module}\" was not found, neither as TS, nor as JS`);\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?: Stats;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private async 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\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\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 await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\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 // NOTE: This is a TS module in the source code, and it turn into JS\n // module in the distributed code, after Babel compilation. As we rely\n // on it for the forked NodeJS process, we need to resolve the correct\n // extention ourselves (as NodeJS will hit the given path, without any\n // additional resolutions / transformations).\n const ssrModulePath = await findModule(`${import.meta.dirname}/ssr-preload`);\n\n const cp = fork(ssrModulePath);\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve, reject) => {\n cp.on('exit', (code) => {\n if (code) reject(Error('SSR process crashed'));\n });\n\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\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\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 // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n // BEWARE: Although we also do the registration inside SSR testing code,\n // we still need it here to correctly process imported Webpack configurations\n // (which are imported directly from this module).\n register({\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // eslint-disable-next-line import/dynamic-import-chunkname\n const { setBuildInfo } = await import('../../isomorphy/buildInfo');\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 revert();\n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CAAC,CACjC,IAAI,CAAC,UAAU,CAAG,OAAO,CACzB,IAAI,CAAC,OAAO,CAAG,OAAO,CAEtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,CAAC,CACP,UAAU,CAAE,CAAC,KAAK,CAAE,MAAM,CAAE,KAAK,CAAE,MAAM,CAAE,MAAM,CACnD,CAAC,CAAC,CACJ,CAEA,KAAM,MAAK,EAAkB,CAC3B,KAAM,MAAK,CAAC,KAAK,CAAC,CAAC,CACnB,KAAM,KAAI,CAAC,UAAU,CAAC,CAAC,CAEvB;AACA,KAAM,CAAE,YAAa,CAAC,CAAG,KAAM,OAAM,gCAA6B,CAClE,YAAY,CAAC,SAAS,CAAE,IAAI,CAAC,CAE7B,GAAI,IAAI,CAAC,OAAO,CAAE,KAAM,KAAI,CAAC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC,MAAM,CAAC,6BAA6B,CAAG,IAAI,CAClD,CAEA,KAAM,SAAQ,EAAkB,CAC9B,MAAO,KAAI,CAAC,MAAM,CAAC,6BAA6B,CAEhD,MAAM,CAAC,CAAC,CAER,KAAM,MAAK,CAAC,QAAQ,CAAC,CAAC,CACxB,CACF","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/index.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\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 */\n\nimport { fork } from 'node:child_process';\nimport { access } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration, type Stats } from 'webpack';\n\nimport register, { revert } from '@babel/register';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport { deduceChunkGroups } from 'server/renderer';\n\nimport type { LaunchT, ResultT } from './ssr';\n\nasync function findModule(module: string): Promise<string> {\n try {\n const res = `${module}.ts`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n try {\n const res = `${module}.js`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n throw Error(`Module \"${module}\" was not found, neither as TS, nor as JS`);\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?: Stats;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private async 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\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n if (!options.context) throw Error('Missing context');\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 await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\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 // NOTE: This is a TS module in the source code, and it turn into JS\n // module in the distributed code, after Babel compilation. As we rely\n // on it for the forked NodeJS process, we need to resolve the correct\n // extention ourselves (as NodeJS will hit the given path, without any\n // additional resolutions / transformations).\n const ssrModulePath = await findModule(`${import.meta.dirname}/ssr-preload`);\n\n const cp = fork(ssrModulePath);\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve, reject) => {\n cp.on('exit', (code) => {\n if (code) reject(Error('SSR process crashed'));\n });\n\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\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\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 // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n // BEWARE: Although we also do the registration inside SSR testing code,\n // we still need it here to correctly process imported Webpack configurations\n // (which are imported directly from this module).\n register({\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // eslint-disable-next-line import/dynamic-import-chunkname\n const { setBuildInfo } = await import('../../isomorphy/buildInfo');\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 revert();\n\n await super.teardown();\n }\n}\n"],"mappings":"6DAAA;AACA;AACA;AACA;AACA;AACA,GAEA;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QAAQ,CAAC,CACjC,IAAI,CAAC,UAAU,CAAG,OAAO,CACzB,IAAI,CAAC,OAAO,CAAG,OAAO,CAEtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,CAAC,CACP,UAAU,CAAE,CAAC,KAAK,CAAE,MAAM,CAAE,KAAK,CAAE,MAAM,CAAE,MAAM,CACnD,CAAC,CAAC,CACJ,CAEA,KAAM,MAAK,EAAkB,CAC3B,KAAM,MAAK,CAAC,KAAK,CAAC,CAAC,CACnB,KAAM,KAAI,CAAC,UAAU,CAAC,CAAC,CAEvB;AACA,KAAM,CAAE,YAAa,CAAC,CAAG,KAAM,OAAM,gCAA6B,CAClE,YAAY,CAAC,SAAS,CAAE,IAAI,CAAC,CAE7B,GAAI,IAAI,CAAC,OAAO,CAAE,KAAM,KAAI,CAAC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC,MAAM,CAAC,6BAA6B,CAAG,IAAI,CAClD,CAEA,KAAM,SAAQ,EAAkB,CAC9B,MAAO,KAAI,CAAC,MAAM,CAAC,6BAA6B,CAEhD,MAAM,CAAC,CAAC,CAER,KAAM,MAAK,CAAC,QAAQ,CAAC,CAAC,CACxB,CACF","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- import _JSON$stringify from"core-js-pure/stable/json/stringify.js";/* global document *//* eslint-disable import/no-extraneous-dependencies */import mockdate from"mockdate";import{act}from"react";import{createRoot}from"react-dom/client";import{expect,jest}from"@jest/globals";import{render}from"@testing-library/react";/**
1
+ import _JSON$stringify from"core-js-pure/features/json/stringify.js";/* global document *//* eslint-disable import/no-extraneous-dependencies */import mockdate from"mockdate";import{act}from"react";import{createRoot}from"react-dom/client";import{expect,jest}from"@jest/globals";import{render}from"@testing-library/react";/**
2
2
  * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)
3
3
  * from `react`.
4
4
  */export{act};export{default as getGlobal}from"./global.js";global.IS_REACT_ACT_ENVIRONMENT=true;const originalProcessVersions=process.versions;/**
@@ -49,6 +49,6 @@ return new Promise((resolve,reject)=>{let rejected=false;// BEWARE: The "promise
49
49
  // "reject" argument provided.
50
50
  void promise.then(()=>{if(!rejected){// TODO: These lines are the same as the lines below for sync variant of
51
51
  // the function. We should split and reuse them in both places.
52
- const nodes=res.asFragment().childNodes;expect(nodes.length>1?[...nodes]:nodes[0]).toMatchSnapshot();resolve(res);}},error=>{rejected=true;// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
52
+ if(!res)throw Error("Missing render result");const nodes=res.asFragment().childNodes;expect(nodes.length>1?[...nodes]:nodes[0]).toMatchSnapshot();resolve(res);}},error=>{rejected=true;// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
53
53
  reject(error);});});}const nodes=res.asFragment().childNodes;expect(nodes.length>1?[...nodes]:nodes[0]).toMatchSnapshot();return res;}
54
54
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { expect, jest } from '@jest/globals';\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): `${string}-${string}-${string}-${string}-${string}` {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve, reject) => {\n let rejected = false;\n\n // BEWARE: The \"promise\" returned by act() does not behave as a regular\n // Promise instance:\n // 1. In case of errors its .then() method both calls its \"reject\"\n // callback (first), and then its \"resolve\" callback second.\n // 2. It errors out if a rendering error happens, and there is no\n // \"reject\" argument provided.\n void promise.then(() => {\n if (!rejected) {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n }\n }, (error: unknown) => {\n rejected = true;\n\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"mEAAA,qBACA,sDASA,MAAO,SAAQ,KAAM,UAAU,CAC/B,OAA4C,GAAG,KAAQ,OAAO,CAC9D,OAAoB,UAAU,KAAQ,kBAAkB,CAExD,OAAS,MAAM,CAAE,IAAI,KAAQ,eAAe,CAC5C,OAA4B,MAAM,KAAQ,wBAAwB,CAElE;AACA;AACA;AACA,GACA,OAAS,GAAG,EAAG,OAEN,OAAO,GAAI,UAAS,mBAE7B,MAAM,CAAC,wBAAwB,CAAG,IAAI,CAEtC,KAAM,wBAAuB,CAAG,OAAO,CAAC,QAAQ,CAEhD;AACA;AACA;AACA,GACA,MAAO,SAAS,eAAc,EAAS,CACrC,MAAM,CAAC,cAAc,CAAC,OAAO,CAAE,UAAU,CAAE,CAAE,KAAK,CAAE,SAAU,CAAC,CAAC,CAClE,CAEA;AACA;AACA,GACA,MAAO,SAAS,iBAAgB,EAAS,CACvC,MAAM,CAAC,cAAc,CAAC,OAAO,CAAE,UAAU,CAAE,CACzC,KAAK,CAAE,uBAAuB,CAC9B,QAAQ,CAAE,KACZ,CAAC,CAAC,CACJ,CAEA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,YAAW,CAAC,IAAI,CAAG,CAAC,CAAuD,CACzF,KAAM,EAAC,CAAG,IAAI,CAAC,QA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AAO,CAAC,CACrB,MAAO,QAAO,EAAE,KAAK,CACvB,CAAC,CAAC,CAEF,GAAI,GAAG,GAAK,SAAS,CAAE,KAAM,MAAK,CAAC,eAAe,CAAC,CACnD,GAAI,OAAO,EAAE,KAAK,CAAE,CAClB;AACA;AACA;AACA;AACA,MAAO,IAAI,QAAO,CAAC,CAAC,OAAO,CAAE,MAAM,GAAK,CACtC,GAAI,SAAQ,CAAG,KAAK,CAEpB;AACA;AACA;AACA;AACA;AACA;AACA,IAAK,QAAO,CAAC,IAAI,CAAC,IAAM,CACtB,GAAI,CAAC,QAAQ,CAAE,CACb;AACA;AACA,KAAM,MAAK,CAAG,GAAG,CAAE,UAAU,CAAC,CAAC,CAAC,UAAU,CAC1C,MAAM,CAAC,KAAK,CAAC,MAAM,CAAG,CAAC,CAAG,CAAC,GAAG,KAAK,CAAC,CAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAClE,OAAO,CAAC,GAAI,CAAC,CACf,CACF,CAAC,CAAG,KAAc,EAAK,CACrB,QAAQ,CAAG,IAAI,CAEf;AACA,MAAM,CAAC,KAAK,CAAC,CACf,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA,KAAM,MAAK,CAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CACzC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAG,CAAC,CAAG,CAAC,GAAG,KAAK,CAAC,CAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAClE,MAAO,IAAG,CACZ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { expect, jest } from '@jest/globals';\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): `${string}-${string}-${string}-${string}-${string}` {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve, reject) => {\n let rejected = false;\n\n // BEWARE: The \"promise\" returned by act() does not behave as a regular\n // Promise instance:\n // 1. In case of errors its .then() method both calls its \"reject\"\n // callback (first), and then its \"resolve\" callback second.\n // 2. It errors out if a rendering error happens, and there is no\n // \"reject\" argument provided.\n void promise.then(() => {\n if (!rejected) {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n if (!res) throw Error('Missing render result');\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res);\n }\n }, (error: unknown) => {\n rejected = true;\n\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"qEAAA,qBACA,sDASA,MAAO,SAAQ,KAAM,UAAU,CAC/B,OAA4C,GAAG,KAAQ,OAAO,CAC9D,OAAoB,UAAU,KAAQ,kBAAkB,CAExD,OAAS,MAAM,CAAE,IAAI,KAAQ,eAAe,CAC5C,OAA4B,MAAM,KAAQ,wBAAwB,CAElE;AACA;AACA;AACA,GACA,OAAS,GAAG,EAAG,OAEN,OAAO,GAAI,UAAS,mBAE7B,MAAM,CAAC,wBAAwB,CAAG,IAAI,CAEtC,KAAM,wBAAuB,CAAG,OAAO,C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f,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA,KAAM,MAAK,CAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CACzC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAG,CAAC,CAAG,CAAC,GAAG,KAAK,CAAC,CAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAClE,MAAO,IAAG,CACZ","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- import _pushInstanceProperty from"core-js-pure/stable/instance/push.js";import{c as _c}from"react/compiler-runtime";/* global document */import{Suspense,lazy,useInsertionEffect}from"react";import{Barrier}from"@dr.pogodin/js-utils";import{useSsrContext}from"./globalState.js";import{IS_CLIENT_SIDE,IS_SERVER_SIDE,assertClientSide,getBuildInfo}from"./isomorphy/index.js";import{jsx as _jsx}from"react/jsx-runtime";let clientChunkGroups;export function setClientChunkGroups(groups){assertClientSide();clientChunkGroups=groups;}const refCounts={};function getPublicPath(){return getBuildInfo().publicPath;}/**
1
+ import _pushInstanceProperty from"core-js-pure/features/instance/push.js";import{c as _c}from"react/compiler-runtime";/* global document */import{Suspense,lazy,useInsertionEffect}from"react";import{Barrier}from"@dr.pogodin/js-utils";import{useSsrContext}from"./globalState.js";import{IS_CLIENT_SIDE,IS_SERVER_SIDE,assertClientSide,getBuildInfo}from"./isomorphy/index.js";import{jsx as _jsx}from"react/jsx-runtime";let clientChunkGroups;export function setClientChunkGroups(groups){assertClientSide();clientChunkGroups=groups;}const refCounts=new Map;function getPublicPath(){return getBuildInfo().publicPath;}/**
2
2
  * Client-side only! Ensures the specified CSS stylesheet is loaded into
3
3
  * the document; loads if it is missing; and does simple reference counting
4
4
  * to facilitate future clean-up.
@@ -6,7 +6,7 @@ import _pushInstanceProperty from"core-js-pure/stable/instance/push.js";import{c
6
6
  * @param loadedSheets
7
7
  * @param refCount
8
8
  * @return
9
- */function bookStyleSheet(name,loadedSheets,refCount){let res;const path=`${getPublicPath()}/${name}`;const fullPath=`${document.location.origin}${path}`;if(!loadedSheets.has(fullPath)){let link=document.querySelector(`link[href="${path}"]`);if(!link){link=document.createElement("link");link.setAttribute("rel","stylesheet");link.setAttribute("href",path);document.head.appendChild(link);}res=new Barrier;link.addEventListener("load",()=>{if(!res)throw Error("Internal error");void res.resolve();});link.addEventListener("error",()=>{if(!res)throw Error("Internal error");void res.resolve();});}if(refCount){const current=refCounts[path]??0;refCounts[path]=1+current;}return res;}/**
9
+ */function bookStyleSheet(name,loadedSheets,refCount){let res;const path=`${getPublicPath()}/${name}`;const fullPath=`${document.location.origin}${path}`;if(!loadedSheets.has(fullPath)){let link=document.querySelector(`link[href="${path}"]`);if(!link){link=document.createElement("link");link.setAttribute("rel","stylesheet");link.setAttribute("href",path);document.head.appendChild(link);}res=new Barrier;link.addEventListener("load",()=>{if(!res)throw Error("Internal error");void res.resolve();});link.addEventListener("error",()=>{if(!res)throw Error("Internal error");void res.resolve();});}if(refCount){const current=refCounts.get(path)??0;refCounts.set(path,1+current);}return res;}/**
10
10
  * Generates the set of URLs for currently loaded, linked stylesheets.
11
11
  * @return
12
12
  */function getLoadedStyleSheets(){const res=new Set;const{styleSheets}=document;for(const{href}of styleSheets){if(href)res.add(href);}return res;}function assertChunkName(chunkName,chunkGroups){if(chunkGroups[chunkName])return;throw Error(`Unknown chunk name "${chunkName}"`);}/**
@@ -23,7 +23,7 @@ import _pushInstanceProperty from"core-js-pure/stable/instance/push.js";import{c
23
23
  * (for chunks with larger reference counter values, it just decrements
24
24
  * the reference counter).
25
25
  * @param {string} chunkName
26
- */export function freeStyleSheets(chunkName,chunkGroups){const assets=chunkGroups[chunkName];if(!assets)return;for(const asset of assets){if(asset.endsWith(".css")){const path=`${getPublicPath()}/${asset}`;const pathRefCount=refCounts[path];if(pathRefCount){if(pathRefCount<=1){document.head.querySelector(`link[href="${path}"]`).remove();delete refCounts[path];}else refCounts[path]=pathRefCount-1;}}}}// Holds the set of chunk names already used for splitComponent() calls.
26
+ */export function freeStyleSheets(chunkName,chunkGroups){const assets=chunkGroups[chunkName];if(!assets)return;for(const asset of assets){if(asset.endsWith(".css")){const path=`${getPublicPath()}/${asset}`;const pathRefCount=refCounts.get(path);if(pathRefCount){if(pathRefCount<=1){const node=document.head.querySelector(`link[href="${path}"]`);if(!node)throw Error("Missing node");node.remove();refCounts.delete(path);}else refCounts.set(path,pathRefCount-1);}}}}// Holds the set of chunk names already used for splitComponent() calls.
27
27
  const usedChunkNames=new Set;/**
28
28
  * Given an async component retrieval function `getComponent()` it creates
29
29
  * a special "code split" component, which uses <Suspense> to asynchronously
@@ -1 +1 @@
1
- {"version":3,"file":"splitComponent.js","names":[],"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, useSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n assertClientSide,\n getBuildInfo,\n} from './isomorphy';\n\nlet clientChunkGroups: ChunkGroupsT | undefined;\n\nexport function setClientChunkGroups(groups: ChunkGroupsT): void {\n assertClientSide();\n clientChunkGroups = groups;\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\n // When HMR happens splitComponent() ends up getting called again for some\n // chunks, thus we should not throw this error. Not sure, if we need to do\n // some additional handling in that case, or just not throwing is all we\n // need.\n && !import.meta.webpackHot\n ) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT & {\n chunkGroups: ChunkGroupsT;\n }> = ({\n children,\n chunkGroups,\n ref,\n ...rest\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, chunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, chunkGroups);\n };\n }, [chunkGroups]);\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: FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => {\n let chunkGroups: ChunkGroupsT;\n\n const ssrContext = useSsrContext(false);\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 if (!ssrContext) throw Error('Internal error');\n ({ chunkGroups } = ssrContext);\n const { chunks } = ssrContext;\n\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n } else {\n if (!clientChunkGroups) {\n throw Error('Missing client-side chunk groups data');\n }\n chunkGroups = clientChunkGroups;\n }\n\n assertChunkName(chunkName, chunkGroups);\n\n return (\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 chunkGroups={chunkGroups}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n };\n\n return CodeSplit;\n}\n"],"mappings":"oHAAA,qBAEA,OAKE,QAAQ,CACR,IAAI,CACJ,kBAAkB,KACb,OAAO,CAEd,OAAS,OAAO,KAAQ,sBAAsB,CAAC,OAEnB,aAAa,+BAGvC,cAAc,CACd,cAAc,CACd,gBAAgB,CAChB,YAAY,uEAGd,GAAI,kBA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,0DAHnD,qBAAC,QAAQ,EAAW,QAAW,CAAX,WAAW,uBAC7B,KAAC,aAAa,KAER,EAA2C,CAElC,WAAW,CAAX,WAAW,UAEvB,QAAQ,CACI,CAAC,CACR,CAAC,qEATX,GASW,EAEd,CAED,MAAO,UAAS,CAClB","ignoreList":[]}
1
+ {"version":3,"file":"splitComponent.js","names":[],"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, useSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n assertClientSide,\n getBuildInfo,\n} from './isomorphy';\n\nlet clientChunkGroups: ChunkGroupsT | undefined;\n\nexport function setClientChunkGroups(groups: ChunkGroupsT): void {\n assertClientSide();\n clientChunkGroups = groups;\n}\n\nconst refCounts = new Map<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.get(path) ?? 0;\n refCounts.set(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.get(path);\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n const node = document.head.querySelector(`link[href=\"${path}\"]`);\n if (!node) throw Error('Missing node');\n node.remove();\n refCounts.delete(path);\n } else refCounts.set(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\n // When HMR happens splitComponent() ends up getting called again for some\n // chunks, thus we should not throw this error. Not sure, if we need to do\n // some additional handling in that case, or just not throwing is all we\n // need.\n && !import.meta.webpackHot\n ) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT & {\n chunkGroups: ChunkGroupsT;\n }> = ({\n children,\n chunkGroups,\n ref,\n ...rest\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, chunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, chunkGroups);\n };\n }, [chunkGroups]);\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: FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => {\n let chunkGroups: ChunkGroupsT;\n\n const ssrContext = useSsrContext(false);\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 if (!ssrContext) throw Error('Internal error');\n ({ chunkGroups } = ssrContext);\n const { chunks } = ssrContext;\n\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n } else {\n if (!clientChunkGroups) {\n throw Error('Missing client-side chunk groups data');\n }\n chunkGroups = clientChunkGroups;\n }\n\n assertChunkName(chunkName, chunkGroups);\n\n return (\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 chunkGroups={chunkGroups}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n };\n\n return CodeSplit;\n}\n"],"mappings":"sHAAA,qBAEA,OAKE,QAAQ,CACR,IAAI,CACJ,kBAAkB,KACb,OAAO,CAEd,OAAS,OAAO,KAAQ,sBAAsB,CAAC,OAEnB,aAAa,+BAGvC,cAAc,CACd,cAAc,CACd,gBAAgB,CAChB,YAAY,uEAGd,GAAI,kBAA2C,CAE/C,MAAO,SAAS,qBAAoB,CAAC,MAAoB,CAAQ,CAC/D,gBAAgB,CAAC,CAAC,CAClB,iBAAiB,CAAG,MAAM,CAC5B,CAEA,KAAM,UAAS,CAAG,GAAI,IAAqB,C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AAC,QAAQ,EAAW,QAAW,CAAX,WAAW,uBAC7B,KAAC,aAAa,KAER,EAA2C,CAElC,WAAW,CAAX,WAAW,UAEvB,QAAQ,CACI,CAAC,CACR,CAAC,qEATX,GASW,EAEd,CAED,MAAO,UAAS,CAClB","ignoreList":[]}
@@ -8,8 +8,9 @@ import{createRequire}from"module";import{IS_CLIENT_SIDE,IS_SERVER_SIDE}from"./is
8
8
  */export function requireWeak(modulePath,// TODO: For now `basePath` can be provided directly as a string here,
9
9
  // for backward compatibility. Deprecate it in future, if any other
10
10
  // breaking changes are done for requireWeak().
11
- basePathOrOptions){if(IS_CLIENT_SIDE)return null;let basePath;let ops;if(typeof basePathOrOptions==="string"){basePath=basePathOrOptions;}else{ops=basePathOrOptions??{};({basePath}=ops);}// eslint-disable-next-line @typescript-eslint/unbound-method
12
- const{resolve}=require("node:path");const path=basePath?resolve(basePath,modulePath):modulePath;const module=require(path);if(!("default"in module)||!module.default)return module;const{default:def,...named}=module;const res=def;Object.entries(named).forEach(([name,value])=>{const assigned=res[name];if(assigned===undefined){res[name]=value;}else if(assigned!==value){throw Error("Conflict between default and named exports");}});return res;}/**
11
+ basePathOrOptions){if(IS_CLIENT_SIDE)return null;if(!require)throw Error("Internal error (missing require)");let basePath;let ops;if(typeof basePathOrOptions==="string"){basePath=basePathOrOptions;}else{ops=basePathOrOptions??{};({basePath}=ops);}// eslint-disable-next-line @typescript-eslint/unbound-method
12
+ const{resolve}=require("node:path");const path=basePath?resolve(basePath,modulePath):modulePath;// eslint-disable-next-line import/no-dynamic-require
13
+ const module=require(path);if(!("default"in module)||!module.default)return module;const{default:def,...named}=module;const res=def;Object.entries(named).forEach(([name,value])=>{const assigned=res[name];if(assigned===undefined){res[name]=value;}else if(assigned!==value){throw Error("Conflict between default and named exports");}});return res;}/**
13
14
  * Resolves specified module path with help of Babel's module resolver.
14
15
  * Yes, the function itself just returns its argument to the caller, but Babel
15
16
  * is configured to resolve the first argument of resolveWeak(..) function, thus
@@ -1 +1 @@
1
- {"version":3,"file":"webpack.js","names":[],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import type PathNS from 'node:path';\n\n// eslint-disable-next-line import/enforce-node-protocol-usage, perfectionist/sort-imports\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?: RequireWeakOptionsT | string,\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 modulePath\n * @return Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":"AAEA;AACA,OAAS,aAAa,KAAQ,QAAQ,CAAC,OAE9B,cAAc,CAAE,cAAc,4BAUvC,GAAI,QAA+C,CAEnD,GAAI,cAAc,CAAE,OAAO,CAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAE5D;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,YAAW,CACzB,UAAkB,CAElB;AACA;AACA;AACA,iBAAgD,CACrB,CAC3B,GAAI,cAAc,CAAE,MAAO,KAAI,CAE/B,GAAI,SAA4B,CAChC,GAAI,IAAwB,CAC5B,GAAI,MAAO,kBAAiB,GAAK,QAAQ,CAAE,CACzC,QAAQ,CAAG,iBAAiB,CAC9B,CAAC,IAAM,CACL,GAAG,CAAG,iBAAiB,EAAI,CAAC,CAAC,CAC7B,CAAC,CAAE,QAAS,CAAC,CAAG,GAAG,EACrB,CAEA;AACA,KAAM,CAAE,OAAQ,CAAC,CAAG,OAAO,CAAE,WAAW,CAAkB,CAE1D,KAAM,KAAI,CAAG,QAAQ,CAAG,OAAO,CAAC,QAAQ,CAAE,UAAU,CAAC,CAAG,UAAU,CAElE,KAAM,OAAM,CAAG,OAAO,CAAE,IAAI,CAAM,CAElC,GAAI,EAAE,SAAS,EAAI,OAAM,CAAC,EAAI,CAAC,MAAM,CAAC,OAAO,CAAE,MAAO,OAAM,CAE5D,KAAM,CAAE,OAAO,CAAE,GAAG,CAAE,GAAG,KAAM,CAAC,CAAG,MAAM,CAEzC,KAAM,IAAG,CAAG,GAAyB,CAErC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAE,KAAK,CAAC,GAAK,CAC/C,KAAM,SAAQ,CAAG,GAAG,CAAC,IAAI,CAA6B,CACtD,GAAI,QAAQ,GAAK,SAAS,CAAE,CACzB,GAAG,CAAC,IAAI,CAA6B,CAAe,KAAK,CAC5D,CAAC,IAAM,IAAI,QAAQ,GAAK,KAAK,CAAE,CAC7B,KAAM,MAAK,CAAC,4CAA4C,CAAC,CAC3D,CACF,CAAC,CAAC,CACF,MAAO,IAAG,CACZ,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,YAAW,CAAC,UAAkB,CAAU,CACtD,MAAO,WAAU,CACnB","ignoreList":[]}
1
+ {"version":3,"file":"webpack.js","names":[],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import type PathNS from 'node:path';\n\n// eslint-disable-next-line import/enforce-node-protocol-usage, perfectionist/sort-imports\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?: RequireWeakOptionsT | string,\n): RequireWeakResT<T> | null {\n if (IS_CLIENT_SIDE) return null;\n\n if (!require) throw Error('Internal error (missing require)');\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 // eslint-disable-next-line import/no-dynamic-require\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 modulePath\n * @return Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":"AAEA;AACA,OAAS,aAAa,KAAQ,QAAQ,CAAC,OAE9B,cAAc,CAAE,cAAc,4BAUvC,GAAI,QAA+C,CAEnD,GAAI,cAAc,CAAE,OAAO,CAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAE5D;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,YAAW,CACzB,UAAkB,CAElB;AACA;AACA;AACA,iBAAgD,CACrB,CAC3B,GAAI,cAAc,CAAE,MAAO,KAAI,CAE/B,GAAI,CAAC,OAAO,CAAE,KAAM,MAAK,CAAC,kCAAkC,CAAC,CAE7D,GAAI,SAA4B,CAChC,GAAI,IAAwB,CAC5B,GAAI,MAAO,kBAAiB,GAAK,QAAQ,CAAE,CACzC,QAAQ,CAAG,iBAAiB,CAC9B,CAAC,IAAM,CACL,GAAG,CAAG,iBAAiB,EAAI,CAAC,CAAC,CAC7B,CAAC,CAAE,QAAS,CAAC,CAAG,GAAG,EACrB,CAEA;AACA,KAAM,CAAE,OAAQ,CAAC,CAAG,OAAO,CAAC,WAAW,CAAkB,CAEzD,KAAM,KAAI,CAAG,QAAQ,CAAG,OAAO,CAAC,QAAQ,CAAE,UAAU,CAAC,CAAG,UAAU,CAElE;AACA,KAAM,OAAM,CAAG,OAAO,CAAC,IAAI,CAAM,CAEjC,GAAI,EAAE,SAAS,EAAI,OAAM,CAAC,EAAI,CAAC,MAAM,CAAC,OAAO,CAAE,MAAO,OAAM,CAE5D,KAAM,CAAE,OAAO,CAAE,GAAG,CAAE,GAAG,KAAM,CAAC,CAAG,MAAM,CAEzC,KAAM,IAAG,CAAG,GAAyB,CAErC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAE,KAAK,CAAC,GAAK,CAC/C,KAAM,SAAQ,CAAG,GAAG,CAAC,IAAI,CAA6B,CACtD,GAAI,QAAQ,GAAK,SAAS,CAAE,CACzB,GAAG,CAAC,IAAI,CAA6B,CAAe,KAAK,CAC5D,CAAC,IAAM,IAAI,QAAQ,GAAK,KAAK,CAAE,CAC7B,KAAM,MAAK,CAAC,4CAA4C,CAAC,CAC3D,CACF,CAAC,CAAC,CACF,MAAO,IAAG,CACZ,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,YAAW,CAAC,UAAkB,CAAU,CACtD,MAAO,WAAU,CACnB","ignoreList":[]}
@@ -1,4 +1,4 @@
1
1
  type ConfigT = Record<string, unknown>;
2
- export declare function getConfig<T extends ConfigT>(sync: true): T;
2
+ export declare function getConfig(sync: true): ConfigT;
3
3
  export declare function getConfig<T extends ConfigT>(sync?: boolean): Promise<T> | T;
4
4
  export {};
@@ -1,16 +1,16 @@
1
1
  /**
2
2
  * Implements the static cache.
3
- */export default class Cache{items={};size=0;constructor(maxSize){this.maxSize=maxSize}/**
3
+ */export default class Cache{items=new Map;size=0;constructor(maxSize){this.maxSize=maxSize}/**
4
4
  * Cache lookup.
5
5
  * @param key Item key to look for.
6
6
  * @param [maxage=Number.MAX_VALUE] Optional. The maximum age of
7
7
  * cached item to serve. Default to infinite.
8
8
  * @returns Cached item, or null if the item is absent in cache,
9
9
  * or stale.
10
- */get({key,maxage=Number.MAX_VALUE}){const item=this.items[key];return item&&Date.now()-item.timestamp<maxage?item.data:null;}/**
10
+ */get({key,maxage=Number.MAX_VALUE}){const item=this.items.get(key);return item&&Date.now()-item.timestamp<maxage?item.data:null;}/**
11
11
  * Adds item to cache.
12
12
  * @param data Item to add.
13
13
  * @param key Key to store the item at.
14
14
  * @param size Byte size of the item.
15
- */add(data,key,size){const cached=this.items[key];if(cached)this.size-=cached.size;this.items[key]={data,size,timestamp:Date.now()};this.size+=size;if(this.size>this.maxSize){const entries=Object.entries(this.items);entries.sort((a,b)=>a[1].timestamp-b[1].timestamp);for(const entry of entries){const[itemKey,item]=entry;delete this.items[itemKey];this.size-=item.size;if(this.size<this.maxSize/2)break;}}}}
15
+ */add(data,key,size){const cached=this.items.get(key);if(cached)this.size-=cached.size;this.items.set(key,{data,size,timestamp:Date.now()});this.size+=size;if(this.size>this.maxSize){const entries=[...this.items.entries()];entries.sort((a,b)=>a[1].timestamp-b[1].timestamp);for(const entry of entries){const[itemKey,item]=entry;this.items.delete(itemKey);this.size-=item.size;if(this.size<this.maxSize/2)break;}}}}
16
16
  //# sourceMappingURL=Cache.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Cache.js","names":[],"sources":["../../../src/server/Cache.ts"],"sourcesContent":["type CachedItemT<DatumT> = {\n data: DatumT;\n size: number;\n timestamp: number;\n};\n\n/**\n * Implements the static cache.\n */\nexport default class Cache<DatumT> {\n private items: Record<string, CachedItemT<DatumT>> = {};\n\n private size = 0;\n\n constructor(private maxSize: number) { }\n\n /**\n * Cache lookup.\n * @param key Item key to look for.\n * @param [maxage=Number.MAX_VALUE] Optional. The maximum age of\n * cached item to serve. Default to infinite.\n * @returns Cached item, or null if the item is absent in cache,\n * or stale.\n */\n get({\n key,\n maxage = Number.MAX_VALUE,\n }: {\n key: string;\n maxage?: number;\n }): DatumT | null {\n const item = this.items[key];\n return item && Date.now() - item.timestamp < maxage ? item.data : null;\n }\n\n /**\n * Adds item to cache.\n * @param data Item to add.\n * @param key Key to store the item at.\n * @param size Byte size of the item.\n */\n add(data: DatumT, key: string, size: number): void {\n const cached = this.items[key];\n if (cached) this.size -= cached.size;\n\n this.items[key] = { data, size, timestamp: Date.now() };\n this.size += size;\n\n if (this.size > this.maxSize) {\n const entries = Object.entries(this.items);\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp);\n\n for (const entry of entries) {\n const [itemKey, item] = entry;\n delete this.items[itemKey];\n this.size -= item.size;\n if (this.size < this.maxSize / 2) break;\n }\n }\n }\n}\n"],"mappings":"AAMA;AACA;AACA,GACA,cAAe,MAAM,MAAc,CACzB,KAAK,CAAwC,CAAC,CAAC,CAE/C,IAAI,CAAG,CAAC,CAEhB,WAAW,CAAS,OAAe,CAAE,MAAjB,OAAe,CAAf,OAAmB,CAEvC;AACF;AACA;AACA;AACA;AACA;AACA;AACA,KACE,GAAG,CAAC,CACF,GAAG,CACH,MAAM,CAAG,MAAM,CAAC,SAIlB,CAAC,CAAiB,CAChB,KAAM,KAAI,CAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAC5B,MAAO,KAAI,EAAI,IAAI,CAAC,GAAG,CAAC,CAAC,CAAG,IAAI,CAAC,SAAS,CAAG,MAAM,CAAG,IAAI,CAAC,IAAI,CAAG,IAAI,CACxE,CAEA;AACF;AACA;AACA;AACA;AACA,KACE,GAAG,CAAC,IAAY,CAAE,GAAW,CAAE,IAAY,CAAQ,CACjD,KAAM,OAAM,CAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAC9B,GAAI,MAAM,CAAE,IAAI,CAAC,IAAI,EAAI,MAAM,CAAC,IAAI,CAEpC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAG,CAAE,IAAI,CAAE,IAAI,CAAE,SAAS,CAAE,IAAI,CAAC,GAAG,CAAC,CAAE,CAAC,CACvD,IAAI,CAAC,IAAI,EAAI,IAAI,CAEjB,GAAI,IAAI,CAAC,IAAI,CAAG,IAAI,CAAC,OAAO,CAAE,CAC5B,KAAM,QAAO,CAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAC1C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAE,CAAC,GAAK,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAG,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAEvD,IAAK,KAAM,MAAK,GAAI,QAAO,CAAE,CAC3B,KAAM,CAAC,OAAO,CAAE,IAAI,CAAC,CAAG,KAAK,CAC7B,MAAO,KAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAC1B,IAAI,CAAC,IAAI,EAAI,IAAI,CAAC,IAAI,CACtB,GAAI,IAAI,CAAC,IAAI,CAAG,IAAI,CAAC,OAAO,CAAG,CAAC,CAAE,MACpC,CACF,CACF,CACF","ignoreList":[]}
1
+ {"version":3,"file":"Cache.js","names":[],"sources":["../../../src/server/Cache.ts"],"sourcesContent":["type CachedItemT<DatumT> = {\n data: DatumT;\n size: number;\n timestamp: number;\n};\n\n/**\n * Implements the static cache.\n */\nexport default class Cache<DatumT> {\n private items = new Map<string, CachedItemT<DatumT>>();\n\n private size = 0;\n\n constructor(private maxSize: number) { }\n\n /**\n * Cache lookup.\n * @param key Item key to look for.\n * @param [maxage=Number.MAX_VALUE] Optional. The maximum age of\n * cached item to serve. Default to infinite.\n * @returns Cached item, or null if the item is absent in cache,\n * or stale.\n */\n get({\n key,\n maxage = Number.MAX_VALUE,\n }: {\n key: string;\n maxage?: number;\n }): DatumT | null {\n const item = this.items.get(key);\n return item && Date.now() - item.timestamp < maxage ? item.data : null;\n }\n\n /**\n * Adds item to cache.\n * @param data Item to add.\n * @param key Key to store the item at.\n * @param size Byte size of the item.\n */\n add(data: DatumT, key: string, size: number): void {\n const cached = this.items.get(key);\n if (cached) this.size -= cached.size;\n\n this.items.set(key, { data, size, timestamp: Date.now() });\n this.size += size;\n\n if (this.size > this.maxSize) {\n const entries = [...this.items.entries()];\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp);\n\n for (const entry of entries) {\n const [itemKey, item] = entry;\n this.items.delete(itemKey);\n this.size -= item.size;\n if (this.size < this.maxSize / 2) break;\n }\n }\n }\n}\n"],"mappings":"AAMA;AACA;AACA,GACA,cAAe,MAAM,MAAc,CACzB,KAAK,CAAG,GAAI,IAAkC,CAE9C,IAAI,CAAG,CAAC,CAEhB,WAAW,CAAS,OAAe,CAAE,MAAjB,OAAe,CAAf,OAAmB,CAEvC;AACF;AACA;AACA;AACA;AACA;AACA;AACA,KACE,GAAG,CAAC,CACF,GAAG,CACH,MAAM,CAAG,MAAM,CAAC,SAIlB,CAAC,CAAiB,CAChB,KAAM,KAAI,CAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAChC,MAAO,KAAI,EAAI,IAAI,CAAC,GAAG,CAAC,CAAC,CAAG,IAAI,CAAC,SAAS,CAAG,MAAM,CAAG,IAAI,CAAC,IAAI,CAAG,IAAI,CACxE,CAEA;AACF;AACA;AACA;AACA;AACA,KACE,GAAG,CAAC,IAAY,CAAE,GAAW,CAAE,IAAY,CAAQ,CACjD,KAAM,OAAM,CAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAClC,GAAI,MAAM,CAAE,IAAI,CAAC,IAAI,EAAI,MAAM,CAAC,IAAI,CAEpC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAE,CAAE,IAAI,CAAE,IAAI,CAAE,SAAS,CAAE,IAAI,CAAC,GAAG,CAAC,CAAE,CAAC,CAAC,CAC1D,IAAI,CAAC,IAAI,EAAI,IAAI,CAEjB,GAAI,IAAI,CAAC,IAAI,CAAG,IAAI,CAAC,OAAO,CAAE,CAC5B,KAAM,QAAO,CAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CACzC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAE,CAAC,GAAK,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAG,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAEvD,IAAK,KAAM,MAAK,GAAI,QAAO,CAAE,CAC3B,KAAM,CAAC,OAAO,CAAE,IAAI,CAAC,CAAG,KAAK,CAC7B,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAC1B,IAAI,CAAC,IAAI,EAAI,IAAI,CAAC,IAAI,CACtB,GAAI,IAAI,CAAC,IAAI,CAAG,IAAI,CAAC,OAAO,CAAG,CAAC,CAAE,MACpC,CACF,CACF,CACF","ignoreList":[]}
@@ -127,5 +127,5 @@ import"raf/polyfill.js";import{SCRIPT_LOCATIONS,newDefaultLogger}from"./renderer
127
127
  */export async function launchServer(webpackConfig,options={}){/* Options normalization. */const ops=cloneDeep(options);// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
128
128
  ops.port=normalizePort(ops.port||process.env.PORT||3000);defaults(ops,{httpsRedirect:true});// TODO: Need a separate type for normalized options, which guarantees
129
129
  // the logger is set!
130
- ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});/* Creates servers, resolves and sets the port. */const expressServer=await serverFactory(webpackConfig,ops);let httpServer;if(ops.https){httpServer=https.createServer({cert:ops.https.cert,key:ops.https.key},expressServer);}else httpServer=http.createServer(expressServer);/* Sets error handler for HTTP(S) server. */httpServer.on("error",error=>{if(error.syscall!=="listen")throw error;const bind=typeof ops.port==="string"?`Pipe ${ops.port}`:`Port ${ops.port}`;/* Human-readable message for some specific listen errors. */switch(error.code){case"EACCES":ops.logger.error(`${bind} requires elevated privileges`);return process.exit(1);case"EADDRINUSE":ops.logger.error(`${bind} is already in use`);return process.exit(1);case undefined:default:throw error;}});/* Listening event handler for HTTP(S) server. */httpServer.on("listening",()=>{const addr=httpServer.address();const bind=typeof addr==="string"?`pipe ${addr}`:`port ${addr.port}`;ops.logger.info(`Server listening on ${bind} in ${process.env.NODE_ENV} mode`);});httpServer.listen(ops.port);return{expressServer,httpServer};}
130
+ ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});/* Creates servers, resolves and sets the port. */const expressServer=await serverFactory(webpackConfig,ops);let httpServer;if(ops.https){httpServer=https.createServer({cert:ops.https.cert,key:ops.https.key},expressServer);}else httpServer=http.createServer(expressServer);/* Sets error handler for HTTP(S) server. */httpServer.on("error",error=>{if(error.syscall!=="listen")throw error;const bind=typeof ops.port==="string"?`Pipe ${ops.port}`:`Port ${ops.port?ops.port.toString():"undefined"}`;if(!ops.logger)throw Error("Missing logger");/* Human-readable message for some specific listen errors. */switch(error.code){case"EACCES":ops.logger.error(`${bind} requires elevated privileges`);return process.exit(1);case"EADDRINUSE":ops.logger.error(`${bind} is already in use`);return process.exit(1);case undefined:default:throw error;}});/* Listening event handler for HTTP(S) server. */httpServer.on("listening",()=>{const addr=httpServer.address();if(!addr)throw Error("Missing address");const bind=typeof addr==="string"?`pipe ${addr}`:`port ${addr.port.toString()}`;if(!ops.logger)throw Error("Missing logger");ops.logger.info(`Server listening on ${bind} in ${process.env.NODE_ENV??"undefined"} mode`);});httpServer.listen(ops.port);return{expressServer,httpServer};}
131
131
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register.js';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport { cloneDeep, defaults } from 'lodash-es';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill.js';\n\nimport type { Configuration } from 'webpack';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nexport * from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport {\n SCRIPT_LOCATIONS,\n type ServerT,\n getDefaultCspSettings,\n};\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String).\n */\nfunction normalizePort(value: number | string) {\n const port = typeof value === 'string' ? parseInt(value) : value;\n if (Number.isFinite(port)) return port; /* port number */\n return value; /* named pipe */\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` &rArr; `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel='info'] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &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 * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @return Resolves to an object with created Express and HTTP servers.\n */\nexport async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = typeof ops.port === 'string' ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger!.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger!.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address()!;\n const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger!.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n"],"mappings":"AAAA;AACA,MAAO,gCAAgC,CAEvC,MAAO,KAAI,KAAM,WAAW,CAC5B,MAAO,MAAK,KAAM,YAAY,CAE9B,OAAS,SAAS,CAAE,QAAQ,KAAQ,WAAW,CAE/C;AACA;AACA;AACA,MAAO,iBAAiB,CAAC,OAIhB,gBAAgB,CAAE,gBAAgB,2BAEpC,cAAa,EAGlB,qBAAqB,iDAYvB,OACE,gBAAgB,CAEhB,qBAAqB,EAGvB;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,cAAa,CAAC,KAAsB,CAAE,CAC7C,KAAM,KAAI,CAAG,MAAO,MAAK,GAAK,QAAQ,CAAG,QAAQ,CAAC,KAAK,CAAC,CAAG,KAAK,CAChE,GAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAE,MAAO,KAAI,CAAE,iBACxC,MAAO,MAAK,CAAE,gBAChB,CAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,eAAe,aAAY,CAChC,aAA4B,CAC5B,OAAiB,CAAG,CAAC,CAAC,CAIrB,CACD,4BACA,KAAM,IAAG,CAAG,SAAS,CAAC,OAAO,CAAC,CAE9B;AACA,GAAG,CAAC,IAAI,CAAG,aAAa,CAAC,GAAG,CAAC,IAAI,EAAI,OAAO,CAAC,GAAG,CAAC,IAAI,EAAI,IAAI,CAAC,CAC9D,QAAQ,CAAC,GAAG,CAAE,CAAE,aAAa,CAAE,IAAK,CAAC,CAAC,CAEtC;AACA;AACA,GAAG,CAAC,MAAM,GAAK,gBAAgB,CAAC,CAC9B,eAAe,CAAE,GAAG,CAAC,qBACvB,CAAC,CAAC,CAEF,kDACA,KAAM,cAAa,CAAG,KAAM,cAAa,CAAC,aAAa,CAAE,GAAG,CAAC,CAE7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OAAO,CAAC,CAChC,CAAC,CAAC,CAEF,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAE3B,MAAO,CACL,aAAa,CACb,UACF,CAAC,CACH","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register.js';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport { cloneDeep, defaults } from 'lodash-es';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill.js';\n\nimport type { Configuration } from 'webpack';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nexport * from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport {\n SCRIPT_LOCATIONS,\n type ServerT,\n getDefaultCspSettings,\n};\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String).\n */\nfunction normalizePort(value: number | string) {\n const port = typeof value === 'string' ? parseInt(value) : value;\n if (Number.isFinite(port)) return port; /* port number */\n return value; /* named pipe */\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` &rArr; `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel='info'] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &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 * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @return Resolves to an object with created Express and HTTP servers.\n */\nexport async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = typeof ops.port === 'string'\n ? `Pipe ${ops.port}`\n : `Port ${ops.port ? ops.port.toString() : 'undefined'}`;\n\n if (!ops.logger) throw Error('Missing logger');\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address();\n if (!addr) throw Error('Missing address');\n\n const bind = typeof addr === 'string'\n ? `pipe ${addr}` : `port ${addr.port.toString()}`;\n\n if (!ops.logger) throw Error('Missing logger');\n ops.logger.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV ?? 'undefined'} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n"],"mappings":"AAAA;AACA,MAAO,gCAAgC,CAEvC,MAAO,KAAI,KAAM,WAAW,CAC5B,MAAO,MAAK,KAAM,YAAY,CAE9B,OAAS,SAAS,CAAE,QAAQ,KAAQ,WAAW,CAE/C;AACA;AACA;AACA,MAAO,iBAAiB,CAAC,OAIhB,gBAAgB,CAAE,gBAAgB,2BAEpC,cAAa,EAGlB,qBAAqB,iDAYvB,OACE,gBAAgB,CAEhB,qBAAqB,EAGvB;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,cAAa,CAAC,KAAsB,CAAE,CAC7C,KAAM,KAAI,CAAG,MAAO,MAAK,GAAK,QAAQ,CAAG,QAAQ,CAAC,KAAK,CAAC,CAAG,KAAK,CAChE,GAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAE,MAAO,KAAI,CAAE,iBACxC,MAAO,MAAK,CAAE,gBAChB,CAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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parse from"core-js-pure/features/json/parse.js";import _JSON$stringify from"core-js-pure/features/json/stringify.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 config from"config";import{cloneDeep,defaults,get,mapValues}from"lodash-es";import{prerenderToNodeStream}from"react-dom/static";import{StaticRouter}from"react-router";import serializeJs from"serialize-javascript";import winston from"winston";import{timer}from"@dr.pogodin/js-utils";import{GlobalStateProvider,SsrContext}from"@dr.pogodin/react-global-state";import{HelmetProvider}from"@dr.pogodin/react-helmet";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
@@ -89,16 +89,16 @@ res=null;}return res;}/**
89
89
  */export default function factory(webpackConfig,options){const ops=defaults({...options},{beforeRender:async()=>Promise.resolve({}),maxSsrRounds:10,ssrTimeout:1000,staticCacheSize:1.e7});// Note: in normal use the default logger is created and set in the root
90
90
  // server function, and this initialization is for testing uses, where
91
91
  // renderer is imported directly.
92
- ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});const buildInfo=ops.buildInfo??getBuildInfo(webpackConfig.context);setBuildInfo(buildInfo);// publicPath from webpack.output has a trailing slash at the end.
93
- const{path:outputPath,publicPath}=webpackConfig.output;const manifestLink=fs.existsSync(`${outputPath}/manifest.json`)?`<link rel="manifest" href="${publicPath}manifest.json">`:"";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
94
- const cache=ops.staticCacheController?new Cache(ops.staticCacheSize):null;const CHUNK_GROUPS=readChunkGroupsJson(outputPath);// TODO: Look at it later.
92
+ ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});if(!webpackConfig.context)throw Error("Missing Webpack context");const buildInfo=ops.buildInfo??getBuildInfo(webpackConfig.context);setBuildInfo(buildInfo);if(!webpackConfig.output)throw Error("Missing Webpack output config");// publicPath from webpack.output has a trailing slash at the end.
93
+ const{path:outputPath,publicPath}=webpackConfig.output;if(!outputPath)throw Error("Missing output path");const manifestLink=fs.existsSync(`${outputPath}/manifest.json`)?`<link rel="manifest" href="${publicPath}manifest.json">`:"";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
94
+ if(ops.staticCacheSize===undefined)throw Error("Missing staticCacheSize");const cache=ops.staticCacheController?new Cache(ops.staticCacheSize):null;const CHUNK_GROUPS=readChunkGroupsJson(outputPath);// TODO: Look at it later.
95
95
  // eslint-disable-next-line complexity
96
96
  return async(req,res,next)=>{try{// Ensures any caches always revalidate HTML markup before reuse.
97
- res.set("Cache-Control","no-cache");res.cookie("csrfToken",req.csrfToken());let cacheRef;if(cache){cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){const{buffer,status}=data;if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");if(status!==200)res.status(status);res.send(buffer);}else{await new Promise((done,failed)=>{brotliDecompress(buffer,(error,html)=>{if(error)failed(error);else{let h=html.toString();if(!ops.noCsp){// TODO: Starting from Node v15 we'll be able to use string's
97
+ res.set("Cache-Control","no-cache");res.cookie("csrfToken",req.csrfToken());let cacheRef;if(cache){if(!ops.staticCacheController)throw Error("Missing staticCacheController");cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){const{buffer,status}=data;if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");if(status!==200)res.status(status);res.send(buffer);}else{await new Promise((done,failed)=>{brotliDecompress(buffer,(error,html)=>{if(error)failed(error);else{let h=html.toString();if(!ops.noCsp){// TODO: Starting from Node v15 we'll be able to use string's
98
98
  // .replaceAll() method instead relying on reg. expression for
99
99
  // global matching.
100
100
  const regex=new RegExp(buffer.nonce,"g");// TODO: It should be implemented more careful.
101
- h=h.replace(regex,req.nonce);}if(status!==200)res.status(status);res.send(h);done();}});});}return;}}}const brr=ops.beforeRender(req,publicConfig);const{configToInject,extraScripts,initialState}=await brr;const[cipher,iv]=prepareCipher(buildInfo.key);let helmetState;// Gets the mapping between code chunk names and their asset files.
101
+ h=h.replace(regex,req.nonce);}if(status!==200)res.status(status);res.send(h);done();}});});}return;}}}if(!ops.beforeRender)throw Error("Missing beforeRender");const brr=ops.beforeRender(req,publicConfig);const{configToInject,extraScripts,initialState}=await brr;const[cipher,iv]=prepareCipher(buildInfo.key);let helmetState;// Gets the mapping between code chunk names and their asset files.
102
102
  // These data come from the Webpack compilation, either from the stats
103
103
  // attached to the request (in dev mode), or from a file output during
104
104
  // the build (in prod mode).
@@ -122,10 +122,10 @@ if(!error)resolveArg(arg);};const reject=arg=>{if(error!==undefined&&error!==arg
122
122
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
123
123
  rejectArg(arg);};// TODO: prerenderToNodeStream has (abort) "signal" option,
124
124
  // and we should wire it up to the SSR timeout below.
125
- void prerenderToNodeStream(/*#__PURE__*/_jsx(GlobalStateProvider,{initialState:ssrContext.state,ssrContext:ssrContext,children:/*#__PURE__*/_jsx(StaticRouter,{location:req.url,children:/*#__PURE__*/_jsx(HelmetProvider,{onServerState:state=>{helmetState=state;},children:/*#__PURE__*/_jsx(App2,{})})})}),{onError:reject}).then(result=>{resolve(result.prelude);},reject);});let ssrRound=0;let bailed=false;for(;ssrRound<ops.maxSsrRounds;++ssrRound){stream=await renderPass();if(!ssrContext.dirty)break;const timeout=ops.ssrTimeout+ssrStart-Date.now();bailed=timeout<=0||!(await Promise.race([Promise.allSettled(ssrContext.pending),timer(timeout).then(()=>false)]));if(bailed)break;}let logMsg;if(ssrContext.dirty){// NOTE: In the case of incomplete SSR one more round is necessary
125
+ void prerenderToNodeStream(/*#__PURE__*/_jsx(GlobalStateProvider,{initialState:ssrContext.state,ssrContext:ssrContext,children:/*#__PURE__*/_jsx(StaticRouter,{location:req.url,children:/*#__PURE__*/_jsx(HelmetProvider,{onServerState:state=>{helmetState=state;},children:/*#__PURE__*/_jsx(App2,{})})})}),{onError:reject}).then(result=>{resolve(result.prelude);},reject);});let ssrRound=0;let bailed=false;if(ops.maxSsrRounds===undefined)throw Error("Missing maxSsrRounds");for(;ssrRound<ops.maxSsrRounds;++ssrRound){stream=await renderPass();if(!ssrContext.dirty)break;if(ops.ssrTimeout===undefined)throw Error("Missing SSR timeout");const timeout=ops.ssrTimeout+ssrStart-Date.now();bailed=timeout<=0||!(await Promise.race([Promise.allSettled(ssrContext.pending),timer(timeout).then(()=>false)]));if(bailed)break;}let logMsg;if(ssrContext.dirty){// NOTE: In the case of incomplete SSR one more round is necessary
126
126
  // to ensure the correct hydration when some pending promises have
127
127
  // resolved and placed their data into the initial global state.
128
- stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} second(s)`:`SSR bailed out after ${ops.maxSsrRounds} round(s)`;}else logMsg=`SSR completed in ${ssrRound+1} round(s)`;ops.logger.log(ssrContext.dirty?"warn":"info",logMsg);if(ssrContext.redirectTo){res.redirect(ssrContext.status,ssrContext.redirectTo);return;}await new Promise(ready=>{stream.pipe(new Writable({destroy:ready,write:(chunk,_,done)=>{appHtmlMarkup+=chunk.toString();done();}}));});}/* Encrypts data to be injected into HTML.
128
+ stream=await renderPass();if(ops.ssrTimeout===undefined)throw Error("Missing SSR timeout");logMsg=bailed?`SSR timed out after ${ops.ssrTimeout.toString()} second(s)`:`SSR bailed out after ${ops.maxSsrRounds.toString()} round(s)`;}else logMsg=`SSR completed in ${(ssrRound+1).toString()} round(s)`;if(!ops.logger)throw Error("Missing logger");ops.logger.log(ssrContext.dirty?"warn":"info",logMsg);if(ssrContext.redirectTo){res.redirect(ssrContext.status,ssrContext.redirectTo);return;}await new Promise(ready=>{stream.pipe(new Writable({destroy:ready,write:(chunk,_,done)=>{appHtmlMarkup+=chunk.toString();done();}}));});}/* Encrypts data to be injected into HTML.
129
129
  * Keep in mind, that this encryption is no way secure: as the JS bundle
130
130
  * contains decryption key and is able to decode it at the client side.
131
131
  * Hovewer, for a number of reasons, encryption of injected data is still
@@ -168,7 +168,7 @@ stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} s
168
168
  </body>
169
169
  </html>`;const status=ssrContext.status||200;if(status!==200)res.status(status);if(cacheRef&&status<500){// Note: waiting for the caching to complete is not strictly necessary,
170
170
  // but it greately simplifies testing, and error reporting.
171
- await new Promise((done,failed)=>{brotliCompress(html,(error,buffer)=>{if(error)failed(error);else{const b=buffer;b.nonce=req.nonce;cache.add({buffer:b,status},cacheRef.key,buffer.length);done();}});});}// Note: as caching code above may throw in some cases, sending response
171
+ await new Promise((done,failed)=>{brotliCompress(html,(error,buffer)=>{if(error)failed(error);else{const b=buffer;b.nonce=req.nonce;if(cache===null)throw Error("Missing cache");cache.add({buffer:b,status},cacheRef.key,buffer.length);done();}});});}// Note: as caching code above may throw in some cases, sending response
172
172
  // before it completes will likely hide the error, making it difficult
173
173
  // to debug. Thus, at least for now, lets send response after it.
174
174
  res.send(html);}catch(error){next(error);}};}