@dr.pogodin/react-utils 1.57.1 → 1.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/development/server/Cache.js +7 -7
- package/build/development/server/Cache.js.map +1 -1
- package/build/development/server/index.js +6 -3
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +18 -7
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +12 -6
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/errors.js +10 -10
- package/build/development/server/utils/errors.js.map +1 -1
- package/build/development/shared/components/Button/index.js +1 -1
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +5 -5
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +3 -3
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +3 -0
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +3 -3
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js +2 -2
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +3 -1
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +4 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +7 -4
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +3 -3
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +2 -2
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv/index.js +7 -6
- package/build/development/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/development/shared/utils/jest/index.js +2 -1
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +10 -8
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/webpack.js +2 -1
- package/build/development/shared/utils/webpack.js.map +1 -1
- package/build/production/server/Cache.js +3 -3
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/index.js +1 -1
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +9 -9
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +6 -6
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/errors.js +1 -1
- package/build/production/server/utils/errors.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/Input/index.js +1 -1
- package/build/production/shared/components/Input/index.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/TextArea/index.js +1 -1
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +2 -2
- package/build/production/shared/components/WithTooltip/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 +2 -2
- 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.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv/index.js +2 -2
- package/build/production/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/production/shared/utils/jest/index.js +2 -2
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +3 -3
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/webpack.js +3 -2
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/types-code/shared/utils/config.d.ts +1 -1
- package/build/web/server/Cache.js +3 -3
- package/build/web/server/Cache.js.map +1 -1
- package/build/web/server/index.js +1 -1
- package/build/web/server/index.js.map +1 -1
- package/build/web/server/renderer.js +9 -9
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/server/server.js +6 -6
- package/build/web/server/server.js.map +1 -1
- package/build/web/server/utils/errors.js +1 -1
- package/build/web/server/utils/errors.js.map +1 -1
- package/build/web/shared/components/Button/index.js +1 -1
- package/build/web/shared/components/Button/index.js.map +1 -1
- package/build/web/shared/components/Checkbox/index.js +1 -1
- package/build/web/shared/components/Checkbox/index.js.map +1 -1
- package/build/web/shared/components/Input/index.js +1 -1
- package/build/web/shared/components/Input/index.js.map +1 -1
- package/build/web/shared/components/Modal/index.js +1 -1
- package/build/web/shared/components/Modal/index.js.map +1 -1
- package/build/web/shared/components/TextArea/index.js +1 -1
- package/build/web/shared/components/TextArea/index.js.map +1 -1
- package/build/web/shared/components/WithTooltip/Tooltip.js +1 -1
- package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/web/shared/components/WithTooltip/index.js +2 -2
- package/build/web/shared/components/WithTooltip/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js +2 -2
- package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/Switch/index.js +1 -1
- package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/web/shared/utils/config.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv/index.js +2 -2
- package/build/web/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/web/shared/utils/jest/index.js +2 -2
- package/build/web/shared/utils/jest/index.js.map +1 -1
- package/build/web/shared/utils/splitComponent.js +3 -3
- package/build/web/shared/utils/splitComponent.js.map +1 -1
- package/build/web/shared/utils/webpack.js +3 -2
- package/build/web/shared/utils/webpack.js.map +1 -1
- package/config/babel/webpack.js +6 -1
- package/package.json +19 -19
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/NativeDropdown/index.tsx"],"sourcesContent":["// Implements dropdown based on the native HTML <select> element.\n\nimport type { FunctionComponent } from 'react';\n\nimport { useTheme } from '@dr.pogodin/react-themes';\n\nimport { type PropsT, optionValueName } from '../common';\n\nimport defaultTheme from './theme.scss';\n\n/**\n * Implements a themeable dropdown list. Internally it is rendered with help of\n * the standard HTML `<select>` element, thus the styling support is somewhat\n * limited.\n * @param [props] Component properties.\n * @param [props.filter] Options filter function. If provided, only\n * those elements of `options` list will be used by the dropdown, for which this\n * filter returns `true`.\n * @param [props.label] Dropdown label.\n * @param [props.onChange] Selection event handler.\n * @param [props.options=[]] Array of dropdown\n * options. For string elements the option value and name will be the same.\n * It is allowed to mix DropdownOption and string elements in the same option\n * list.\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props.value] Currently selected value.\n * @param [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nconst Dropdown: FunctionComponent<PropsT<string>> = ({\n filter,\n label,\n onChange,\n onClick,\n options,\n testId,\n theme,\n value,\n}) => {\n let isValidValue = false;\n const optionElements = [];\n\n const composed = useTheme('Dropdown', defaultTheme, theme);\n\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n isValidValue ||= iValue === value;\n optionElements.push(\n <option className={composed.option} key={iValue} value={iValue}>\n {iName}\n </option>,\n );\n }\n }\n\n // NOTE: This element represents the current `value` when it does not match\n // any valid option. In Chrome, and some other browsers, we are able to hide\n // it from the opened dropdown; in others, e.g. Safari, the best we can do is\n // to show it as disabled.\n const hiddenOption = isValidValue ? null : (\n <option\n className={composed.hiddenOption}\n disabled\n key=\"__reactUtilsHiddenOption\"\n value={value}\n >\n {value}\n </option>\n );\n\n let selectClassName = composed.select;\n if (!isValidValue) selectClassName += ` ${composed.invalid}`;\n\n return (\n <div className={composed.container}>\n { label === undefined\n ? null : <div className={composed.label}>{label}</div> }\n <div className={composed.dropdown}>\n <select\n className={selectClassName}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onChange={onChange}\n onClick={onClick}\n value={value}\n >\n {hiddenOption}\n {optionElements}\n </select>\n <div className={composed.arrow} />\n </div>\n </div>\n );\n};\n\nexport default Dropdown;\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/NativeDropdown/index.tsx"],"sourcesContent":["// Implements dropdown based on the native HTML <select> element.\n\nimport type { FunctionComponent } from 'react';\n\nimport { useTheme } from '@dr.pogodin/react-themes';\n\nimport { type PropsT, optionValueName } from '../common';\n\nimport defaultTheme from './theme.scss';\n\n/**\n * Implements a themeable dropdown list. Internally it is rendered with help of\n * the standard HTML `<select>` element, thus the styling support is somewhat\n * limited.\n * @param [props] Component properties.\n * @param [props.filter] Options filter function. If provided, only\n * those elements of `options` list will be used by the dropdown, for which this\n * filter returns `true`.\n * @param [props.label] Dropdown label.\n * @param [props.onChange] Selection event handler.\n * @param [props.options=[]] Array of dropdown\n * options. For string elements the option value and name will be the same.\n * It is allowed to mix DropdownOption and string elements in the same option\n * list.\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props.value] Currently selected value.\n * @param [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nconst Dropdown: FunctionComponent<PropsT<string>> = ({\n filter,\n label,\n onChange,\n onClick,\n options,\n testId,\n theme,\n value,\n}) => {\n let isValidValue = false;\n const optionElements = [];\n\n const composed = useTheme('Dropdown', defaultTheme, theme);\n\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n isValidValue ||= iValue === value;\n optionElements.push(\n <option className={composed.option} key={iValue} value={iValue}>\n {iName}\n </option>,\n );\n }\n }\n\n // NOTE: This element represents the current `value` when it does not match\n // any valid option. In Chrome, and some other browsers, we are able to hide\n // it from the opened dropdown; in others, e.g. Safari, the best we can do is\n // to show it as disabled.\n const hiddenOption = isValidValue ? null : (\n <option\n className={composed.hiddenOption}\n disabled\n key=\"__reactUtilsHiddenOption\"\n value={value}\n >\n {value}\n </option>\n );\n\n let selectClassName = composed.select ?? '';\n if (!isValidValue) selectClassName += ` ${composed.invalid ?? ''}`;\n\n return (\n <div className={composed.container}>\n { label === undefined\n ? null : <div className={composed.label}>{label}</div> }\n <div className={composed.dropdown}>\n <select\n className={selectClassName}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onChange={onChange}\n onClick={onClick}\n value={value}\n >\n {hiddenOption}\n {optionElements}\n </select>\n <div className={composed.arrow} />\n </div>\n </div>\n );\n};\n\nexport default Dropdown;\n"],"mappings":"2EAAA;AAIA,SAAS,QAAQ,QAAQ,0BAA0B;AAAC,SAE9B,eAAe;AAErC;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAlBA;AAmBA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Q,KAAK,YAAY,GAAG,SAAS,GAAG,MAAO;QACxE,QAAQ,EAAE,QAAS;QACnB,OAAO,EAAE,OAAQ;QACjB,KAAK,EAAE,KAAM;QAAA,WAEZ,YAAY,EACZ,cAAc;MAAA,CACT,CAAC,eACT;QAAK,SAAS,EAAE,QAAQ,CAAC;MAAM,CAAE,CAAC;IAAA,CAC/B,CAAC;EAAA,CACH,CAAC;AAEV,CAAC;AAED,eAAe,QAAQ","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import _pushInstanceProperty from "core-js-pure/
|
|
1
|
+
import _pushInstanceProperty from "core-js-pure/features/instance/push.js";
|
|
2
2
|
import { c as _c } from "react/compiler-runtime";
|
|
3
3
|
import { useTheme } from "@dr.pogodin/react-themes";
|
|
4
4
|
import { optionValueName } from "../common.js";
|
|
@@ -33,7 +33,7 @@ export const Switch = t0 => {
|
|
|
33
33
|
let className = composed.option;
|
|
34
34
|
let onPress;
|
|
35
35
|
if (iValue === value) {
|
|
36
|
-
className = className + ` ${composed.selected}`;
|
|
36
|
+
className = className + ` ${composed.selected ?? ""}`;
|
|
37
37
|
} else {
|
|
38
38
|
if (onChange) {
|
|
39
39
|
onPress = () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import type { FunctionComponent, ReactNode } from 'react';\n\nimport { type Theme, useTheme } 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 ThemeT = Theme<'container' | 'label' | 'option' | 'options' | 'selected'>;\n\ntype PropsT = {\n label?: ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<ReactNode>>;\n theme?: ThemeT;\n value?: ValueT;\n};\n\nexport const Switch: FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const composed = useTheme('Switch', defaultTheme, theme);\n\n if (!options || !composed.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 = composed.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${composed.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={composed.container}>\n {label ? <div className={composed.label}>{label}</div> : null}\n\n <div className={composed.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n"],"mappings":";;AAEA,SAAqB,QAAQ,QAAQ,0BAA0B;AAAC,SAK9D,eAAe;AAGjB;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;AAAA;AAAwC;AAYxC,OAAO,MAAM,MAAiC,GAAG;EAAA;EAAC;IAAA;IAAA;IAAA;IAAA;IAAA;EAAA,MAMjD;EACC,iBAAiB,QAAQ,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,CAAC;EAExD,IAAI,CAAC,OAA2B,IAA5B,CAAa,QAAQ,OAAO;IAAE,MAAM,KAAK,CAAC,gBAAgB,CAAC;EAAC;EAAA;EAAA;IAEhE,cAAuC,EAAE;IACzC,KAAK,YAAY,IAAI,OAAO;MAC1B,wBAAwB,eAAe,CAAC,MAAM,CAAC;MAE/C,gBAAwB,QAAQ,OAAO;MACnC;MACJ,IAAI,MAAM,KAAK,KAAK;QAAE,qBAAS,GAAI,IAAI,QAAQ,
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import type { FunctionComponent, ReactNode } from 'react';\n\nimport { type Theme, useTheme } 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 ThemeT = Theme<'container' | 'label' | 'option' | 'options' | 'selected'>;\n\ntype PropsT = {\n label?: ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<ReactNode>>;\n theme?: ThemeT;\n value?: ValueT;\n};\n\nexport const Switch: FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const composed = useTheme('Switch', defaultTheme, theme);\n\n if (!options || !composed.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 = composed.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${composed.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={composed.container}>\n {label ? <div className={composed.label}>{label}</div> : null}\n\n <div className={composed.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n"],"mappings":";;AAEA,SAAqB,QAAQ,QAAQ,0BAA0B;AAAC,SAK9D,eAAe;AAGjB;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;AAAA;AAAwC;AAYxC,OAAO,MAAM,MAAiC,GAAG;EAAA;EAAC;IAAA;IAAA;IAAA;IAAA;IAAA;EAAA,MAMjD;EACC,iBAAiB,QAAQ,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,CAAC;EAExD,IAAI,CAAC,OAA2B,IAA5B,CAAa,QAAQ,OAAO;IAAE,MAAM,KAAK,CAAC,gBAAgB,CAAC;EAAC;EAAA;EAAA;IAEhE,cAAuC,EAAE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Content":["/* global document */\n\nimport { parseCookie } from 'cookie';\n\nimport clientGetInj from '../../client/getInj';\n\nimport { IS_CLIENT_SIDE } from './isomorphy/environment-check';\nimport { requireWeak } from './webpack';\n\ntype ConfigT = Record<string, unknown>;\n\nlet config: ConfigT | Promise<ConfigT> | undefined;\n\n/**\n * Injects CSRF token into config (on client-side only).\n *\n * BEWARE: It mutates the argument, and also returns it as the result,\n * for chaining.\n */\nfunction injectCsrfToken(cfg: ConfigT): ConfigT {\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.\n if (IS_CLIENT_SIDE && typeof document !== 'undefined') {\n // eslint-disable-next-line no-param-reassign\n cfg.CSRF = parseCookie(document.cookie).csrfToken;\n }\n\n return cfg;\n}\n\nexport function getConfig
|
|
1
|
+
{"version":3,"file":"config.js","names":[],"sources":["../../../../src/shared/utils/config.ts"],"sourcesContent":["/* global document */\n\nimport { parseCookie } from 'cookie';\n\nimport clientGetInj from '../../client/getInj';\n\nimport { IS_CLIENT_SIDE } from './isomorphy/environment-check';\nimport { requireWeak } from './webpack';\n\ntype ConfigT = Record<string, unknown>;\n\nlet config: ConfigT | Promise<ConfigT> | undefined;\n\n/**\n * Injects CSRF token into config (on client-side only).\n *\n * BEWARE: It mutates the argument, and also returns it as the result,\n * for chaining.\n */\nfunction injectCsrfToken(cfg: ConfigT): ConfigT {\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.\n if (IS_CLIENT_SIDE && typeof document !== 'undefined') {\n // eslint-disable-next-line no-param-reassign\n cfg.CSRF = parseCookie(document.cookie).csrfToken;\n }\n\n return cfg;\n}\n\nexport function getConfig(sync: true): ConfigT;\n\nexport function getConfig<T extends ConfigT>(sync?: boolean): Promise<T> | T;\n\nexport function getConfig<T extends ConfigT>(sync?: boolean): Promise<T> | T {\n if (!config) {\n if (IS_CLIENT_SIDE) {\n const inj = clientGetInj();\n config = inj instanceof Promise\n ? inj.then((injection) => {\n const res = injectCsrfToken(injection.CONFIG ?? {});\n config = res;\n return res;\n })\n : injectCsrfToken(inj.CONFIG ?? {});\n } else {\n const weak = requireWeak<ConfigT>('config');\n if (!weak) throw Error('Internal error');\n config = weak;\n }\n }\n\n if (sync && (config instanceof Promise)) {\n throw Error('The config is not available yet');\n }\n\n return config as T;\n}\n"],"mappings":"AAAA,qBAEA,SAAS,WAAW,QAAQ,QAAQ;AAAC,OAE9B,YAAY;AAAA,SAEV,cAAc;AAAA,SACd,WAAW;AAIpB,IAAI,MAA8C,CAElD;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,eAAe,CAAC,GAAY,EAAW;EAC9C;EACA;EACA;EACA,IAAI,cAAc,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE;IACrD;IACA,GAAG,CAAC,IAAI,GAAG,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,SAAS;EACnD;EAEA,OAAO,GAAG;AACZ;AAMA,OAAO,SAAS,SAAS,CAAoB,IAAc,EAAkB;EAC3E,IAAI,CAAC,MAAM,EAAE;IACX,IAAI,cAAc,EAAE;MAClB,MAAM,GAAG,GAAG,YAAY,CAAC,CAAC;MAC1B,MAAM,GAAG,GAAG,YAAY,OAAO,GAC3B,GAAG,CAAC,IAAI,CAAE,SAAS,IAAK;QACxB,MAAM,GAAG,GAAG,eAAe,CAAC,SAAS,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC;QACnD,MAAM,GAAG,GAAG;QACZ,OAAO,GAAG;MACZ,CAAC,CAAC,GACA,eAAe,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC;IACvC,CAAC,MAAM;MACL,MAAM,IAAI,GAAG,WAAW,CAAU,QAAQ,CAAC;MAC3C,IAAI,CAAC,IAAI,EAAE,MAAM,KAAK,CAAC,gBAAgB,CAAC;MACxC,MAAM,GAAG,IAAI;IACf;EACF;EAEA,IAAI,IAAI,IAAK,MAAM,YAAY,OAAQ,EAAE;IACvC,MAAM,KAAK,CAAC,iCAAiC,CAAC;EAChD;EAEA,OAAO,MAAM;AACf","ignoreList":[]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import _JSON$parse from "core-js-pure/
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
import _JSON$parse from "core-js-pure/features/json/parse.js"; /**
|
|
2
|
+
* Jest environment for end-to-end SSR and client-side testing. It relies on
|
|
3
|
+
* the standard react-utils mechanics to execute SSR of given scene, and also
|
|
4
|
+
* Webpack build of the code for client-side execution, it further exposes
|
|
5
|
+
* Jsdom environment for the client-side testing of the outcomes.
|
|
6
|
+
*/ // BEWARE: The module is not imported into the JU module / the main assembly of
|
|
7
7
|
// the library, because doing so easily breaks stuff:
|
|
8
8
|
// 1) This module depends on Node-specific modules, which would make JU
|
|
9
9
|
// incompatible with JsDom if included into JU.
|
|
@@ -61,6 +61,7 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
61
61
|
factory = "default" in factory ? factory.default : factory;
|
|
62
62
|
this.global.webpackConfig = factory(options);
|
|
63
63
|
const fs = this.global.webpackOutputFs;
|
|
64
|
+
if (!options.context) throw Error("Missing context");
|
|
64
65
|
let buildInfo = `${options.context}/.build-info`;
|
|
65
66
|
if (fs.existsSync(buildInfo)) {
|
|
66
67
|
buildInfo = fs.readFileSync(buildInfo, "utf8");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/index.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport { fork } from 'node:child_process';\nimport { access } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration, type Stats } from 'webpack';\n\nimport register, { revert } from '@babel/register';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport { deduceChunkGroups } from 'server/renderer';\n\nimport type { LaunchT, ResultT } from './ssr';\n\nasync function findModule(module: string): Promise<string> {\n try {\n const res = `${module}.ts`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n try {\n const res = `${module}.js`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n throw Error(`Module \"${module}\" was not found, neither as TS, nor as JS`);\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: Stats;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private async loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n // NOTE: This is a TS module in the source code, and it turn into JS\n // module in the distributed code, after Babel compilation. As we rely\n // on it for the forked NodeJS process, we need to resolve the correct\n // extention ourselves (as NodeJS will hit the given path, without any\n // additional resolutions / transformations).\n const ssrModulePath = await findModule(`${import.meta.dirname}/ssr-preload`);\n\n const cp = fork(ssrModulePath);\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve, reject) => {\n cp.on('exit', (code) => {\n if (code) reject(Error('SSR process crashed'));\n });\n\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n // BEWARE: Although we also do the registration inside SSR testing code,\n // we still need it here to correctly process imported Webpack configurations\n // (which are imported directly from this module).\n register({\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // eslint-disable-next-line import/dynamic-import-chunkname\n const { setBuildInfo } = await import('../../isomorphy/buildInfo');\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n revert();\n\n await super.teardown();\n }\n}\n"],"mappings":"4DAAA;AACA;AACA;AACA;AACA;AACA,+DALA,CAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAEA,SAAS,IAAI,QAAQ,oBAAoB;AACzC,SAAS,MAAM,QAAQ,kBAAkB;AACzC,OAAO,IAAI,MAAM,WAAW;AAE5B,OAAO,QAAQ,MAAM,wBAAwB;AAC7C,SAAS,QAAQ,EAAE,GAAG,QAAQ,WAAW;AACzC,SAAS,MAAM,EAAE,kBAAkB,QAAQ,OAAO;AAClD,OAAO,OAAO,MAA0C,SAAS;AAEjE,OAAO,QAAQ,IAAI,MAAM,QAAQ,iBAAiB;AAAC,SAO1C,iBAAiB;AAI1B,eAAe,UAAU,CAAC,MAAc,EAAmB;EACzD,IAAI;IACF,MAAM,GAAG,GAAG,GAAG,MAAM,KAAK;IAC1B,MAAM,MAAM,CAAC,GAAG,CAAC;IACjB,OAAO,GAAG;EACZ,CAAE,OAAM,CACN;EAAA;EAGF,IAAI;IACF,MAAM,GAAG,GAAG,GAAG,MAAM,KAAK;IAC1B,MAAM,MAAM,CAAC,GAAG,CAAC;IACjB,OAAO,GAAG;EACZ,CAAE,OAAM,CACN;EAAA;EAGF,MAAM,KAAK,CAAC,WAAW,MAAM,2CAA2C,CAAC;AAC3E;AAEA,eAAe,MAAM,SAAS,SAAS,QAAS;EAC9C,OAAO;EAEP,UAAU;EAEV,OAAO;EAEP,UAAU;EAEV,OAAO;EAEP,YAAY,CAEZ;AACF;AACA;AACA;EACE,MAAc,iBAAiB,GAAG;IAChC,MAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,wBAAwB,CAAW;IAEtE,MAAM,OAAO,GAAI,aAAa,GAAG,YAAW,aAAa,CAAC,GAAG,CAAC,CACvC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ACpC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC;IAChD,IAAI,CAAC,OAAO,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC;IACjC,IAAI,CAAC,UAAU,GAAG,OAAO;IACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAEtB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,QAAQ,CAAC;MACP,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM;IACnD,CAAC,CAAC;EACJ;EAEA,MAAM,KAAK,GAAkB;IAC3B,MAAM,KAAK,CAAC,KAAK,CAAC,CAAC;IACnB,MAAM,IAAI,CAAC,UAAU,CAAC,CAAC,CAEvB;IACA,MAAM;MAAE;IAAa,CAAC,GAAG,MAAM,MAAM,gCAA6B;IAClE,YAAY,CAAC,SAAS,EAAE,IAAI,CAAC;IAE7B,IAAI,IAAI,CAAC,OAAO,EAAE,MAAM,IAAI,CAAC,MAAM,CAAC,CAAC;IACrC,IAAI,CAAC,MAAM,CAAC,6BAA6B,GAAG,IAAI;EAClD;EAEA,MAAM,QAAQ,GAAkB;IAC9B,OAAO,IAAI,CAAC,MAAM,CAAC,6BAA6B;IAEhD,MAAM,CAAC,CAAC;IAER,MAAM,KAAK,CAAC,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/index.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport { fork } from 'node:child_process';\nimport { access } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration, type Stats } from 'webpack';\n\nimport register, { revert } from '@babel/register';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport { deduceChunkGroups } from 'server/renderer';\n\nimport type { LaunchT, ResultT } from './ssr';\n\nasync function findModule(module: string): Promise<string> {\n try {\n const res = `${module}.ts`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n try {\n const res = `${module}.js`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n throw Error(`Module \"${module}\" was not found, neither as TS, nor as JS`);\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: Stats;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private async loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n if (!options.context) throw Error('Missing context');\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n // NOTE: This is a TS module in the source code, and it turn into JS\n // module in the distributed code, after Babel compilation. As we rely\n // on it for the forked NodeJS process, we need to resolve the correct\n // extention ourselves (as NodeJS will hit the given path, without any\n // additional resolutions / transformations).\n const ssrModulePath = await findModule(`${import.meta.dirname}/ssr-preload`);\n\n const cp = fork(ssrModulePath);\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve, reject) => {\n cp.on('exit', (code) => {\n if (code) reject(Error('SSR process crashed'));\n });\n\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n // BEWARE: Although we also do the registration inside SSR testing code,\n // we still need it here to correctly process imported Webpack configurations\n // (which are imported directly from this module).\n register({\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // eslint-disable-next-line import/dynamic-import-chunkname\n const { setBuildInfo } = await import('../../isomorphy/buildInfo');\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\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OAAO,GAAG,aAAa,CAAC,OAAO;IACpC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC;IAChD,IAAI,CAAC,OAAO,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC;IACjC,IAAI,CAAC,UAAU,GAAG,OAAO;IACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAEtB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,QAAQ,CAAC;MACP,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM;IACnD,CAAC,CAAC;EACJ;EAEA,MAAM,KAAK,GAAkB;IAC3B,MAAM,KAAK,CAAC,KAAK,CAAC,CAAC;IACnB,MAAM,IAAI,CAAC,UAAU,CAAC,CAAC,CAEvB;IACA,MAAM;MAAE;IAAa,CAAC,GAAG,MAAM,MAAM,gCAA6B;IAClE,YAAY,CAAC,SAAS,EAAE,IAAI,CAAC;IAE7B,IAAI,IAAI,CAAC,OAAO,EAAE,MAAM,IAAI,CAAC,MAAM,CAAC,CAAC;IACrC,IAAI,CAAC,MAAM,CAAC,6BAA6B,GAAG,IAAI;EAClD;EAEA,MAAM,QAAQ,GAAkB;IAC9B,OAAO,IAAI,CAAC,MAAM,CAAC,6BAA6B;IAEhD,MAAM,CAAC,CAAC;IAER,MAAM,KAAK,CAAC,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import _JSON$stringify from "core-js-pure/
|
|
1
|
+
import _JSON$stringify from "core-js-pure/features/json/stringify.js"; /* global document */ /* eslint-disable import/no-extraneous-dependencies */
|
|
2
2
|
import mockdate from "mockdate";
|
|
3
3
|
import { act } from "react";
|
|
4
4
|
import { createRoot } from "react-dom/client";
|
|
@@ -137,6 +137,7 @@ export function snapshot(element, options) {
|
|
|
137
137
|
if (!rejected) {
|
|
138
138
|
// TODO: These lines are the same as the lines below for sync variant of
|
|
139
139
|
// the function. We should split and reuse them in both places.
|
|
140
|
+
if (!res) throw Error("Missing render result");
|
|
140
141
|
const nodes = res.asFragment().childNodes;
|
|
141
142
|
expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();
|
|
142
143
|
resolve(res);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { expect, jest } from '@jest/globals';\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): `${string}-${string}-${string}-${string}-${string}` {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve, reject) => {\n let rejected = false;\n\n // BEWARE: The \"promise\" returned by act() does not behave as a regular\n // Promise instance:\n // 1. In case of errors its .then() method both calls its \"reject\"\n // callback (first), and then its \"resolve\" callback second.\n // 2. It errors out if a rendering error happens, and there is no\n // \"reject\" argument provided.\n void promise.then(() => {\n if (!rejected) {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n }\n }, (error: unknown) => {\n rejected = true;\n\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n });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M;QACtB,IAAI,CAAC,QAAQ,EAAE;UACb;UACA;UACA,MAAM,KAAK,GAAG,GAAG,CAAE,UAAU,CAAC,CAAC,CAAC,UAAU;UAC1C,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC;UAClE,OAAO,CAAC,GAAI,CAAC;QACf;MACF,CAAC,EAAG,KAAc,IAAK;QACrB,QAAQ,GAAG,IAAI,CAEf;QACA,MAAM,CAAC,KAAK,CAAC;MACf,CAAC,CAAC;IACJ,CAAC,CAAC;EACJ;EAEA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU;EACzC,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC;EAClE,OAAO,GAAG;AACZ","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { expect, jest } from '@jest/globals';\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): `${string}-${string}-${string}-${string}-${string}` {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve, reject) => {\n let rejected = false;\n\n // BEWARE: The \"promise\" returned by act() does not behave as a regular\n // Promise instance:\n // 1. In case of errors its .then() method both calls its \"reject\"\n // callback (first), and then its \"resolve\" callback second.\n // 2. It errors out if a rendering error happens, and there is no\n // \"reject\" argument provided.\n void promise.then(() => {\n if (!rejected) {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n if (!res) throw Error('Missing render result');\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res);\n }\n }, (error: unknown) => {\n rejected = true;\n\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"sEAAA,uBACA;AASA,OAAO,QAAQ,MAAM,UAAU;AAC/B,SAA4C,GAAG,QAAQ,OAAO;AAC9D,SAAoB,UAAU,QAAQ,kBAAkB;AAExD,SAAS,MAAM,EAAE,IAAI,QAAQ,eAAe;AAC5C,SAA4B,MAAM,QAAQ,wBAAwB,CAElE;AACA;AACA;AACA;AACA,SAAS,GAAG;AAAG,SAEN,OAAO,IAAI,SAAS;AAE7B,MAAM,CAAC,wBAAwB,GAAG,IAAI;AAEtC,MAAM,uBAAuB,GAAG,OAAO,CAAC,QAAQ,CAEhD;AACA;AACA;AACA;AACA,OAAO,SAAS,cAAc,GAAS;EACrC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,UAAU,EAAE;IAAE,KAAK,EAAE;EAAU,CAAC,CAAC;AAClE,CAEA;AACA;AACA;AACA,OAAO,SAAS,gBAAgB,GAAS;EACvC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,UAAU,EAAE;IACzC,KAAK,EAAE,uBAAuB;IAC9B,QAAQ,EAAE;EACZ,CAAC,CAAC;AACJ,CAEA;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-pure/
|
|
1
|
+
import _pushInstanceProperty from "core-js-pure/features/instance/push.js";
|
|
2
2
|
import { c as _c } from "react/compiler-runtime"; /* global document */
|
|
3
3
|
import { Suspense, lazy, useInsertionEffect } from "react";
|
|
4
4
|
import { Barrier } from "@dr.pogodin/js-utils";
|
|
@@ -10,7 +10,7 @@ export function setClientChunkGroups(groups) {
|
|
|
10
10
|
assertClientSide();
|
|
11
11
|
clientChunkGroups = groups;
|
|
12
12
|
}
|
|
13
|
-
const refCounts =
|
|
13
|
+
const refCounts = new Map();
|
|
14
14
|
function getPublicPath() {
|
|
15
15
|
return getBuildInfo().publicPath;
|
|
16
16
|
} /**
|
|
@@ -45,8 +45,8 @@ function bookStyleSheet(name, loadedSheets, refCount) {
|
|
|
45
45
|
});
|
|
46
46
|
}
|
|
47
47
|
if (refCount) {
|
|
48
|
-
const current = refCounts
|
|
49
|
-
refCounts
|
|
48
|
+
const current = refCounts.get(path) ?? 0;
|
|
49
|
+
refCounts.set(path, 1 + current);
|
|
50
50
|
}
|
|
51
51
|
return res;
|
|
52
52
|
} /**
|
|
@@ -102,12 +102,14 @@ export function freeStyleSheets(chunkName, chunkGroups) {
|
|
|
102
102
|
for (const asset of assets) {
|
|
103
103
|
if (asset.endsWith(".css")) {
|
|
104
104
|
const path = `${getPublicPath()}/${asset}`;
|
|
105
|
-
const pathRefCount = refCounts
|
|
105
|
+
const pathRefCount = refCounts.get(path);
|
|
106
106
|
if (pathRefCount) {
|
|
107
107
|
if (pathRefCount <= 1) {
|
|
108
|
-
document.head.querySelector(`link[href="${path}"]`)
|
|
109
|
-
|
|
110
|
-
|
|
108
|
+
const node = document.head.querySelector(`link[href="${path}"]`);
|
|
109
|
+
if (!node) throw Error("Missing node");
|
|
110
|
+
node.remove();
|
|
111
|
+
refCounts.delete(path);
|
|
112
|
+
} else refCounts.set(path, pathRefCount - 1);
|
|
111
113
|
}
|
|
112
114
|
}
|
|
113
115
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitComponent.js","names":[],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, useSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n assertClientSide,\n getBuildInfo,\n} from './isomorphy';\n\nlet clientChunkGroups: ChunkGroupsT | undefined;\n\nexport function setClientChunkGroups(groups: ChunkGroupsT): void {\n assertClientSide();\n clientChunkGroups = groups;\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\ntype GenericComponentPropsT = {\n children?: ReactNode;\n ref?: RefObject<unknown>;\n\n // NOTE: This is necessary, as without it this type (with only optional\n // fields) will be conisdered as \"weak\" by TypeScript, and it will be\n // a error to assign to it any type that does not use \"children\", or \"ref\".\n [propName: string]: unknown;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends GenericComponentPropsT,\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)\n\n // When HMR happens splitComponent() ends up getting called again for some\n // chunks, thus we should not throw this error. Not sure, if we need to do\n // some additional handling in that case, or just not throwing is all we\n // need.\n && !import.meta.webpackHot\n ) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT & {\n chunkGroups: ChunkGroupsT;\n }> = ({\n children,\n chunkGroups,\n ref,\n ...rest\n }) => {\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, chunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, chunkGroups);\n };\n }, [chunkGroups]);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => {\n let chunkGroups: ChunkGroupsT;\n\n const ssrContext = useSsrContext(false);\n\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n if (!ssrContext) throw Error('Internal error');\n ({ chunkGroups } = ssrContext);\n const { chunks } = ssrContext;\n\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n } else {\n if (!clientChunkGroups) {\n throw Error('Missing client-side chunk groups data');\n }\n chunkGroups = clientChunkGroups;\n }\n\n assertChunkName(chunkName, chunkGroups);\n\n return (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n\n chunkGroups={chunkGroups}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n };\n\n return CodeSplit;\n}\n"],"mappings":";iDAAA;AAEA,SAKE,QAAQ,EACR,IAAI,EACJ,kBAAkB,QACb,OAAO;AAEd,SAAS,OAAO,QAAQ,sBAAsB;AAAC,SAEnB,aAAa;AAAA,SAGvC,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,YAAY;AAAA;AAGd,IAAI,iBAA2C;AAE/C,OAAO,SAAS,oBAAoB,CAAC,MAAoB,EAAQ;EAC/D,gBAAgB,CAAC,CAAC;EAClB,iBAAiB,GAAG,MAAM;AAC5B;AAEA,MAAM,SAAiC,GAAG,CAAC,CAAC;AAE5C,SAAS,aAAa,GAAG;EACvB,OAAO,YAAY,CAAC,CAAC,CAAC,UAAU;AAClC,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,cAAc,CACrB,IAAY,EACZ,YAAyB,EACzB,QAAiB,EACU;EAC3B,IAAI,GAA8B;EAClC,MAAM,IAAI,GAAG,G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AAS,EAAE,WAAW,CAAC;IAM7B,eAAI;IAAuC;IAAA;MAHnD,uBAAC,QAAQ;QAAW,QAAW,EAAX,WAAW;QAAA,uBAC7B,KAAC,aAAa;UAAA,GAER,EAA2C;UAElC,WAAW,EAAX,WAAW;UAAA,UAEvB;QAAQ,CACI;MAAC,CACR,CAAC;MAAA;MAAA;MAAA;MAAA;IAAA;MAAA;IAAA;IAAA,OATX,EASW;EAAA,CAEd;EAED,OAAO,SAAS;AAClB","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"splitComponent.js","names":[],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, useSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n assertClientSide,\n getBuildInfo,\n} from './isomorphy';\n\nlet clientChunkGroups: ChunkGroupsT | undefined;\n\nexport function setClientChunkGroups(groups: ChunkGroupsT): void {\n assertClientSide();\n clientChunkGroups = groups;\n}\n\nconst refCounts = new Map<string, number>();\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts.get(path) ?? 0;\n refCounts.set(path, 1 + current);\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts.get(path);\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n const node = document.head.querySelector(`link[href=\"${path}\"]`);\n if (!node) throw Error('Missing node');\n node.remove();\n refCounts.delete(path);\n } else refCounts.set(path, pathRefCount - 1);\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\ntype GenericComponentPropsT = {\n children?: ReactNode;\n ref?: RefObject<unknown>;\n\n // NOTE: This is necessary, as without it this type (with only optional\n // fields) will be conisdered as \"weak\" by TypeScript, and it will be\n // a error to assign to it any type that does not use \"children\", or \"ref\".\n [propName: string]: unknown;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends GenericComponentPropsT,\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)\n\n // When HMR happens splitComponent() ends up getting called again for some\n // chunks, thus we should not throw this error. Not sure, if we need to do\n // some additional handling in that case, or just not throwing is all we\n // need.\n && !import.meta.webpackHot\n ) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT & {\n chunkGroups: ChunkGroupsT;\n }> = ({\n children,\n chunkGroups,\n ref,\n ...rest\n }) => {\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, chunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, chunkGroups);\n };\n }, [chunkGroups]);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => {\n let chunkGroups: ChunkGroupsT;\n\n const ssrContext = useSsrContext(false);\n\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n if (!ssrContext) throw Error('Internal error');\n ({ chunkGroups } = ssrContext);\n const { chunks } = ssrContext;\n\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n } else {\n if (!clientChunkGroups) {\n throw Error('Missing client-side chunk groups data');\n }\n chunkGroups = clientChunkGroups;\n }\n\n assertChunkName(chunkName, chunkGroups);\n\n return (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n\n chunkGroups={chunkGroups}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n };\n\n return CodeSplit;\n}\n"],"mappings":";iDAAA;AAEA,SAKE,QAAQ,EACR,IAAI,EACJ,kBAAkB,QACb,OAAO;AAEd,SAAS,OAAO,QAAQ,sBAAsB;AAAC,SAEnB,aAAa;AAAA,SAGvC,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,YAAY;AAAA;AAGd,IAAI,iBAA2C;AAE/C,OAAO,S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AA;IAAA;IAAA;MAAC;QAAA;QAAA;MAAA,MAGrC;MAAA;MAAA;MAAA;IAAA;MAAA;MAAA;IAAA;IACZ;IAEJ,mBAAmB,aAAa,CAAC,KAAK,CAAC;IAIvC,IAAI,cAAc;MAChB,IAAI,CAAC,UAAU;QAAE,MAAM,KAAK,CAAC,gBAAgB,CAAC;MAAC;MAC9C;QAAA;MAAA,IAAkB,UAAU;MAC7B;QAAA;MAAA,IAAmB,UAAU;MAE7B,IAAI,CAAC,MAAM,SAAS,CAAC,SAAS,CAAC;QAAE,4BAAM,OAAN,MAAM,EAAM,SAAS,CAAC;MAAA;IAAC;MAExD,IAAI,CAAC,iBAAiB;QACpB,MAAM,KAAK,CAAC,uCAAuC,CAAC;MAAC;MAEvD,cAAc,iBAAiB;IAApB;IAGb,eAAe,CAAC,SAAS,EAAE,WAAW,CAAC;IAM7B,eAAI;IAAuC;IAAA;MAHnD,uBAAC,QAAQ;QAAW,QAAW,EAAX,WAAW;QAAA,uBAC7B,KAAC,aAAa;UAAA,GAER,EAA2C;UAElC,WAAW,EAAX,WAAW;UAAA,UAEvB;QAAQ,CACI;MAAC,CACR,CAAC;MAAA;MAAA;MAAA;MAAA;IAAA;MAAA;IAAA;IAAA,OATX,EASW;EAAA,CAEd;EAED,OAAO,SAAS;AAClB","ignoreList":[]}
|
|
@@ -15,6 +15,7 @@ export function requireWeak(modulePath,
|
|
|
15
15
|
// breaking changes are done for requireWeak().
|
|
16
16
|
basePathOrOptions) {
|
|
17
17
|
if (IS_CLIENT_SIDE) return null;
|
|
18
|
+
if (!require) throw Error("Internal error (missing require)");
|
|
18
19
|
let basePath;
|
|
19
20
|
let ops;
|
|
20
21
|
if (typeof basePathOrOptions === "string") {
|
|
@@ -28,7 +29,7 @@ basePathOrOptions) {
|
|
|
28
29
|
const {
|
|
29
30
|
resolve
|
|
30
31
|
} = require("node:path");
|
|
31
|
-
const path = basePath ? resolve(basePath, modulePath) : modulePath;
|
|
32
|
+
const path = basePath ? resolve(basePath, modulePath) : modulePath; // eslint-disable-next-line import/no-dynamic-require
|
|
32
33
|
const module = require(path);
|
|
33
34
|
if (!("default" in module) || !module.default) return module;
|
|
34
35
|
const {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webpack.js","names":[],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import type PathNS from 'node:path';\n\n// eslint-disable-next-line import/enforce-node-protocol-usage, perfectionist/sort-imports\nimport { createRequire } from 'module';\n\nimport { IS_CLIENT_SIDE, IS_SERVER_SIDE } from './isomorphy';\n\ntype RequireWeakOptionsT = {\n basePath?: string;\n};\n\ntype RequireWeakResT<T> = T extends { default: infer D }\n ? (D extends null | undefined ? T : D & Omit<T, 'default'>)\n : T;\n\nlet require: ((url: string) => unknown) | undefined;\n\nif (IS_SERVER_SIDE) require = createRequire(import.meta.url);\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak<T extends object>(\n modulePath: string,\n\n // TODO: For now `basePath` can be provided directly as a string here,\n // for backward compatibility. Deprecate it in future, if any other\n // breaking changes are done for requireWeak().\n basePathOrOptions?: RequireWeakOptionsT | string,\n): RequireWeakResT<T> | null {\n if (IS_CLIENT_SIDE) return null;\n\n let basePath: string | undefined;\n let ops: RequireWeakOptionsT;\n if (typeof basePathOrOptions === 'string') {\n basePath = basePathOrOptions;\n } else {\n ops = basePathOrOptions ?? {};\n ({ basePath } = ops);\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { resolve } = require
|
|
1
|
+
{"version":3,"file":"webpack.js","names":[],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import type PathNS from 'node:path';\n\n// eslint-disable-next-line import/enforce-node-protocol-usage, perfectionist/sort-imports\nimport { createRequire } from 'module';\n\nimport { IS_CLIENT_SIDE, IS_SERVER_SIDE } from './isomorphy';\n\ntype RequireWeakOptionsT = {\n basePath?: string;\n};\n\ntype RequireWeakResT<T> = T extends { default: infer D }\n ? (D extends null | undefined ? T : D & Omit<T, 'default'>)\n : T;\n\nlet require: ((url: string) => unknown) | undefined;\n\nif (IS_SERVER_SIDE) require = createRequire(import.meta.url);\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak<T extends object>(\n modulePath: string,\n\n // TODO: For now `basePath` can be provided directly as a string here,\n // for backward compatibility. Deprecate it in future, if any other\n // breaking changes are done for requireWeak().\n basePathOrOptions?: RequireWeakOptionsT | string,\n): RequireWeakResT<T> | null {\n if (IS_CLIENT_SIDE) return null;\n\n if (!require) throw Error('Internal error (missing require)');\n\n let basePath: string | undefined;\n let ops: RequireWeakOptionsT;\n if (typeof basePathOrOptions === 'string') {\n basePath = basePathOrOptions;\n } else {\n ops = basePathOrOptions ?? {};\n ({ basePath } = ops);\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { resolve } = require('node:path') as typeof PathNS;\n\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n\n // eslint-disable-next-line import/no-dynamic-require\n const module = require(path) as T;\n\n if (!('default' in module) || !module.default) return module as RequireWeakResT<T>;\n\n const { default: def, ...named } = module;\n\n const res = def as RequireWeakResT<T>;\n\n Object.entries(named).forEach(([name, value]) => {\n const assigned = res[name as keyof RequireWeakResT<T>];\n if (assigned === undefined) {\n (res[name as keyof RequireWeakResT<T>] as unknown) = value;\n } else if (assigned !== value) {\n throw Error('Conflict between default and named exports');\n }\n });\n return res;\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param modulePath\n * @return Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":"AAEA;AACA,SAAS,aAAa,QAAQ,QAAQ;AAAC,SAE9B,cAAc,EAAE,cAA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;MAC7B,MAAM,KAAK,CAAC,4CAA4C,CAAC;IAC3D;EACF,CAAC,CAAC;EACF,OAAO,GAAG;AACZ,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,WAAW,CAAC,UAAkB,EAAU;EACtD,OAAO,UAAU;AACnB","ignoreList":[]}
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Implements the static cache.
|
|
3
|
-
*/export default class Cache{items=
|
|
3
|
+
*/export default class Cache{items=new Map;size=0;constructor(maxSize){this.maxSize=maxSize;}/**
|
|
4
4
|
* Cache lookup.
|
|
5
5
|
* @param key Item key to look for.
|
|
6
6
|
* @param [maxage=Number.MAX_VALUE] Optional. The maximum age of
|
|
7
7
|
* cached item to serve. Default to infinite.
|
|
8
8
|
* @returns Cached item, or null if the item is absent in cache,
|
|
9
9
|
* or stale.
|
|
10
|
-
*/get({key,maxage=Number.MAX_VALUE}){const item=this.items
|
|
10
|
+
*/get({key,maxage=Number.MAX_VALUE}){const item=this.items.get(key);return item&&Date.now()-item.timestamp<maxage?item.data:null;}/**
|
|
11
11
|
* Adds item to cache.
|
|
12
12
|
* @param data Item to add.
|
|
13
13
|
* @param key Key to store the item at.
|
|
14
14
|
* @param size Byte size of the item.
|
|
15
|
-
*/add(data,key,size){const cached=this.items
|
|
15
|
+
*/add(data,key,size){const cached=this.items.get(key);if(cached)this.size-=cached.size;this.items.set(key,{data,size,timestamp:Date.now()});this.size+=size;if(this.size>this.maxSize){const entries=[...this.items.entries()];entries.sort((a,b)=>a[1].timestamp-b[1].timestamp);for(const entry of entries){const[itemKey,item]=entry;this.items.delete(itemKey);this.size-=item.size;if(this.size<this.maxSize/2)break;}}}}
|
|
16
16
|
//# sourceMappingURL=Cache.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Cache.js","names":[],"sources":["../../../src/server/Cache.ts"],"sourcesContent":["type CachedItemT<DatumT> = {\n data: DatumT;\n size: number;\n timestamp: number;\n};\n\n/**\n * Implements the static cache.\n */\nexport default class Cache<DatumT> {\n private items
|
|
1
|
+
{"version":3,"file":"Cache.js","names":[],"sources":["../../../src/server/Cache.ts"],"sourcesContent":["type CachedItemT<DatumT> = {\n data: DatumT;\n size: number;\n timestamp: number;\n};\n\n/**\n * Implements the static cache.\n */\nexport default class Cache<DatumT> {\n private items = new Map<string, CachedItemT<DatumT>>();\n\n private size = 0;\n\n constructor(private maxSize: number) { }\n\n /**\n * Cache lookup.\n * @param key Item key to look for.\n * @param [maxage=Number.MAX_VALUE] Optional. The maximum age of\n * cached item to serve. Default to infinite.\n * @returns Cached item, or null if the item is absent in cache,\n * or stale.\n */\n get({\n key,\n maxage = Number.MAX_VALUE,\n }: {\n key: string;\n maxage?: number;\n }): DatumT | null {\n const item = this.items.get(key);\n return item && Date.now() - item.timestamp < maxage ? item.data : null;\n }\n\n /**\n * Adds item to cache.\n * @param data Item to add.\n * @param key Key to store the item at.\n * @param size Byte size of the item.\n */\n add(data: DatumT, key: string, size: number): void {\n const cached = this.items.get(key);\n if (cached) this.size -= cached.size;\n\n this.items.set(key, { data, size, timestamp: Date.now() });\n this.size += size;\n\n if (this.size > this.maxSize) {\n const entries = [...this.items.entries()];\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp);\n\n for (const entry of entries) {\n const [itemKey, item] = entry;\n this.items.delete(itemKey);\n this.size -= item.size;\n if (this.size < this.maxSize / 2) break;\n }\n }\n }\n}\n"],"mappings":"AAMA;AACA;AACA,GACA,cAAe,MAAM,MAAc,CACzB,KAAK,CAAG,GAAI,IAAkC,CAE9C,IAAI,CAAG,CAAC,CAEhB,WAAW,CAAS,OAAe,CAAE,MAAjB,OAAe,CAAf,OAAmB,EAEvC;AACF;AACA;AACA;AACA;AACA;AACA;AACA,KACE,GAAG,CAAC,CACF,GAAG,CACH,MAAM,CAAG,MAAM,CAAC,SAIlB,CAAC,CAAiB,CAChB,KAAM,KAAI,CAAG,IAAI,CAAC,KAAK,C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./renderer
|
|
|
127
127
|
*/export async function launchServer(webpackConfig,options={}){/* Options normalization. */const ops=cloneDeep(options);// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
|
128
128
|
ops.port=normalizePort(ops.port||process.env.PORT||3000);defaults(ops,{httpsRedirect:true});// TODO: Need a separate type for normalized options, which guarantees
|
|
129
129
|
// the logger is set!
|
|
130
|
-
ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});/* Creates servers, resolves and sets the port. */const expressServer=await serverFactory(webpackConfig,ops);let httpServer;if(ops.https){httpServer=https.createServer({cert:ops.https.cert,key:ops.https.key},expressServer);}else httpServer=http.createServer(expressServer);/* Sets error handler for HTTP(S) server. */httpServer.on("error",error=>{if(error.syscall!=="listen")throw error;const bind=typeof ops.port==="string"?`Pipe ${ops.port}`:`Port ${ops.port}
|
|
130
|
+
ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});/* Creates servers, resolves and sets the port. */const expressServer=await serverFactory(webpackConfig,ops);let httpServer;if(ops.https){httpServer=https.createServer({cert:ops.https.cert,key:ops.https.key},expressServer);}else httpServer=http.createServer(expressServer);/* Sets error handler for HTTP(S) server. */httpServer.on("error",error=>{if(error.syscall!=="listen")throw error;const bind=typeof ops.port==="string"?`Pipe ${ops.port}`:`Port ${ops.port?ops.port.toString():"undefined"}`;if(!ops.logger)throw Error("Missing logger");/* Human-readable message for some specific listen errors. */switch(error.code){case"EACCES":ops.logger.error(`${bind} requires elevated privileges`);return process.exit(1);case"EADDRINUSE":ops.logger.error(`${bind} is already in use`);return process.exit(1);case undefined:default:throw error;}});/* Listening event handler for HTTP(S) server. */httpServer.on("listening",()=>{const addr=httpServer.address();if(!addr)throw Error("Missing address");const bind=typeof addr==="string"?`pipe ${addr}`:`port ${addr.port.toString()}`;if(!ops.logger)throw Error("Missing logger");ops.logger.info(`Server listening on ${bind} in ${process.env.NODE_ENV??"undefined"} mode`);});httpServer.listen(ops.port);return{expressServer,httpServer};}
|
|
131
131
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register.js';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport { cloneDeep, defaults } from 'lodash-es';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill.js';\n\nimport type { Configuration } from 'webpack';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nexport * from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport {\n SCRIPT_LOCATIONS,\n type ServerT,\n getDefaultCspSettings,\n};\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String).\n */\nfunction normalizePort(value: number | string) {\n const port = typeof value === 'string' ? parseInt(value) : value;\n if (Number.isFinite(port)) return port; /* port number */\n return value; /* named pipe */\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` ⇒ `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel='info'] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` – the cache key for the response;\n * - `maxage?: number` – the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @return Resolves to an object with created Express and HTTP servers.\n */\nexport async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = typeof ops.port === 'string' ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger!.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger!.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address()!;\n const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger!.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n"],"mappings":"AAAA;AACA,MAAO,gCAAgC,CAEvC,MAAO,KAAI,KAAM,WAAW,CAC5B,MAAO,MAAK,KAAM,YAAY,CAE9B,OAAS,SAAS,CAAE,QAAQ,KAAQ,WAAW,CAE/C;AACA;AACA;AACA,MAAO,iBAAiB,CAAC,OAIhB,gBAAgB,CAAE,gBAAgB,2BAEpC,cAAa,EAGlB,qBAAqB,iDAYvB,OACE,gBAAgB,CAEhB,qBAAqB,EAGvB;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,cAAa,CAAC,KAAsB,CAAE,CAC7C,KAAM,KAAI,CAAG,MAAO,MAAK,GAAK,QAAQ,CAAG,QAAQ,CAAC,KAAK,CAAC,CAAG,KAAK,CAChE,GAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAE,MAAO,KAAI,CAAE,iBACxC,MAAO,MAAK,CAAE,gBAChB,CAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,eAAe,aAAY,CAChC,aAA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,KAAK,CAAC,GAAG,IAAI,oBAAoB,CAAC,CAC9C,MAAO,QAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CACxB,IAAK,UAAS,CACd,QACE,KAAM,MAAK,CACf,CACF,CAAC,CAAC,CAEF,iDACA,UAAU,CAAC,EAAE,CAAC,WAAW,CAAE,IAAM,CAC/B,KAAM,KAAI,CAAG,UAAU,CAAC,OAAO,CAAC,CAAE,CAClC,KAAM,KAAI,CAAG,MAAO,KAAI,GAAK,QAAQ,CAAG,QAAQ,IAAI,EAAE,CAAG,QAAQ,IAAI,CAAC,IAAI,EAAE,CAC5E,GAAG,CAAC,MAAM,CAAE,IAAI,CAAC,uBAAuB,IAAI,OAC1C,OAAO,CAAC,GAAG,CAAC,QAAQ,OAAO,CAAC,CAChC,CAAC,CAAC,CAEF,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAE3B,MAAO,CACL,aAAa,CACb,UACF,CAAC,CACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register.js';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport { cloneDeep, defaults } from 'lodash-es';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill.js';\n\nimport type { Configuration } from 'webpack';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nexport * from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport {\n SCRIPT_LOCATIONS,\n type ServerT,\n getDefaultCspSettings,\n};\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String).\n */\nfunction normalizePort(value: number | string) {\n const port = typeof value === 'string' ? parseInt(value) : value;\n if (Number.isFinite(port)) return port; /* port number */\n return value; /* named pipe */\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` ⇒ `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel='info'] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` – the cache key for the response;\n * - `maxage?: number` – the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @return Resolves to an object with created Express and HTTP servers.\n */\nexport async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = typeof ops.port === 'string'\n ? `Pipe ${ops.port}`\n : `Port ${ops.port ? ops.port.toString() : 'undefined'}`;\n\n if (!ops.logger) throw Error('Missing logger');\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address();\n if (!addr) throw Error('Missing address');\n\n const bind = typeof addr === 'string'\n ? `pipe ${addr}` : `port ${addr.port.toString()}`;\n\n if (!ops.logger) throw Error('Missing logger');\n ops.logger.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV ?? 'undefined'} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n"],"mappings":"AAAA;AACA,MAAO,gCAAgC,CAEvC,MAAO,KAAI,KAAM,WAAW,CAC5B,MAAO,MAAK,KAAM,YAAY,CAE9B,OAAS,SAAS,CAAE,QAAQ,KAAQ,WAAW,CAE/C;AACA;AACA;AACA,MAAO,iBAAiB,CAAC,OAIhB,gBAAgB,CAAE,gBAAgB,2BAEpC,cAAa,EAGlB,qBAAqB,iDAYvB,OACE,gBAAgB,CAEhB,qBAAqB,EAGvB;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,cAAa,CAAC,KAAsB,CAAE,CAC7C,KAAM,KAAI,CAAG,MAAO,MAAK,GAAK,QAAQ,CAAG,QAAQ,CAAC,KAAK,CAAC,CAAG,KAAK,CAChE,GAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAE,MAAO,KAAI,CAAE,iBACxC,MAAO,MAAK,CAAE,gBAChB,CAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,eAAe,aAAY,CAChC,aAA4B,CAC5B,OAAiB,CAAG,CAAC,CAAC,CAIrB,CACD,4BACA,KAAM,IAAG,CAAG,SAAS,CAAC,OAAO,CAAC,CAE9B;AACA,GAAG,CAAC,IAAI,CAAG,aAAa,CAAC,GAAG,CAAC,IAAI,EAAI,OAAO,CAAC,GAAG,CAAC,IAAI,EAAI,IAAI,CAAC,CAC9D,QAAQ,CAAC,GAAG,CAAE,CAAE,aAAa,CAAE,IAAK,CAAC,CAAC,CAEtC;AACA;AACA,GAAG,CAAC,MAAM,GAAK,gBAAgB,CAAC,CAC9B,eAAe,CAAE,GAAG,CAAC,qBACvB,CAAC,CAAC,CAEF,kDACA,KAAM,cAAa,CAAG,KAAM,cAAa,CAAC,aAAa,CAAE,GAAG,CAAC,CAE7D,GAAI,WAAuB,CAC3B,GAAI,GAAG,CAAC,KAAK,CAAE,CACb,UAAU,CAAG,KAAK,CAAC,YAAY,CAAC,C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