@dr.pogodin/react-utils 1.49.1 → 1.50.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 (210) hide show
  1. package/babel.scripts.config.js +19 -0
  2. package/build/development/client/getInj.js +18 -29
  3. package/build/development/client/getInj.js.map +1 -1
  4. package/build/development/client/index.js +11 -14
  5. package/build/development/client/index.js.map +1 -1
  6. package/build/development/client/init.js +9 -17
  7. package/build/development/client/init.js.map +1 -1
  8. package/build/development/index.js +26 -4
  9. package/build/development/index.js.map +1 -1
  10. package/build/development/server/Cache.js +15 -20
  11. package/build/development/server/Cache.js.map +1 -1
  12. package/build/development/server/index.js +142 -160
  13. package/build/development/server/index.js.map +1 -1
  14. package/build/development/server/renderer.js +150 -197
  15. package/build/development/server/renderer.js.map +1 -1
  16. package/build/development/server/server.js +63 -86
  17. package/build/development/server/server.js.map +1 -1
  18. package/build/development/server/utils/errors.js +72 -87
  19. package/build/development/server/utils/errors.js.map +1 -1
  20. package/build/development/shared/components/Button/index.js +8 -17
  21. package/build/development/shared/components/Button/index.js.map +1 -1
  22. package/build/development/shared/components/Checkbox/index.js +4 -4
  23. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  24. package/build/development/shared/components/GenericLink/index.js +54 -58
  25. package/build/development/shared/components/GenericLink/index.js.map +1 -1
  26. package/build/development/shared/components/Input/index.js +16 -24
  27. package/build/development/shared/components/Input/index.js.map +1 -1
  28. package/build/development/shared/components/Link.js +2 -5
  29. package/build/development/shared/components/Link.js.map +1 -1
  30. package/build/development/shared/components/Modal/index.js +28 -41
  31. package/build/development/shared/components/Modal/index.js.map +1 -1
  32. package/build/development/shared/components/NavLink.js +2 -3
  33. package/build/development/shared/components/NavLink.js.map +1 -1
  34. package/build/development/shared/components/PageLayout/index.js +19 -20
  35. package/build/development/shared/components/PageLayout/index.js.map +1 -1
  36. package/build/development/shared/components/TextArea/index.js +12 -28
  37. package/build/development/shared/components/TextArea/index.js.map +1 -1
  38. package/build/development/shared/components/Throbber/index.js +11 -12
  39. package/build/development/shared/components/Throbber/index.js.map +1 -1
  40. package/build/development/shared/components/WithTooltip/Tooltip.js +46 -68
  41. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  42. package/build/development/shared/components/WithTooltip/index.js +21 -28
  43. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  44. package/build/development/shared/components/YouTubeVideo/index.js +21 -25
  45. package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
  46. package/build/development/shared/components/index.js +1 -3
  47. package/build/development/shared/components/index.js.map +1 -1
  48. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +6 -7
  49. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  50. package/build/development/shared/components/selectors/CustomDropdown/index.js +7 -9
  51. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  52. package/build/development/shared/components/selectors/NativeDropdown/index.js +23 -27
  53. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  54. package/build/development/shared/components/selectors/Switch/index.js +4 -4
  55. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  56. package/build/development/shared/components/selectors/common.js +2 -5
  57. package/build/development/shared/components/selectors/common.js.map +1 -1
  58. package/build/development/shared/utils/config.js +11 -15
  59. package/build/development/shared/utils/config.js.map +1 -1
  60. package/build/development/shared/utils/globalState.js +1 -7
  61. package/build/development/shared/utils/globalState.js.map +1 -1
  62. package/build/development/shared/utils/index.js +2 -2
  63. package/build/development/shared/utils/index.js.map +1 -1
  64. package/build/development/shared/utils/isomorphy/buildInfo.js +15 -24
  65. package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
  66. package/build/development/shared/utils/isomorphy/environment-check.js +4 -9
  67. package/build/development/shared/utils/isomorphy/environment-check.js.map +1 -1
  68. package/build/development/shared/utils/isomorphy/index.js +17 -23
  69. package/build/development/shared/utils/isomorphy/index.js.map +1 -1
  70. package/build/development/shared/utils/jest/E2eSsrEnv.js +48 -77
  71. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  72. package/build/development/shared/utils/jest/index.js +48 -72
  73. package/build/development/shared/utils/jest/index.js.map +1 -1
  74. package/build/development/shared/utils/splitComponent.js +67 -74
  75. package/build/development/shared/utils/splitComponent.js.map +1 -1
  76. package/build/development/shared/utils/time.js +25 -28
  77. package/build/development/shared/utils/time.js.map +1 -1
  78. package/build/development/shared/utils/webpack.js +22 -29
  79. package/build/development/shared/utils/webpack.js.map +1 -1
  80. package/build/production/client/getInj.js.map +1 -1
  81. package/build/production/client/index.js.map +1 -1
  82. package/build/production/index.js +26 -1
  83. package/build/production/index.js.map +1 -1
  84. package/build/production/server/Cache.js.map +1 -1
  85. package/build/production/server/index.js.map +1 -1
  86. package/build/production/server/renderer.js.map +1 -1
  87. package/build/production/server/server.js.map +1 -1
  88. package/build/production/shared/components/Button/index.js.map +1 -1
  89. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  90. package/build/production/shared/components/GenericLink/index.js +2 -2
  91. package/build/production/shared/components/GenericLink/index.js.map +1 -1
  92. package/build/production/shared/components/Input/index.js.map +1 -1
  93. package/build/production/shared/components/Link.js.map +1 -1
  94. package/build/production/shared/components/Modal/index.js.map +1 -1
  95. package/build/production/shared/components/NavLink.js.map +1 -1
  96. package/build/production/shared/components/PageLayout/index.js.map +1 -1
  97. package/build/production/shared/components/TextArea/index.js.map +1 -1
  98. package/build/production/shared/components/Throbber/index.js.map +1 -1
  99. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  100. package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
  101. package/build/production/shared/components/index.js.map +1 -1
  102. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  103. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  104. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  105. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  106. package/build/production/shared/utils/config.js.map +1 -1
  107. package/build/production/shared/utils/index.js.map +1 -1
  108. package/build/production/shared/utils/jest/index.js.map +1 -1
  109. package/build/production/shared/utils/splitComponent.js +20 -3
  110. package/build/production/shared/utils/splitComponent.js.map +1 -1
  111. package/build/production/shared/utils/time.js.map +1 -1
  112. package/build/production/shared/utils/webpack.js.map +1 -1
  113. package/build/types-code/shared/components/GenericLink/index.d.ts +0 -1
  114. package/build/web/client/getInj.js +10 -70
  115. package/build/web/client/getInj.js.map +1 -1
  116. package/build/web/client/index.js +2 -27
  117. package/build/web/client/index.js.map +1 -1
  118. package/build/web/client/init.js +10 -44
  119. package/build/web/client/init.js.map +1 -1
  120. package/build/web/index.js +26 -6
  121. package/build/web/index.js.map +1 -1
  122. package/build/web/server/Cache.js +3 -41
  123. package/build/web/server/Cache.js.map +1 -1
  124. package/build/web/server/index.js +7 -78
  125. package/build/web/server/index.js.map +1 -1
  126. package/build/web/server/renderer.js +61 -420
  127. package/build/web/server/renderer.js.map +1 -1
  128. package/build/web/server/server.js +38 -212
  129. package/build/web/server/server.js.map +1 -1
  130. package/build/web/server/utils/errors.js +9 -48
  131. package/build/web/server/utils/errors.js.map +1 -1
  132. package/build/web/server/utils/index.js +1 -2
  133. package/build/web/server/utils/index.js.map +1 -1
  134. package/build/web/shared/components/Button/index.js +12 -101
  135. package/build/web/shared/components/Button/index.js.map +1 -1
  136. package/build/web/shared/components/Checkbox/index.js +1 -40
  137. package/build/web/shared/components/Checkbox/index.js.map +1 -1
  138. package/build/web/shared/components/Checkbox/theme.scss +1 -0
  139. package/build/web/shared/components/GenericLink/index.js +12 -65
  140. package/build/web/shared/components/GenericLink/index.js.map +1 -1
  141. package/build/web/shared/components/GenericLink/style.scss +1 -0
  142. package/build/web/shared/components/Input/index.js +11 -69
  143. package/build/web/shared/components/Input/index.js.map +1 -1
  144. package/build/web/shared/components/Link.js +2 -12
  145. package/build/web/shared/components/Link.js.map +1 -1
  146. package/build/web/shared/components/Modal/index.js +10 -130
  147. package/build/web/shared/components/Modal/index.js.map +1 -1
  148. package/build/web/shared/components/NavLink.js +2 -10
  149. package/build/web/shared/components/NavLink.js.map +1 -1
  150. package/build/web/shared/components/PageLayout/index.js +2 -27
  151. package/build/web/shared/components/PageLayout/index.js.map +1 -1
  152. package/build/web/shared/components/TextArea/index.js +21 -106
  153. package/build/web/shared/components/TextArea/index.js.map +1 -1
  154. package/build/web/shared/components/Throbber/index.js +2 -24
  155. package/build/web/shared/components/Throbber/index.js.map +1 -1
  156. package/build/web/shared/components/WithTooltip/Tooltip.js +16 -145
  157. package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -1
  158. package/build/web/shared/components/WithTooltip/index.js +12 -104
  159. package/build/web/shared/components/WithTooltip/index.js.map +1 -1
  160. package/build/web/shared/components/YouTubeVideo/index.js +5 -43
  161. package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
  162. package/build/web/shared/components/index.js +1 -15
  163. package/build/web/shared/components/index.js.map +1 -1
  164. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +6 -81
  165. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  166. package/build/web/shared/components/selectors/CustomDropdown/index.js +7 -122
  167. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  168. package/build/web/shared/components/selectors/NativeDropdown/index.js +7 -68
  169. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  170. package/build/web/shared/components/selectors/Switch/index.js +1 -49
  171. package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
  172. package/build/web/shared/components/selectors/common.js +1 -10
  173. package/build/web/shared/components/selectors/common.js.map +1 -1
  174. package/build/web/shared/components/selectors/index.js +1 -3
  175. package/build/web/shared/components/selectors/index.js.map +1 -1
  176. package/build/web/shared/utils/config.js +6 -40
  177. package/build/web/shared/utils/config.js.map +1 -1
  178. package/build/web/shared/utils/globalState.js +2 -11
  179. package/build/web/shared/utils/globalState.js.map +1 -1
  180. package/build/web/shared/utils/index.js +1 -9
  181. package/build/web/shared/utils/index.js.map +1 -1
  182. package/build/web/shared/utils/isomorphy/buildInfo.js +4 -25
  183. package/build/web/shared/utils/isomorphy/buildInfo.js.map +1 -1
  184. package/build/web/shared/utils/isomorphy/environment-check.js +3 -9
  185. package/build/web/shared/utils/isomorphy/environment-check.js.map +1 -1
  186. package/build/web/shared/utils/isomorphy/index.js +5 -27
  187. package/build/web/shared/utils/isomorphy/index.js.map +1 -1
  188. package/build/web/shared/utils/jest/E2eSsrEnv.js +51 -221
  189. package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  190. package/build/web/shared/utils/jest/global.js +1 -3
  191. package/build/web/shared/utils/jest/global.js.map +1 -1
  192. package/build/web/shared/utils/jest/index.js +27 -146
  193. package/build/web/shared/utils/jest/index.js.map +1 -1
  194. package/build/web/shared/utils/splitComponent.js +34 -197
  195. package/build/web/shared/utils/splitComponent.js.map +1 -1
  196. package/build/web/shared/utils/time.js +5 -69
  197. package/build/web/shared/utils/time.js.map +1 -1
  198. package/build/web/shared/utils/webpack.js +6 -53
  199. package/build/web/shared/utils/webpack.js.map +1 -1
  200. package/config/babel/webpack.js +1 -1
  201. package/eslint.config.mjs +1 -0
  202. package/package.json +5 -8
  203. package/bin/build.js +0 -236
  204. package/config/webpack/lib-base.d.ts +0 -22
  205. package/config/webpack/lib-base.js +0 -167
  206. package/config/webpack/lib-development.d.ts +0 -5
  207. package/config/webpack/lib-development.js +0 -35
  208. package/config/webpack/lib-production.d.ts +0 -5
  209. package/config/webpack/lib-production.js +0 -42
  210. package/webpack.config.ts +0 -49
@@ -1 +1 @@
1
- {"version":3,"file":"E2eSsrEnv.js","names":["path","JsdomEnv","defaults","set","Volume","createFsFromVolume","webpack","register","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","ssrFactory","renderer","status","markup","ssrRequest","cookie","send","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","dirname","testPath","withSsr","root","process","cwd","envName","babelEnv","extensions","setup","require","cache","setBuildInfo","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\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 path from 'node:path';\n\nimport type { Request, Response } from 'express';\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport type { ReactNode } from 'react';\nimport webpack, { type Configuration } from 'webpack';\n\nimport register from '@babel/register/experimental-worker';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nfunction noop() {\n // NOOP\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private 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 const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n const module = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n p\n ) as NodeJS.Module;\n\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const { default: ssrFactory } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */ 'server/renderer');\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\n\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 register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n\n const { setBuildInfo } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */'../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 // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n await super.teardown();\n }\n}\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA,OAAOA,IAAI,MAAM,WAAW;AAG5B,OAAOC,QAAQ,MAAM,wBAAwB;AAC7C,SAASC,QAAQ,EAAEC,GAAG,QAAQ,WAAW;AACzC,SAASC,MAAM,EAAEC,kBAAkB,QAAQ,OAAO;AAElD,OAAOC,OAAO,MAA8B,SAAS;AAErD,OAAOC,QAAQ,MAAM,qCAAqC;AAO1D,SAASC,IAAIA,CAAA,EAAG;EACd;AAAA;AAGF,eAAe,MAAMC,SAAS,SAASR,QAAQ,CAAC;EAa9C;AACF;AACA;AACA;EACE,MAAcS,iBAAiBA,CAAA,EAAG;IAChC,MAAMC,aAAa,GAAG,IAAI,CAACC,OAAO,CAAC,wBAAwB,CAAW;IAEtE,MAAMC,OAAO,GAAIF,aAAa,GAAGG,IAAI,CAACC,KAAK,CAACJ,aAAa,CAAC,GAAG,CAAC,CACvC;IAEvBT,QAAQ,CAACW,OAAO,EAAE;MAChBG,OAAO,EAAE,IAAI,CAACC,UAAU;MACxBC,EAAE,EAAE,IAAI,CAACC,MAAM,CAACC;IAClB,CAAC,CAAC;IAEF,MAAMC,WAAW,GAAG,IAAI,CAACT,OAAO,CAAC,wBAAwB,CAAW;IAEpE,IAAIU,OAAO,GAAG,MAAM,MAAM,CAAC;IACzBtB,IAAI,CAACuB,OAAO,CAAC,IAAI,CAACC,OAAO,EAAEH,WAAW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AC,CAAC;;IAEvB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA6D,OAAO,CAACC,KAAK,GAAG,CAAC,CAAC;IAElB,MAAM;MAAEC;IAAa,CAAC,GAAG,MAAM,MAAM,CAAC,mEAAmE,CAAC;IAC1GA,YAAY,CAACC,SAAS,EAAE,IAAI,CAAC;IAE7B,IAAI,IAAI,CAACX,OAAO,EAAE,MAAM,IAAI,CAACrC,MAAM,CAAC,CAAC;IACrC,IAAI,CAAC3B,MAAM,CAAC4E,6BAA6B,GAAG,IAAI;EAClD;EAEA,MAAMC,QAAQA,CAAA,EAAkB;IAC9B,OAAO,IAAI,CAAC7E,MAAM,CAAC4E,6BAA6B;;IAEhD;IACA;IACA;IACA;IACA;IACA;IACAE,MAAM,CAACC,IAAI,CAACP,OAAO,CAACC,KAAK,CAAC,CAACO,OAAO,CAAEC,GAAG,IAAK;MAC1C,OAAOT,OAAO,CAACC,KAAK,CAACQ,GAAG,CAAC;IAC3B,CAAC,CAAC;IACF7F,QAAQ,CAAC8F,MAAM,CAAC,CAAC;IACjB,MAAM,KAAK,CAACL,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
1
+ {"version":3,"file":"E2eSsrEnv.js","names":["path","JsdomEnv","defaults","set","Volume","createFsFromVolume","webpack","register","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","ssrFactory","renderer","status","markup","ssrRequest","cookie","send","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","dirname","testPath","withSsr","root","process","cwd","envName","babelEnv","extensions","setup","require","cache","setBuildInfo","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\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 path from 'node:path';\n\nimport type { Request, Response } from 'express';\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport type { ReactNode } from 'react';\nimport webpack, { type Configuration } from 'webpack';\n\nimport register from '@babel/register/experimental-worker';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nfunction noop() {\n // NOOP\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private 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 const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n const module = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n p\n ) as NodeJS.Module;\n\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const { default: ssrFactory } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */ 'server/renderer');\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\n\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 register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n\n const { setBuildInfo } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */'../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 // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA6D,OAAO,CAACC,KAAK,CAAG,CAAC,CAAC,CAElB,KAAM,CAAEC,YAAa,CAAC,CAAG,KAAM,OAAM,CAAC,mEAAmE,CAAC,CAC1GA,YAAY,CAACC,SAAS,CAAE,IAAI,CAAC,CAE7B,GAAI,IAAI,CAACX,OAAO,CAAE,KAAM,KAAI,CAACrC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC3B,MAAM,CAAC4E,6BAA6B,CAAG,IAAI,CAClD,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAkB,CAC9B,MAAO,KAAI,CAAC7E,MAAM,CAAC4E,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAACP,OAAO,CAACC,KAAK,CAAC,CAACO,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,CAAAT,OAAO,CAACC,KAAK,CAACQ,GAAG,CAAC,CAC3B,CAAC,CAAC,CACF7F,QAAQ,CAAC8F,MAAM,CAAC,CAAC,CACjB,KAAM,MAAK,CAACL,QAAQ,CAAC,CAAC,CACxB,CACF","ignoreList":[]}
@@ -1,4 +1,2 @@
1
- export default function getGlobal() {
2
- return global;
3
- }
1
+ export default function getGlobal(){return global;}
4
2
  //# sourceMappingURL=global.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"global.js","names":["getGlobal","global"],"sources":["../../../../../src/shared/utils/jest/global.ts"],"sourcesContent":["import type { IFs } from 'memfs';\nimport type { Configuration, StatsCompilation } from 'webpack';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n ssrMarkup: string | undefined;\n ssrStatus: number | undefined;\n webpackConfig: Configuration | undefined;\n webpackOutputFs: IFs;\n webpackStats?: StatsCompilation;\n }\n}\n\nexport default function getGlobal(): Window {\n return global as unknown as Window;\n}\n"],"mappings":"AAcA,eAAe,SAASA,SAASA,CAAA,EAAW;EAC1C,OAAOC,MAAM;AACf","ignoreList":[]}
1
+ {"version":3,"file":"global.js","names":["getGlobal","global"],"sources":["../../../../../src/shared/utils/jest/global.ts"],"sourcesContent":["import type { IFs } from 'memfs';\nimport type { Configuration, StatsCompilation } from 'webpack';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n ssrMarkup: string | undefined;\n ssrStatus: number | undefined;\n webpackConfig: Configuration | undefined;\n webpackOutputFs: IFs;\n webpackStats?: StatsCompilation;\n }\n}\n\nexport default function getGlobal(): Window {\n return global as unknown as Window;\n}\n"],"mappings":"AAcA,cAAe,SAAS,CAAAA,SAASA,CAAA,CAAW,CAC1C,MAAO,CAAAC,MAAM,CACf","ignoreList":[]}
@@ -1,166 +1,47 @@
1
- import "core-js/modules/es.json.stringify.js";
2
- /* global jest, document */
3
- /* eslint-disable import/no-extraneous-dependencies */
4
-
5
- import mockdate from 'mockdate';
6
- import { act } from 'react';
7
- import { createRoot } from 'react-dom/client';
8
- import { render } from '@testing-library/react';
9
-
10
- /**
1
+ import"core-js/modules/es.json.stringify.js";/* global jest, document *//* eslint-disable import/no-extraneous-dependencies */import mockdate from"mockdate";import{act}from"react";import{createRoot}from"react-dom/client";import{render}from"@testing-library/react";/**
11
2
  * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)
12
3
  * from `react`.
13
- */
14
- export { act };
15
- export { default as getGlobal } from "./global";
16
- global.IS_REACT_ACT_ENVIRONMENT = true;
17
- const originalProcessVersions = process.versions;
18
-
19
- /**
4
+ */export{act};export{default as getGlobal}from"./global";global.IS_REACT_ACT_ENVIRONMENT=true;const originalProcessVersions=process.versions;/**
20
5
  * Tricks **react-utils** into thinking the test is running within client-side
21
6
  * (browser) environment.
22
- */
23
- export function mockClientSide() {
24
- Object.defineProperty(process, 'versions', {
25
- value: undefined
26
- });
27
- }
28
-
29
- /**
7
+ */export function mockClientSide(){Object.defineProperty(process,"versions",{value:undefined});}/**
30
8
  * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.
31
- */
32
- export function unmockClientSide() {
33
- Object.defineProperty(process, 'versions', {
34
- value: originalProcessVersions,
35
- writable: false
36
- });
37
- }
38
-
39
- /**
9
+ */export function unmockClientSide(){Object.defineProperty(process,"versions",{value:originalProcessVersions,writable:false});}/**
40
10
  * Generates a mock UUID, or better said it determenistically transforms given
41
11
  * `seed` number into a UUID-formatted string.
42
12
  * @param {number} seed
43
13
  * @return {string}
44
- */
45
- export function getMockUuid(seed = 0) {
46
- const x = seed.toString(16).padStart(32, '0');
47
- return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;
48
- }
49
- export function mockAxios(handlers) {
50
- const axios = jest.requireActual('axios');
51
- axios.defaults.adapter = async config => {
52
- for (const handler of handlers) {
53
- const res = handler(config);
54
- if (res) {
55
- return {
56
- config: config,
57
- data: null,
58
- headers: {},
59
- status: 200,
60
- statusText: 'OK',
61
- ...res
62
- };
63
- }
64
- }
65
-
66
- // Fallback to the regular network request.
67
- let res;
68
- try {
69
- res = await axios({
70
- ...config,
71
- adapter: ['xhr', 'http', 'fetch']
72
- });
73
- // eslint-disable-next-line no-console
74
- console.warn('Network request has not been mocked for a test.\n\nConfig:\n', config, '\n\nResult:\n', JSON.stringify(res, null, 2));
75
- } catch (e) {
76
- // eslint-disable-next-line no-console
77
- console.warn('Network request has not been mocked for a test, and failed.\n\nConfig:\n', config, '\n\nError\n', JSON.stringify(e, null, 2));
78
- throw e;
79
- }
80
- return res;
81
- };
82
- return axios;
83
- }
84
-
85
- /**
14
+ */export function getMockUuid(seed=0){const x=seed.toString(16).padStart(32,"0");return`${x.slice(0,8)}-${x.slice(8,12)}-${x.slice(12,16)}-${x.slice(16,20)}-${x.slice(20)}`;}export function mockAxios(handlers){const axios=jest.requireActual("axios");axios.defaults.adapter=async config=>{for(const handler of handlers){const res=handler(config);if(res){return{config:config,data:null,headers:{},status:200,statusText:"OK",...res};}}// Fallback to the regular network request.
15
+ let res;try{res=await axios({...config,adapter:["xhr","http","fetch"]});// eslint-disable-next-line no-console
16
+ console.warn("Network request has not been mocked for a test.\n\nConfig:\n",config,"\n\nResult:\n",JSON.stringify(res,null,2));}catch(e){// eslint-disable-next-line no-console
17
+ console.warn("Network request has not been mocked for a test, and failed.\n\nConfig:\n",config,"\n\nError\n",JSON.stringify(e,null,2));throw e;}return res;};return axios;}/**
86
18
  * Advances mock timers, and mock date by the specified time.
87
19
  * @param {number} time Time step [ms].
88
20
  * @returns {Promise} Wait for this to "jump after" any async code which should
89
21
  * be executed because of the mock time movement.
90
- */
91
- export async function mockTimer(time) {
92
- mockdate.set(time + Date.now());
93
- await jest.advanceTimersByTimeAsync(time);
94
- }
95
- /**
22
+ */export async function mockTimer(time){mockdate.set(time+Date.now());await jest.advanceTimersByTimeAsync(time);}/**
96
23
  * Mounts `scene` to the DOM, and returns the root scene element.
97
24
  * @param scene
98
25
  * @return Created container DOM element with destroy() function
99
26
  * attached.
100
- */
101
- export function mount(scene) {
102
- let root;
103
- const element = document.createElement('div');
104
- document.body.appendChild(element);
105
- const res = element;
106
- res.destroy = () => {
107
- // NOTE: As it seems @testing-library may reset this flag to false
108
- // when it is simulating user events.
109
- global.IS_REACT_ACT_ENVIRONMENT = true;
110
- act(() => {
111
- root.unmount();
112
- });
113
- res.remove();
114
- };
115
- res.snapshot = () => {
116
- expect(res).toMatchSnapshot();
117
- };
118
-
119
- // NOTE: As it seems @testing-library may reset this flag to false
120
- // when it is simulating user events.
121
- global.IS_REACT_ACT_ENVIRONMENT = true;
122
- act(() => {
123
- root = createRoot(res);
124
- root.render(scene);
125
- });
126
- return res;
127
- }
128
-
129
- // NOTE: If in future we have additional options here, they should be distributed
27
+ */export function mount(scene){let root;const element=document.createElement("div");document.body.appendChild(element);const res=element;res.destroy=()=>{// NOTE: As it seems @testing-library may reset this flag to false
28
+ // when it is simulating user events.
29
+ global.IS_REACT_ACT_ENVIRONMENT=true;act(()=>{root.unmount();});res.remove();};res.snapshot=()=>{expect(res).toMatchSnapshot();};// NOTE: As it seems @testing-library may reset this flag to false
30
+ // when it is simulating user events.
31
+ global.IS_REACT_ACT_ENVIRONMENT=true;act(()=>{root=createRoot(res);root.render(scene);});return res;}// NOTE: If in future we have additional options here, they should be distributed
130
32
  // across two objects, depending whether they are applicable to the sync, or async
131
33
  // versions of snapshot(), or both.
132
-
133
- export function snapshot(element, options) {
134
- let res;
135
-
136
- // TODO: Just adding async to the actor function breaks stuff, as it makes
137
- // act() asynchronous no matter the `options.await` value, thus breaking all
138
- // calls that do not await for snapshot() result... thus... perhaps we need
139
- // to have a more complex typing to ensure it all works as intended in all
140
- // cases, and while being correctly enforced by TypeScript.
141
- // eslint-disable-next-line @typescript-eslint/promise-function-async
142
- const promise = act(() => {
143
- res = render(element);
144
- return options?.await;
145
- });
146
- if (res === undefined) throw Error('Render failed');
147
- if (options?.await) {
148
- // BEWARE: Although `promise` is thenable (i.e. it has .then() method),
149
- // it is not an instance of proper Promise class, and returning it directly
150
- // breaks some async logic in Jest test or React test functions... thus, we
151
- // wrap it into Promise instance here.
152
- return new Promise(resolve => {
153
- void promise.then(() => {
154
- // TODO: These lines are the same as the lines below for sync variant of
155
- // the function. We should split and reuse them in both places.
156
- const nodes = res.asFragment().childNodes;
157
- expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();
158
- resolve(res);
159
- });
160
- });
161
- }
162
- const nodes = res.asFragment().childNodes;
163
- expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();
164
- return res;
165
- }
34
+ export function snapshot(element,options){let res;// TODO: Just adding async to the actor function breaks stuff, as it makes
35
+ // act() asynchronous no matter the `options.await` value, thus breaking all
36
+ // calls that do not await for snapshot() result... thus... perhaps we need
37
+ // to have a more complex typing to ensure it all works as intended in all
38
+ // cases, and while being correctly enforced by TypeScript.
39
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
40
+ const promise=act(()=>{res=render(element);return options?.await;});if(res===undefined)throw Error("Render failed");if(options?.await){// BEWARE: Although `promise` is thenable (i.e. it has .then() method),
41
+ // it is not an instance of proper Promise class, and returning it directly
42
+ // breaks some async logic in Jest test or React test functions... thus, we
43
+ // wrap it into Promise instance here.
44
+ return new Promise(resolve=>{void promise.then(()=>{// TODO: These lines are the same as the lines below for sync variant of
45
+ // the function. We should split and reuse them in both places.
46
+ const nodes=res.asFragment().childNodes;expect(nodes.length>1?[...nodes]:nodes[0]).toMatchSnapshot();resolve(res);});});}const nodes=res.asFragment().childNodes;expect(nodes.length>1?[...nodes]:nodes[0]).toMatchSnapshot();return res;}
166
47
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["mockdate","act","createRoot","render","default","getGlobal","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","jest","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","unmount","remove","snapshot","expect","toMatchSnapshot","options","promise","await","Error","Promise","resolve","then","nodes","asFragment","childNodes","length"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global jest, 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 { 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 {\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: React.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) => {\n void promise.then(() => {\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 });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":";AAAA;AACA;;AASA,OAAOA,QAAQ,MAAM,UAAU;AAC/B,SAA4CC,GAAG,QAAQ,OAAO;AAC9D,SAAoBC,UAAU,QAAQ,kBAAkB;AAExD,SAA4BC,MAAM,QAAQ,wBAAwB;;AAElE;AACA;AACA;AACA;AACA,SAASF,GAAG;AAEZ,SAASG,OAAO,IAAIC,SAAS;AAE7BC,MAAM,CAACC,wBAAwB,GAAG,IAAI;AAEtC,MAAMC,uBAAuB,GAAGC,OAAO,CAACC,QAAQ;;AAEhD;AACA;AACA;AACA;AACA,OAAO,SAASC,cAAcA,CAAA,EAAS;EACrCC,MAAM,CAACC,cAAc,CAACJ,OAAO,EAAE,UAAU,EAAE;IAAEK,KAAK,EAAEC;EAAU,CAAC,CAAC;AAClE;;AAEA;AACA;AACA;AACA,OAAO,SAASC,gBAAgBA,CAAA,EAAS;EACvCJ,MAAM,CAACC,cAAc,CAACJ,OAAO,EAAE,UAAU,EAAE;IACzCK,KAAK,EAAEN,uBAAuB;IAC9BS,QAAQ,EAAE;EACZ,CAAC,CAAC;AACJ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,WAAWA,CAACC,IAAI,GAAG,CAAC,EAAU;EAC5C,MAAMC,CAAC,GAAGD,IAAI,CAACE,QAAQ,CAAC,EAAE,CAAC,CAACC,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC;EAC7C,OAAO,GAAGF,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A;EACA;EACA;EACA,MAAM+B,OAAO,GAAG/D,GAAG,CAAC,MAAM;IACxBgC,GAAG,GAAG9B,MAAM,CAACiD,OAAO,CAAC;IACrB,OAAOW,OAAO,EAAEE,KAAK;EACvB,CAAC,CAAC;EAEF,IAAIhC,GAAG,KAAKlB,SAAS,EAAE,MAAMmD,KAAK,CAAC,eAAe,CAAC;EACnD,IAAIH,OAAO,EAAEE,KAAK,EAAE;IAClB;IACA;IACA;IACA;IACA,OAAO,IAAIE,OAAO,CAAEC,OAAO,IAAK;MAC9B,KAAKJ,OAAO,CAACK,IAAI,CAAC,MAAM;QACtB;QACA;QACA,MAAMC,KAAK,GAAGrC,GAAG,CAAEsC,UAAU,CAAC,CAAC,CAACC,UAAU;QAC1CX,MAAM,CAACS,KAAK,CAACG,MAAM,GAAG,CAAC,GAAG,CAAC,GAAGH,KAAK,CAAC,GAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC;QAClEM,OAAO,CAACnC,GAAI,CAAC;MACf,CAAC,CAAC;IACJ,CAAC,CAAC;EACJ;EAEA,MAAMqC,KAAK,GAAGrC,GAAG,CAACsC,UAAU,CAAC,CAAC,CAACC,UAAU;EACzCX,MAAM,CAACS,KAAK,CAACG,MAAM,GAAG,CAAC,GAAG,CAAC,GAAGH,KAAK,CAAC,GAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC;EAClE,OAAO7B,GAAG;AACZ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["mockdate","act","createRoot","render","default","getGlobal","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","jest","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","unmount","remove","snapshot","expect","toMatchSnapshot","options","promise","await","Error","Promise","resolve","then","nodes","asFragment","childNodes","length"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global jest, 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 { 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 {\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: React.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) => {\n void promise.then(() => {\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 });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"6CAAA,2BACA,sDASA,MAAO,CAAAA,QAAQ,KAAM,UAAU,CAC/B,OAA4CC,GAAG,KAAQ,OAAO,CAC9D,OAAoBC,UAAU,KAAQ,kBAAkB,CAExD,OAA4BC,MAAM,KAAQ,wBAAwB,CAElE;AACA;AACA;AACA,GACA,OAASF,GAAG,EAEZ,OAASG,OAAO,GAAI,CAAAC,SAAS,gBAE7BC,MAAM,CAACC,wBAAwB,CAAG,IAAI,CAEtC,KAAM,CAAAC,uBAAuB,CAAGC,OAAO,CAACC,QAAQ,CAEhD;AACA;AACA;AACA,GACA,MAAO,SAA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AC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC,CAClEM,OAAO,CAACnC,GAAI,CAAC,CACf,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA,KAAM,CAAAqC,KAAK,CAAGrC,GAAG,CAACsC,UAAU,CAAC,CAAC,CAACC,UAAU,CACzCX,MAAM,CAACS,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC,CAClE,MAAO,CAAA7B,GAAG,CACZ","ignoreList":[]}
@@ -1,35 +1,4 @@
1
- import "core-js/modules/es.array.push.js";
2
- import "core-js/modules/es.iterator.constructor.js";
3
- import "core-js/modules/es.set.difference.v2.js";
4
- import "core-js/modules/es.set.intersection.v2.js";
5
- import "core-js/modules/es.set.is-disjoint-from.v2.js";
6
- import "core-js/modules/es.set.is-subset-of.v2.js";
7
- import "core-js/modules/es.set.is-superset-of.v2.js";
8
- import "core-js/modules/es.set.symmetric-difference.v2.js";
9
- import "core-js/modules/es.set.union.v2.js";
10
- /* global document */
11
-
12
- import { Suspense, lazy, useInsertionEffect } from 'react';
13
- import { Barrier } from '@dr.pogodin/js-utils';
14
- import { getSsrContext } from "./globalState";
15
- import { IS_CLIENT_SIDE, IS_SERVER_SIDE, getBuildInfo } from "./isomorphy";
16
- import { jsx as _jsx } from "react/jsx-runtime";
17
- function getClientChunkGroups() {
18
- if (!IS_CLIENT_SIDE) return undefined;
19
- return (async () => {
20
- const {
21
- default: getInj
22
- } = await import(/* webpackChunkName: "react-utils-client-side-code" */"../../client/getInj");
23
- const inj = await getInj();
24
- return inj.CHUNK_GROUPS ?? {};
25
- })();
26
- }
27
- const refCounts = {};
28
- function getPublicPath() {
29
- return getBuildInfo().publicPath;
30
- }
31
-
32
- /**
1
+ import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.set.difference.v2.js";import"core-js/modules/es.set.intersection.v2.js";import"core-js/modules/es.set.is-disjoint-from.v2.js";import"core-js/modules/es.set.is-subset-of.v2.js";import"core-js/modules/es.set.is-superset-of.v2.js";import"core-js/modules/es.set.symmetric-difference.v2.js";import"core-js/modules/es.set.union.v2.js";/* global document */import{Suspense,lazy,useInsertionEffect}from"react";import{Barrier}from"@dr.pogodin/js-utils";import{getSsrContext}from"./globalState";import{IS_CLIENT_SIDE,IS_SERVER_SIDE,getBuildInfo}from"./isomorphy";import{jsx as _jsx}from"react/jsx-runtime";function getClientChunkGroups(){if(!IS_CLIENT_SIDE)return undefined;return(async()=>{const{default:getInj}=await import(/* webpackChunkName: "react-utils-client-side-code" */"../../client/getInj");const inj=await getInj();return inj.CHUNK_GROUPS??{};})();}const refCounts={};function getPublicPath(){return getBuildInfo().publicPath;}/**
33
2
  * Client-side only! Ensures the specified CSS stylesheet is loaded into
34
3
  * the document; loads if it is missing; and does simple reference counting
35
4
  * to facilitate future clean-up.
@@ -37,58 +6,10 @@ function getPublicPath() {
37
6
  * @param loadedSheets
38
7
  * @param refCount
39
8
  * @return
40
- */
41
- function bookStyleSheet(name, loadedSheets, refCount) {
42
- let res;
43
- const path = `${getPublicPath()}/${name}`;
44
- const fullPath = `${document.location.origin}${path}`;
45
- if (!loadedSheets.has(fullPath)) {
46
- let link = document.querySelector(`link[href="${path}"]`);
47
- if (!link) {
48
- link = document.createElement('link');
49
- link.setAttribute('rel', 'stylesheet');
50
- link.setAttribute('href', path);
51
- document.head.appendChild(link);
52
- }
53
- res = new Barrier();
54
- link.addEventListener('load', () => {
55
- if (!res) throw Error('Internal error');
56
- void res.resolve();
57
- });
58
- link.addEventListener('error', () => {
59
- if (!res) throw Error('Internal error');
60
- void res.resolve();
61
- });
62
- }
63
- if (refCount) {
64
- const current = refCounts[path] ?? 0;
65
- refCounts[path] = 1 + current;
66
- }
67
- return res;
68
- }
69
-
70
- /**
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;}/**
71
10
  * Generates the set of URLs for currently loaded, linked stylesheets.
72
11
  * @return
73
- */
74
- function getLoadedStyleSheets() {
75
- const res = new Set();
76
- const {
77
- styleSheets
78
- } = document;
79
- for (const {
80
- href
81
- } of styleSheets) {
82
- if (href) res.add(href);
83
- }
84
- return res;
85
- }
86
- function assertChunkName(chunkName, chunkGroups) {
87
- if (chunkGroups[chunkName]) return;
88
- throw Error(`Unknown chunk name "${chunkName}"`);
89
- }
90
-
91
- /**
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}"`);}/**
92
13
  * Client-side only! Ensures all CSS stylesheets required for the specified
93
14
  * code chunk are loaded into the document; loads the missing ones; and does
94
15
  * simple reference counting to facilitate future clean-up.
@@ -96,47 +17,14 @@ function assertChunkName(chunkName, chunkGroups) {
96
17
  * @param refCount
97
18
  * @return Resolves once all pending stylesheets, necessary for
98
19
  * the chunk, are either loaded, or failed to load.
99
- */
100
- export async function bookStyleSheets(chunkName, chunkGroups, refCount) {
101
- const promises = [];
102
- const assets = chunkGroups[chunkName];
103
- if (!assets) return Promise.resolve();
104
- const loadedSheets = getLoadedStyleSheets();
105
- for (const asset of assets) {
106
- if (asset.endsWith('.css')) {
107
- const promise = bookStyleSheet(asset, loadedSheets, refCount);
108
- if (promise) promises.push(promise);
109
- }
110
- }
111
- return promises.length ? Promise.allSettled(promises).then() : Promise.resolve();
112
- }
113
-
114
- /**
20
+ */export async function bookStyleSheets(chunkName,chunkGroups,refCount){const promises=[];const assets=chunkGroups[chunkName];if(!assets)return Promise.resolve();const loadedSheets=getLoadedStyleSheets();for(const asset of assets){if(asset.endsWith(".css")){const promise=bookStyleSheet(asset,loadedSheets,refCount);if(promise)promises.push(promise);}}return promises.length?Promise.allSettled(promises).then():Promise.resolve();}/**
115
21
  * Client-side only! Frees from the document all CSS stylesheets that are
116
22
  * required by the specified chunk, and have reference counter equal to one
117
23
  * (for chunks with larger reference counter values, it just decrements
118
24
  * the reference counter).
119
25
  * @param {string} chunkName
120
- */
121
- export function freeStyleSheets(chunkName, chunkGroups) {
122
- const assets = chunkGroups[chunkName];
123
- if (!assets) return;
124
- for (const asset of assets) {
125
- if (asset.endsWith('.css')) {
126
- const path = `${getPublicPath()}/${asset}`;
127
- const pathRefCount = refCounts[path];
128
- if (pathRefCount) {
129
- if (pathRefCount <= 1) {
130
- document.head.querySelector(`link[href="${path}"]`).remove();
131
- delete refCounts[path];
132
- } else refCounts[path] = pathRefCount - 1;
133
- }
134
- }
135
- }
136
- }
137
-
138
- // Holds the set of chunk names already used for splitComponent() calls.
139
- const usedChunkNames = new Set();
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.
27
+ // const usedChunkNames = new Set();
140
28
  /**
141
29
  * Given an async component retrieval function `getComponent()` it creates
142
30
  * a special "code split" component, which uses <Suspense> to asynchronously
@@ -146,83 +34,32 @@ const usedChunkNames = new Set();
146
34
  * @param {function} options.getComponent
147
35
  * @param {React.Element} [options.placeholder]
148
36
  * @return {React.ElementType}
149
- */
150
- export default function splitComponent({
151
- chunkName,
152
- getComponent,
153
- placeholder
154
- }) {
155
- // The correct usage of splitComponent() assumes a single call per chunk.
156
- if (usedChunkNames.has(chunkName)) {
157
- throw Error(`Repeated splitComponent() call for the chunk "${chunkName}"`);
158
- } else usedChunkNames.add(chunkName);
159
- const LazyComponent = /*#__PURE__*/lazy(async () => {
160
- const clientChunkGroups = await getClientChunkGroups();
161
-
162
- // On the client side we can check right away if the chunk name is known.
163
- if (IS_CLIENT_SIDE) {
164
- if (!clientChunkGroups) throw Error('Internal error');
165
- assertChunkName(chunkName, clientChunkGroups);
166
- }
167
- const resolved = await getComponent();
168
- const Component = 'default' in resolved ? resolved.default : resolved;
169
-
170
- // This pre-loads necessary stylesheets prior to the first mount of
171
- // the component (the lazy load function is executed by React one at
172
- // the frist mount).
173
- if (IS_CLIENT_SIDE) {
174
- if (!clientChunkGroups) throw Error('Internal error');
175
- await bookStyleSheets(chunkName, clientChunkGroups, false);
176
- }
177
- const Wrapper = ({
178
- children,
179
- ref,
180
- ...rest
181
- }) => {
182
- // On the server side we'll assert the chunk name here,
183
- // and also push it to the SSR chunks array.
184
- if (IS_SERVER_SIDE) {
185
- const {
186
- chunkGroups,
187
- chunks
188
- } = getSsrContext();
189
- assertChunkName(chunkName, chunkGroups);
190
- if (!chunks.includes(chunkName)) chunks.push(chunkName);
191
- }
192
-
193
- // This takes care about stylesheets management every time an instance of
194
- // this component is mounted / unmounted.
195
- useInsertionEffect(() => {
196
- if (!clientChunkGroups) throw Error('Internal error');
197
- void bookStyleSheets(chunkName, clientChunkGroups, true);
198
- return () => {
199
- freeStyleSheets(chunkName, clientChunkGroups);
200
- };
201
- }, []);
202
- return /*#__PURE__*/_jsx(Component
203
- // eslint-disable-next-line react/jsx-props-no-spreading
204
- , {
205
- ...rest,
206
- ref: ref,
207
- children: children
208
- });
209
- };
210
- return {
211
- default: Wrapper
212
- };
213
- });
214
- const CodeSplit = ({
215
- children,
216
- ...rest
217
- }) => /*#__PURE__*/_jsx(Suspense, {
218
- fallback: placeholder,
219
- children: /*#__PURE__*/_jsx(LazyComponent
220
- // eslint-disable-next-line react/jsx-props-no-spreading
221
- , {
222
- ...rest,
223
- children: children
224
- })
225
- });
226
- return CodeSplit;
227
- }
37
+ */export default function splitComponent({chunkName,getComponent,placeholder}){// TODO: For now I commented out this safeguard check, as I am not sure how
38
+ // to easily make it work: it should not be triggered in HMR mode, but if I
39
+ // add the code relying on import.meta, it fails in Jest environment, because
40
+ // Jest does not support ES modules yet, and import.meta is not support in
41
+ // CommonJS modules, and the "babel-plugin-transform-import-meta" plugin
42
+ // we use to workaround this issue for import.meta.dirname, etc. does not
43
+ // transform import.meta.webpackHot
44
+ // The correct usage of splitComponent() assumes a single call per chunk.
45
+ // if (usedChunkNames.has(chunkName)
46
+ // When HMR happens splitComponent() ends up getting called again for some
47
+ // chunks, thus we should not throw this error. Not sure, if we need to do
48
+ // some additional handling in that case, or just not throwing is all we
49
+ // need.
50
+ // && !import.meta.webpackHot
51
+ // ) {
52
+ // throw Error(`Repeated splitComponent() call for the chunk "${chunkName}"`);
53
+ // } else usedChunkNames.add(chunkName);
54
+ const LazyComponent=/*#__PURE__*/lazy(async()=>{const clientChunkGroups=await getClientChunkGroups();// On the client side we can check right away if the chunk name is known.
55
+ if(IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");assertChunkName(chunkName,clientChunkGroups);}const resolved=await getComponent();const Component="default"in resolved?resolved.default:resolved;// This pre-loads necessary stylesheets prior to the first mount of
56
+ // the component (the lazy load function is executed by React one at
57
+ // the frist mount).
58
+ if(IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");await bookStyleSheets(chunkName,clientChunkGroups,false);}const Wrapper=({children,ref,...rest})=>{// On the server side we'll assert the chunk name here,
59
+ // and also push it to the SSR chunks array.
60
+ if(IS_SERVER_SIDE){const{chunkGroups,chunks}=getSsrContext();assertChunkName(chunkName,chunkGroups);if(!chunks.includes(chunkName))chunks.push(chunkName);}// This takes care about stylesheets management every time an instance of
61
+ // this component is mounted / unmounted.
62
+ useInsertionEffect(()=>{if(!clientChunkGroups)throw Error("Internal error");void bookStyleSheets(chunkName,clientChunkGroups,true);return()=>{freeStyleSheets(chunkName,clientChunkGroups);};},[]);return/*#__PURE__*/_jsx(Component// eslint-disable-next-line react/jsx-props-no-spreading
63
+ ,{...rest,ref:ref,children:children});};return{default:Wrapper};});const CodeSplit=({children,...rest})=>/*#__PURE__*/_jsx(Suspense,{fallback:placeholder,children:/*#__PURE__*/_jsx(LazyComponent// eslint-disable-next-line react/jsx-props-no-spreading
64
+ ,{...rest,children:children})});return CodeSplit;}
228
65
  //# sourceMappingURL=splitComponent.js.map