@dr.pogodin/react-utils 1.58.0 → 1.58.1
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/client/getInj.js +17 -2
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/server/Cache.js +35 -3
- package/build/development/server/Cache.js.map +1 -1
- package/build/development/server/renderer.js +53 -7
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +8 -6
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/errors.js +11 -11
- package/build/development/server/utils/errors.js.map +1 -1
- package/build/development/server/utils/modules.js +35 -1
- package/build/development/server/utils/modules.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +5 -2
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +3 -0
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +5 -2
- 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/jest/E2eSsrEnv/index.js +10 -10
- package/build/development/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/development/shared/utils/jest/index.js +3 -3
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +77 -3
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/webpack.js +3 -1
- package/build/development/shared/utils/webpack.js.map +1 -1
- package/build/production/client/getInj.js +1 -1
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/server/Cache.js +1 -1
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/renderer.js +4 -4
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +4 -4
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/errors.js +2 -2
- package/build/production/server/utils/errors.js.map +1 -1
- package/build/production/server/utils/modules.js +1 -1
- package/build/production/server/utils/modules.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/jest/E2eSsrEnv/index.js +3 -3
- package/build/production/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/production/shared/utils/jest/index.js +3 -3
- 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 +1 -1
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/web/client/getInj.js +1 -1
- package/build/web/client/getInj.js.map +1 -1
- package/build/web/server/Cache.js +1 -1
- package/build/web/server/Cache.js.map +1 -1
- package/build/web/server/renderer.js +4 -4
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/server/server.js +4 -4
- package/build/web/server/server.js.map +1 -1
- package/build/web/server/utils/errors.js +2 -2
- package/build/web/server/utils/errors.js.map +1 -1
- package/build/web/server/utils/modules.js +1 -1
- package/build/web/server/utils/modules.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/jest/E2eSsrEnv/index.js +3 -3
- package/build/web/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/web/shared/utils/jest/index.js +3 -3
- 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 +1 -1
- package/build/web/shared/utils/webpack.js.map +1 -1
- package/config/babel/webpack.js +11 -2
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["id","selected","e","openList","dropdownRef","opsContainerClass","opsPos","opsRef","containerClassName"],"sources":["../../../../../../src/shared/components/selectors/CustomDropdown/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { useTheme } from '@dr.pogodin/react-themes';\n\nimport { type PropsT, type ValueT, optionValueName } from '../common';\n\nimport Options, { type ContainerPosT, type RefT, areEqual } from './Options';\n\nimport defaultTheme from './theme.scss';\n\nconst CustomDropdown: FunctionComponent<\n PropsT<ReactNode, (value: ValueT) => void>\n> = ({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const custom = useTheme('CustomDropdown', defaultTheme, theme);\n\n const [active, setActive] = useState(false);\n\n const dropdownRef = useRef<HTMLDivElement>(null);\n const opsRef = useRef<RefT>(null);\n\n const [opsPos, setOpsPos] = useState<ContainerPosT>();\n const [upward, setUpward] = useState(false);\n\n useEffect(() => {\n if (!active) return undefined;\n\n let id: number;\n const cb = () => {\n const anchor = dropdownRef.current?.getBoundingClientRect();\n const opsRect = opsRef.current?.measure();\n if (anchor && opsRect) {\n const fitsDown = anchor.bottom + opsRect.height\n < (window.visualViewport?.height ?? 0);\n const fitsUp = anchor.top - opsRect.height > 0;\n\n const up = !fitsDown && fitsUp;\n setUpward(up);\n\n const pos = up ? {\n left: anchor.left,\n top: anchor.top - opsRect.height - 1,\n width: anchor.width,\n } : {\n left: anchor.left,\n top: anchor.bottom,\n width: anchor.width,\n };\n\n setOpsPos((now) => (areEqual(now, pos) ? now : pos));\n }\n id = requestAnimationFrame(cb);\n };\n requestAnimationFrame(cb);\n\n return () => {\n cancelAnimationFrame(id);\n };\n }, [active]);\n\n const openList = (\n e: React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLDivElement>,\n ) => {\n const view = window.visualViewport;\n if (!dropdownRef.current) throw Error('Missing dropdown reference');\n const rect = dropdownRef.current.getBoundingClientRect();\n setActive(true);\n\n // NOTE: This first opens the dropdown off-screen, where it is measured\n // by an effect declared above, and then positioned below, or above\n // the original dropdown element, depending where it fits best\n // (if we first open it downward, it would flick if we immediately\n // move it above, at least with the current position update via local\n // react state, and not imperatively).\n setOpsPos({\n left: view?.width ?? 0,\n top: view?.height ?? 0,\n width: rect.width,\n });\n\n e.stopPropagation();\n };\n\n let selected: React.ReactNode = <>‌</>;\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n if (iValue === value) {\n selected = iName;\n break;\n }\n }\n }\n\n let containerClassName = custom.container ?? '';\n if (active) containerClassName += ` ${custom.active ?? ''}`;\n\n let opsContainerClass = custom.select ?? '';\n if (upward) {\n containerClassName += ` ${custom.upward ?? ''}`;\n opsContainerClass += ` ${custom.upward ?? ''}`;\n }\n\n return (\n <div className={containerClassName}>\n {label === undefined ? null\n : <div className={custom.label}>{label}</div>}\n <div\n className={custom.dropdown}\n onClick={openList}\n onKeyDown={(e) => {\n if (e.key === 'Enter') openList(e);\n }}\n ref={dropdownRef}\n role=\"listbox\"\n tabIndex={0}\n >\n {selected}\n <div className={custom.arrow} />\n </div>\n {\n active ? (\n <Options\n containerClass={opsContainerClass}\n containerStyle={opsPos}\n onCancel={() => {\n setActive(false);\n }}\n onChange={(newValue) => {\n setActive(false);\n if (onChange) onChange(newValue);\n }}\n optionClass={custom.option ?? ''}\n options={options}\n ref={opsRef}\n />\n ) : null\n }\n </div>\n );\n};\n\nexport default CustomDropdown;\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":["id","selected","e","openList","dropdownRef","opsContainerClass","opsPos","opsRef","containerClassName"],"sources":["../../../../../../src/shared/components/selectors/CustomDropdown/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { useTheme } from '@dr.pogodin/react-themes';\n\nimport { type PropsT, type ValueT, optionValueName } from '../common';\n\nimport Options, { type ContainerPosT, type RefT, areEqual } from './Options';\n\nimport defaultTheme from './theme.scss';\n\nconst CustomDropdown: FunctionComponent<\n PropsT<ReactNode, (value: ValueT) => void>\n> = ({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const custom = useTheme('CustomDropdown', defaultTheme, theme);\n\n const [active, setActive] = useState(false);\n\n const dropdownRef = useRef<HTMLDivElement>(null);\n const opsRef = useRef<RefT>(null);\n\n const [opsPos, setOpsPos] = useState<ContainerPosT>();\n const [upward, setUpward] = useState(false);\n\n useEffect(() => {\n if (!active) return undefined;\n\n let id: number;\n const cb = () => {\n const anchor = dropdownRef.current?.getBoundingClientRect();\n const opsRect = opsRef.current?.measure();\n if (anchor && opsRect) {\n const fitsDown = anchor.bottom + opsRect.height\n < (window.visualViewport?.height ?? 0);\n const fitsUp = anchor.top - opsRect.height > 0;\n\n const up = !fitsDown && fitsUp;\n setUpward(up);\n\n const pos = up ? {\n left: anchor.left,\n top: anchor.top - opsRect.height - 1,\n width: anchor.width,\n } : {\n left: anchor.left,\n top: anchor.bottom,\n width: anchor.width,\n };\n\n setOpsPos((now) => (areEqual(now, pos) ? now : pos));\n }\n id = requestAnimationFrame(cb);\n };\n requestAnimationFrame(cb);\n\n return () => {\n cancelAnimationFrame(id);\n };\n }, [active]);\n\n const openList = (\n e: React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLDivElement>,\n ) => {\n const view = window.visualViewport;\n if (!dropdownRef.current) throw Error('Missing dropdown reference');\n const rect = dropdownRef.current.getBoundingClientRect();\n setActive(true);\n\n // NOTE: This first opens the dropdown off-screen, where it is measured\n // by an effect declared above, and then positioned below, or above\n // the original dropdown element, depending where it fits best\n // (if we first open it downward, it would flick if we immediately\n // move it above, at least with the current position update via local\n // react state, and not imperatively).\n setOpsPos({\n left: view?.width ?? 0,\n top: view?.height ?? 0,\n width: rect.width,\n });\n\n e.stopPropagation();\n };\n\n let selected: React.ReactNode = <>‌</>;\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n if (iValue === value) {\n selected = iName;\n break;\n }\n }\n }\n\n let containerClassName = custom.container ?? '';\n if (active) containerClassName += ` ${custom.active ?? ''}`;\n\n let opsContainerClass = custom.select ?? '';\n if (upward) {\n containerClassName += ` ${custom.upward ?? ''}`;\n opsContainerClass += ` ${custom.upward ?? ''}`;\n }\n\n return (\n <div className={containerClassName}>\n {label === undefined ? null\n : <div className={custom.label}>{label}</div>}\n <div\n className={custom.dropdown}\n onClick={openList}\n onKeyDown={(e) => {\n if (e.key === 'Enter') openList(e);\n }}\n ref={dropdownRef}\n role=\"listbox\"\n tabIndex={0}\n >\n {selected}\n <div className={custom.arrow} />\n </div>\n {\n active ? (\n <Options\n containerClass={opsContainerClass}\n containerStyle={opsPos}\n onCancel={() => {\n setActive(false);\n }}\n onChange={(newValue) => {\n setActive(false);\n if (onChange) onChange(newValue);\n }}\n optionClass={custom.option ?? ''}\n options={options}\n ref={opsRef}\n />\n ) : null\n }\n </div>\n );\n};\n\nexport default CustomDropdown;\n"],"mappings":"6IAAA,OAGE,SAAS,CACT,MAAM,CACN,QAAQ,KACH,OAAO,CAEd,OAAS,QAAQ,KAAQ,0BAA0B,CAAC,OAEjB,eAAe,0BAE3C,QAAO,EAAmC,QAAQ,0BAEzD,MAA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AEV,CACIC,GAAW,CAAX,WAAW,CACX,IAAS,CAAT,SAAS,CACJ,QAAC,CAAD,CAAC,WAEV,QAAQ,CACT,EAAgC,EAC7B,CAAC,qMAEJ,SAAM,cAAN,KACG,OAAO,EACUC,cAAiB,CAAjB,iBAAiB,CACjBC,cAAM,CAAN,MAAM,CACZ,QAET,CAFS,KACR,SAAS,CAAC,KAAK,CAAC,CACjB,CACS,QAGT,CAHS,WACR,SAAS,CAAC,KAAK,CAAC,CAChB,GAAI,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAClC,CACY,WAAmB,CAAnB,MAAM,OAAa,EAAnB,EAAmB,CACvB,OAAO,CAAP,OAAO,CACXC,GAAM,CAAN,MAAM,CAER,CAAC,CAfR,IAeQ,sMAhCZ,8BAAgBC,SAAkB,CAAlB,kBAAkB,WAC/B,EAC8C,CAC/C,EAYM,CAEJ,EAeQ,EAEP,CAAC,oFAlCN,IAkCM,CAET,CAED,cAAe,eAAc","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";// Implements dropdown based on the native HTML <select> element.
|
|
2
2
|
import{useTheme}from"@dr.pogodin/react-themes";import{optionValueName}from"../common.js";import defaultTheme from"./theme.scss";/**
|
|
3
3
|
* Implements a themeable dropdown list. Internally it is rendered with help of
|
|
4
4
|
* the standard HTML `<select>` element, thus the styling support is somewhat
|
|
@@ -17,7 +17,7 @@ import{useTheme}from"@dr.pogodin/react-themes";import{optionValueName}from"../co
|
|
|
17
17
|
* @param [props.value] Currently selected value.
|
|
18
18
|
* @param [props....]
|
|
19
19
|
* [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)
|
|
20
|
-
*/import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const Dropdown=({filter,label,onChange,onClick,options,testId,theme,value})=>{let isValidValue=false;const optionElements=[];const composed=useTheme("Dropdown",defaultTheme,theme);for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);isValidValue||=iValue===value;
|
|
20
|
+
*/import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const Dropdown=({filter,label,onChange,onClick,options,testId,theme,value})=>{let isValidValue=false;const optionElements=[];const composed=useTheme("Dropdown",defaultTheme,theme);for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);isValidValue||=iValue===value;optionElements.push(/*#__PURE__*/_jsx("option",{className:composed.option,value:iValue,children:iName},iValue));}}// NOTE: This element represents the current `value` when it does not match
|
|
21
21
|
// any valid option. In Chrome, and some other browsers, we are able to hide
|
|
22
22
|
// it from the opened dropdown; in others, e.g. Safari, the best we can do is
|
|
23
23
|
// to show it as disabled.
|
|
@@ -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":"0IAAA;AAIA,OAAS,QAAQ,KAAQ,0BAA0B,CAAC,OAE9B,eAAe,oBAErC,MAAO,aAAY,oBAEnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAlBA,yDAmBA,KAAM,SAA2C,CAAG,CAAC,CACnD,MAAM,CACN,KAAK,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E,OAAQ,CACjB,KAAK,CAAE,KAAM,WAEZ,YAAY,CACZ,cAAc,EACT,CAAC,cACT,YAAK,SAAS,CAAE,QAAQ,CAAC,KAAM,CAAE,CAAC,EAC/B,CAAC,EACH,CAAC,CAEV,CAAC,CAED,cAAe,SAAQ","ignoreList":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
1
|
+
import"core-js/modules/es.array.push.js";import{c as _c}from"react/compiler-runtime";import{useTheme}from"@dr.pogodin/react-themes";import{optionValueName}from"../common.js";import defaultTheme from"./theme.scss";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";export const Switch=t0=>{const $=_c(16);const{label,onChange,options,theme,value}=t0;const composed=useTheme("Switch",defaultTheme,theme);if(!options||!composed.option){throw Error("Internal error");}let optionNodes;if($[0]!==composed.option||$[1]!==composed.selected||$[2]!==onChange||$[3]!==options||$[4]!==value){optionNodes=[];for(const option of options){const[iValue,iName]=optionValueName(option);let className=composed.option;let onPress;if(iValue===value){className=className+` ${composed.selected??""}`;}else{if(onChange){onPress=()=>{onChange(iValue)};}}optionNodes.push(onPress?/*#__PURE__*/_jsx("div",{className:className,onClick:onPress,onKeyDown:e=>{if(e.key==="Enter"){onPress()}},role:"button",tabIndex:0,children:iName},iValue):/*#__PURE__*/_jsx("div",{className:className,children:iName},iValue))}$[0]=composed.option;$[1]=composed.selected;$[2]=onChange;$[3]=options;$[4]=value;$[5]=optionNodes}else{optionNodes=$[5]}let t1;if($[6]!==composed.label||$[7]!==label){t1=label?/*#__PURE__*/_jsx("div",{className:composed.label,children:label}):null;$[6]=composed.label;$[7]=label;$[8]=t1}else{t1=$[8]}let t2;if($[9]!==composed.options||$[10]!==optionNodes){t2=/*#__PURE__*/_jsx("div",{className:composed.options,children:optionNodes});$[9]=composed.options;$[10]=optionNodes;$[11]=t2}else{t2=$[11]}let t3;if($[12]!==composed.container||$[13]!==t1||$[14]!==t2){t3=/*#__PURE__*/_jsxs("div",{className:composed.container,children:[t1,t2]});$[12]=composed.container;$[13]=t1;$[14]=t2;$[15]=t3}else{t3=$[15]}return t3};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["onPress"],"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":"
|
|
1
|
+
{"version":3,"file":"index.js","names":["onPress"],"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":"qFAEA,OAAqB,QAAQ,KAAQ,0BAA0B,CAAC,OAK9D,eAAe,oBAGjB,MAAO,aAAY,oBAAqB,yDAYxC,MAAO,MAAM,OAAiC,CAAG,oBAAC,4CAMjD,CACC,eAAiB,QAAQ,CAAC,QAAQ,CAAE,YAAY,CAAE,KAAK,CAAC,CAExD,GAAI,CAAC,OAA2B,EAA5B,CAAa,QAAQ,OAAO,EAAE,KAAM,MAAK,CAAC,gBAAgB,CAAC,CAAC,qHAEhE,YAAuC,EAAE,CACzC,IAAK,YAAY,GAAI,QAAO,EAC1B,oBAAwB,eAAe,CAAC,MAAM,CAAC,CAE/C,cAAwB,QAAQ,OAAO,CACnCA,GAAA,SACJ,GAAI,MAAM,GAAK,KAAK,EAAE,mBAAS,CAAI,IAAI,QAAQ,SAAe,EAAvB,EAAuB,EAAE,OAC3D,GAAI,QAAQ,EACf,OAAAA,CAAUA,KACR,QAAQ,CAAC,MAAM,CAAC,CACjB,CAFM,CAGR,CAED,WAAW,KAAK,CACd,OAAO,cAAP,YAGiB,SAAS,CAAT,SAAS,CAEXA,OAAO,CAAP,OAAO,CACL,SAEV,CAFU,IACT,GAAI,CAAC,IAAI,GAAK,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,CAClC,CACI,IAAQ,CAAR,QAAQ,CACH,QAAC,CAAD,CAAC,UAEV,KAAK,EARD,MAW6C,CAAC,cAfzD,YAeoB,SAAS,CAAT,SAAS,UAAgB,KAAK,EAAd,MAAoB,CAC1D,CAAC,CACF,wKAII,QAAK,cAAL,YAAwB,SAAc,CAAd,QAAQ,MAAM,UAAG,KAAK,CAAa,CAAC,CAA5D,IAA4D,6GAE7D,4BAAgB,SAAgB,CAAhB,QAAQ,QAAQ,UAC7B,WAAW,CACT,CAAC,8HALR,6BAAgB,SAAkB,CAAlB,QAAQ,UAAU,WAC/B,EAA4D,CAE7D,EAEM,EACH,CAAC,yEANN,GAMM,CAET","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import"core-js/modules/es.json.parse.js";/**
|
|
2
2
|
* Jest environment for end-to-end SSR and client-side testing. It relies on
|
|
3
3
|
* the standard react-utils mechanics to execute SSR of given scene, and also
|
|
4
4
|
* Webpack build of the code for client-side execution, it further exposes
|
|
@@ -19,7 +19,7 @@ import _JSON$parse from"core-js-pure/features/json/parse.js";/**
|
|
|
19
19
|
}throw Error(`Module "${module}" was not found, neither as TS, nor as JS`);}export default class E2eSsrEnv extends JsdomEnv{pragmas;ssrRequest;rootDir;testFolder;withSsr;webpackStats;/**
|
|
20
20
|
* Loads Webpack config, and exposes it to the environment via global
|
|
21
21
|
* webpackConfig object.
|
|
22
|
-
*/async loadWebpackConfig(){const optionsString=this.pragmas["webpack-config-options"];const options=optionsString?
|
|
22
|
+
*/async loadWebpackConfig(){const optionsString=this.pragmas["webpack-config-options"];const options=optionsString?JSON.parse(optionsString):{};defaults(options,{context:this.testFolder,fs:this.global.webpackOutputFs});const factoryPath=this.pragmas["webpack-config-factory"];let factory=await import(/* webpackChunkName: "not-a-valid-chunk" */path.resolve(this.rootDir,factoryPath));factory="default"in factory?factory.default:factory;this.global.webpackConfig=factory(options);const fs=this.global.webpackOutputFs;if(!options.context)throw Error("Missing context");let buildInfo=`${options.context}/.build-info`;if(fs.existsSync(buildInfo)){buildInfo=fs.readFileSync(buildInfo,"utf8");this.global.buildInfo=JSON.parse(buildInfo);}}/**
|
|
23
23
|
* Executes Webpack build.
|
|
24
24
|
* @return {Promise}
|
|
25
25
|
*/async runWebpack(){await this.loadWebpackConfig();if(!this.global.webpackConfig)throw Error("Failed to load Webpack config");const compiler=webpack(this.global.webpackConfig);// TODO: The "as typeof compiler.outputFileSystem" piece below is
|
|
@@ -34,7 +34,7 @@ this.webpackStats=stats;done();});});}async runSsr(){// NOTE: This is a TS modul
|
|
|
34
34
|
// on it for the forked NodeJS process, we need to resolve the correct
|
|
35
35
|
// extention ourselves (as NodeJS will hit the given path, without any
|
|
36
36
|
// additional resolutions / transformations).
|
|
37
|
-
const ssrModulePath=await findModule(`${import.meta.dirname}/ssr-preload`);const cp=fork(ssrModulePath);const optionsString=this.pragmas["ssr-options"];const options=optionsString?
|
|
37
|
+
const ssrModulePath=await findModule(`${import.meta.dirname}/ssr-preload`);const cp=fork(ssrModulePath);const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON.parse(optionsString):{};options.buildInfo??=this.global.buildInfo;if(!this.webpackStats)throw Error("Missing Webpack stats");options.chunkGroups=deduceChunkGroups(this.webpackStats);return new Promise((resolve,reject)=>{cp.on("exit",code=>{if(code)reject(Error("SSR process crashed"));});cp.on("message",message=>{this.global.ssrMarkup=message.markup;this.global.ssrOptions=options;this.global.ssrStatus=message.status;cp.kill();resolve();});if(!this.global.webpackConfig)throw Error("Missing Webpack config");cp.send({options,root:options.root==="TEST"?this.testFolder:process.cwd(),ssrRequest:this.ssrRequest,testFolder:this.testFolder,webpackConfig:this.global.webpackConfig});});}constructor(config,context){const pragmas=context.docblockPragmas;const requestString=pragmas["ssr-request"];const request=requestString?JSON.parse(requestString):{};request.url??="/";// This ensures the initial JsDom URL matches the value we use for SSR.
|
|
38
38
|
set(config.projectConfig,"testEnvironmentOptions.url",`http://localhost${request.url}`);super(config,context);this.global.dom=this.dom;this.global.webpackOutputFs=createFsFromVolume(new Volume);// Extracts necessary settings from config and context.
|
|
39
39
|
const{projectConfig}=config;this.rootDir=projectConfig.rootDir;this.testFolder=path.dirname(context.testPath);this.withSsr=!pragmas["no-ssr"];this.ssrRequest=request;this.pragmas=pragmas;// BEWARE: Anything imported prior to this register() call seems to be
|
|
40
40
|
// transpiled again by Babel if loaded after this call. This causes very
|
|
@@ -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 if (!options.context) throw Error('Missing context');\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n // NOTE: This is a TS module in the source code, and it turn into JS\n // module in the distributed code, after Babel compilation. As we rely\n // on it for the forked NodeJS process, we need to resolve the correct\n // extention ourselves (as NodeJS will hit the given path, without any\n // additional resolutions / transformations).\n const ssrModulePath = await findModule(`${import.meta.dirname}/ssr-preload`);\n\n const cp = fork(ssrModulePath);\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve, reject) => {\n cp.on('exit', (code) => {\n if (code) reject(Error('SSR process crashed'));\n });\n\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n // BEWARE: Although we also do the registration inside SSR testing code,\n // we still need it here to correctly process imported Webpack configurations\n // (which are imported directly from this module).\n register({\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // eslint-disable-next-line import/dynamic-import-chunkname\n const { setBuildInfo } = await import('../../isomorphy/buildInfo');\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n revert();\n\n await super.teardown();\n }\n}\n"],"mappings":"6DAAA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA,sDAEA,OAAS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OAAO,CAAG,OAAO,CAEtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,CAAC,CACP,UAAU,CAAE,CAAC,KAAK,CAAE,MAAM,CAAE,KAAK,CAAE,MAAM,CAAE,MAAM,CACnD,CAAC,CAAC,CACJ,CAEA,KAAM,MAAK,EAAkB,CAC3B,KAAM,MAAK,CAAC,KAAK,CAAC,CAAC,CACnB,KAAM,KAAI,CAAC,UAAU,CAAC,CAAC,CAEvB;AACA,KAAM,CAAE,YAAa,CAAC,CAAG,KAAM,OAAM,gCAA6B,CAClE,YAAY,CAAC,SAAS,CAAE,IAAI,CAAC,CAE7B,GAAI,IAAI,CAAC,OAAO,CAAE,KAAM,KAAI,CAAC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC,MAAM,CAAC,6BAA6B,CAAG,IAAI,CAClD,CAEA,KAAM,SAAQ,EAAkB,CAC9B,MAAO,KAAI,CAAC,MAAM,CAAC,6BAA6B,CAEhD,MAAM,CAAC,CAAC,CAER,KAAM,MAAK,CAAC,QAAQ,CAAC,CAAC,CACxB,CACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/index.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport { fork } from 'node:child_process';\nimport { access } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration, type Stats } from 'webpack';\n\nimport register, { revert } from '@babel/register';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport { deduceChunkGroups } from 'server/renderer';\n\nimport type { LaunchT, ResultT } from './ssr';\n\nasync function findModule(module: string): Promise<string> {\n try {\n const res = `${module}.ts`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n try {\n const res = `${module}.js`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n throw Error(`Module \"${module}\" was not found, neither as TS, nor as JS`);\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: Stats;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private async loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n if (!options.context) throw Error('Missing context');\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n // NOTE: This is a TS module in the source code, and it turn into JS\n // module in the distributed code, after Babel compilation. As we rely\n // on it for the forked NodeJS process, we need to resolve the correct\n // extention ourselves (as NodeJS will hit the given path, without any\n // additional resolutions / transformations).\n const ssrModulePath = await findModule(`${import.meta.dirname}/ssr-preload`);\n\n const cp = fork(ssrModulePath);\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve, reject) => {\n cp.on('exit', (code) => {\n if (code) reject(Error('SSR process crashed'));\n });\n\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n // BEWARE: Although we also do the registration inside SSR testing code,\n // we still need it here to correctly process imported Webpack configurations\n // (which are imported directly from this module).\n register({\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // eslint-disable-next-line import/dynamic-import-chunkname\n const { setBuildInfo } = await import('../../isomorphy/buildInfo');\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n revert();\n\n await super.teardown();\n }\n}\n"],"mappings":"yCAAA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AAC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,CAAC,OAAO,CAAC,QAAQ,CAAC,CACjC,IAAI,CAAC,UAAU,CAAG,OAAO,CACzB,IAAI,CAAC,OAAO,CAAG,OAAO,CAEtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,CAAC,CACP,UAAU,CAAE,CAAC,KAAK,CAAE,MAAM,CAAE,KAAK,CAAE,MAAM,CAAE,MAAM,CACnD,CAAC,CAAC,CACJ,CAEA,KAAM,MAAK,EAAkB,CAC3B,KAAM,MAAK,CAAC,KAAK,CAAC,CAAC,CACnB,KAAM,KAAI,CAAC,UAAU,CAAC,CAAC,CAEvB;AACA,KAAM,CAAE,YAAa,CAAC,CAAG,KAAM,OAAM,gCAA6B,CAClE,YAAY,CAAC,SAAS,CAAE,IAAI,CAAC,CAE7B,GAAI,IAAI,CAAC,OAAO,CAAE,KAAM,KAAI,CAAC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC,MAAM,CAAC,6BAA6B,CAAG,IAAI,CAClD,CAEA,KAAM,SAAQ,EAAkB,CAC9B,MAAO,KAAI,CAAC,MAAM,CAAC,6BAA6B,CAEhD,MAAM,CAAC,CAAC,CAER,KAAM,MAAK,CAAC,QAAQ,CAAC,CAAC,CACxB,CACF","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import"core-js/modules/es.json.stringify.js";/* global document *//* eslint-disable import/no-extraneous-dependencies */import mockdate from"mockdate";import{act}from"react";import{createRoot}from"react-dom/client";import{expect,jest}from"@jest/globals";import{render}from"@testing-library/react";/**
|
|
2
2
|
* An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)
|
|
3
3
|
* from `react`.
|
|
4
4
|
*/export{act};export{default as getGlobal}from"./global.js";global.IS_REACT_ACT_ENVIRONMENT=true;const originalProcessVersions=process.versions;/**
|
|
@@ -13,8 +13,8 @@ import _JSON$stringify from"core-js-pure/features/json/stringify.js";/* global d
|
|
|
13
13
|
* @return {string}
|
|
14
14
|
*/export function getMockUuid(seed=0){const x=seed.toString(16).padStart(32,"0");return`${x.slice(0,8)}-${x.slice(8,12)}-${x.slice(12,16)}-${x.slice(16,20)}-${x.slice(20)}`;}export function mockAxios(handlers){const axios=jest.requireActual("axios");axios.defaults.adapter=async config=>{for(const handler of handlers){const res=handler(config);if(res){return{config:config,data:null,headers:{},status:200,statusText:"OK",...res};}}// Fallback to the regular network request.
|
|
15
15
|
let res;try{res=await axios({...config,adapter:["xhr","http","fetch"]});// eslint-disable-next-line no-console
|
|
16
|
-
console.warn("Network request has not been mocked for a test.\n\nConfig:\n",config,"\n\nResult:\n",
|
|
17
|
-
console.warn("Network request has not been mocked for a test, and failed.\n\nConfig:\n",config,"\n\nError\n",
|
|
16
|
+
console.warn("Network request has not been mocked for a test.\n\nConfig:\n",config,"\n\nResult:\n",JSON.stringify(res,null,2));}catch(e){// eslint-disable-next-line no-console
|
|
17
|
+
console.warn("Network request has not been mocked for a test, and failed.\n\nConfig:\n",config,"\n\nError\n",JSON.stringify(e,null,2));throw e;}return res;};return axios;}/**
|
|
18
18
|
* Advances mock timers, and mock date by the specified time.
|
|
19
19
|
* @param {number} time Time step [ms].
|
|
20
20
|
* @returns {Promise} Wait for this to "jump after" any async code which should
|
|
@@ -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 if (!res) throw Error('Missing render result');\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res);\n }\n }, (error: unknown) => {\n rejected = true;\n\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"qEAAA,qBACA,sDASA,MAAO,SAAQ,KAAM,UAAU,CAC/B,OAA4C,GAAG,KAAQ,OAAO,CAC9D,OAAoB,UAAU,KAAQ,kBAAkB,CAExD,OAAS,MAAM,CAAE,IAAI,KAAQ,eAAe,CAC5C,OAA4B,MAAM,KAAQ,wBAAwB,CAElE;AACA;AACA;AACA,GACA,OAAS,GAAG,EAAG,OAEN,OAAO,GAAI,UAAS,mBAE7B,MAAM,CAAC,wBAAwB,CAAG,IAAI,CAEtC,KAAM,wBAAuB,CAAG,OAAO,CAAC,QAAQ,CAEhD;AACA;AACA;AACA,GACA,MAAO,SAAS,eAAc,EAAS,CACrC,MAAM,CAAC,cAAc,CAAC,OAAO,CAAE,UAAU,CAAE,CAAE,KAAK,CAAE,SAAU,CAAC,CAAC,CAClE,CAEA;AACA;AACA,GACA,MAAO,SAAS,iBAAgB,EA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AAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAClE,MAAO,IAAG,CACZ","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { expect, jest } from '@jest/globals';\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): `${string}-${string}-${string}-${string}-${string}` {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve, reject) => {\n let rejected = false;\n\n // BEWARE: The \"promise\" returned by act() does not behave as a regular\n // Promise instance:\n // 1. In case of errors its .then() method both calls its \"reject\"\n // callback (first), and then its \"resolve\" callback second.\n // 2. It errors out if a rendering error happens, and there is no\n // \"reject\" argument provided.\n void promise.then(() => {\n if (!rejected) {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n if (!res) throw Error('Missing render result');\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res);\n }\n }, (error: unknown) => {\n rejected = true;\n\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"6CAAA,qBACA,sD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K,CAAC,uBAAuB,CAAC,CAC9C,KAAM,MAAK,CAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CACzC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAG,CAAC,CAAG,CAAC,GAAG,KAAK,CAAC,CAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAClE,OAAO,CAAC,GAAG,CAAC,CACd,CACF,CAAC,CAAG,KAAc,EAAK,CACrB,QAAQ,CAAG,IAAI,CAEf;AACA,MAAM,CAAC,KAAK,CAAC,CACf,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA,KAAM,MAAK,CAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CACzC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAG,CAAC,CAAG,CAAC,GAAG,KAAK,CAAC,CAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAClE,MAAO,IAAG,CACZ","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.map.get-or-insert.js";import"core-js/modules/es.map.get-or-insert-computed.js";import"core-js/modules/es.set.difference.v2.js";import"core-js/modules/es.set.intersection.v2.js";import"core-js/modules/es.set.is-disjoint-from.v2.js";import"core-js/modules/es.set.is-subset-of.v2.js";import"core-js/modules/es.set.is-superset-of.v2.js";import"core-js/modules/es.set.symmetric-difference.v2.js";import"core-js/modules/es.set.union.v2.js";import"core-js/modules/esnext.iterator.chunks.js";import"core-js/modules/esnext.map.delete-all.js";import"core-js/modules/esnext.map.emplace.js";import"core-js/modules/esnext.map.every.js";import"core-js/modules/esnext.map.filter.js";import"core-js/modules/esnext.map.find.js";import"core-js/modules/esnext.map.find-key.js";import"core-js/modules/esnext.map.includes.js";import"core-js/modules/esnext.map.key-of.js";import"core-js/modules/esnext.map.map-keys.js";import"core-js/modules/esnext.map.map-values.js";import"core-js/modules/esnext.map.merge.js";import"core-js/modules/esnext.map.reduce.js";import"core-js/modules/esnext.map.some.js";import"core-js/modules/esnext.map.update.js";import"core-js/modules/esnext.set.add-all.js";import"core-js/modules/esnext.set.delete-all.js";import"core-js/modules/esnext.set.difference.js";import"core-js/modules/esnext.set.every.js";import"core-js/modules/esnext.set.filter.js";import"core-js/modules/esnext.set.find.js";import"core-js/modules/esnext.set.intersection.js";import"core-js/modules/esnext.set.is-disjoint-from.js";import"core-js/modules/esnext.set.is-subset-of.js";import"core-js/modules/esnext.set.is-superset-of.js";import"core-js/modules/esnext.set.join.js";import"core-js/modules/esnext.set.map.js";import"core-js/modules/esnext.set.reduce.js";import"core-js/modules/esnext.set.some.js";import"core-js/modules/esnext.set.symmetric-difference.js";import"core-js/modules/esnext.set.union.js";import{c as _c}from"react/compiler-runtime";/* global document */import{Suspense,lazy,useInsertionEffect}from"react";import{Barrier}from"@dr.pogodin/js-utils";import{useSsrContext}from"./globalState.js";import{IS_CLIENT_SIDE,IS_SERVER_SIDE,assertClientSide,getBuildInfo}from"./isomorphy/index.js";import{jsx as _jsx}from"react/jsx-runtime";let clientChunkGroups;export function setClientChunkGroups(groups){assertClientSide();clientChunkGroups=groups;}const refCounts=new Map;function getPublicPath(){return getBuildInfo().publicPath;}/**
|
|
2
2
|
* Client-side only! Ensures the specified CSS stylesheet is loaded into
|
|
3
3
|
* the document; loads if it is missing; and does simple reference counting
|
|
4
4
|
* to facilitate future clean-up.
|
|
@@ -17,7 +17,7 @@ import _pushInstanceProperty from"core-js-pure/features/instance/push.js";import
|
|
|
17
17
|
* @param refCount
|
|
18
18
|
* @return Resolves once all pending stylesheets, necessary for
|
|
19
19
|
* the chunk, are either loaded, or failed to load.
|
|
20
|
-
*/export async function bookStyleSheets(chunkName,chunkGroups,refCount){const promises=[];const assets=chunkGroups[chunkName];if(!assets)return Promise.resolve();const loadedSheets=getLoadedStyleSheets();for(const asset of assets){if(asset.endsWith(".css")){const promise=bookStyleSheet(asset,loadedSheets,refCount);if(promise)
|
|
20
|
+
*/export async function bookStyleSheets(chunkName,chunkGroups,refCount){const promises=[];const assets=chunkGroups[chunkName];if(!assets)return Promise.resolve();const loadedSheets=getLoadedStyleSheets();for(const asset of assets){if(asset.endsWith(".css")){const promise=bookStyleSheet(asset,loadedSheets,refCount);if(promise)promises.push(promise);}}return promises.length?Promise.allSettled(promises).then():Promise.resolve();}/**
|
|
21
21
|
* Client-side only! Frees from the document all CSS stylesheets that are
|
|
22
22
|
* required by the specified chunk, and have reference counter equal to one
|
|
23
23
|
* (for chunks with larger reference counter values, it just decrements
|
|
@@ -41,5 +41,5 @@ if(usedChunkNames.has(chunkName)// When HMR happens splitComponent() ends up get
|
|
|
41
41
|
&&!import.meta.webpackHot){throw Error(`Repeated splitComponent() call for the chunk "${chunkName}"`);}else usedChunkNames.add(chunkName);const LazyComponent=/*#__PURE__*/lazy(async()=>{const resolved=await getComponent();const Component="default"in resolved?resolved.default:resolved;// This pre-loads necessary stylesheets prior to the first mount of
|
|
42
42
|
// the component (the lazy load function is executed by React one at
|
|
43
43
|
// the frist mount).
|
|
44
|
-
if(IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");await bookStyleSheets(chunkName,clientChunkGroups,false);}const Wrapper=t0=>{const $=_c(12);let children;let chunkGroups;let ref;let rest;if($[0]!==t0){({children,chunkGroups,ref,...rest}=t0);$[0]=t0;$[1]=children;$[2]=chunkGroups;$[3]=ref;$[4]=rest}else{children=$[1];chunkGroups=$[2];ref=$[3];rest=$[4]}let t1;let t2;if($[5]!==chunkGroups){t1=()=>{if(!clientChunkGroups){throw Error("Internal error");}bookStyleSheets(chunkName,chunkGroups,true);return()=>{freeStyleSheets(chunkName,chunkGroups)}};t2=[chunkGroups];$[5]=chunkGroups;$[6]=t1;$[7]=t2}else{t1=$[6];t2=$[7]}useInsertionEffect(t1,t2);const t3=rest;let t4;if($[8]!==children||$[9]!==ref||$[10]!==t3){t4=/*#__PURE__*/_jsx(Component,{...t3,ref:ref,children:children});$[8]=children;$[9]=ref;$[10]=t3;$[11]=t4}else{t4=$[11]}return t4};return{default:Wrapper};});const CodeSplit=t0=>{const $=_c(7);let children;let rest;if($[0]!==t0){({children,...rest}=t0);$[0]=t0;$[1]=children;$[2]=rest}else{children=$[1];rest=$[2]}let chunkGroups;const ssrContext=useSsrContext(false);if(IS_SERVER_SIDE){if(!ssrContext){throw Error("Internal error");}({chunkGroups}=ssrContext);const{chunks}=ssrContext;if(!chunks.includes(chunkName)){
|
|
44
|
+
if(IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");await bookStyleSheets(chunkName,clientChunkGroups,false);}const Wrapper=t0=>{const $=_c(12);let children;let chunkGroups;let ref;let rest;if($[0]!==t0){({children,chunkGroups,ref,...rest}=t0);$[0]=t0;$[1]=children;$[2]=chunkGroups;$[3]=ref;$[4]=rest}else{children=$[1];chunkGroups=$[2];ref=$[3];rest=$[4]}let t1;let t2;if($[5]!==chunkGroups){t1=()=>{if(!clientChunkGroups){throw Error("Internal error");}bookStyleSheets(chunkName,chunkGroups,true);return()=>{freeStyleSheets(chunkName,chunkGroups)}};t2=[chunkGroups];$[5]=chunkGroups;$[6]=t1;$[7]=t2}else{t1=$[6];t2=$[7]}useInsertionEffect(t1,t2);const t3=rest;let t4;if($[8]!==children||$[9]!==ref||$[10]!==t3){t4=/*#__PURE__*/_jsx(Component,{...t3,ref:ref,children:children});$[8]=children;$[9]=ref;$[10]=t3;$[11]=t4}else{t4=$[11]}return t4};return{default:Wrapper};});const CodeSplit=t0=>{const $=_c(7);let children;let rest;if($[0]!==t0){({children,...rest}=t0);$[0]=t0;$[1]=children;$[2]=rest}else{children=$[1];rest=$[2]}let chunkGroups;const ssrContext=useSsrContext(false);if(IS_SERVER_SIDE){if(!ssrContext){throw Error("Internal error");}({chunkGroups}=ssrContext);const{chunks}=ssrContext;if(!chunks.includes(chunkName)){chunks.push(chunkName)}}else{if(!clientChunkGroups){throw Error("Missing client-side chunk groups data");}chunkGroups=clientChunkGroups;}assertChunkName(chunkName,chunkGroups);const t1=rest;let t2;if($[3]!==children||$[4]!==chunkGroups||$[5]!==t1){t2=/*#__PURE__*/_jsx(Suspense,{fallback:placeholder,children:/*#__PURE__*/_jsx(LazyComponent,{...t1,chunkGroups:chunkGroups,children:children})});$[3]=children;$[4]=chunkGroups;$[5]=t1;$[6]=t2}else{t2=$[6]}return t2};return CodeSplit;}
|
|
45
45
|
//# sourceMappingURL=splitComponent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitComponent.js","names":["chunkGroups","placeholder"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, useSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n assertClientSide,\n getBuildInfo,\n} from './isomorphy';\n\nlet clientChunkGroups: ChunkGroupsT | undefined;\n\nexport function setClientChunkGroups(groups: ChunkGroupsT): void {\n assertClientSide();\n clientChunkGroups = groups;\n}\n\nconst refCounts = new Map<string, number>();\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts.get(path) ?? 0;\n refCounts.set(path, 1 + current);\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts.get(path);\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n const node = document.head.querySelector(`link[href=\"${path}\"]`);\n if (!node) throw Error('Missing node');\n node.remove();\n refCounts.delete(path);\n } else refCounts.set(path, pathRefCount - 1);\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\ntype GenericComponentPropsT = {\n children?: ReactNode;\n ref?: RefObject<unknown>;\n\n // NOTE: This is necessary, as without it this type (with only optional\n // fields) will be conisdered as \"weak\" by TypeScript, and it will be\n // a error to assign to it any type that does not use \"children\", or \"ref\".\n [propName: string]: unknown;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends GenericComponentPropsT,\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)\n\n // When HMR happens splitComponent() ends up getting called again for some\n // chunks, thus we should not throw this error. Not sure, if we need to do\n // some additional handling in that case, or just not throwing is all we\n // need.\n && !import.meta.webpackHot\n ) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT & {\n chunkGroups: ChunkGroupsT;\n }> = ({\n children,\n chunkGroups,\n ref,\n ...rest\n }) => {\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, chunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, chunkGroups);\n };\n }, [chunkGroups]);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => {\n let chunkGroups: ChunkGroupsT;\n\n const ssrContext = useSsrContext(false);\n\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n if (!ssrContext) throw Error('Internal error');\n ({ chunkGroups } = ssrContext);\n const { chunks } = ssrContext;\n\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n } else {\n if (!clientChunkGroups) {\n throw Error('Missing client-side chunk groups data');\n }\n chunkGroups = clientChunkGroups;\n }\n\n assertChunkName(chunkName, chunkGroups);\n\n return (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n\n chunkGroups={chunkGroups}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n };\n\n return CodeSplit;\n}\n"],"mappings":"sHAAA,qBAEA,OAKE,QAAQ,CACR,IAAI,CACJ,kBAAkB,KACb,OAAO,CAEd,OAAS,OAAO,KAAQ,sBAAsB,CAAC,OAEnB,aAAa,+BAGvC,cAAc,CACd,cAAc,CACd,gBA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,SAAS,CAAC,CAAC,MAExD,GAAI,CAAC,iBAAiB,EACpB,KAAM,MAAK,CAAC,uCAAuC,CAAC,CAAC,CAEvD,WAAAA,CAAc,iBAAiB,CAApB,CAGb,eAAe,CAAC,SAAS,CAAE,WAAW,CAAC,CAM7B,aAAI,CAAuC,0DAHnD,qBAAC,QAAQ,EAAWC,QAAW,CAAX,WAAW,uBAC7B,KAAC,aAAa,KAER,EAA2C,CAElC,WAAW,CAAX,WAAW,UAEvB,QAAQ,CACI,CAAC,CACR,CAAC,mEATX,GASW,CAEd,CAED,MAAO,UAAS,CAClB","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"splitComponent.js","names":["chunkGroups","placeholder"],"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":"+/DAAA,qBAEA,OAKE,QAAQ,CACR,IAAI,CACJ,kBAAkB,KACb,OAAO,CAEd,OAAS,OAAO,KAAQ,sBAAsB,CAAC,OAEnB,aAAa,+BAGvC,c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AM,KAAK,CAAC,SAAS,CAAC,CAAC,MAExD,GAAI,CAAC,iBAAiB,EACpB,KAAM,MAAK,CAAC,uCAAuC,CAAC,CAAC,CAEvD,WAAAA,CAAc,iBAAiB,CAApB,CAGb,eAAe,CAAC,SAAS,CAAE,WAAW,CAAC,CAM7B,aAAI,CAAuC,0DAHnD,qBAAC,QAAQ,EAAWC,QAAW,CAAX,WAAW,uBAC7B,KAAC,aAAa,KAER,EAA2C,CAElC,WAAW,CAAX,WAAW,UAEvB,QAAQ,CACI,CAAC,CACR,CAAC,mEATX,GASW,CAEd,CAED,MAAO,UAAS,CAClB","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";// eslint-disable-next-line import/enforce-node-protocol-usage, perfectionist/sort-imports
|
|
2
2
|
import{createRequire}from"module";import{IS_CLIENT_SIDE,IS_SERVER_SIDE}from"./isomorphy/index.js";let require;if(IS_SERVER_SIDE)require=createRequire(import.meta.url);/**
|
|
3
3
|
* Requires the specified module without including it into the bundle during
|
|
4
4
|
* Webpack build.
|
|
@@ -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 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":"
|
|
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":"mGAEA;AACA,OAAS,aAAa,KAAQ,QAAQ,CAAC,OAE9B,cAAc,CAAE,cAAc,4BAUvC,GAAI,QAA+C,CAEnD,GAAI,cAAc,CAAE,OA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F,CAAC,CAAC,CACF,MAAO,IAAG,CACZ,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,YAAW,CAAC,UAAkB,CAAU,CACtD,MAAO,WAAU,CACnB","ignoreList":[]}
|
package/config/babel/webpack.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import coreJsPackage from 'core-js
|
|
1
|
+
import coreJsPackage from 'core-js/package.json' with { type: 'json' };
|
|
2
2
|
import { localIdentNameFactory, } from '@dr.pogodin/babel-plugin-react-css-modules/utils';
|
|
3
3
|
const localIdentNameDev = localIdentNameFactory('[package]___[path][name]___[local]___[hash:base64:6]');
|
|
4
4
|
const localIdentNameProd = localIdentNameFactory('[hash:base64:6]');
|
|
@@ -25,7 +25,16 @@ function newBaseConfig(options) {
|
|
|
25
25
|
extensions: ['.js', '.jsx', '.ts', '.tsx'],
|
|
26
26
|
root: ['./src/shared', './src'],
|
|
27
27
|
}], '@babel/transform-runtime', ['polyfill-corejs3', {
|
|
28
|
-
|
|
28
|
+
// BEWARE: On paper, "usage-pure" is the best option we want here;
|
|
29
|
+
// in practice, it seems to fail sometimes in obscure ways, e.g. I saw
|
|
30
|
+
// the polyfilled code crashing when calling Promise.allSettled, which was
|
|
31
|
+
// supposed to be polyfilled for the target environment, while the same
|
|
32
|
+
// code built with "usage-global" worked just fine (the polyfilled
|
|
33
|
+
// Promise.allSettled worked as designed). I don't have time to deep dive
|
|
34
|
+
// into it right now, let's just pin this option for "usage-global" for
|
|
35
|
+
// now, and look into it more later.
|
|
36
|
+
// TODO: Investigate more!
|
|
37
|
+
method: 'usage-global',
|
|
29
38
|
proposals: true,
|
|
30
39
|
version: coreJsPackage.version,
|
|
31
40
|
}]);
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "1.58.
|
|
2
|
+
"version": "1.58.1",
|
|
3
3
|
"bin": {
|
|
4
4
|
"react-utils-build": "bin/build.js",
|
|
5
5
|
"react-utils-run-with-babel": "bin/run-with-babel.js",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"config": "^5.0.1",
|
|
25
25
|
"cookie": "^2.0.1",
|
|
26
26
|
"cookie-parser": "^1.4.7",
|
|
27
|
-
"core-js
|
|
27
|
+
"core-js": "^3.51.0",
|
|
28
28
|
"cross-env": "^10.1.0",
|
|
29
29
|
"dayjs": "^1.11.23",
|
|
30
30
|
"express": "^5.3.0",
|
|
@@ -92,10 +92,10 @@
|
|
|
92
92
|
"jest": "^30.5.2",
|
|
93
93
|
"jest-environment-jsdom": "^30.5.2",
|
|
94
94
|
"memfs": "^4.71.0",
|
|
95
|
-
"minimizer-webpack-plugin": "^5.13.
|
|
95
|
+
"minimizer-webpack-plugin": "^5.13.1",
|
|
96
96
|
"mockdate": "^3.0.5",
|
|
97
97
|
"nodelist-foreach-polyfill": "^1.2.0",
|
|
98
|
-
"postcss": "^8.5.
|
|
98
|
+
"postcss": "^8.5.31",
|
|
99
99
|
"postcss-loader": "^8.2.1",
|
|
100
100
|
"postcss-scss": "^4.0.9",
|
|
101
101
|
"pretty": "^2.0.0",
|
|
@@ -112,7 +112,7 @@
|
|
|
112
112
|
"typed-scss-modules": "^8.1.1",
|
|
113
113
|
"typescript": "^6.0.3",
|
|
114
114
|
"webpack": "^5.112.0",
|
|
115
|
-
"webpack-dev-middleware": "^8.
|
|
115
|
+
"webpack-dev-middleware": "^8.5.0",
|
|
116
116
|
"webpack-merge": "^6.0.1",
|
|
117
117
|
"workbox-core": "^7.4.1",
|
|
118
118
|
"workbox-precaching": "^7.4.1",
|