@dr.pogodin/react-utils 1.46.2 → 1.47.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/babel.config.js +1 -0
- package/babel.libweb.config.js +16 -0
- package/bin/build.js +16 -10
- package/bin/setup.js +11 -8
- package/build/development/client/index.js.map +1 -1
- package/build/development/index.js +9 -4
- package/build/development/index.js.map +1 -1
- package/build/development/server/Cache.js.map +1 -1
- package/build/development/server/index.js +13 -8
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +15 -8
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +18 -15
- package/build/development/server/server.js.map +1 -1
- package/build/development/shared/components/Button/index.js +6 -6
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +8 -8
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/GenericLink/index.js +5 -1
- package/build/development/shared/components/GenericLink/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +10 -9
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Link.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +8 -6
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/NavLink.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js +6 -6
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +13 -9
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js +6 -6
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js +1 -0
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +7 -7
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +9 -9
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +11 -11
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +12 -12
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +7 -7
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/utils/config.js +5 -6
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/globalState.js.map +1 -1
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js +14 -10
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +18 -21
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/time.js.map +1 -1
- package/build/production/client/index.js.map +1 -1
- package/build/production/index.js +5 -3
- package/build/production/index.js.map +1 -1
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/index.js +5 -5
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +7 -7
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +5 -7
- package/build/production/server/server.js.map +1 -1
- package/build/production/shared/components/Button/index.js +1 -1
- 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 +2 -2
- package/build/production/shared/components/GenericLink/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +1 -1
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Link.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +1 -1
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/NavLink.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js +1 -1
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js +1 -1
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js +1 -1
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +1 -1
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js +1 -1
- 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/utils/config.js +3 -5
- package/build/production/shared/utils/config.js.map +1 -1
- package/build/production/shared/utils/globalState.js.map +1 -1
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +8 -7
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +6 -17
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/time.js.map +1 -1
- package/build/types-code/index.d.ts +2 -2
- package/build/web/client/getInj.js +47 -0
- package/build/web/client/getInj.js.map +1 -0
- package/build/web/client/index.js +31 -0
- package/build/web/client/index.js.map +1 -0
- package/build/web/client/init.js +47 -0
- package/build/web/client/init.js.map +1 -0
- package/build/web/index.js +23 -0
- package/build/web/index.js.map +1 -0
- package/build/web/server/Cache.js +54 -0
- package/build/web/server/Cache.js.map +1 -0
- package/build/web/server/index.js +211 -0
- package/build/web/server/index.js.map +1 -0
- package/build/web/server/renderer.js +516 -0
- package/build/web/server/renderer.js.map +1 -0
- package/build/web/server/server.js +233 -0
- package/build/web/server/server.js.map +1 -0
- package/build/web/server/utils/errors.js +103 -0
- package/build/web/server/utils/errors.js.map +1 -0
- package/build/web/server/utils/index.js +4 -0
- package/build/web/server/utils/index.js.map +1 -0
- package/build/web/shared/components/Button/index.js +90 -0
- package/build/web/shared/components/Button/index.js.map +1 -0
- package/build/web/shared/components/Button/style.scss +54 -0
- package/build/web/shared/components/Checkbox/index.js +35 -0
- package/build/web/shared/components/Checkbox/index.js.map +1 -0
- package/build/web/shared/components/Checkbox/theme.scss +63 -0
- package/build/web/shared/components/GenericLink/index.js +107 -0
- package/build/web/shared/components/GenericLink/index.js.map +1 -0
- package/build/web/shared/components/GenericLink/style.scss +3 -0
- package/build/web/shared/components/Input/index.js +71 -0
- package/build/web/shared/components/Input/index.js.map +1 -0
- package/build/web/shared/components/Input/theme.scss +52 -0
- package/build/web/shared/components/Link.js +20 -0
- package/build/web/shared/components/Link.js.map +1 -0
- package/build/web/shared/components/Modal/base-theme.scss +38 -0
- package/build/web/shared/components/Modal/index.js +128 -0
- package/build/web/shared/components/Modal/index.js.map +1 -0
- package/build/web/shared/components/Modal/styles.scss +3 -0
- package/build/web/shared/components/NavLink.js +13 -0
- package/build/web/shared/components/NavLink.js.map +1 -0
- package/build/web/shared/components/PageLayout/base-theme.scss +30 -0
- package/build/web/shared/components/PageLayout/index.js +38 -0
- package/build/web/shared/components/PageLayout/index.js.map +1 -0
- package/build/web/shared/components/TextArea/index.js +106 -0
- package/build/web/shared/components/TextArea/index.js.map +1 -0
- package/build/web/shared/components/TextArea/style.scss +68 -0
- package/build/web/shared/components/Throbber/index.js +26 -0
- package/build/web/shared/components/Throbber/index.js.map +1 -0
- package/build/web/shared/components/Throbber/theme.scss +26 -0
- package/build/web/shared/components/WithTooltip/Tooltip.js +226 -0
- package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -0
- package/build/web/shared/components/WithTooltip/default-theme.scss +36 -0
- package/build/web/shared/components/WithTooltip/index.js +117 -0
- package/build/web/shared/components/WithTooltip/index.js.map +1 -0
- package/build/web/shared/components/YouTubeVideo/base.scss +15 -0
- package/build/web/shared/components/YouTubeVideo/index.js +56 -0
- package/build/web/shared/components/YouTubeVideo/index.js.map +1 -0
- package/build/web/shared/components/YouTubeVideo/throbber.scss +11 -0
- package/build/web/shared/components/index.js +18 -0
- package/build/web/shared/components/index.js.map +1 -0
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +79 -0
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -0
- package/build/web/shared/components/selectors/CustomDropdown/Options/style.scss +6 -0
- package/build/web/shared/components/selectors/CustomDropdown/index.js +120 -0
- package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -0
- package/build/web/shared/components/selectors/CustomDropdown/theme.scss +118 -0
- package/build/web/shared/components/selectors/NativeDropdown/index.js +82 -0
- package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -0
- package/build/web/shared/components/selectors/NativeDropdown/theme.scss +81 -0
- package/build/web/shared/components/selectors/Switch/index.js +49 -0
- package/build/web/shared/components/selectors/Switch/index.js.map +1 -0
- package/build/web/shared/components/selectors/Switch/theme.scss +39 -0
- package/build/web/shared/components/selectors/common.js +12 -0
- package/build/web/shared/components/selectors/common.js.map +1 -0
- package/build/web/shared/components/selectors/index.js +4 -0
- package/build/web/shared/components/selectors/index.js.map +1 -0
- package/build/web/shared/utils/config.js +19 -0
- package/build/web/shared/utils/config.js.map +1 -0
- package/build/web/shared/utils/globalState.js +15 -0
- package/build/web/shared/utils/globalState.js.map +1 -0
- package/build/web/shared/utils/index.js +13 -0
- package/build/web/shared/utils/index.js.map +1 -0
- package/build/web/shared/utils/isomorphy/buildInfo.js +44 -0
- package/build/web/shared/utils/isomorphy/buildInfo.js.map +1 -0
- package/build/web/shared/utils/isomorphy/environment-check.js +17 -0
- package/build/web/shared/utils/isomorphy/environment-check.js.map +1 -0
- package/build/web/shared/utils/isomorphy/index.js +36 -0
- package/build/web/shared/utils/isomorphy/index.js.map +1 -0
- package/build/web/shared/utils/jest/E2eSsrEnv.js +230 -0
- package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -0
- package/build/web/shared/utils/jest/global.js +4 -0
- package/build/web/shared/utils/jest/global.js.map +1 -0
- package/build/web/shared/utils/jest/index.js +165 -0
- package/build/web/shared/utils/jest/index.js.map +1 -0
- package/build/web/shared/utils/splitComponent.js +218 -0
- package/build/web/shared/utils/splitComponent.js.map +1 -0
- package/build/web/shared/utils/time.js +85 -0
- package/build/web/shared/utils/time.js.map +1 -0
- package/build/web/shared/utils/webpack.js +61 -0
- package/build/web/shared/utils/webpack.js.map +1 -0
- package/build/web/styles/_global/reset.css +52 -0
- package/build/web/styles/_mixins/fonts.scss +40 -0
- package/build/web/styles/_mixins/media.scss +150 -0
- package/build/web/styles/_mixins/typography.scss +83 -0
- package/build/web/styles/global.scss +11 -0
- package/build/web/styles/mixins.scss +6 -0
- package/config/babel/node-ssr.js +5 -2
- package/config/jest/default.js +7 -2
- package/config/webpack/app-base.js +10 -7
- package/config/webpack/app-development.js +3 -2
- package/package.json +24 -34
- package/src/index.ts +9 -7
- package/src/server/index.ts +6 -8
- package/src/server/renderer.tsx +7 -9
- package/src/server/server.ts +13 -15
- package/src/shared/components/Modal/base-theme.scss +1 -1
- package/src/shared/components/PageLayout/base-theme.scss +1 -1
- package/src/shared/utils/config.ts +5 -10
- package/src/shared/utils/jest/E2eSsrEnv.ts +8 -1
- package/src/shared/utils/splitComponent.tsx +17 -20
- package/build/development/__chunk_groups__.json +0 -6
- package/build/development/style.css +0 -909
- package/build/development/web.bundle.js +0 -752
- package/build/production/__chunk_groups__.json +0 -6
- package/build/production/style.css +0 -2
- package/build/production/style.css.map +0 -1
- package/build/production/web.bundle.js +0 -3
- package/build/production/web.bundle.js.LICENSE.txt +0 -9
- package/build/production/web.bundle.js.map +0 -1
- package/dev-styles.js +0 -1
- package/node-entry.js +0 -15
- package/null.js +0 -1
- package/prod-styles.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_reactThemes","_interopRequireDefault","require","_common","_jsxRuntime","defaultTheme","BaseSwitch","label","onChange","options","theme","value","option","Error","optionNodes","iValue","iName","optionValueName","className","onPress","selected","push","
|
|
1
|
+
{"version":3,"file":"index.js","names":["_reactThemes","_interopRequireDefault","require","_common","_jsxRuntime","defaultTheme","BaseSwitch","label","onChange","options","theme","value","option","Error","optionNodes","iValue","iName","optionValueName","className","onPress","selected","push","_jsx","onClick","onKeyDown","e","key","role","tabIndex","children","_jsxs","container","_default","exports","default","themed"],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport {\n type OptionsT,\n type ValueT,\n optionValueName,\n} from '../common';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeKeyT = 'container' | 'label' | 'option' | 'options' | 'selected';\n\ntype PropsT = {\n label?: React.ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<React.ReactNode>>;\n theme: Theme<ThemeKeyT>;\n value?: ValueT;\n};\n\nconst BaseSwitch: React.FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n if (!options || !theme.option) throw Error('Internal error');\n\n const optionNodes: React.ReactNode[] = [];\n for (const option of options) {\n const [iValue, iName] = optionValueName(option);\n\n let className: string = theme.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${theme.selected}`;\n else if (onChange) {\n onPress = () => {\n onChange(iValue);\n };\n }\n\n optionNodes.push(\n onPress\n ? (\n <div\n className={className}\n key={iValue}\n onClick={onPress}\n onKeyDown={(e) => {\n if (e.key === 'Enter') onPress();\n }}\n role=\"button\"\n tabIndex={0}\n >\n {iName}\n </div>\n )\n : <div className={className} key={iValue}>{iName}</div>,\n );\n }\n\n return (\n <div className={theme.container}>\n {label ? <div className={theme.label}>{label}</div> : null}\n\n <div className={theme.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n\nexport default themed(BaseSwitch, 'Switch', defaultTheme);\n"],"mappings":"gLAAA,IAAAA,YAAA,CAAAC,sBAAA,CAAAC,OAAA,8BAEA,IAAAC,OAAA,CAAAD,OAAA,cAMwC,IAAAE,WAAA,CAAAF,OAAA,4BAAAG,YAAA,mIAYxC,KAAM,CAAAC,UAA2C,CAAGA,CAAC,CACnDC,KAAK,CACLC,QAAQ,CACRC,OAAO,CACPC,KAAK,CACLC,KACF,CAAC,GAAK,CACJ,GAAI,CAACF,OAAO,EAAI,CAACC,KAAK,CAACE,MAAM,CAAE,KAAM,CAAAC,KAAK,CAAC,gBAAgB,CAAC,CAE5D,KAAM,CAAAC,WAA8B,CAAG,EAAE,CACzC,IAAK,KAAM,CAAAF,MAAM,GAAI,CAAAH,OAAO,CAAE,CAC5B,KAAM,CAACM,MAAM,CAAEC,KAAK,CAAC,CAAG,GAAAC,uBAAe,EAACL,MAAM,CAAC,CAE/C,GAAI,CAAAM,SAAiB,CAAGR,KAAK,CAACE,MAAM,CACpC,GAAI,CAAAO,OAAiC,CACrC,GAAIJ,MAAM,GAAKJ,KAAK,CAAEO,SAAS,EAAI,IAAIR,KAAK,CAACU,QAAQ,EAAE,CAAC,IACnD,IAAIZ,QAAQ,CAAE,CACjBW,OAAO,CAAGA,CAAA,GAAM,CACdX,QAAQ,CAACO,MAAM,CACjB,CACF,CAEAD,WAAW,CAACO,IAAI,CACdF,OAAO,cAEH,GAAAG,eAAA,SACEJ,SAAS,CAAEA,SAAU,CAErBK,OAAO,CAAEJ,OAAQ,CACjBK,SAAS,CAAGC,CAAC,EAAK,CAChB,GAAIA,CAAC,CAACC,GAAG,GAAK,OAAO,CAAEP,OAAO,CAAC,CACjC,CAAE,CACFQ,IAAI,CAAC,QAAQ,CACbC,QAAQ,CAAE,CAAE,CAAAC,QAAA,CAEXb,KAAK,EARDD,MASF,CAAC,cAEN,GAAAO,eAAA,SAAKJ,SAAS,CAAEA,SAAU,CAAAW,QAAA,CAAeb,KAAK,EAAdD,MAAoB,CAC1D,CACF,CAEA,mBACE,GAAAe,gBAAA,SAAKZ,SAAS,CAAER,KAAK,CAACqB,SAAU,CAAAF,QAAA,EAC7BtB,KAAK,cAAG,GAAAe,eAAA,SAAKJ,SAAS,CAAER,KAAK,CAACH,KAAM,CAAAsB,QAAA,CAAEtB,KAAK,CAAM,CAAC,CAAG,IAAI,cAE1D,GAAAe,eAAA,SAAKJ,SAAS,CAAER,KAAK,CAACD,OAAQ,CAAAoB,QAAA,CAC3Bf,WAAW,CACT,CAAC,EACH,CAET,CAAC,KAAAkB,QAAA,CAAAC,OAAA,CAAAC,OAAA,CAEc,GAAAC,oBAAM,EAAC7B,UAAU,CAAE,QAAQ,CAAED,YAAY,CAAC","ignoreList":[]}
|
|
@@ -1,9 +1,7 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _environmentCheck=require("./isomorphy/environment-check");var _webpack=require("./webpack");/* global document */// TODO: The internal type casting is somewhat messed up here,
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _cookie=require("cookie");var _getInj=_interopRequireDefault(require("../../client/getInj"));var _environmentCheck=require("./isomorphy/environment-check");var _webpack=require("./webpack");/* global document */// TODO: The internal type casting is somewhat messed up here,
|
|
2
2
|
// to be corrected later.
|
|
3
|
-
const config=(_environmentCheck.IS_CLIENT_SIDE
|
|
4
|
-
?require("../../client/getInj").default().CONFIG:(0,_webpack.requireWeak)("config"))??{};// The safeguard for "document" is necessary because in non-Node environments,
|
|
3
|
+
const config=(_environmentCheck.IS_CLIENT_SIDE?(0,_getInj.default)().CONFIG:(0,_webpack.requireWeak)("config"))??{};// The safeguard for "document" is necessary because in non-Node environments,
|
|
5
4
|
// like React Native, IS_CLIENT_SIDE is "true", however "document" and a bunch
|
|
6
5
|
// of other browser-world features are not available.
|
|
7
|
-
if(_environmentCheck.IS_CLIENT_SIDE&&typeof document!=="undefined"){
|
|
8
|
-
const cookie=require("cookie");config.CSRF=cookie.parse(document.cookie).csrfToken}var _default=exports.default=config;
|
|
6
|
+
if(_environmentCheck.IS_CLIENT_SIDE&&typeof document!=="undefined"){config.CSRF=(0,_cookie.parse)(document.cookie).csrfToken}var _default=exports.default=config;
|
|
9
7
|
//# sourceMappingURL=config.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","names":["
|
|
1
|
+
{"version":3,"file":"config.js","names":["_cookie","require","_getInj","_interopRequireDefault","_environmentCheck","_webpack","config","IS_CLIENT_SIDE","clientGetInj","CONFIG","requireWeak","document","CSRF","parse","cookie","csrfToken","_default","exports","default"],"sources":["../../../../src/shared/utils/config.ts"],"sourcesContent":["/* global document */\n\nimport { parse } from 'cookie';\n\nimport clientGetInj from '../../client/getInj';\n\nimport { IS_CLIENT_SIDE } from './isomorphy/environment-check';\nimport { requireWeak } from './webpack';\n\n// TODO: The internal type casting is somewhat messed up here,\n// to be corrected later.\nconst config: Record<string, unknown> = (\n IS_CLIENT_SIDE ? clientGetInj().CONFIG : requireWeak('config')\n) as (Record<string, unknown> | undefined) ?? ({} as Record<string, unknown>);\n\n// The safeguard for \"document\" is necessary because in non-Node environments,\n// like React Native, IS_CLIENT_SIDE is \"true\", however \"document\" and a bunch\n// of other browser-world features are not available.\nif (IS_CLIENT_SIDE && typeof document !== 'undefined') {\n config.CSRF = parse(document.cookie).csrfToken;\n}\n\nexport default config;\n"],"mappings":"gLAEA,IAAAA,OAAA,CAAAC,OAAA,WAEA,IAAAC,OAAA,CAAAC,sBAAA,CAAAF,OAAA,yBAEA,IAAAG,iBAAA,CAAAH,OAAA,kCACA,IAAAI,QAAA,CAAAJ,OAAA,cAPA,qBASA;AACA;AACA,KAAM,CAAAK,MAA+B,CAAG,CACtCC,gCAAc,CAAG,GAAAC,eAAY,EAAC,CAAC,CAACC,MAAM,CAAG,GAAAC,oBAAW,EAAC,QAAQ,CAAC,GACjB,CAAC,CAA6B,CAE7E;AACA;AACA;AACA,GAAIH,gCAAc,EAAI,MAAO,CAAAI,QAAQ,GAAK,WAAW,CAAE,CACrDL,MAAM,CAACM,IAAI,CAAG,GAAAC,aAAK,EAACF,QAAQ,CAACG,MAAM,CAAC,CAACC,SACvC,KAAAC,QAAA,CAAAC,OAAA,CAAAC,OAAA,CAEeZ,MAAM","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"globalState.js","names":["_reactGlobalState","require","getSsrContext","withGlobalStateType","exports"],"sources":["../../../../src/shared/utils/globalState.ts"],"sourcesContent":["import type { Request } from 'express';\n\nimport { type SsrContext, withGlobalStateType } from '@dr.pogodin/react-global-state';\n\n/** Mapping \"chunkName\" > array of asset paths. */\nexport type ChunkGroupsT = Record<string, string[]>;\n\n// The type of data object injected by server into generated markup.\nexport type InjT = {\n CHUNK_GROUPS?: ChunkGroupsT;\n CONFIG?: Record<string, unknown>;\n ISTATE?: unknown;\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n REACT_UTILS_INJECTION?: InjT;\n }\n}\n\n// TODO: Not 100% sure now, whether it indeed can be replaced by type,\n// or do we really need it to be an interface. Keeping the interface for now.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface SsrContextT<StateT> extends SsrContext<StateT> {\n chunkGroups: ChunkGroupsT;\n chunks: string[];\n\n /** If set at the end of SSR, the rendered will trigger\n * server-side redirect to this URL (and use the status\n * code). */\n redirectTo?: string;\n\n req: Request;\n status: number;\n}\n\nconst {\n getSsrContext,\n} = withGlobalStateType<unknown, SsrContextT<unknown>>();\n\nexport {\n getSsrContext,\n};\n"],"mappings":"mGAEA,IAAAA,iBAAA,CAAAC,OAAA,mCAEA,kDAGA;AAcA;AACA;AACA;AAcA,KAAM,CACJC,aACF,CAAC,CAAG,GAAAC,qCAAmB,EAAgC,CAAC,
|
|
1
|
+
{"version":3,"file":"globalState.js","names":["_reactGlobalState","require","getSsrContext","withGlobalStateType","exports"],"sources":["../../../../src/shared/utils/globalState.ts"],"sourcesContent":["import type { Request } from 'express';\n\nimport { type SsrContext, withGlobalStateType } from '@dr.pogodin/react-global-state';\n\n/** Mapping \"chunkName\" > array of asset paths. */\nexport type ChunkGroupsT = Record<string, string[]>;\n\n// The type of data object injected by server into generated markup.\nexport type InjT = {\n CHUNK_GROUPS?: ChunkGroupsT;\n CONFIG?: Record<string, unknown>;\n ISTATE?: unknown;\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n REACT_UTILS_INJECTION?: InjT;\n }\n}\n\n// TODO: Not 100% sure now, whether it indeed can be replaced by type,\n// or do we really need it to be an interface. Keeping the interface for now.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface SsrContextT<StateT> extends SsrContext<StateT> {\n chunkGroups: ChunkGroupsT;\n chunks: string[];\n\n /** If set at the end of SSR, the rendered will trigger\n * server-side redirect to this URL (and use the status\n * code). */\n redirectTo?: string;\n\n req: Request;\n status: number;\n}\n\nconst {\n getSsrContext,\n} = withGlobalStateType<unknown, SsrContextT<unknown>>();\n\nexport {\n getSsrContext,\n};\n"],"mappings":"mGAEA,IAAAA,iBAAA,CAAAC,OAAA,mCAEA,kDAGA;AAcA;AACA;AACA;AAcA,KAAM,CACJC,aACF,CAAC,CAAG,GAAAC,qCAAmB,EAAgC,CAAC,CAAAC,OAAA,CAAAF,aAAA,CAAAA,aAAA","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_reactThemes","_interopRequireWildcard","require","_config","_interopRequireDefault","isomorphy","exports","_time","webpack","_jsUtils","_globalState","_splitComponent","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","themed","themedImpl","COMPOSE","PRIORITY"],"sources":["../../../../src/shared/utils/index.ts"],"sourcesContent":["import themedImpl, {\n COMPOSE,\n PRIORITY,\n type Theme,\n ThemeProvider,\n} from '@dr.pogodin/react-themes';\n\nimport config from './config';\nimport * as isomorphy from './isomorphy';\nimport time from './time';\nimport * as webpack from './webpack';\n\nexport {\n assertEmptyObject,\n type Listener,\n type ObjectKey,\n Barrier,\n Cached,\n Emitter,\n Semaphore,\n withRetries,\n} from '@dr.pogodin/js-utils';\n\nexport { getSsrContext } from './globalState';\nexport { default as splitComponent } from './splitComponent';\n\ntype ThemedT = typeof themedImpl & {\n COMPOSE: typeof COMPOSE;\n PRIORITY: typeof PRIORITY;\n};\n\nconst themed: ThemedT = themedImpl as ThemedT;\n\nthemed.COMPOSE = COMPOSE;\nthemed.PRIORITY = PRIORITY;\n\nexport {\n type Theme,\n config,\n isomorphy,\n themed,\n ThemeProvider,\n time,\n webpack,\n};\n"],"mappings":"o2CAAA,IAAAA,YAAA,CAAAC,uBAAA,CAAAC,OAAA,8BAOA,IAAAC,OAAA,CAAAC,sBAAA,CAAAF,OAAA,cACA,IAAAG,SAAA,CAAAJ,uBAAA,CAAAC,OAAA,
|
|
1
|
+
{"version":3,"file":"index.js","names":["_reactThemes","_interopRequireWildcard","require","_config","_interopRequireDefault","isomorphy","exports","_time","webpack","_jsUtils","_globalState","_splitComponent","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","themed","themedImpl","COMPOSE","PRIORITY"],"sources":["../../../../src/shared/utils/index.ts"],"sourcesContent":["import themedImpl, {\n COMPOSE,\n PRIORITY,\n type Theme,\n ThemeProvider,\n} from '@dr.pogodin/react-themes';\n\nimport config from './config';\nimport * as isomorphy from './isomorphy';\nimport time from './time';\nimport * as webpack from './webpack';\n\nexport {\n assertEmptyObject,\n type Listener,\n type ObjectKey,\n Barrier,\n Cached,\n Emitter,\n Semaphore,\n withRetries,\n} from '@dr.pogodin/js-utils';\n\nexport { getSsrContext } from './globalState';\nexport { default as splitComponent } from './splitComponent';\n\ntype ThemedT = typeof themedImpl & {\n COMPOSE: typeof COMPOSE;\n PRIORITY: typeof PRIORITY;\n};\n\nconst themed: ThemedT = themedImpl as ThemedT;\n\nthemed.COMPOSE = COMPOSE;\nthemed.PRIORITY = PRIORITY;\n\nexport {\n type Theme,\n config,\n isomorphy,\n themed,\n ThemeProvider,\n time,\n webpack,\n};\n"],"mappings":"o2CAAA,IAAAA,YAAA,CAAAC,uBAAA,CAAAC,OAAA,8BAOA,IAAAC,OAAA,CAAAC,sBAAA,CAAAF,OAAA,cACA,IAAAG,SAAA,CAAAJ,uBAAA,CAAAC,OAAA,iBAAqBI,OAAA,CAAAD,SAAA,CAAAA,SAAA,CACrB,IAAAE,KAAA,CAAAH,sBAAA,CAAAF,OAAA,YACA,IAAAM,OAAA,CAAAP,uBAAA,CAAAC,OAAA,eAAmBI,OAAA,CAAAE,OAAA,CAAAA,OAAA,CAEnB,IAAAC,QAAA,CAAAP,OAAA,yBAWA,IAAAQ,YAAA,CAAAR,OAAA,kBACA,IAAAS,eAAA,CAAAP,sBAAA,CAAAF,OAAA,sBAAkC,SAAAD,wBAAAW,CAAA,CAAAC,CAAA,wBAAAC,OAAA,KAAAC,CAAA,KAAAD,OAAA,CAAAE,CAAA,KAAAF,OAAA,QAAAb,uBAAA,SAAAA,CAAAW,CAAA,CAAAC,CAAA,MAAAA,CAAA,EAAAD,CAAA,EAAAA,CAAA,CAAAK,UAAA,QAAAL,CAAA,KAAAM,CAAA,CAAAC,CAAA,CAAAC,CAAA,EAAAC,SAAA,MAAAC,OAAA,CAAAV,CAAA,YAAAA,CAAA,mBAAAA,CAAA,qBAAAA,CAAA,QAAAQ,CAAA,IAAAF,CAAA,CAAAL,CAAA,CAAAG,CAAA,CAAAD,CAAA,KAAAG,CAAA,CAAAK,GAAA,CAAAX,CAAA,SAAAM,CAAA,CAAAM,GAAA,CAAAZ,CAAA,EAAAM,CAAA,CAAAO,GAAA,CAAAb,CAAA,CAAAQ,CAAA,YAAAP,CAAA,IAAAD,CAAA,aAAAC,CAAA,KAAAa,cAAA,CAAAC,IAAA,CAAAf,CAAA,CAAAC,CAAA,KAAAM,CAAA,EAAAD,CAAA,CAAAU,MAAA,CAAAC,cAAA,GAAAD,MAAA,CAAAE,wBAAA,CAAAlB,CAAA,CAAAC,CAAA,KAAAM,CAAA,CAAAK,GAAA,EAAAL,CAAA,CAAAM,GAAA,EAAAP,CAAA,CAAAE,CAAA,CAAAP,CAAA,CAAAM,CAAA,EAAAC,CAAA,CAAAP,CAAA,EAAAD,CAAA,CAAAC,CAAA,UAAAO,CAAA,GAAAR,CAAA,CAAAC,CAAA,EAOlC,KAAM,CAAAkB,MAAe,CAAAzB,OAAA,CAAAyB,MAAA,CAAGC,oBAAqB,CAE7CD,MAAM,CAACE,OAAO,CAAGA,oBAAO,CACxBF,MAAM,CAACG,QAAQ,CAAGA,qBAAQ","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _nodePath=_interopRequireDefault(require("node:path"));var
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _nodePath=_interopRequireDefault(require("node:path"));var _defaults=_interopRequireDefault(require("lodash/defaults"));var _set=_interopRequireDefault(require("lodash/set"));var _experimentalWorker=_interopRequireDefault(require("@babel/register/experimental-worker"));var _jestEnvironmentJsdom=_interopRequireDefault(require("jest-environment-jsdom"));var _memfs=require("memfs");var _webpack=_interopRequireDefault(require("webpack"));var _renderer=_interopRequireDefault(require("../../../server/renderer"));var _buildInfo=require("../isomorphy/buildInfo");/**
|
|
2
2
|
* Jest environment for end-to-end SSR and client-side testing. It relies on
|
|
3
3
|
* the standard react-utils mechanics to execute SSR of given scene, and also
|
|
4
4
|
* Webpack build of the code for client-side execution, it further exposes
|
|
@@ -14,10 +14,11 @@
|
|
|
14
14
|
// TODO: We need to add correct typing for environment options.
|
|
15
15
|
// As this environment is a part of the Jest testing utils,
|
|
16
16
|
// we assume development dependencies are available when it is used.
|
|
17
|
-
/* eslint-disable import/no-extraneous-dependencies *//* eslint-enable import/no-extraneous-dependencies */
|
|
17
|
+
/* eslint-disable import/no-extraneous-dependencies *//* eslint-enable import/no-extraneous-dependencies */function noop(){// NOOP
|
|
18
|
+
}class E2eSsrEnv extends _jestEnvironmentJsdom.default{/**
|
|
18
19
|
* Loads Webpack config, and exposes it to the environment via global
|
|
19
20
|
* webpackConfig object.
|
|
20
|
-
*/loadWebpackConfig(){const optionsString=this.pragmas["webpack-config-options"];const options=optionsString?JSON.parse(optionsString):{};(0,
|
|
21
|
+
*/loadWebpackConfig(){const optionsString=this.pragmas["webpack-config-options"];const options=optionsString?JSON.parse(optionsString):{};(0,_defaults.default)(options,{context:this.testFolder,fs:this.global.webpackOutputFs});const factoryPath=this.pragmas["webpack-config-factory"];// eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports
|
|
21
22
|
let factory=require(_nodePath.default.resolve(this.rootDir,factoryPath));factory="default"in factory?factory.default:factory;this.global.webpackConfig=factory(options);const fs=this.global.webpackOutputFs;let buildInfo=`${options.context}/.build-info`;if(fs.existsSync(buildInfo)){buildInfo=fs.readFileSync(buildInfo,"utf8");this.global.buildInfo=JSON.parse(buildInfo)}}/**
|
|
22
23
|
* Executes Webpack build.
|
|
23
24
|
* @return {Promise}
|
|
@@ -29,19 +30,19 @@ console.error(stats.toJson().errors);fail(Error("Webpack compilation failed"))}t
|
|
|
29
30
|
// explicitly passed to the server-side renderer alongside the request,
|
|
30
31
|
// so that it can to pick up asset paths for different named chunks.
|
|
31
32
|
this.webpackStats=stats;done()})})}async runSsr(){const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON.parse(optionsString):{};// TODO: This is temporary to shortcut the logging added to SSR.
|
|
32
|
-
options.logger??={debug:
|
|
33
|
+
options.logger??={debug:noop,info:noop,log:noop,warn:noop};options.buildInfo??=this.global.buildInfo;let cleanup;if(options.entry){const p=_nodePath.default.resolve(this.testFolder,options.entry);// TODO: This sure can be replaced by a dynamic import().
|
|
33
34
|
// eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports
|
|
34
35
|
const module=require(p);if("cleanup"in module)cleanup=module.cleanup;const exportName=options.entryExportName||"default";if(exportName in module){options.Application=module[exportName]}}const renderer=(0,_renderer.default)(this.global.webpackConfig,options);let status=200;// OK
|
|
35
36
|
const markup=await new Promise((done,fail)=>{void renderer(this.ssrRequest,// TODO: This will do for now, with the current implementation of
|
|
36
37
|
// the renderer, but it will require a rework once the renderer is
|
|
37
38
|
// updated to do streaming.
|
|
38
|
-
{cookie:
|
|
39
|
+
{cookie:noop,send:done,set:noop,status:value=>{status=value},// This is how up-to-date Webpack stats are passed to the server in
|
|
39
40
|
// development mode, and we use this here always, instead of having
|
|
40
41
|
// to pass some information via filesystem.
|
|
41
42
|
locals:{webpack:{devMiddleware:{stats:this.webpackStats}}}},error=>{// TODO: Strictly speaking, that error as Error casting is not all
|
|
42
43
|
// correct, but it works, so no need to spend time on it right now.
|
|
43
|
-
if(error)fail(error);else done("")})});this.global.ssrMarkup=markup;this.global.ssrOptions=options;this.global.ssrStatus=status;if(cleanup)cleanup()}constructor(config,context){const pragmas=context.docblockPragmas;const requestString=pragmas["ssr-request"];const request=requestString?JSON.parse(requestString):{};request.url??="/";request.csrfToken=
|
|
44
|
-
(0,
|
|
44
|
+
if(error)fail(error);else done("")})});this.global.ssrMarkup=markup;this.global.ssrOptions=options;this.global.ssrStatus=status;if(cleanup)cleanup()}constructor(config,context){const pragmas=context.docblockPragmas;const requestString=pragmas["ssr-request"];const request=requestString?JSON.parse(requestString):{};request.url??="/";request.csrfToken=noop;// This ensures the initial JsDom URL matches the value we use for SSR.
|
|
45
|
+
(0,_set.default)(config.projectConfig,"testEnvironmentOptions.url",`http://localhost${request.url}`);super(config,context);this.global.dom=this.dom;this.global.webpackOutputFs=(0,_memfs.createFsFromVolume)(new _memfs.Volume);// Extracts necessary settings from config and context.
|
|
45
46
|
const{projectConfig}=config;this.rootDir=projectConfig.rootDir;this.testFolder=_nodePath.default.dirname(context.testPath);this.withSsr=!pragmas["no-ssr"];this.ssrRequest=request;this.pragmas=pragmas;// The usual "babel-jest" transformation setup does not apply to
|
|
46
47
|
// the environment code and imports from it, this workaround enables it.
|
|
47
48
|
const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON.parse(optionsString):{};let root;switch(options.root){case"TEST":root=this.testFolder;break;default:root=process.cwd()}(0,_experimentalWorker.default)({envName:options.babelEnv,extensions:[".js",".jsx",".ts",".tsx",".svg"],root})}async setup(){await super.setup();await this.runWebpack();// NOTE: It is possible that the Webpack run above, and the SSR run below
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"E2eSsrEnv.js","names":["_nodePath","_interopRequireDefault","require","_lodash","_experimentalWorker","_jestEnvironmentJsdom","_memfs","_webpack","_renderer","_buildInfo","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","noop","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';\nimport { defaults, noop, set } from 'lodash';\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\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,sB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AI,CAACX,OAAO,CAAE,KAAM,KAAI,CAACzC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC7B,MAAM,CAACkF,6BAA6B,CAAG,IAC9C,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAkB,CAC9B,MAAO,KAAI,CAACnF,MAAM,CAACkF,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAACzG,OAAO,CAACmG,KAAK,CAAC,CAACO,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,CAAA3G,OAAO,CAACmG,KAAK,CAACQ,GAAG,CAC1B,CAAC,CAAC,CACFb,2BAAQ,CAACc,MAAM,CAAC,CAAC,CACjB,KAAM,MAAK,CAACL,QAAQ,CAAC,CACvB,CACF,CAACM,OAAA,CAAAlF,OAAA,CAAAnB,SAAA","ignoreList":[]}
|
|
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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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,15 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.bookStyleSheets=bookStyleSheets;exports.default=splitComponent;exports.freeStyleSheets=freeStyleSheets;var _react=require("react");var _jsUtils=require("@dr.pogodin/js-utils");var _globalState=require("./globalState");var _isomorphy=require("./isomorphy");var _jsxRuntime=require("react/jsx-runtime")
|
|
2
|
-
// the module; at the server-side we only can get them within React render flow.
|
|
3
|
-
// Thus, we set and use the following variable at the client-side, and then when
|
|
4
|
-
// needed on the server side, we'll fetch it differently.
|
|
5
|
-
let clientChunkGroups;if(_isomorphy.IS_CLIENT_SIDE){// TODO: Rewrite to avoid these overrides of ESLint rules.
|
|
6
|
-
/* eslint-disable @typescript-eslint/no-unsafe-assignment,
|
|
7
|
-
@typescript-eslint/no-require-imports,
|
|
8
|
-
@typescript-eslint/no-unsafe-call,
|
|
9
|
-
@typescript-eslint/no-unsafe-member-access */clientChunkGroups=require("../../client/getInj").default().CHUNK_GROUPS??{};/* eslint-enable @typescript-eslint/no-unsafe-assignment,
|
|
10
|
-
@typescript-eslint/no-require-imports,
|
|
11
|
-
@typescript-eslint/no-unsafe-call,
|
|
12
|
-
@typescript-eslint/no-unsafe-member-access */}const refCounts={};function getPublicPath(){return(0,_isomorphy.getBuildInfo)().publicPath}/**
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.bookStyleSheets=bookStyleSheets;exports.default=splitComponent;exports.freeStyleSheets=freeStyleSheets;var _react=require("react");var _jsUtils=require("@dr.pogodin/js-utils");var _globalState=require("./globalState");var _isomorphy=require("./isomorphy");var _jsxRuntime=require("react/jsx-runtime");function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap,n=new WeakMap;return(_interopRequireWildcard=function(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f)}for(const t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(i.get||i.set)?o(f,t,i):f[t]=e[t]);return f})(e,t)}/* global document */function getClientChunkGroups(){if(!_isomorphy.IS_CLIENT_SIDE)return undefined;return(async()=>{const{default:getInj}=await Promise.resolve().then(()=>_interopRequireWildcard(require(/* webpackChunkName: "react-utils-client-side-code" */"../../client/getInj")));return getInj().CHUNK_GROUPS??{}})()}const refCounts={};function getPublicPath(){return(0,_isomorphy.getBuildInfo)().publicPath}/**
|
|
13
2
|
* Client-side only! Ensures the specified CSS stylesheet is loaded into
|
|
14
3
|
* the document; loads if it is missing; and does simple reference counting
|
|
15
4
|
* to facilitate future clean-up.
|
|
@@ -44,16 +33,16 @@ const usedChunkNames=new Set;/**
|
|
|
44
33
|
* @param {function} options.getComponent
|
|
45
34
|
* @param {React.Element} [options.placeholder]
|
|
46
35
|
* @return {React.ElementType}
|
|
47
|
-
*/function splitComponent({chunkName,getComponent,placeholder}){//
|
|
48
|
-
if(
|
|
49
|
-
if(
|
|
36
|
+
*/function splitComponent({chunkName,getComponent,placeholder}){// The correct usage of splitComponent() assumes a single call per chunk.
|
|
37
|
+
if(usedChunkNames.has(chunkName)){throw Error(`Repeated splitComponent() call for the chunk "${chunkName}"`)}else usedChunkNames.add(chunkName);const LazyComponent=/*#__PURE__*/(0,_react.lazy)(async()=>{const clientChunkGroups=await getClientChunkGroups();// On the client side we can check right away if the chunk name is known.
|
|
38
|
+
if(_isomorphy.IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");assertChunkName(chunkName,clientChunkGroups)}const resolved=await getComponent();const Component="default"in resolved?resolved.default:resolved;// This pre-loads necessary stylesheets prior to the first mount of
|
|
50
39
|
// the component (the lazy load function is executed by React one at
|
|
51
40
|
// the frist mount).
|
|
52
|
-
if(_isomorphy.IS_CLIENT_SIDE){await bookStyleSheets(chunkName,clientChunkGroups,false)}const Wrapper=({children,ref,...rest})=>{// On the server side we'll assert the chunk name here,
|
|
41
|
+
if(_isomorphy.IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");await bookStyleSheets(chunkName,clientChunkGroups,false)}const Wrapper=({children,ref,...rest})=>{// On the server side we'll assert the chunk name here,
|
|
53
42
|
// and also push it to the SSR chunks array.
|
|
54
43
|
if(_isomorphy.IS_SERVER_SIDE){const{chunkGroups,chunks}=(0,_globalState.getSsrContext)();assertChunkName(chunkName,chunkGroups);if(!chunks.includes(chunkName))chunks.push(chunkName)}// This takes care about stylesheets management every time an instance of
|
|
55
44
|
// this component is mounted / unmounted.
|
|
56
|
-
(0,_react.useInsertionEffect)(()=>{void bookStyleSheets(chunkName,clientChunkGroups,true);return()=>{freeStyleSheets(chunkName,clientChunkGroups)}},[]);return/*#__PURE__*/(0,_jsxRuntime.jsx)(Component// eslint-disable-next-line react/jsx-props-no-spreading
|
|
45
|
+
(0,_react.useInsertionEffect)(()=>{if(!clientChunkGroups)throw Error("Internal error");void bookStyleSheets(chunkName,clientChunkGroups,true);return()=>{freeStyleSheets(chunkName,clientChunkGroups)}},[]);return/*#__PURE__*/(0,_jsxRuntime.jsx)(Component// eslint-disable-next-line react/jsx-props-no-spreading
|
|
57
46
|
,{...rest,ref:ref,children:children})};return{default:Wrapper}});const CodeSplit=({children,...rest})=>/*#__PURE__*/(0,_jsxRuntime.jsx)(_react.Suspense,{fallback:placeholder,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(LazyComponent// eslint-disable-next-line react/jsx-props-no-spreading
|
|
58
47
|
,{...rest,children:children})});return CodeSplit}
|
|
59
48
|
//# sourceMappingURL=splitComponent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitComponent.js","names":["_react","require","_jsUtils","_globalState","_isomorphy","_jsxRuntime","clientChunkGroups","IS_CLIENT_SIDE","default","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","resolved","Component","Wrapper","children","ref","rest","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","jsx","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\n// Note: At the client side we can get chunk groups immediately when loading\n// the module; at the server-side we only can get them within React render flow.\n// Thus, we set and use the following variable at the client-side, and then when\n// needed on the server side, we'll fetch it differently.\nlet clientChunkGroups: ChunkGroupsT;\n\nif (IS_CLIENT_SIDE) {\n // TODO: Rewrite to avoid these overrides of ESLint rules.\n /* eslint-disable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n clientChunkGroups = require('client/getInj').default().CHUNK_GROUPS ?? {};\n /* eslint-enable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) assertChunkName(chunkName, clientChunkGroups);\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":"qLAEA,IAAAA,MAAA,CAAAC,OAAA,UAUA,IAAAC,QAAA,CAAAD,OAAA,yBAEA,IAAAE,YAAA,CAAAF,OAAA,kBAEA,IAAAG,UAAA,CAAAH,OAAA,gBAIqB,IAAAI,WAAA,CAAAJ,OAAA,sBApBrB,qBAsBA;AACA;AACA;AACA;AACA,GAAI,CAAAK,iBAA+B,CAEnC,GAAIC,yBAAc,CAAE,CAClB;AACA;AACF;AACA;AACA,iDACED,iBAAiB,CAAGL,OAAO,sBAAgB,CAAC,CAACO,OAAO,CAAC,CAAC,CAACC,YAAY,EAAI,CAAC,CAAC,CACzE;AACF;AACA;AACA,iDACA,CAEA,KAAM,CAAAC,SAAiC,CAAG,CAAC,CAAC,CAE5C,QAAS,CAAAC,aAAaA,CAAA,CAAG,CACvB,MAAO,GAAAC,uBAAY,EAAC,CAAC,CAACC,UACxB,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,CAAAC,cAAcA,CACrBC,IAAY,CACZC,YAAyB,CACzBC,QAAiB,CACU,CAC3B,GAAI,CAAAC,GAA8B,CAClC,KAAM,CAAAC,IAAI,CAAG,GAAGR,aAAa,CAAC,CAAC,IAAII,IAAI,EAAE,CACzC,KAAM,CAAAK,QAAQ,CAAG,GAAGC,QAAQ,CAACC,QAAQ,CAACC,MAAM,GAAGJ,IAAI,EAAE,CAErD,GAAI,CAACH,YAAY,CAACQ,GAAG,CAACJ,QAAQ,CAAC,CAAE,CAC/B,GAAI,CAAAK,IAAI,CAAGJ,QAAQ,CAACK,aAAa,CAAC,cAAcP,IAAI,IAAI,CAAC,CAEzD,GAAI,CAACM,IAAI,CAAE,CACTA,IAAI,CAAGJ,QAAQ,CAACM,aAAa,CAAC,MAAM,CAAC,CACrCF,IAAI,CAACG,YAAY,CAAC,KA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AE,CAChD/B,eAAe,CAACC,SAAS,CAAEC,WAAW,CAAC,CACvC,GAAI,CAAC4B,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,GAAAD,WAAA,CAAAsE,GAAA,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,GAAAhE,WAAA,CAAAsE,GAAA,EAAC3E,MAAA,CAAA6E,QAAQ,EAACC,QAAQ,CAAEjB,WAAY,CAAAM,QAAA,cAC9B,GAAA9D,WAAA,CAAAsE,GAAA,EAACb,aACC;AAAA,KACIO,IAAI,CAAAF,QAAA,CAEPA,QAAQ,CACI,CAAC,CACR,CACX,CAED,MAAO,CAAAS,SACT","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"splitComponent.js","names":["_react","require","_jsUtils","_globalState","_isomorphy","_jsxRuntime","_interopRequireWildcard","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","getClientChunkGroups","IS_CLIENT_SIDE","undefined","getInj","Promise","resolve","then","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","Error","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","asset","endsWith","promise","push","length","allSettled","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","clientChunkGroups","resolved","Component","Wrapper","children","ref","rest","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","_jsx","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\nfunction getClientChunkGroups(): Promise<ChunkGroupsT> | undefined {\n if (!IS_CLIENT_SIDE) return undefined;\n\n return (async () => {\n const { default: getInj } = await import(/* webpackChunkName: \"react-utils-client-side-code\" */ '../../client/getInj');\n return getInj().CHUNK_GROUPS ?? {};\n })();\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const clientChunkGroups = await getClientChunkGroups();\n\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n assertChunkName(chunkName, clientChunkGroups);\n }\n\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":"qLAEA,IAAAA,MAAA,CAAAC,OAAA,UAUA,IAAAC,QAAA,CAAAD,OAAA,yBAEA,IAAAE,YAAA,CAAAF,OAAA,kBAEA,IAAAG,UAAA,CAAAH,OAAA,gBAIqB,IAAAI,WAAA,CAAAJ,OAAA,+BAAAK,wBAAAC,CAAA,CAAAC,CAAA,wBAAAC,OAAA,KAAAC,CAAA,KAAAD,OAAA,CAAAE,CAAA,KAAAF,OAAA,QAAAH,uBAAA,SAAAA,CAAAC,CAAA,CAAAC,CAAA,MAAAA,CAAA,EAAAD,CAAA,EAAAA,CAAA,CAAAK,UAAA,QAAAL,CAAA,KAAAM,CAAA,CAAAC,CAAA,CAAAC,CAAA,EAAAC,SAAA,MAAAC,OAAA,CAAAV,CAAA,YAAAA,CAAA,mBAAAA,CAAA,qBAAAA,CAAA,QAAAQ,CAAA,IAAAF,CAAA,CAAAL,CAAA,CAAAG,CAAA,CAAAD,CAAA,KAAAG,CAAA,CAAAK,GA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DT,QAAQ,CACR,GAAGE,IACY,CAAC,gBAChB,GAAAM,eAAA,EAACE,eAAQ,EAACC,QAAQ,CAAElB,WAAY,CAAAO,QAAA,cAC9B,GAAAQ,eAAA,EAACd,aACC;AAAA,KACIQ,IAAI,CAAAF,QAAA,CAEPA,QAAQ,CACI,CAAC,CACR,CACX,CAED,MAAO,CAAAS,SACT","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"time.js","names":["_cookie","require","_react","_dayjs","_interopRequireDefault","_jsUtils","_reactGlobalState","_globalState","useCurrent","autorefresh","globalStatePath","precision","SEC_MS","now","setter","useGlobalState","Date","useEffect","timerId","update","old","neu","Math","abs","setTimeout","clearTimeout","useTimezoneOffset","cookieName","ssrContext","getSsrContext","offset","setOffset","value","req","cookies","parseInt","date","getTimezoneOffset","document","cookie","serialize","toString","path","time","DAY_MS","HOUR_MS","MIN_MS","YEAR_MS","timer","_default","exports","default","Object","assign","dayjs"],"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":"0PAAA,IAAAA,OAAA,CAAAC,OAAA,WACA,IAAAC,MAAA,CAAAD,OAAA,UACA,IAAAE,MAAA,CAAAC,sBAAA,CAAAH,OAAA,WAEA,IAAAI,QAAA,CAAAJ,OAAA,yBASA,IAAAK,iBAAA,CAAAL,OAAA,mCAEA,IAAAM,YAAA,CAAAN,OAAA,kBAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA;AACA;AACO,QAAS,CAAAO,UAAUA,C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AClD,MAAO,CAAAK,KAAK,CAAGG,QAAQ,CAACH,KAAK,CAAC,CAAG,CACnC,CACF,CAAC,CACD,GAAAf,gBAAS,EAAC,IAAM,CACd,KAAM,CAAAmB,IAAI,CAAG,GAAI,CAAApB,IAAM,CACvB,KAAM,CAAAgB,KAAK,CAAGI,IAAI,CAACC,iBAAiB,CAAC,CAAC,CACtCN,SAAS,CAACC,KAAK,CAAC,CAChB,GAAIL,UAAU,CAAE,CACdW,QAAQ,CAACC,MAAM,CAAG,GAAAC,iBAAS,EAACb,UAAU,CAAEK,KAAK,CAACS,QAAQ,CAAC,CAAC,CAAE,CAAEC,IAAI,CAAE,GAAI,CAAC,CACzE,CACF,CAAC,CAAE,CAACf,UAAU,CAAEI,SAAS,CAAC,CAAC,CAC3B,MAAO,CAAAD,MACT,CAEA,KAAM,CAAAa,IAAI,CAAG,CACXC,MAAM,CAANA,eAAM,CACNC,OAAO,CAAPA,gBAAO,CACPC,MAAM,CAANA,eAAM,CACNlC,MAAM,CAANA,eAAM,CACNmC,OAAO,CAAPA,gBAAO,CACPlC,GAAG,CAAEG,IAAI,CAACH,GAAG,CACbmC,KAAK,CAALA,cAAK,CACLxC,UAAU,CACVkB,iBACF,CAAC,
|
|
1
|
+
{"version":3,"file":"time.js","names":["_cookie","require","_react","_dayjs","_interopRequireDefault","_jsUtils","_reactGlobalState","_globalState","useCurrent","autorefresh","globalStatePath","precision","SEC_MS","now","setter","useGlobalState","Date","useEffect","timerId","update","old","neu","Math","abs","setTimeout","clearTimeout","useTimezoneOffset","cookieName","ssrContext","getSsrContext","offset","setOffset","value","req","cookies","parseInt","date","getTimezoneOffset","document","cookie","serialize","toString","path","time","DAY_MS","HOUR_MS","MIN_MS","YEAR_MS","timer","_default","exports","default","Object","assign","dayjs"],"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":"0PAAA,IAAAA,OAAA,CAAAC,OAAA,WACA,IAAAC,MAAA,CAAAD,OAAA,UACA,IAAAE,MAAA,CAAAC,sBAAA,CAAAH,OAAA,WAEA,IAAAI,QAAA,CAAAJ,OAAA,yBASA,IAAAK,iBAAA,CAAAL,OAAA,mCAEA,IAAAM,YAAA,CAAAN,OAAA,kBAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA;AACA;AACO,QAAS,CAAAO,UAAUA,CAAC,CACzBC,WAAW,CAAG,KAAK,CACnBC,eAAe,CAAG,aAAa,CAC/BC,SAAS,CAAG,CAAC,CAAGC,eAClB,CAAC,CAAG,CAAC,CAAC,CAAU,CACd,KAAM,CAACC,GAAG,CAAEC,MAAM,CAAC,CAAG,GAAAC,gCAAc,EAClCL,eAAe,CACfM,IAAI,CAACH,GACP,CAAC,CACD,GAAAI,gBAAS,EAAC,IAAM,CACd,GAAI,CAAAC,OAAmC,CACvC,KAAM,CAAAC,MAAM,CAAGA,CAAA,GAAY,CACzBL,MAAM,CAAEM,GAAG,EAAK,CACd,KAAM,CAAAC,GAAG,CAAGL,IAAI,CAACH,GAAG,CAAC,CAAC,CACtB,MAAO,CAAAS,IAAI,CAACC,GAAG,CAACF,GAAG,CAAGD,GAAG,CAAC,CAAGT,SAAS,CAAGU,GAAG,CAAGD,GACjD,CAAC,CAAC,CACF,GAAIX,WAAW,CAAES,OAAO,CAAGM,UAAU,CAACL,MAAM,CAAER,SAAS,CACzD,CAAC,CACDQ,MAAM,CAAC,CAAC,CACR,MAAO,IAAY,CACjB,GAAID,OAAO,CAAEO,YAAY,CAACP,OAAO,CACnC,CACF,CAAC,CAAE,CAAC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U,CACVkB,iBACF,CAAC,KAAAuB,QAAA,CAAAC,OAAA,CAAAC,OAAA,CAEcC,MAAM,CAACC,MAAM,CAACC,cAAK,CAAEX,IAAI,CAAC","ignoreList":[]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import 'styles/global.scss';
|
|
2
|
-
import
|
|
2
|
+
import clientModule from './client';
|
|
3
3
|
import type * as ServerFactoryM from './server';
|
|
4
4
|
declare const server: (typeof ServerFactoryM.default & Omit<typeof ServerFactoryM, "default">) | null;
|
|
5
|
-
declare const client: typeof
|
|
5
|
+
declare const client: typeof clientModule | undefined;
|
|
6
6
|
export { type AsyncCollectionT, type AsyncCollectionLoaderT, type AsyncDataEnvelopeT, type AsyncDataLoaderT, type ForceT, type UseAsyncDataOptionsT, type UseAsyncDataResT, type UseGlobalStateResT, type ValueOrInitializerT, getGlobalState, GlobalStateProvider, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState, withGlobalStateType, } from '@dr.pogodin/react-global-state';
|
|
7
7
|
export * from './shared/components';
|
|
8
8
|
export { type BeforeRenderResT, type BeforeRenderT, type ConfigT, type ServerSsrContext, type ServerT, } from './server';
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Encapsulates retrieval of server-side data injection into HTML template.
|
|
2
|
+
|
|
3
|
+
/* global document */
|
|
4
|
+
|
|
5
|
+
// Note: this way, only required part of "node-forge": AES, and some utils,
|
|
6
|
+
// is bundled into client-side code.
|
|
7
|
+
import forge from 'node-forge/lib/forge';
|
|
8
|
+
|
|
9
|
+
// eslint-disable-next-line import/no-unassigned-import
|
|
10
|
+
import 'node-forge/lib/aes';
|
|
11
|
+
import { getBuildInfo } from "../shared/utils/isomorphy/buildInfo";
|
|
12
|
+
|
|
13
|
+
// Safeguard is needed here, because the server-side version of Docusaurus docs
|
|
14
|
+
// is compiled (at least now) with settings suggesting it is a client-side
|
|
15
|
+
// environment, but there is no document.
|
|
16
|
+
let inj = {};
|
|
17
|
+
const metaElement = typeof document === 'undefined' ? null : document.querySelector('meta[itemprop="drpruinj"]');
|
|
18
|
+
if (metaElement) {
|
|
19
|
+
metaElement.remove();
|
|
20
|
+
let data = forge.util.decode64(metaElement.content);
|
|
21
|
+
const {
|
|
22
|
+
key
|
|
23
|
+
} = getBuildInfo();
|
|
24
|
+
const d = forge.cipher.createDecipher('AES-CBC', key);
|
|
25
|
+
d.start({
|
|
26
|
+
iv: data.slice(0, key.length)
|
|
27
|
+
});
|
|
28
|
+
d.update(forge.util.createBuffer(data.slice(key.length)));
|
|
29
|
+
d.finish();
|
|
30
|
+
data = forge.util.decodeUtf8(d.output.data);
|
|
31
|
+
|
|
32
|
+
// TODO: Double-check, if there is a safer alternative to parse it?
|
|
33
|
+
// eslint-disable-next-line no-eval
|
|
34
|
+
inj = eval(`(${data})`);
|
|
35
|
+
} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {
|
|
36
|
+
inj = window.REACT_UTILS_INJECTION;
|
|
37
|
+
delete window.REACT_UTILS_INJECTION;
|
|
38
|
+
} else {
|
|
39
|
+
// Otherwise, a bunch of dependent stuff will easily fail in non-standard
|
|
40
|
+
// environments, where no client-side initialization is performed. Like tests,
|
|
41
|
+
// Docusaurus examples, etc.
|
|
42
|
+
inj = {};
|
|
43
|
+
}
|
|
44
|
+
export default function getInj() {
|
|
45
|
+
return inj;
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=getInj.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getInj.js","names":["forge","getBuildInfo","inj","metaElement","document","querySelector","remove","data","util","decode64","content","key","d","cipher","createDecipher","start","iv","slice","length","update","createBuffer","finish","decodeUtf8","output","eval","window","REACT_UTILS_INJECTION","getInj"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\n\n// eslint-disable-next-line import/no-unassigned-import\nimport 'node-forge/lib/aes';\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\n// Safeguard is needed here, because the server-side version of Docusaurus docs\n// is compiled (at least now) with settings suggesting it is a client-side\n// environment, but there is no document.\nlet inj: InjT = {};\n\nconst metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\nif (metaElement) {\n metaElement.remove();\n let data = forge.util.decode64(metaElement.content);\n\n const { key } = getBuildInfo();\n const d = forge.cipher.createDecipher('AES-CBC', key);\n d.start({ iv: data.slice(0, key.length) });\n d.update(forge.util.createBuffer(data.slice(key.length)));\n d.finish();\n\n data = forge.util.decodeUtf8(d.output.data);\n\n // TODO: Double-check, if there is a safer alternative to parse it?\n // eslint-disable-next-line no-eval\n inj = eval(`(${data})`) as InjT;\n} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n inj = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n} else {\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n inj = {};\n}\n\nexport default function getInj(): InjT {\n return inj;\n}\n"],"mappings":"AAAA;;AAEA;;AAEA;AACA;AACA,OAAOA,KAAK,MAAM,sBAAsB;;AAExC;AACA,OAAO,oBAAoB;AAI3B,SAASC,YAAY;;AAErB;AACA;AACA;AACA,IAAIC,GAAS,GAAG,CAAC,CAAC;AAElB,MAAMC,WAAmC,GAAG,OAAOC,QAAQ,KAAK,WAAW,GACvE,IAAI,GAAGA,QAAQ,CAACC,aAAa,CAAC,2BAA2B,CAAC;AAE9D,IAAIF,WAAW,EAAE;EACfA,WAAW,CAACG,MAAM,CAAC,CAAC;EACpB,IAAIC,IAAI,GAAGP,KAAK,CAACQ,IAAI,CAACC,QAAQ,CAACN,WAAW,CAACO,OAAO,CAAC;EAEnD,MAAM;IAAEC;EAAI,CAAC,GAAGV,YAAY,CAAC,CAAC;EAC9B,MAAMW,CAAC,GAAGZ,KAAK,CAACa,MAAM,CAACC,cAAc,CAAC,SAAS,EAAEH,GAAG,CAAC;EACrDC,CAAC,CAACG,KAAK,CAAC;IAAEC,EAAE,EAAET,IAAI,CAACU,KAAK,CAAC,CAAC,EAAEN,GAAG,CAACO,MAAM;EAAE,CAAC,CAAC;EAC1CN,CAAC,CAACO,MAAM,CAACnB,KAAK,CAACQ,IAAI,CAACY,YAAY,CAACb,IAAI,CAACU,KAAK,CAACN,GAAG,CAACO,MAAM,CAAC,CAAC,CAAC;EACzDN,CAAC,CAACS,MAAM,CAAC,CAAC;EAEVd,IAAI,GAAGP,KAAK,CAACQ,IAAI,CAACc,UAAU,CAACV,CAAC,CAACW,MAAM,CAAChB,IAAI,CAAC;;EAE3C;EACA;EACAL,GAAG,GAAGsB,IAAI,CAAC,IAAIjB,IAAI,GAAG,CAAS;AACjC,CAAC,MAAM,IAAI,OAAOkB,MAAM,KAAK,WAAW,IAAIA,MAAM,CAACC,qBAAqB,EAAE;EACxExB,GAAG,GAAGuB,MAAM,CAACC,qBAAqB;EAClC,OAAOD,MAAM,CAACC,qBAAqB;AACrC,CAAC,MAAM;EACL;EACA;EACA;EACAxB,GAAG,GAAG,CAAC,CAAC;AACV;AAEA,eAAe,SAASyB,MAAMA,CAAA,EAAS;EACrC,OAAOzB,GAAG;AACZ","ignoreList":[]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Initialization of client-side code.
|
|
2
|
+
/* global document */
|
|
3
|
+
|
|
4
|
+
import { createRoot, hydrateRoot } from 'react-dom/client';
|
|
5
|
+
import { HelmetProvider } from '@dr.pogodin/react-helmet';
|
|
6
|
+
import { BrowserRouter } from 'react-router';
|
|
7
|
+
import { GlobalStateProvider } from '@dr.pogodin/react-global-state';
|
|
8
|
+
import getInj from "./getInj";
|
|
9
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
10
|
+
/**
|
|
11
|
+
* Prepares and launches the app at client side.
|
|
12
|
+
* @param Application Root application component
|
|
13
|
+
* @param [options={}] Optional. Additional settings.
|
|
14
|
+
*/
|
|
15
|
+
export default function Launch(Application, options = {}) {
|
|
16
|
+
const container = document.getElementById('react-view');
|
|
17
|
+
if (!container) throw Error('Failed to find container for React app');
|
|
18
|
+
const scene = /*#__PURE__*/_jsx(GlobalStateProvider, {
|
|
19
|
+
initialState: getInj().ISTATE ?? options.initialState,
|
|
20
|
+
children: /*#__PURE__*/_jsx(BrowserRouter, {
|
|
21
|
+
children: /*#__PURE__*/_jsx(HelmetProvider, {
|
|
22
|
+
children: /*#__PURE__*/_jsx(Application, {})
|
|
23
|
+
})
|
|
24
|
+
})
|
|
25
|
+
});
|
|
26
|
+
if (options.dontHydrate) {
|
|
27
|
+
const root = createRoot(container);
|
|
28
|
+
root.render(scene);
|
|
29
|
+
} else hydrateRoot(container, scene);
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["createRoot","hydrateRoot","HelmetProvider","BrowserRouter","GlobalStateProvider","getInj","jsx","_jsx","Launch","Application","options","container","document","getElementById","Error","scene","initialState","ISTATE","children","dontHydrate","root","render"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport type { ComponentType } from 'react';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { BrowserRouter } from 'react-router';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: unknown;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n): void {\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={getInj().ISTATE ?? options.initialState}>\n <BrowserRouter>\n <HelmetProvider>\n <Application />\n </HelmetProvider>\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":"AAAA;AACA;;AAGA,SAASA,UAAU,EAAEC,WAAW,QAAQ,kBAAkB;AAC1D,SAASC,cAAc,QAAQ,0BAA0B;AACzD,SAASC,aAAa,QAAQ,cAAc;AAE5C,SAASC,mBAAmB,QAAQ,gCAAgC;AAEpE,OAAOC,MAAM;AAAiB,SAAAC,GAAA,IAAAC,IAAA;AAO9B;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,MAAMA,CAC5BC,WAA0B,EAC1BC,OAAiB,GAAG,CAAC,CAAC,EAChB;EACN,MAAMC,SAAS,GAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC;EACvD,IAAI,CAACF,SAAS,EAAE,MAAMG,KAAK,CAAC,wCAAwC,CAAC;EACrE,MAAMC,KAAK,gBACTR,IAAA,CAACH,mBAAmB;IAACY,YAAY,EAAEX,MAAM,CAAC,CAAC,CAACY,MAAM,IAAIP,OAAO,CAACM,YAAa;IAAAE,QAAA,eACzEX,IAAA,CAACJ,aAAa;MAAAe,QAAA,eACZX,IAAA,CAACL,cAAc;QAAAgB,QAAA,eACbX,IAAA,CAACE,WAAW,IAAE;MAAC,CACD;IAAC,CACJ;EAAC,CACG,CACtB;EAED,IAAIC,OAAO,CAACS,WAAW,EAAE;IACvB,MAAMC,IAAI,GAAGpB,UAAU,CAACW,SAAS,CAAC;IAClCS,IAAI,CAACC,MAAM,CAACN,KAAK,CAAC;EACpB,CAAC,MAAMd,WAAW,CAACU,SAAS,EAAEI,KAAK,CAAC;AACtC","ignoreList":[]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Initialization of client-side environment.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/* global window */
|
|
6
|
+
|
|
7
|
+
import { getBuildInfo } from "../shared/utils/isomorphy/buildInfo";
|
|
8
|
+
const buildInfo = getBuildInfo();
|
|
9
|
+
|
|
10
|
+
// TODO: Should be moved into buildInfo module?
|
|
11
|
+
|
|
12
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
13
|
+
// eslint-disable-next-line no-console
|
|
14
|
+
console.warn('Dev mode: "BUILD_INFO" attached to the global "window"');
|
|
15
|
+
|
|
16
|
+
// eslint-disable-next-line no-underscore-dangle
|
|
17
|
+
window.__DEV_BUILD_INFO__ = BUILD_INFO;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */
|
|
21
|
+
const {
|
|
22
|
+
useServiceWorker
|
|
23
|
+
} = buildInfo;
|
|
24
|
+
if (useServiceWorker) {
|
|
25
|
+
const {
|
|
26
|
+
navigator
|
|
27
|
+
} = window;
|
|
28
|
+
if ('serviceWorker' in navigator) {
|
|
29
|
+
window.addEventListener('load', () => {
|
|
30
|
+
void (async () => {
|
|
31
|
+
try {
|
|
32
|
+
// Note: no matter the "publicPath", we want to serve the service worker
|
|
33
|
+
// from the web app root, to allow it control any and all pages of the
|
|
34
|
+
// web app (otherwise, it will be restricted to the scope of its path).
|
|
35
|
+
// The server takes it into account.
|
|
36
|
+
const reg = await navigator.serviceWorker.register('/__service-worker.js');
|
|
37
|
+
// eslint-disable-next-line no-console
|
|
38
|
+
console.log('SW registered:', reg);
|
|
39
|
+
} catch (err) {
|
|
40
|
+
// eslint-disable-next-line no-console
|
|
41
|
+
console.log('SW registration failed:', err);
|
|
42
|
+
}
|
|
43
|
+
})();
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=init.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"init.js","names":["getBuildInfo","buildInfo","process","env","NODE_ENV","console","warn","window","__DEV_BUILD_INFO__","BUILD_INFO","useServiceWorker","navigator","addEventListener","reg","serviceWorker","register","log","err"],"sources":["../../../src/client/init.ts"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global window */\n\nimport { type BuildInfoT, getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nconst buildInfo = getBuildInfo();\n\n// TODO: Should be moved into buildInfo module?\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n __DEV_BUILD_INFO__: BuildInfoT | undefined;\n }\n}\n\ndeclare const BUILD_INFO: BuildInfoT | undefined;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.warn('Dev mode: \"BUILD_INFO\" attached to the global \"window\"');\n\n // eslint-disable-next-line no-underscore-dangle\n window.__DEV_BUILD_INFO__ = BUILD_INFO;\n}\n\n/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */\nconst { useServiceWorker } = buildInfo;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', () => {\n void (async () => {\n try {\n // Note: no matter the \"publicPath\", we want to serve the service worker\n // from the web app root, to allow it control any and all pages of the\n // web app (otherwise, it will be restricted to the scope of its path).\n // The server takes it into account.\n const reg = await navigator\n .serviceWorker.register('/__service-worker.js');\n // eslint-disable-next-line no-console\n console.log('SW registered:', reg);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.log('SW registration failed:', err);\n }\n })();\n });\n }\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA;;AAEA,SAA0BA,YAAY;AAEtC,MAAMC,SAAS,GAAGD,YAAY,CAAC,CAAC;;AAEhC;;AAUA,IAAIE,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;EACzC;EACAC,OAAO,CAACC,IAAI,CAAC,wDAAwD,CAAC;;EAEtE;EACAC,MAAM,CAACC,kBAAkB,GAAGC,UAAU;AACxC;;AAEA;AACA,MAAM;EAAEC;AAAiB,CAAC,GAAGT,SAAS;AACtC,IAAIS,gBAAgB,EAAE;EACpB,MAAM;IAAEC;EAAU,CAAC,GAAGJ,MAAM;EAC5B,IAAI,eAAe,IAAII,SAAS,EAAE;IAChCJ,MAAM,CAACK,gBAAgB,CAAC,MAAM,EAAE,MAAM;MACpC,KAAK,CAAC,YAAY;QAChB,IAAI;UACF;UACA;UACA;UACA;UACA,MAAMC,GAAG,GAAG,MAAMF,SAAS,CACxBG,aAAa,CAACC,QAAQ,CAAC,sBAAsB,CAAC;UACjD;UACAV,OAAO,CAACW,GAAG,CAAC,gBAAgB,EAAEH,GAAG,CAAC;QACpC,CAAC,CAAC,OAAOI,GAAG,EAAE;UACZ;UACAZ,OAAO,CAACW,GAAG,CAAC,yBAAyB,EAAEC,GAAG,CAAC;QAC7C;MACF,CAAC,EAAE,CAAC;IACN,CAAC,CAAC;EACJ;AACF","ignoreList":[]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import "./styles/global.scss";
|
|
2
|
+
import clientModule from "./client";
|
|
3
|
+
import { webpack } from "./shared/utils";
|
|
4
|
+
// It is a safeguard against multiple instances / versions of the library
|
|
5
|
+
// being loaded into environment by mistake (e.g. because of different
|
|
6
|
+
// packages pinning down different exact versions of the lib, thus preventing
|
|
7
|
+
// a proper dedupe and using a single common library version).
|
|
8
|
+
if (global.REACT_UTILS_LIBRARY_LOADED) {
|
|
9
|
+
throw Error('React utils library is already loaded');
|
|
10
|
+
} else global.REACT_UTILS_LIBRARY_LOADED = true;
|
|
11
|
+
|
|
12
|
+
// TODO: This is a rapid workaround to get rid of __dirname. I guess, later
|
|
13
|
+
// we'll re-implement requireWeak() to accept import.meta.url directly, and
|
|
14
|
+
// this workaround won't be needed.
|
|
15
|
+
let dirname = import.meta.url;
|
|
16
|
+
dirname = dirname.slice(5, dirname.lastIndexOf('/'));
|
|
17
|
+
const server = webpack.requireWeak('./server', dirname);
|
|
18
|
+
const client = server ? undefined : clientModule;
|
|
19
|
+
export { getGlobalState, GlobalStateProvider, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState, withGlobalStateType } from '@dr.pogodin/react-global-state';
|
|
20
|
+
export * from "./shared/components";
|
|
21
|
+
export { assertEmptyObject, config, Barrier, Cached, Emitter, isomorphy, getSsrContext, Semaphore, splitComponent, themed, ThemeProvider, time, webpack, withRetries } from "./shared/utils";
|
|
22
|
+
export { client, server };
|
|
23
|
+
//# sourceMappingURL=index.js.map
|