@dr.pogodin/react-utils 1.47.0-alpha.1 → 1.47.0-alpha.11
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.
- package/babel.config.js +1 -1
- package/babel.module.config.js +11 -0
- package/bin/build.js +8 -4
- package/bin/setup.js +2 -3
- package/build/development/client/getInj.js +57 -44
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/client/index.js +15 -21
- package/build/development/client/index.js.map +1 -1
- package/build/development/client/init.js +2 -6
- package/build/development/client/init.js.map +1 -1
- package/build/development/index.js +3 -183
- package/build/development/index.js.map +1 -1
- package/build/development/server/Cache.js +1 -8
- package/build/development/server/Cache.js.map +1 -1
- package/build/development/server/index.js +22 -50
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +83 -92
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +58 -62
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/errors.js +8 -31
- package/build/development/server/utils/errors.js.map +1 -1
- package/build/development/server/utils/index.js +2 -9
- package/build/development/server/utils/index.js.map +1 -1
- package/build/development/shared/components/Button/index.js +9 -16
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +6 -13
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/GenericLink/index.js +4 -10
- package/build/development/shared/components/GenericLink/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +11 -18
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Link.js +6 -13
- package/build/development/shared/components/Link.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +16 -22
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/NavLink.js +6 -13
- package/build/development/shared/components/NavLink.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js +7 -14
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +15 -22
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js +7 -14
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js +12 -18
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +16 -23
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +10 -17
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/index.js +16 -130
- package/build/development/shared/components/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +18 -19
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +24 -28
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +19 -19
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +12 -17
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/components/selectors/common.js +1 -7
- package/build/development/shared/components/selectors/common.js.map +1 -1
- package/build/development/shared/components/selectors/index.js +3 -27
- package/build/development/shared/components/selectors/index.js.map +1 -1
- package/build/development/shared/utils/config.js +40 -21
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/globalState.js +3 -8
- package/build/development/shared/utils/globalState.js.map +1 -1
- package/build/development/shared/utils/index.js +12 -89
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/isomorphy/buildInfo.js +2 -9
- package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/development/shared/utils/isomorphy/environment-check.js +2 -8
- package/build/development/shared/utils/isomorphy/environment-check.js.map +1 -1
- package/build/development/shared/utils/isomorphy/index.js +7 -32
- package/build/development/shared/utils/isomorphy/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js +24 -31
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/development/shared/utils/jest/global.js +1 -7
- package/build/development/shared/utils/jest/global.js.map +1 -1
- package/build/development/shared/utils/jest/index.js +20 -44
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +54 -46
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/time.js +22 -31
- package/build/development/shared/utils/time.js.map +1 -1
- package/build/development/shared/utils/webpack.js +17 -16
- package/build/development/shared/utils/webpack.js.map +1 -1
- package/build/production/client/getInj.js +13 -11
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/client/index.js +3 -3
- package/build/production/client/index.js.map +1 -1
- package/build/production/client/init.js +2 -2
- package/build/production/client/init.js.map +1 -1
- package/build/production/index.js +2 -6
- package/build/production/index.js.map +1 -1
- package/build/production/server/Cache.js +3 -3
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/index.js +8 -8
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +24 -25
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +9 -11
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/errors.js +9 -9
- package/build/production/server/utils/errors.js.map +1 -1
- package/build/production/server/utils/index.js +2 -1
- package/build/production/server/utils/index.js.map +1 -1
- package/build/production/shared/components/Button/index.js +4 -4
- package/build/production/shared/components/Button/index.js.map +1 -1
- package/build/production/shared/components/Checkbox/index.js +1 -1
- package/build/production/shared/components/Checkbox/index.js.map +1 -1
- package/build/production/shared/components/GenericLink/index.js +4 -4
- package/build/production/shared/components/GenericLink/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +5 -5
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Link.js +3 -3
- package/build/production/shared/components/Link.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +7 -7
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/NavLink.js +2 -2
- package/build/production/shared/components/NavLink.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js +2 -2
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js +5 -5
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js +2 -2
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js +4 -4
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +4 -4
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +4 -4
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/index.js +3 -1
- package/build/production/shared/components/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +2 -2
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js +2 -2
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js +4 -4
- package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/Switch/index.js +1 -1
- package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/production/shared/components/selectors/common.js +2 -2
- package/build/production/shared/components/selectors/common.js.map +1 -1
- package/build/production/shared/components/selectors/index.js +1 -1
- package/build/production/shared/components/selectors/index.js.map +1 -1
- package/build/production/shared/utils/config.js +8 -6
- package/build/production/shared/utils/config.js.map +1 -1
- package/build/production/shared/utils/globalState.js +2 -2
- package/build/production/shared/utils/globalState.js.map +1 -1
- package/build/production/shared/utils/index.js +1 -1
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/isomorphy/buildInfo.js +3 -3
- package/build/production/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/production/shared/utils/isomorphy/environment-check.js +3 -3
- package/build/production/shared/utils/isomorphy/environment-check.js.map +1 -1
- package/build/production/shared/utils/isomorphy/index.js +4 -4
- package/build/production/shared/utils/isomorphy/index.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +14 -14
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/jest/global.js +1 -1
- package/build/production/shared/utils/jest/global.js.map +1 -1
- package/build/production/shared/utils/jest/index.js +11 -11
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +11 -22
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/time.js +3 -3
- package/build/production/shared/utils/time.js.map +1 -1
- package/build/production/shared/utils/webpack.js +6 -6
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/types-code/client/getInj.d.ts +1 -2
- package/build/types-code/client/index.d.ts +1 -1
- package/build/types-code/index.d.ts +1 -7
- package/build/types-code/server/index.d.ts +6 -11
- package/build/types-code/server/utils/index.d.ts +1 -1
- package/build/types-code/shared/utils/config.d.ts +4 -2
- package/build/types-code/shared/utils/index.d.ts +2 -2
- package/build/types-code/shared/utils/splitComponent.d.ts +6 -4
- package/build/web/client/getInj.js +55 -44
- package/build/web/client/getInj.js.map +1 -1
- package/build/web/client/index.js +15 -21
- package/build/web/client/index.js.map +1 -1
- package/build/web/client/init.js +2 -4
- package/build/web/client/init.js.map +1 -1
- package/build/web/index.js +1 -15
- package/build/web/index.js.map +1 -1
- package/build/web/server/index.js +12 -21
- package/build/web/server/index.js.map +1 -1
- package/build/web/server/renderer.js +34 -40
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/server/server.js +14 -11
- package/build/web/server/server.js.map +1 -1
- package/build/web/server/utils/index.js +1 -1
- package/build/web/server/utils/index.js.map +1 -1
- package/build/web/shared/components/Button/index.js +1 -1
- package/build/web/shared/components/Button/index.js.map +1 -1
- package/build/web/shared/components/Checkbox/index.js +1 -1
- package/build/web/shared/components/Checkbox/index.js.map +1 -1
- package/build/web/shared/components/Input/index.js +1 -1
- package/build/web/shared/components/Input/index.js.map +1 -1
- package/build/web/shared/components/Modal/index.js +3 -3
- package/build/web/shared/components/Modal/index.js.map +1 -1
- package/build/web/shared/components/PageLayout/index.js +1 -1
- package/build/web/shared/components/PageLayout/index.js.map +1 -1
- package/build/web/shared/components/TextArea/index.js +1 -1
- package/build/web/shared/components/TextArea/index.js.map +1 -1
- package/build/web/shared/components/Throbber/index.js +1 -1
- package/build/web/shared/components/Throbber/index.js.map +1 -1
- package/build/web/shared/components/WithTooltip/index.js +1 -1
- package/build/web/shared/components/WithTooltip/index.js.map +1 -1
- package/build/web/shared/components/YouTubeVideo/index.js +1 -1
- package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +3 -0
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js +3 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js +4 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/Switch/index.js +2 -1
- package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/web/shared/utils/config.js +38 -14
- package/build/web/shared/utils/config.js.map +1 -1
- package/build/web/shared/utils/index.js +2 -2
- package/build/web/shared/utils/index.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv.js +3 -2
- package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/web/shared/utils/splitComponent.js +27 -20
- package/build/web/shared/utils/splitComponent.js.map +1 -1
- package/build/web/shared/utils/webpack.js +13 -7
- package/build/web/shared/utils/webpack.js.map +1 -1
- package/config/babel/node-ssr.js +12 -6
- package/config/babel/webpack.js +6 -1
- package/config/jest/default.js +8 -2
- package/config/jest/setup.js +8 -1
- package/config/webpack/app-base.js +23 -15
- package/config/webpack/app-development.js +2 -3
- package/config/webpack/lib-base.js +1 -2
- package/package.json +35 -25
- package/types.d.ts +1 -6
- package/node-entry.js +0 -15
- package/src/client/getInj.ts +0 -51
- package/src/client/index.tsx +0 -43
- package/src/client/init.ts +0 -52
- package/src/index.ts +0 -79
- package/src/server/Cache.ts +0 -61
- package/src/server/index.ts +0 -249
- package/src/server/renderer.tsx +0 -653
- package/src/server/server.ts +0 -332
- package/src/server/utils/errors.ts +0 -122
- package/src/server/utils/index.ts +0 -3
- package/src/shared/components/Button/index.tsx +0 -130
- package/src/shared/components/Button/style.scss +0 -54
- package/src/shared/components/Checkbox/index.tsx +0 -53
- package/src/shared/components/Checkbox/theme.scss +0 -63
- package/src/shared/components/GenericLink/index.tsx +0 -141
- package/src/shared/components/GenericLink/style.scss +0 -3
- package/src/shared/components/Input/index.tsx +0 -96
- package/src/shared/components/Input/theme.scss +0 -52
- package/src/shared/components/Link.tsx +0 -25
- package/src/shared/components/Modal/base-theme.scss +0 -38
- package/src/shared/components/Modal/index.tsx +0 -177
- package/src/shared/components/Modal/styles.scss +0 -3
- package/src/shared/components/NavLink.tsx +0 -18
- package/src/shared/components/PageLayout/base-theme.scss +0 -30
- package/src/shared/components/PageLayout/index.tsx +0 -51
- package/src/shared/components/TextArea/index.tsx +0 -139
- package/src/shared/components/TextArea/style.scss +0 -68
- package/src/shared/components/Throbber/index.tsx +0 -28
- package/src/shared/components/Throbber/theme.scss +0 -26
- package/src/shared/components/WithTooltip/Tooltip.tsx +0 -274
- package/src/shared/components/WithTooltip/default-theme.scss +0 -36
- package/src/shared/components/WithTooltip/index.tsx +0 -186
- package/src/shared/components/YouTubeVideo/base.scss +0 -15
- package/src/shared/components/YouTubeVideo/index.tsx +0 -73
- package/src/shared/components/YouTubeVideo/throbber.scss +0 -11
- package/src/shared/components/index.ts +0 -20
- package/src/shared/components/selectors/CustomDropdown/Options/index.tsx +0 -124
- package/src/shared/components/selectors/CustomDropdown/Options/style.scss +0 -6
- package/src/shared/components/selectors/CustomDropdown/index.tsx +0 -146
- package/src/shared/components/selectors/CustomDropdown/theme.scss +0 -118
- package/src/shared/components/selectors/NativeDropdown/index.tsx +0 -90
- package/src/shared/components/selectors/NativeDropdown/theme.scss +0 -81
- package/src/shared/components/selectors/Switch/index.tsx +0 -74
- package/src/shared/components/selectors/Switch/theme.scss +0 -39
- package/src/shared/components/selectors/common.ts +0 -57
- package/src/shared/components/selectors/index.ts +0 -8
- package/src/shared/utils/config.ts +0 -28
- package/src/shared/utils/globalState.ts +0 -44
- package/src/shared/utils/index.ts +0 -45
- package/src/shared/utils/isomorphy/buildInfo.ts +0 -50
- package/src/shared/utils/isomorphy/environment-check.ts +0 -18
- package/src/shared/utils/isomorphy/index.ts +0 -36
- package/src/shared/utils/jest/E2eSsrEnv.ts +0 -305
- package/src/shared/utils/jest/global.ts +0 -17
- package/src/shared/utils/jest/index.ts +0 -215
- package/src/shared/utils/splitComponent.tsx +0 -275
- package/src/shared/utils/time.ts +0 -101
- package/src/shared/utils/webpack.ts +0 -74
- package/src/styles/_global/reset.css +0 -52
- package/src/styles/_mixins/fonts.scss +0 -40
- package/src/styles/_mixins/media.scss +0 -150
- package/src/styles/_mixins/typography.scss +0 -83
- package/src/styles/global.scss +0 -11
- package/src/styles/mixins.scss +0 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"E2eSsrEnv.js","names":["_nodePath","_interopRequireDefault","require","_defaults","_set","_experimentalWorker","_jestEnvironmentJsdom","_memfs","_webpack","_renderer","_buildInfo","noop","E2eSsrEnv","JsdomEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","defaults","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","path","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","webpack","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","renderer","ssrFactory","status","markup","ssrRequest","cookie","send","set","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","createFsFromVolume","Volume","dirname","testPath","withSsr","root","process","cwd","register","envName","babelEnv","extensions","setup","cache","setBuildInfo","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert","exports"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\nimport path from 'node:path';\n\nimport type { Request, Response } from 'express';\n\nimport defaults from 'lodash/defaults';\nimport set from 'lodash/set';\n\nimport type { ReactNode } from 'react';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration } from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport ssrFactory from 'server/renderer';\n\nimport { setBuildInfo } from '../isomorphy/buildInfo';\n\nfunction noop() {\n // NOOP\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n let factory = require(path.resolve(this.rootDir, factoryPath)) as\n (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n if (!compiler) throw Error('Failed to construct Webpack compiler');\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n // TODO: This sure can be replaced by a dynamic import().\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n const module = require(p) as NodeJS.Module;\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\n register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n await super.teardown();\n }\n}\n"],"mappings":"gLAkBA,IAAAA,SAAA,CAAAC,sBAAA,CAAAC,OAAA,eAIA,IAAAC,SAAA,CAAAF,sBAAA,CAAAC,OAAA,qBACA,IAAAE,IAAA,CAAAH,sBAAA,CAAAC,OAAA,gBAOA,IAAAG,mBAAA,CAAAJ,sBAAA,CAAAC,OAAA,yCAEA,IAAAI,qBAAA,CAAAL,sBAAA,CAAAC,OAAA,4BACA,IAAAK,MAAA,CAAAL,OAAA,UACA,IAAAM,QAAA,CAAAP,sBAAA,CAAAC,OAAA,aAQA,IAAAO,SAAA,CAAAR,sBAAA,CAAAC,OAAA,8BAEA,IAAAQ,UAAA,CAAAR,OAAA,2BA5CA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAWA;AACA;AACA,sDAMA,qDAWA,QAAS,CAAAS,IAAIA,CAAA,CAAG,CACd;AAAA,CAGa,KAAM,CAAAC,SAAS,QAAS,CAAAC,6BAAS,CAa9C;AACF;AACA;AACA,KACUC,iBAAiBA,CAAA,CAAG,CAC1B,KAAM,CAAAC,aAAa,CAAG,IAAI,CAACC,OAAO,CAAC,wBAAwB,CAAW,CAEtE,KAAM,CAAAC,OAAO,CAAIF,aAAa,CAAGG,IAAI,CAACC,KAAK,CAACJ,aAAa,CAAC,CAAG,CAAC,CACvC,CAEvB,GAAAK,iBAAQ,EAACH,OAAO,CAAE,CAChBI,OAAO,CAAE,IAAI,CAACC,UAAU,CACxBC,EAAE,CAAE,IAAI,CAACC,MAAM,CAACC,eAClB,CAAC,CAAC,CAEF,KAAM,CAAAC,WAAW,CAAG,IAAI,CAACV,OAAO,CAAC,wBAAwB,CAAW,CACpE;AACA,GAAI,CAAAW,OAAO,CAAGzB,OAAO,CAAC0B,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C,CACH,CAEA,KAAM,CAAAO,KAAKA,CAAA,CAAkB,CAC3B,KAAM,MAAK,CAACA,KAAK,CAAC,CAAC,CACnB,KAAM,KAAI,CAACjE,UAAU,CAAC,CAAC,CAEvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAlC,OAAO,CAACoG,KAAK,CAAG,CAAC,CAAC,CAClB,GAAAC,uBAAY,EAACC,SAAS,CAAE,IAAI,CAAC,CAE7B,GAAI,IAAI,CAACX,OAAO,CAAE,KAAM,KAAI,CAACxC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC7B,MAAM,CAACiF,6BAA6B,CAAG,IAC9C,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAkB,CAC9B,MAAO,KAAI,CAAClF,MAAM,CAACiF,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAAC1G,OAAO,CAACoG,KAAK,CAAC,CAACO,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,CAAA5G,OAAO,CAACoG,KAAK,CAACQ,GAAG,CAC1B,CAAC,CAAC,CACFb,2BAAQ,CAACc,MAAM,CAAC,CAAC,CACjB,KAAM,MAAK,CAACL,QAAQ,CAAC,CACvB,CACF,CAAAM,OAAA,CAAAjF,OAAA,CAAAnB,SAAA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"E2eSsrEnv.js","names":["path","defaults","set","register","JsdomEnv","Volume","createFsFromVolume","webpack","ssrFactory","setBuildInfo","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","require","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","renderer","status","markup","ssrRequest","cookie","send","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","dirname","testPath","withSsr","root","process","cwd","envName","babelEnv","extensions","setup","cache","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\nimport path from 'node:path';\n\nimport type { Request, Response } from 'express';\n\nimport { defaults, set } from 'lodash-es';\n\nimport type { ReactNode } from 'react';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration } from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport ssrFactory from 'server/renderer';\n\nimport { setBuildInfo } from '../isomorphy/buildInfo';\n\nfunction noop() {\n // NOOP\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n let factory = require(path.resolve(this.rootDir, factoryPath)) as\n (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n if (!compiler) throw Error('Failed to construct Webpack compiler');\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n // TODO: This sure can be replaced by a dynamic import().\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n const module = require(p) as NodeJS.Module;\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\n register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n await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,CAAC,CAE7B,GAAI,IAAI,CAACT,OAAO,CAAE,KAAM,KAAI,CAACpC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC5B,MAAM,CAAC0E,6BAA6B,CAAG,IAC9C,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAkB,CAC9B,MAAO,KAAI,CAAC3E,MAAM,CAAC0E,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAACzE,OAAO,CAACoE,KAAK,CAAC,CAACM,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,CAAA3E,OAAO,CAACoE,KAAK,CAACO,GAAG,CAC1B,CAAC,CAAC,CACFjG,QAAQ,CAACkG,MAAM,CAAC,CAAC,CACjB,KAAM,MAAK,CAACL,QAAQ,CAAC,CACvB,CACF","ignoreList":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
export default function getGlobal(){return global}
|
|
2
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":"
|
|
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,MACT","ignoreList":[]}
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
|
|
1
|
+
/* 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";/**
|
|
2
2
|
* An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)
|
|
3
3
|
* from `react`.
|
|
4
|
-
*/global.IS_REACT_ACT_ENVIRONMENT=true;const originalProcessVersions=process.versions;/**
|
|
4
|
+
*/export{act};export{default as getGlobal}from"./global.js";global.IS_REACT_ACT_ENVIRONMENT=true;const originalProcessVersions=process.versions;/**
|
|
5
5
|
* Tricks **react-utils** into thinking the test is running within client-side
|
|
6
6
|
* (browser) environment.
|
|
7
|
-
*/function mockClientSide(){Object.defineProperty(process,"versions",{value:undefined})}/**
|
|
7
|
+
*/export function mockClientSide(){Object.defineProperty(process,"versions",{value:undefined})}/**
|
|
8
8
|
* Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.
|
|
9
|
-
*/function unmockClientSide(){Object.defineProperty(process,"versions",{value:originalProcessVersions,writable:false})}/**
|
|
9
|
+
*/export function unmockClientSide(){Object.defineProperty(process,"versions",{value:originalProcessVersions,writable:false})}/**
|
|
10
10
|
* Generates a mock UUID, or better said it determenistically transforms given
|
|
11
11
|
* `seed` number into a UUID-formatted string.
|
|
12
12
|
* @param {number} seed
|
|
13
13
|
* @return {string}
|
|
14
|
-
*/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)}`}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.
|
|
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
15
|
let res;try{res=await axios({...config,adapter:["xhr","http","fetch"]});// eslint-disable-next-line no-console
|
|
16
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
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}/**
|
|
@@ -19,25 +19,25 @@ console.warn("Network request has not been mocked for a test, and failed.\n\nCon
|
|
|
19
19
|
* @param {number} time Time step [ms].
|
|
20
20
|
* @returns {Promise} Wait for this to "jump after" any async code which should
|
|
21
21
|
* be executed because of the mock time movement.
|
|
22
|
-
*/async function mockTimer(time){
|
|
22
|
+
*/export async function mockTimer(time){mockdate.set(time+Date.now());await jest.advanceTimersByTimeAsync(time)}/**
|
|
23
23
|
* Mounts `scene` to the DOM, and returns the root scene element.
|
|
24
24
|
* @param scene
|
|
25
25
|
* @return Created container DOM element with destroy() function
|
|
26
26
|
* attached.
|
|
27
|
-
*/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
|
|
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
28
|
// when it is simulating user events.
|
|
29
|
-
global.IS_REACT_ACT_ENVIRONMENT=true;
|
|
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
30
|
// when it is simulating user events.
|
|
31
|
-
global.IS_REACT_ACT_ENVIRONMENT=true;
|
|
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
|
|
32
32
|
// across two objects, depending whether they are applicable to the sync, or async
|
|
33
33
|
// versions of snapshot(), or both.
|
|
34
|
-
function snapshot(element,options){let res;// TODO: Just adding async to the actor function breaks stuff, as it makes
|
|
34
|
+
export function snapshot(element,options){let res;// TODO: Just adding async to the actor function breaks stuff, as it makes
|
|
35
35
|
// act() asynchronous no matter the `options.await` value, thus breaking all
|
|
36
36
|
// calls that do not await for snapshot() result... thus... perhaps we need
|
|
37
37
|
// to have a more complex typing to ensure it all works as intended in all
|
|
38
38
|
// cases, and while being correctly enforced by TypeScript.
|
|
39
39
|
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
40
|
-
const promise=
|
|
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
41
|
// it is not an instance of proper Promise class, and returning it directly
|
|
42
42
|
// breaks some async logic in Jest test or React test functions... thus, we
|
|
43
43
|
// wrap it into Promise instance here.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_mockdate","_interopRequireDefault","require","_react","_client","_react2","_global","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","mockdate","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","act","unmount","remove","snapshot","expect","toMatchSnapshot","createRoot","render","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":"4iBAUA,IAAAA,SAAA,CAAAC,sBAAA,CAAAC,OAAA,cACA,IAAAC,MAAA,CAAAD,OAAA,UACA,IAAAE,OAAA,CAAAF,OAAA,qBAEA,IAAAG,OAAA,CAAAH,OAAA,2BAQA,IAAAI,OAAA,CAAAL,sBAAA,CAAAC,OAAA,cAtBA,2BACA,sDAeA;AACA;AACA;AACA,GAKAK,MAAM,CAACC,wBAAwB,CAAG,IAAI,CAEtC,KAAM,CAAA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AACV,eAAe,CAAC,CAAC,CAClEQ,OAAO,CAACvC,GAAI,CACd,CAAC,CACH,CAAC,CACH,CAEA,KAAM,CAAAyC,KAAK,CAAGzC,GAAG,CAAC0C,UAAU,CAAC,CAAC,CAACC,UAAU,CACzCb,MAAM,CAACW,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACV,eAAe,CAAC,CAAC,CAClE,MAAO,CAAA/B,GACT","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":"AAAA,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,SAEHG,OAAO,GAAI,CAAAC,SAAS,mBAE7BC,MAAM,CAACC,wBAAwB,CAAG,IAAI,CAEtC,KAAM,CAAAC,uBAAuB,CAAGC,OAAO,CAACC,QAAQ,CAEhD;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,cAAcA,CAAA,CAAS,CACrCC,MAAM,CAACC,cAAc,CAACJ,OAAO,CAAE,UAAU,CAAE,CAAEK,KAAK,CAAEC,SAAU,CAAC,CACjE,CAEA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,gBAAgBA,CAAA,CAAS,CACvCJ,MAAM,CAACC,cAAc,CAACJ,OAAO,CAAE,UAAU,CAAE,CACzCK,KAAK,CAAEN,uBAAuB,CAC9BS,QAAQ,CAAE,KACZ,CAAC,CACH,CAEA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,WAAWA,CAACC,IAAI,CAAG,CAAC,CAAU,CAC5C,KAAM,CAAAC,CAAC,CAAGD,IAAI,CAACE,QAAQ,CAAC,EAAE,CAAC,CAACC,QAAQ,CAAC,EAAE,CAAE,GAAG,CAAC,CAC7C,MAAO,GAAGF,CAAC,CAACG,KAAK,CAAC,CAAC,CAAE,CAAC,CAAC,IAAIH,C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AAA+B,OAAO,CAAG/D,GAAG,CAAC,IAAM,CACxBgC,GAAG,CAAG9B,MAAM,CAACiD,OAAO,CAAC,CACrB,MAAO,CAAAW,OAAO,EAAEE,KAClB,CAAC,CAAC,CAEF,GAAIhC,GAAG,GAAKlB,SAAS,CAAE,KAAM,CAAAmD,KAAK,CAAC,eAAe,CAAC,CACnD,GAAIH,OAAO,EAAEE,KAAK,CAAE,CAClB;AACA;AACA;AACA;AACA,MAAO,IAAI,CAAAE,OAAO,CAAEC,OAAO,EAAK,CAC9B,IAAK,CAAAJ,OAAO,CAACK,IAAI,CAAC,IAAM,CACtB;AACA;AACA,KAAM,CAAAC,KAAK,CAAGrC,GAAG,CAAEsC,UAAU,CAAC,CAAC,CAACC,UAAU,CAC1CX,MAAM,CAACS,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC,CAClEM,OAAO,CAACnC,GAAI,CACd,CAAC,CACH,CAAC,CACH,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,GACT","ignoreList":[]}
|
|
@@ -1,15 +1,4 @@
|
|
|
1
|
-
"
|
|
2
|
-
// the module; at the server-side we only can get them within React render flow.
|
|
3
|
-
// Thus, we set and use the following variable at the client-side, and then when
|
|
4
|
-
// needed on the server side, we'll fetch it differently.
|
|
5
|
-
let clientChunkGroups;if(_isomorphy.IS_CLIENT_SIDE){// TODO: Rewrite to avoid these overrides of ESLint rules.
|
|
6
|
-
/* eslint-disable @typescript-eslint/no-unsafe-assignment,
|
|
7
|
-
@typescript-eslint/no-require-imports,
|
|
8
|
-
@typescript-eslint/no-unsafe-call,
|
|
9
|
-
@typescript-eslint/no-unsafe-member-access */clientChunkGroups=require("../../client/getInj").default().CHUNK_GROUPS??{};/* eslint-enable @typescript-eslint/no-unsafe-assignment,
|
|
10
|
-
@typescript-eslint/no-require-imports,
|
|
11
|
-
@typescript-eslint/no-unsafe-call,
|
|
12
|
-
@typescript-eslint/no-unsafe-member-access */}const refCounts={};function getPublicPath(){return(0,_isomorphy.getBuildInfo)().publicPath}/**
|
|
1
|
+
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";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.js";import{IS_CLIENT_SIDE,IS_SERVER_SIDE,getBuildInfo}from"./isomorphy/index.js";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}/**
|
|
13
2
|
* Client-side only! Ensures the specified CSS stylesheet is loaded into
|
|
14
3
|
* the document; loads if it is missing; and does simple reference counting
|
|
15
4
|
* to facilitate future clean-up.
|
|
@@ -17,7 +6,7 @@ let clientChunkGroups;if(_isomorphy.IS_CLIENT_SIDE){// TODO: Rewrite to avoid th
|
|
|
17
6
|
* @param loadedSheets
|
|
18
7
|
* @param refCount
|
|
19
8
|
* @return
|
|
20
|
-
*/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
|
|
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}/**
|
|
21
10
|
* Generates the set of URLs for currently loaded, linked stylesheets.
|
|
22
11
|
* @return
|
|
23
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}"`)}/**
|
|
@@ -28,13 +17,13 @@ let clientChunkGroups;if(_isomorphy.IS_CLIENT_SIDE){// TODO: Rewrite to avoid th
|
|
|
28
17
|
* @param refCount
|
|
29
18
|
* @return Resolves once all pending stylesheets, necessary for
|
|
30
19
|
* the chunk, are either loaded, or failed to load.
|
|
31
|
-
*/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()}/**
|
|
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()}/**
|
|
32
21
|
* Client-side only! Frees from the document all CSS stylesheets that are
|
|
33
22
|
* required by the specified chunk, and have reference counter equal to one
|
|
34
23
|
* (for chunks with larger reference counter values, it just decrements
|
|
35
24
|
* the reference counter).
|
|
36
25
|
* @param {string} chunkName
|
|
37
|
-
*/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[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.
|
|
38
27
|
const usedChunkNames=new Set;/**
|
|
39
28
|
* Given an async component retrieval function `getComponent()` it creates
|
|
40
29
|
* a special "code split" component, which uses <Suspense> to asynchronously
|
|
@@ -44,16 +33,16 @@ const usedChunkNames=new Set;/**
|
|
|
44
33
|
* @param {function} options.getComponent
|
|
45
34
|
* @param {React.Element} [options.placeholder]
|
|
46
35
|
* @return {React.ElementType}
|
|
47
|
-
*/function splitComponent({chunkName,getComponent,placeholder}){//
|
|
48
|
-
if(
|
|
49
|
-
if(
|
|
36
|
+
*/export default function splitComponent({chunkName,getComponent,placeholder}){// The correct usage of splitComponent() assumes a single call per chunk.
|
|
37
|
+
if(usedChunkNames.has(chunkName)){throw Error(`Repeated splitComponent() call for the chunk "${chunkName}"`)}else usedChunkNames.add(chunkName);const LazyComponent=/*#__PURE__*/lazy(async()=>{const clientChunkGroups=await getClientChunkGroups();// On the client side we can check right away if the chunk name is known.
|
|
38
|
+
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
|
|
50
39
|
// the component (the lazy load function is executed by React one at
|
|
51
40
|
// the frist mount).
|
|
52
|
-
if(
|
|
41
|
+
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,
|
|
53
42
|
// and also push it to the SSR chunks array.
|
|
54
|
-
if(
|
|
43
|
+
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
|
|
55
44
|
// this component is mounted / unmounted.
|
|
56
|
-
|
|
57
|
-
,{...rest,ref:ref,children:children})};return{default:Wrapper}});const CodeSplit=({children,...rest})=>/*#__PURE__*/(
|
|
45
|
+
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
|
|
46
|
+
,{...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
|
|
58
47
|
,{...rest,children:children})});return CodeSplit}
|
|
59
48
|
//# sourceMappingURL=splitComponent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitComponent.js","names":["_react","require","_jsUtils","_globalState","_isomorphy","_jsxRuntime","clientChunkGroups","IS_CLIENT_SIDE","default","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","resolved","Component","Wrapper","children","ref","rest","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","_jsx","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\n// Note: At the client side we can get chunk groups immediately when loading\n// the module; at the server-side we only can get them within React render flow.\n// Thus, we set and use the following variable at the client-side, and then when\n// needed on the server side, we'll fetch it differently.\nlet clientChunkGroups: ChunkGroupsT;\n\nif (IS_CLIENT_SIDE) {\n // TODO: Rewrite to avoid these overrides of ESLint rules.\n /* eslint-disable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n clientChunkGroups = require('client/getInj').default().CHUNK_GROUPS ?? {};\n /* eslint-enable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) assertChunkName(chunkName, clientChunkGroups);\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyCompon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,MAAM,CAACE,QAAQ,CAAC/B,SAAS,CAAC,CAAE6B,MAAM,CAACpB,IAAI,CAACT,SAAS,CACxD,CAEA;AACA;AACA,GAAAgC,yBAAkB,EAAC,IAAM,CACvB,IAAK,CAAA9B,eAAe,CAACF,SAAS,CAAEpC,iBAAiB,CAAE,IAAI,CAAC,CACxD,MAAO,IAAM,CACXiD,eAAe,CAACb,SAAS,CAAEpC,iBAAiB,CAC9C,CACF,CAAC,CAAE,EAAE,CAAC,CAEN,mBACE,GAAAqE,eAAA,EAACV,SACC;AAAA,KACKI,IAAI,CACTD,GAAG,CAAEA,GAAI,CAAAD,QAAA,CAERA,QAAQ,CACA,CAEf,CAAC,CAED,MAAO,CAAE3D,OAAO,CAAE0D,OAAQ,CAC5B,CAAC,CAAC,CAEF,KAAM,CAAAU,SAAmD,CAAGA,CAAC,CAC3DT,QAAQ,CACR,GAAGE,IACY,CAAC,gBAChB,GAAAM,eAAA,EAACE,eAAQ,EAACC,QAAQ,CAAEjB,WAAY,CAAAM,QAAA,cAC9B,GAAAQ,eAAA,EAACb,aACC;AAAA,KACIO,IAAI,CAAAF,QAAA,CAEPA,QAAQ,CACI,CAAC,CACR,CACX,CAED,MAAO,CAAAS,SACT","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"splitComponent.js","names":["Suspense","lazy","useInsertionEffect","Barrier","getSsrContext","IS_CLIENT_SIDE","IS_SERVER_SIDE","getBuildInfo","jsx","_jsx","getClientChunkGroups","undefined","default","getInj","inj","CHUNK_GROUPS","refCounts","getPublicPath","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","clientChunkGroups","resolved","Component","Wrapper","children","ref","rest","chunks","includes","CodeSplit","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\nfunction getClientChunkGroups(): Promise<ChunkGroupsT> | undefined {\n if (!IS_CLIENT_SIDE) return undefined;\n\n return (async () => {\n const { default: getInj } = await import(/* webpackChunkName: \"react-utils-client-side-code\" */ '../../client/getInj');\n\n const inj = await getInj();\n return inj.CHUNK_GROUPS ?? {};\n })();\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\ntype GenericComponentPropsT = {\n children?: ReactNode;\n ref?: RefObject<unknown>;\n\n // NOTE: This is necessary, as without it this type (with only optional\n // fields) will be conisdered as \"weak\" by TypeScript, and it will be\n // a error to assign to it any type that does not use \"children\", or \"ref\".\n [propName: string]: unknown;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends GenericComponentPropsT,\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const clientChunkGroups = await getClientChunkGroups();\n\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n assertChunkName(chunkName, clientChunkGroups);\n }\n\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":"83BAAA,qBAEA,OAKEA,QAAQ,CACRC,IAAI,CACJC,kBAAkB,KACb,OAAO,CAEd,OAASC,OAAO,KAAQ,sBAAsB,QAElBC,aAAa,+BAGvCC,cAAc,CACdC,cAAc,CACdC,YAAY,4BACO,OAAAC,GAAA,IAAAC,IAAA,yBAErB,QAAS,CAAAC,oBAAoBA,CAAA,CAAsC,CACjE,GAAI,CAACL,cAAc,CAAE,MAAO,CAAAM,SAAS,CAErC,MAAO,CAAC,SAAY,CAClB,KAAM,CAAEC,OAAO,CAAEC,MAAO,CAAC,CAAG,KAAM,OAAM,CAAC,2EAA4E,CAAC,CAEtH,KAAM,CAAAC,GAAG,CAAG,KAAM,CAAAD,MAAM,CAAC,CAAC,CAC1B,MAAO,CAAAC,GAAG,CAACC,YAAY,EAAI,CAAC,CAC9B,CAAC,EAAE,CACL,CAEA,KAAM,CAAAC,SAAiC,CAAG,CAAC,CAAC,CAE5C,QAAS,CAAAC,aAAaA,CAAA,CAAG,CACvB,MAAO,CAAAV,YAAY,CAAC,CAAC,CAACW,UACxB,CAEA;AACA;AACA;AACA;AACA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,mBACE1D,IAAA,CAAC4D,SACC;AAAA,KACKI,IAAI,CACTD,GAAG,CAAEA,GAAI,CAAAD,QAAA,CAERA,QAAQ,CACA,CAEf,CAAC,CAED,MAAO,CAAE3D,OAAO,CAAE0D,OAAQ,CAC5B,CAAC,CAAC,CAEF,KAAM,CAAAM,SAAmD,CAAGA,CAAC,CAC3DL,QAAQ,CACR,GAAGE,IACY,CAAC,gBAChBhE,IAAA,CAACT,QAAQ,EAAC6E,QAAQ,CAAEZ,WAAY,CAAAM,QAAA,cAC9B9D,IAAA,CAACyD,aACC;AAAA,KACIO,IAAI,CAAAF,QAAA,CAEPA,QAAQ,CACI,CAAC,CACR,CACX,CAED,MAAO,CAAAK,SACT","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import{serialize}from"cookie";import{useEffect}from"react";import dayjs from"dayjs";import{DAY_MS,HOUR_MS,MIN_MS,SEC_MS,YEAR_MS,timer}from"@dr.pogodin/js-utils";import{useGlobalState}from"@dr.pogodin/react-global-state";import{getSsrContext}from"./globalState.js";/**
|
|
2
2
|
* This react hook wraps Date.now() function in a SSR friendly way,
|
|
3
3
|
* ensuring that all calls to useCurrent() within the same render return
|
|
4
4
|
* exactly the same time (which is retrieved from Date.now() first, and
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* with a finite precision to avoid infinite re-rendering loops.
|
|
8
8
|
*/// TODO: Should we request the state type as generic parameter, to be able
|
|
9
9
|
// to verify the give globalStatePath is correct?
|
|
10
|
-
function useCurrent({autorefresh=false,globalStatePath="currentTime",precision=5*
|
|
10
|
+
export function useCurrent({autorefresh=false,globalStatePath="currentTime",precision=5*SEC_MS}={}){const[now,setter]=useGlobalState(globalStatePath,Date.now);useEffect(()=>{let timerId;const update=()=>{setter(old=>{const neu=Date.now();return Math.abs(neu-old)>precision?neu:old});if(autorefresh)timerId=setTimeout(update,precision)};update();return()=>{if(timerId)clearTimeout(timerId)}},[autorefresh,precision,setter]);return now}/**
|
|
11
11
|
* Wraps the standard Date.getTimezoneOffset() method in a SSR-friendly way.
|
|
12
12
|
* This hook retrieves the offset value at the client side and uses a cookie
|
|
13
13
|
* to pass it to the server in subsequent requests from that user. At the server
|
|
@@ -17,5 +17,5 @@ function useCurrent({autorefresh=false,globalStatePath="currentTime",precision=5
|
|
|
17
17
|
* as the default value.
|
|
18
18
|
*/// TODO: Should we request the state type as generic parameter, to be able
|
|
19
19
|
// to verify the give globalStatePath is correct?
|
|
20
|
-
function useTimezoneOffset({cookieName="timezoneOffset",globalStatePath="timezoneOffset"}={}){const ssrContext=
|
|
20
|
+
export function useTimezoneOffset({cookieName="timezoneOffset",globalStatePath="timezoneOffset"}={}){const ssrContext=getSsrContext(false);const[offset,setOffset]=useGlobalState(globalStatePath,()=>{const value=cookieName&&ssrContext?.req.cookies[cookieName];return value?parseInt(value):0});useEffect(()=>{const date=new Date;const value=date.getTimezoneOffset();setOffset(value);if(cookieName){document.cookie=serialize(cookieName,value.toString(),{path:"/"})}},[cookieName,setOffset]);return offset}const time={DAY_MS,HOUR_MS,MIN_MS,SEC_MS,YEAR_MS,now:Date.now,timer,useCurrent,useTimezoneOffset};export default Object.assign(dayjs,time);
|
|
21
21
|
//# sourceMappingURL=time.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"time.js","names":["
|
|
1
|
+
{"version":3,"file":"time.js","names":["serialize","useEffect","dayjs","DAY_MS","HOUR_MS","MIN_MS","SEC_MS","YEAR_MS","timer","useGlobalState","getSsrContext","useCurrent","autorefresh","globalStatePath","precision","now","setter","Date","timerId","update","old","neu","Math","abs","setTimeout","clearTimeout","useTimezoneOffset","cookieName","ssrContext","offset","setOffset","value","req","cookies","parseInt","date","getTimezoneOffset","document","cookie","toString","path","time","Object","assign"],"sources":["../../../../src/shared/utils/time.ts"],"sourcesContent":["import { serialize } from 'cookie';\nimport { useEffect } from 'react';\nimport dayjs from 'dayjs';\n\nimport {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n timer,\n} from '@dr.pogodin/js-utils';\n\nimport { type ForceT, useGlobalState } from '@dr.pogodin/react-global-state';\n\nimport { getSsrContext } from './globalState';\n\n/**\n * This react hook wraps Date.now() function in a SSR friendly way,\n * ensuring that all calls to useCurrent() within the same render return\n * exactly the same time (which is retrieved from Date.now() first, and\n * then stored in the global state to be reused in all other calls), which\n * is also passed and used in the first client side render, and then updated\n * with a finite precision to avoid infinite re-rendering loops.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useCurrent({\n autorefresh = false,\n globalStatePath = 'currentTime',\n precision = 5 * SEC_MS,\n} = {}): number {\n const [now, setter] = useGlobalState<ForceT, number>(\n globalStatePath,\n Date.now,\n );\n useEffect(() => {\n let timerId: NodeJS.Timeout | undefined;\n const update = (): void => {\n setter((old) => {\n const neu = Date.now();\n return Math.abs(neu - old) > precision ? neu : old;\n });\n if (autorefresh) timerId = setTimeout(update, precision);\n };\n update();\n return (): void => {\n if (timerId) clearTimeout(timerId);\n };\n }, [autorefresh, precision, setter]);\n return now;\n}\n\n/**\n * Wraps the standard Date.getTimezoneOffset() method in a SSR-friendly way.\n * This hook retrieves the offset value at the client side and uses a cookie\n * to pass it to the server in subsequent requests from that user. At the server\n * side the value from cookie is used in renders and passed back to the client\n * via the global state. Prior to the value being known (in the very first\n * request from the user, when the cookie is still missing), zero value is used\n * as the default value.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useTimezoneOffset({\n cookieName = 'timezoneOffset',\n globalStatePath = 'timezoneOffset',\n} = {}): number {\n const ssrContext = getSsrContext(false);\n const [offset, setOffset] = useGlobalState<ForceT, number>(\n globalStatePath,\n () => {\n const value = cookieName\n && ssrContext?.req.cookies[cookieName] as string;\n return value ? parseInt(value) : 0;\n },\n );\n useEffect(() => {\n const date = new Date();\n const value = date.getTimezoneOffset();\n setOffset(value);\n if (cookieName) {\n document.cookie = serialize(cookieName, value.toString(), { path: '/' });\n }\n }, [cookieName, setOffset]);\n return offset;\n}\n\nconst time = {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n now: Date.now,\n timer,\n useCurrent,\n useTimezoneOffset,\n};\n\nexport default Object.assign(dayjs, time);\n"],"mappings":"AAAA,OAASA,SAAS,KAAQ,QAAQ,CAClC,OAASC,SAAS,KAAQ,OAAO,CACjC,MAAO,CAAAC,KAAK,KAAM,OAAO,CAEzB,OACEC,MAAM,CACNC,OAAO,CACPC,MAAM,CACNC,MAAM,CACNC,OAAO,CACPC,KAAK,KACA,sBAAsB,CAE7B,OAAsBC,cAAc,KAAQ,gCAAgC,QAEnEC,aAAa,wBAEtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA;AACA;AACA,MAAO,SAAS,CAAAC,UAAUA,CAAC,CACzBC,WAAW,CAAG,KAAK,CACnBC,eAAe,CAAG,aAAa,CAC/BC,SAAS,CAAG,CAAC,CAAGR,MAClB,CAAC,CAAG,CAAC,CAAC,CAAU,CACd,KAAM,CAACS,GAAG,CAAEC,MAAM,CAAC,CAAGP,cAAc,CAClCI,eAAe,CACfI,IAAI,CAACF,GACP,CAAC,CACDd,SAAS,CAAC,IAAM,CACd,GAAI,CAAAiB,OAAmC,CACvC,KAAM,CAAAC,MAAM,CAAGA,CAAA,GAAY,CACzBH,MAAM,CAAEI,GAAG,EAAK,CACd,KAAM,CAAAC,GAAG,CAAGJ,IAAI,CAACF,GAAG,CAAC,CAAC,CACtB,MAAO,CAAAO,IAAI,CAACC,GAAG,CAACF,GAAG,CAAGD,GAAG,CAAC,CAAGN,SAAS,CAAGO,GAAG,CAAGD,GACjD,CAAC,CAAC,CACF,GAAIR,WAAW,CAAEM,OAAO,CAAGM,UAAU,CAACL,MAAM,CAAEL,SAAS,CACzD,CAAC,CACDK,MAAM,CAAC,CAAC,CACR,MAAO,IAAY,CACjB,GAAID,OAAO,CAAEO,YAAY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AM,CAACzC,KAAK,CAAEuC,IAAI,CAAC","ignoreList":[]}
|
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
"
|
|
1
|
+
import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";// eslint-disable-next-line import/enforce-node-protocol-usage
|
|
2
|
+
import{createRequire}from"module";import{IS_CLIENT_SIDE,IS_SERVER_SIDE}from"./isomorphy/index.js";let require;if(IS_SERVER_SIDE)require=createRequire(import.meta.url);/**
|
|
2
3
|
* Requires the specified module without including it into the bundle during
|
|
3
4
|
* Webpack build.
|
|
4
5
|
* @param modulePath
|
|
5
6
|
* @param [basePath]
|
|
6
7
|
* @return Required module.
|
|
7
|
-
*/function requireWeak(modulePath,// TODO: For now `basePath` can be provided directly as a string here,
|
|
8
|
+
*/export function requireWeak(modulePath,// TODO: For now `basePath` can be provided directly as a string here,
|
|
8
9
|
// for backward compatibility. Deprecate it in future, if any other
|
|
9
10
|
// breaking changes are done for requireWeak().
|
|
10
|
-
basePathOrOptions){if(
|
|
11
|
-
const
|
|
12
|
-
const{resolve}=req("path");const path=basePath?resolve(basePath,modulePath):modulePath;const module=req(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)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;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}/**
|
|
13
13
|
* Resolves specified module path with help of Babel's module resolver.
|
|
14
14
|
* Yes, the function itself just returns its argument to the caller, but Babel
|
|
15
15
|
* is configured to resolve the first argument of resolveWeak(..) function, thus
|
|
16
16
|
* the result will be the resolved path.
|
|
17
17
|
* @param {string} modulePath
|
|
18
18
|
* @return {string} Absolute or relative path to the module.
|
|
19
|
-
*/function resolveWeak(modulePath){return modulePath}
|
|
19
|
+
*/export function resolveWeak(modulePath){return modulePath}
|
|
20
20
|
//# sourceMappingURL=webpack.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webpack.js","names":["
|
|
1
|
+
{"version":3,"file":"webpack.js","names":["createRequire","IS_CLIENT_SIDE","IS_SERVER_SIDE","require","import","meta","url","requireWeak","modulePath","basePathOrOptions","basePath","ops","resolve","path","module","default","def","named","res","Object","entries","forEach","name","value","assigned","undefined","Error","resolveWeak"],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import type PathNS from 'node:path';\n\n// eslint-disable-next-line import/enforce-node-protocol-usage\nimport { createRequire } from 'module';\n\nimport { IS_CLIENT_SIDE, IS_SERVER_SIDE } from './isomorphy';\n\ntype RequireWeakOptionsT = {\n basePath?: string;\n};\n\ntype RequireWeakResT<T> = T extends { default: infer D }\n ? (D extends null | undefined ? T : D & Omit<T, 'default'>)\n : T;\n\nlet require: ((url: string) => unknown) | undefined;\n\nif (IS_SERVER_SIDE) require = createRequire(import.meta.url);\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak<T extends object>(\n modulePath: string,\n\n // TODO: For now `basePath` can be provided directly as a string here,\n // for backward compatibility. Deprecate it in future, if any other\n // breaking changes are done for requireWeak().\n basePathOrOptions?: string | RequireWeakOptionsT,\n): RequireWeakResT<T> | null {\n if (IS_CLIENT_SIDE) return null;\n\n let basePath: string | undefined;\n let ops: RequireWeakOptionsT;\n if (typeof basePathOrOptions === 'string') {\n basePath = basePathOrOptions;\n } else {\n ops = basePathOrOptions ?? {};\n ({ basePath } = ops);\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { resolve } = require!('node:path') as typeof PathNS;\n\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n\n const module = require!(path) as T;\n\n if (!('default' in module) || !module.default) return module as RequireWeakResT<T>;\n\n const { default: def, ...named } = module;\n\n const res = def as RequireWeakResT<T>;\n\n Object.entries(named).forEach(([name, value]) => {\n const assigned = res[name as keyof RequireWeakResT<T>];\n if (assigned === undefined) {\n (res[name as keyof RequireWeakResT<T>] as unknown) = value;\n } else if (assigned !== value) {\n throw Error('Conflict between default and named exports');\n }\n });\n return res;\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":"sMAEA;AACA,OAASA,aAAa,KAAQ,QAAQ,QAE7BC,cAAc,CAAEC,cAAc,4BAUvC,GAAI,CAAAC,OAA+C,CAEnD,GAAID,cAAc,CAAEC,OAAO,CAAGH,aAAa,CAACI,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC,CAE5D;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,WAAWA,CACzBC,UAAkB,CAElB;AACA;AACA;AACAC,iBAAgD,CACrB,CAC3B,GAAIR,cAAc,CAAE,MAAO,KAAI,CAE/B,GAAI,CAAAS,QAA4B,CAChC,GAAI,CAAAC,GAAwB,CAC5B,GAAI,MAAO,CAAAF,iBAAiB,GAAK,QAAQ,CAAE,CACzCC,QAAQ,CAAGD,iBACb,CAAC,IAAM,CACLE,GAAG,CAAGF,iBAAiB,EAAI,CAAC,CAAC,CAC7B,CAAC,CAAEC,QAAS,CAAC,CAAGC,GAAG,CACrB,CAEA;AACA,KAAM,CAAEC,OAAQ,CAAC,CAAGT,OAAO,CAAE,WAAW,CAAkB,CAE1D,KAAM,CAAAU,IAAI,CAAGH,QAAQ,CAAGE,OAAO,CAACF,QAAQ,CAAEF,UAAU,CAAC,CAAGA,UAAU,CAElE,KAAM,CAAAM,MAAM,CAAGX,OAAO,CAAEU,IAAI,CAAM,CAElC,GAAI,EAAE,SAAS,EAAI,CAAAC,MAAM,CAAC,EAAI,CAACA,MAAM,CAACC,OAAO,CAAE,MAAO,CAAAD,MAAM,CAE5D,KAAM,CAAEC,OAAO,CAAEC,GAAG,CAAE,GAAGC,KAAM,CAAC,CAAGH,MAAM,CAEzC,KAAM,CAAAI,GAAG,CAAGF,GAAyB,CAErCG,MAAM,CAACC,OAAO,CAACH,KAAK,CAAC,CAACI,OAAO,CAAC,CAAC,CAACC,IAAI,CAAEC,KAAK,CAAC,GAAK,CAC/C,KAAM,CAAAC,QAAQ,CAAGN,GAAG,CAACI,IAAI,CAA6B,CACtD,GAAIE,QAAQ,GAAKC,SAAS,CAAE,CACzBP,GAAG,CAACI,IAAI,CAA6B,CAAeC,KACvD,CAAC,IAAM,IAAIC,QAAQ,GAAKD,KAAK,CAAE,CAC7B,KAAM,CAAAG,KAAK,CAAC,4CAA4C,CAC1D,CACF,CAAC,CAAC,CACF,MAAO,CAAAR,GACT,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAS,WAAWA,CAACnB,UAAkB,CAAU,CACtD,MAAO,CAAAA,UACT","ignoreList":[]}
|
|
@@ -8,5 +8,5 @@ type OptionsT = {
|
|
|
8
8
|
* @param Application Root application component
|
|
9
9
|
* @param [options={}] Optional. Additional settings.
|
|
10
10
|
*/
|
|
11
|
-
export
|
|
11
|
+
export declare function launchClient(Application: ComponentType, options?: OptionsT): Promise<void>;
|
|
12
12
|
export {};
|
|
@@ -1,10 +1,4 @@
|
|
|
1
|
-
import 'styles/global.scss';
|
|
2
|
-
import type * as ClientM from './client';
|
|
3
|
-
import type * as ServerFactoryM from './server';
|
|
4
|
-
declare const server: (typeof ServerFactoryM.default & Omit<typeof ServerFactoryM, "default">) | null;
|
|
5
|
-
declare const client: typeof ClientM.default | undefined;
|
|
6
1
|
export { type AsyncCollectionT, type AsyncCollectionLoaderT, type AsyncDataEnvelopeT, type AsyncDataLoaderT, type ForceT, type UseAsyncDataOptionsT, type UseAsyncDataResT, type UseGlobalStateResT, type ValueOrInitializerT, getGlobalState, GlobalStateProvider, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState, withGlobalStateType, } from '@dr.pogodin/react-global-state';
|
|
7
2
|
export * from './shared/components';
|
|
8
3
|
export { type BeforeRenderResT, type BeforeRenderT, type ConfigT, type ServerSsrContext, type ServerT, } from './server';
|
|
9
|
-
export { assertEmptyObject,
|
|
10
|
-
export { client, server };
|
|
4
|
+
export { assertEmptyObject, Barrier, Cached, Emitter, getConfig, isomorphy, getSsrContext, type Listener, type ObjectKey, Semaphore, splitComponent, type Theme, themed, ThemeProvider, time, webpack, withRetries, } from './shared/utils';
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import 'source-map-support/register';
|
|
1
|
+
import 'source-map-support/register.js';
|
|
2
2
|
import http from 'node:http';
|
|
3
|
-
import 'raf/polyfill';
|
|
3
|
+
import 'raf/polyfill.js';
|
|
4
4
|
import type { Configuration } from 'webpack';
|
|
5
5
|
import { type OptionsT as ServerOptionsT, type ServerT, getDefaultCspSettings } from './server';
|
|
6
|
-
import {
|
|
6
|
+
import { SCRIPT_LOCATIONS } from './renderer';
|
|
7
|
+
export * from './utils';
|
|
7
8
|
export type { BeforeRenderResT, BeforeRenderT, ConfigT, ServerSsrContext, } from './renderer';
|
|
8
|
-
export {
|
|
9
|
+
export { getDefaultCspSettings, SCRIPT_LOCATIONS, type ServerT, };
|
|
9
10
|
type OptionsT = ServerOptionsT & {
|
|
10
11
|
https?: {
|
|
11
12
|
cert: string;
|
|
@@ -131,13 +132,7 @@ type OptionsT = ServerOptionsT & {
|
|
|
131
132
|
* defaults to 1 second.
|
|
132
133
|
* @return Resolves to an object with created Express and HTTP servers.
|
|
133
134
|
*/
|
|
134
|
-
declare function launchServer(webpackConfig: Configuration, options?: OptionsT): Promise<{
|
|
135
|
+
export declare function launchServer(webpackConfig: Configuration, options?: OptionsT): Promise<{
|
|
135
136
|
expressServer: ServerT;
|
|
136
137
|
httpServer: http.Server;
|
|
137
138
|
}>;
|
|
138
|
-
declare namespace launchServer {
|
|
139
|
-
var SCRIPT_LOCATIONS: typeof import("./renderer").SCRIPT_LOCATIONS;
|
|
140
|
-
var getDefaultCspSettings: typeof import("./server").getDefaultCspSettings;
|
|
141
|
-
var errors: typeof import("./utils/errors");
|
|
142
|
-
}
|
|
143
|
-
export default launchServer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export *
|
|
1
|
+
export * from './errors';
|