@dr.pogodin/react-utils 1.54.0 → 1.54.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/build/development/index.js +1 -1
  2. package/build/development/index.js.map +1 -1
  3. package/build/development/shared/components/TextArea/index.js +57 -38
  4. package/build/development/shared/components/TextArea/index.js.map +1 -1
  5. package/build/development/shared/utils/config.js +2 -2
  6. package/build/development/shared/utils/config.js.map +1 -1
  7. package/build/development/shared/utils/index.js +1 -1
  8. package/build/development/shared/utils/index.js.map +1 -1
  9. package/build/development/shared/utils/jest/index.js +19 -7
  10. package/build/development/shared/utils/jest/index.js.map +1 -1
  11. package/build/development/shared/utils/splitComponent.js +1 -1
  12. package/build/development/shared/utils/splitComponent.js.map +1 -1
  13. package/build/development/shared/utils/time.js +5 -3
  14. package/build/development/shared/utils/time.js.map +1 -1
  15. package/build/production/index.js +1 -1
  16. package/build/production/index.js.map +1 -1
  17. package/build/production/shared/components/TextArea/index.js +1 -1
  18. package/build/production/shared/components/TextArea/index.js.map +1 -1
  19. package/build/production/shared/utils/config.js +2 -2
  20. package/build/production/shared/utils/config.js.map +1 -1
  21. package/build/production/shared/utils/index.js +1 -1
  22. package/build/production/shared/utils/index.js.map +1 -1
  23. package/build/production/shared/utils/jest/index.js +10 -3
  24. package/build/production/shared/utils/jest/index.js.map +1 -1
  25. package/build/production/shared/utils/splitComponent.js +1 -1
  26. package/build/production/shared/utils/splitComponent.js.map +1 -1
  27. package/build/production/shared/utils/time.js +2 -2
  28. package/build/production/shared/utils/time.js.map +1 -1
  29. package/build/types-code/index.d.ts +1 -1
  30. package/build/types-code/shared/components/TextArea/index.d.ts +2 -1
  31. package/build/types-code/shared/utils/index.d.ts +1 -1
  32. package/build/web/index.js +1 -1
  33. package/build/web/index.js.map +1 -1
  34. package/build/web/shared/components/TextArea/index.js +1 -1
  35. package/build/web/shared/components/TextArea/index.js.map +1 -1
  36. package/build/web/shared/utils/config.js +2 -2
  37. package/build/web/shared/utils/config.js.map +1 -1
  38. package/build/web/shared/utils/index.js +1 -1
  39. package/build/web/shared/utils/index.js.map +1 -1
  40. package/build/web/shared/utils/jest/index.js +10 -3
  41. package/build/web/shared/utils/jest/index.js.map +1 -1
  42. package/build/web/shared/utils/splitComponent.js +1 -1
  43. package/build/web/shared/utils/splitComponent.js.map +1 -1
  44. package/build/web/shared/utils/time.js +2 -2
  45. package/build/web/shared/utils/time.js.map +1 -1
  46. package/config/jest/default.js +1 -0
  47. package/package.json +5 -5
@@ -1,4 +1,4 @@
1
- import"core-js/modules/es.json.stringify.js";/* global jest, document *//* eslint-disable import/no-extraneous-dependencies */import mockdate from"mockdate";import{act}from"react";import{createRoot}from"react-dom/client";import{render}from"@testing-library/react";/**
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";global.IS_REACT_ACT_ENVIRONMENT=true;const originalProcessVersions=process.versions;/**
@@ -41,7 +41,14 @@ const promise=act(()=>{res=render(element);return options?.await;});if(res===und
41
41
  // it is not an instance of proper Promise class, and returning it directly
42
42
  // breaks some async logic in Jest test or React test functions... thus, we
43
43
  // wrap it into Promise instance here.
44
- return new Promise(resolve=>{void promise.then(()=>{// TODO: These lines are the same as the lines below for sync variant of
44
+ return new Promise((resolve,reject)=>{let rejected=false;// BEWARE: The "promise" returned by act() does not behave as a regular
45
+ // Promise instance:
46
+ // 1. In case of errors its .then() method both calls its "reject"
47
+ // callback (first), and then its "resolve" callback second.
48
+ // 2. It errors out if a rendering error happens, and there is no
49
+ // "reject" argument provided.
50
+ void promise.then(()=>{if(!rejected){// TODO: These lines are the same as the lines below for sync variant of
45
51
  // the function. We should split and reuse them in both places.
46
- const nodes=res.asFragment().childNodes;expect(nodes.length>1?[...nodes]:nodes[0]).toMatchSnapshot();resolve(res);});});}const nodes=res.asFragment().childNodes;expect(nodes.length>1?[...nodes]:nodes[0]).toMatchSnapshot();return res;}
52
+ const nodes=res.asFragment().childNodes;expect(nodes.length>1?[...nodes]:nodes[0]).toMatchSnapshot();resolve(res);}},error=>{rejected=true;// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
53
+ reject(error);});});}const nodes=res.asFragment().childNodes;expect(nodes.length>1?[...nodes]:nodes[0]).toMatchSnapshot();return res;}
47
54
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["mockdate","act","createRoot","render","default","getGlobal","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","jest","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","unmount","remove","snapshot","expect","toMatchSnapshot","options","promise","await","Error","Promise","resolve","then","nodes","asFragment","childNodes","length"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global jest, document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): `${string}-${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: React.ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve) => {\n void promise.then(() => {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"6CAAA,2BACA,sDASA,MAAO,CAAAA,QAAQ,KAAM,UAAU,CAC/B,OAA4CC,GAAG,KAAQ,OAAO,CAC9D,OAAoBC,UAAU,KAAQ,kBAAkB,CAExD,OAA4BC,MAAM,KAAQ,wBAAwB,CAElE;AACA;AACA;AACA,GACA,OAASF,GAAG,EAEZ,OAASG,OAAO,GAAI,CAAAC,SAAS,gBAE7BC,MAAM,CAACC,wBAAwB,CAAG,IAAI,CAEtC,KAAM,CAAAC,uBAAuB,CAAGC,OAAO,CAACC,QAAQ,CAEhD;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,cAAcA,CAAA,CAAS,CACrCC,MAAM,CAACC,cAAc,CAACJ,OAAO,CAAE,UAAU,CAAE,CAAEK,KAAK,CAAEC,SAAU,CAAC,CAAC,CAClE,CAEA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,gBAAgBA,CAAA,CAAS,CACvCJ,MAAM,CAACC,cAAc,CAACJ,OAAO,CAAE,UAAU,CAAE,CACzCK,KAAK,CAAEN,uBAAuB,CAC9BS,QAAQ,CAAE,KACZ,CAAC,CAAC,CACJ,CAEA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,WAAWA,CAACC,IAAI,CAAG,CAAC,CAAuD,CACzF,KAAM,CAAAC,CAAC,CAAGD,IAAI,CAACE,QAAQ,CAAC,EAAE,CAAC,CAACC,QAAQ,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,MAAO,CAAAjB,GAAG,CACZ,CAEA;AACA;AACA;AAYA,MAAO,SAAS,CAAA2B,QAAQA,CACtBR,OAA2B,CAC3BW,OAA+B,CACO,CACtC,GAAI,CAAA9B,GAA6B,CAEjC;AACA;AACA;AACA;AACA;AACA;AACA,KAAM,CAAA+B,OAAO,CAAG/D,GAAG,CAAC,IAAM,CACxBgC,GAAG,CAAG9B,MAAM,CAACiD,OAAO,CAAC,CACrB,MAAO,CAAAW,OAAO,EAAEE,KAAK,CACvB,CAAC,CAAC,CAEF,GAAIhC,GAAG,GAAKlB,SAAS,CAAE,KAAM,CAAAmD,KAAK,CAAC,eAAe,CAAC,CACnD,GAAIH,OAAO,EAAEE,KAAK,CAAE,CAClB;AACA;AACA;AACA;AACA,MAAO,IAAI,CAAAE,OAAO,CAAEC,OAAO,EAAK,CAC9B,IAAK,CAAAJ,OAAO,CAACK,IAAI,CAAC,IAAM,CACtB;AACA;AACA,KAAM,CAAAC,KAAK,CAAGrC,GAAG,CAAEsC,UAAU,CAAC,CAAC,CAACC,UAAU,CAC1CX,MAAM,CAACS,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC,CAClEM,OAAO,CAACnC,GAAI,CAAC,CACf,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA,KAAM,CAAAqC,KAAK,CAAGrC,GAAG,CAACsC,UAAU,CAAC,CAAC,CAACC,UAAU,CACzCX,MAAM,CAACS,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC,CAClE,MAAO,CAAA7B,GAAG,CACZ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["mockdate","act","createRoot","expect","jest","render","default","getGlobal","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","unmount","remove","snapshot","toMatchSnapshot","options","promise","await","Error","Promise","resolve","reject","rejected","then","nodes","asFragment","childNodes","length","error"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { expect, jest } from '@jest/globals';\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): `${string}-${string}-${string}-${string}-${string}` {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve, reject) => {\n let rejected = false;\n\n // BEWARE: The \"promise\" returned by act() does not behave as a regular\n // Promise instance:\n // 1. In case of errors its .then() method both calls its \"reject\"\n // callback (first), and then its \"resolve\" callback second.\n // 2. It errors out if a rendering error happens, and there is no\n // \"reject\" argument provided.\n void promise.then(() => {\n if (!rejected) {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n }\n }, (error: unknown) => {\n rejected = true;\n\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n });\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,sDASA,MAAO,CAAAA,QAAQ,KAAM,UAAU,CAC/B,OAA4CC,GAAG,KAAQ,OAAO,CAC9D,OAAoBC,UAAU,KAAQ,kBAAkB,CAExD,OAASC,MAAM,CAAEC,IAAI,KAAQ,eAAe,CAC5C,OAA4BC,MAAM,KAAQ,wBAAwB,CAElE;AACA;AACA;AACA,GACA,OAASJ,GAAG,EAEZ,OAASK,OAAO,GAAI,CAAAC,SAAS,gBAE7BC,MAAM,CAACC,wBAAwB,CAAG,IAAI,CAEtC,KAAM,CAAAC,uBAAuB,CAAGC,OAAO,CAACC,QAAQ,CAEhD;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,cAAcA,CAAA,CAAS,CACrCC,MAAM,CAACC,cAAc,CAACJ,OAAO,CAAE,UAAU,CAAE,CAAEK,KAAK,CAAEC,SAAU,CAAC,CAAC,CAClE,CAEA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,gBAAgBA,CAAA,CAAS,CACvCJ,MAAM,CAACC,cAAc,CAACJ,OAAO,CAAE,UAAU,CAAE,CACzCK,KAAK,CAAEN,uBAAuB,CAC9BS,QAAQ,CAAE,KACZ,CAAC,CAAC,CACJ,CAEA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,WAAWA,CAACC,IAAI,CAAG,CAAC,CAAuD,CACzF,KAAM,CAAAC,CAAC,CAAGD,IAAI,CAACE,QAAQ,CAAC,EAAE,CAAC,CAACC,QAAQ,CAAC,EAAE,CAAE,GAAG,CAAC,CAC7C,MAAO,GAAGF,CAAC,CAACG,KAAK,CAAC,CAAC,CAAE,CAAC,CAAC,IAAIH,CAAC,CAACG,KAAK,CAAC,CAAC,CAAE,EAAE,CAAC,IAAIH,CAAC,C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-js/modules/es.iterator.cons
54
54
  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
55
55
  // the component (the lazy load function is executed by React one at
56
56
  // the frist mount).
57
- 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("Internal error");}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;}
57
+ 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;}
58
58
  //# sourceMappingURL=splitComponent.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"splitComponent.js","names":["Suspense","lazy","useInsertionEffect","Barrier","useSsrContext","IS_CLIENT_SIDE","IS_SERVER_SIDE","assertClientSide","getBuildInfo","jsx","_jsx","clientChunkGroups","setClientChunkGroups","groups","refCounts","getPublicPath","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","splitComponent","getComponent","placeholder","LazyComponent","resolved","Component","default","Wrapper","t0","$","_c","children","ref","rest","t1","t2","t3","t4","CodeSplit","ssrContext","chunks","includes"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, useSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n assertClientSide,\n getBuildInfo,\n} from './isomorphy';\n\nlet clientChunkGroups: ChunkGroupsT | undefined;\n\nexport function setClientChunkGroups(groups: ChunkGroupsT): void {\n assertClientSide();\n clientChunkGroups = groups;\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\n// const 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 // TODO: For now I commented out this safeguard check, as I am not sure how\n // to easily make it work: it should not be triggered in HMR mode, but if I\n // add the code relying on import.meta, it fails in Jest environment, because\n // Jest does not support ES modules yet, and import.meta is not support in\n // CommonJS modules, and the \"babel-plugin-transform-import-meta\" plugin\n // we use to workaround this issue for import.meta.dirname, etc. does not\n // transform import.meta.webpackHot\n\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) throw Error('Internal error');\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":"2eAAA,qBAEA,OAKEA,QAAQ,CACRC,IAAI,CACJC,kBAAkB,KACb,OAAO,CAEd,OAASC,OAAO,KAAQ,sBAAsB,CAE9C,OAA4BC,aAAa,qBAEzC,OACEC,cAAc,CACdC,cAAc,CACdC,gBAAgB,CAChBC,YAAY,mBACO,OAAAC,GAAA,IAAAC,IAAA,yBAErB,GAAI,CAAAC,iBAA2C,CAE/C,MAAO,SAAS,CAAAC,oBAAoBA,CAACC,MAAoB,CAAQ,CAC/DN,gBAAgB,CAAC,CAAC,CAClBI,iBAAiB,CAAGE,MAAM,CAC5B,CAEA,KAAM,CAAAC,SAAiC,CAAG,CAAC,CAAC,CAE5C,QAAS,CAAAC,aAAaA,CAAA,CAAG,CACvB,MAAO,CAAAP,YAAY,CAAC,CAAC,CAACQ,UAAU,CAClC,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,CAAAC,cAAcA,CACrBC,IAAY,CACZC,YAAyB,CACzBC,QAAiB,CACU,CAC3B,GAAI,CAAAC,GAA8B,CAClC,KAAM,CAAAC,IAAI,CAAG,GAAGP,aAAa,CAAC,CAAC,IAAIG,IAAI,EAAE,CACzC,KAAM,CAAAK,QAAQ,CAAG,GAAGC,QAAQ,CAACC,QAAQ,CAACC,MAAM,GAAGJ,IAAI,EAAE,CAErD,GAAI,CAACH,YAAY,CAACQ,GAAG,CAACJ,QAAQ,CAAC,CAAE,CAC/B,GAAI,CAAAK,IAAI,CAAGJ,QAAQ,CAACK,aAAa,CAAC,cAAcP,IAAI,IAAI,CAAC,CAEzD,GAAI,CAACM,IAAI,CAAE,CACTA,IAAI,CAAGJ,QAAQ,CAACM,aAAa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,CAAAM,EASW,CAEd,CAED,MAAO,CAAAG,SAAS,CAClB","ignoreList":[]}
1
+ {"version":3,"file":"splitComponent.js","names":["Suspense","lazy","useInsertionEffect","Barrier","useSsrContext","IS_CLIENT_SIDE","IS_SERVER_SIDE","assertClientSide","getBuildInfo","jsx","_jsx","clientChunkGroups","setClientChunkGroups","groups","refCounts","getPublicPath","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","splitComponent","getComponent","placeholder","LazyComponent","resolved","Component","default","Wrapper","t0","$","_c","children","ref","rest","t1","t2","t3","t4","CodeSplit","ssrContext","chunks","includes"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, useSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n assertClientSide,\n getBuildInfo,\n} from './isomorphy';\n\nlet clientChunkGroups: ChunkGroupsT | undefined;\n\nexport function setClientChunkGroups(groups: ChunkGroupsT): void {\n assertClientSide();\n clientChunkGroups = groups;\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\n// const 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 // TODO: For now I commented out this safeguard check, as I am not sure how\n // to easily make it work: it should not be triggered in HMR mode, but if I\n // add the code relying on import.meta, it fails in Jest environment, because\n // Jest does not support ES modules yet, and import.meta is not support in\n // CommonJS modules, and the \"babel-plugin-transform-import-meta\" plugin\n // we use to workaround this issue for import.meta.dirname, etc. does not\n // transform import.meta.webpackHot\n\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":"2eAAA,qBAEA,OAKEA,QAAQ,CACRC,IAAI,CACJC,kBAAkB,KACb,OAAO,CAEd,OAASC,OAAO,KAAQ,sBAAsB,CAE9C,OAA4BC,aAAa,qBAEzC,OACEC,cAAc,CACdC,cAAc,CACdC,gBAAgB,CAChBC,YAAY,mBACO,OAAAC,GAAA,IAAAC,IAAA,yBAErB,GAAI,CAAAC,iBAA2C,CAE/C,MAAO,SAAS,CAAAC,oBAAoBA,CAACC,MAAoB,CAAQ,CAC/DN,gBAAgB,CAAC,CAAC,CAClBI,iBAAiB,CAAGE,MAAM,CAC5B,CAEA,KAAM,CAAAC,SAAiC,CAAG,CAAC,CAAC,CAE5C,QAAS,CAAAC,aAAaA,CAAA,CAAG,CACvB,MAAO,CAAAP,YAAY,CAAC,CAAC,CAACQ,UAAU,CAClC,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,CAAAC,cAAcA,CACrBC,IAAY,CACZC,YAAyB,CACzBC,QAAiB,CACU,CAC3B,GAAI,CAAAC,GAA8B,CAClC,KAAM,CAAAC,IAAI,CAAG,GAAGP,aAAa,CAAC,CAAC,IAAIG,IAAI,EAAE,CACzC,KAAM,CAAAK,QAAQ,CAAG,GAAGC,QAAQ,CAACC,QAAQ,CAACC,MAAM,GAAGJ,IAAI,EAAE,CAErD,GAAI,CAACH,YAAY,CAACQ,GAAG,CAACJ,QAAQ,CAAC,CAAE,CAC/B,GAAI,CAAAK,IAAI,CAAGJ,QAAQ,CAACK,aAAa,CAAC,cAAcP,IAAI,IAAI,CAAC,CAEzD,GAAI,CAACM,IAAI,CAAE,CACTA,IAAI,CAAGJ,QAAQ,CAACM,aAAa,CAA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AAM,EASW,CAEd,CAED,MAAO,CAAAG,SAAS,CAClB","ignoreList":[]}
@@ -1,4 +1,4 @@
1
- import{c as _c}from"react/compiler-runtime";import{serialize}from"cookie";import dayjs from"dayjs";import{useEffect}from"react";import{DAY_MS,HOUR_MS,MIN_MS,SEC_MS,YEAR_MS,timer}from"@dr.pogodin/js-utils";import{useGlobalState}from"@dr.pogodin/react-global-state";import{useSsrContext}from"./globalState";/**
1
+ import{c as _c}from"react/compiler-runtime";import{stringifySetCookie}from"cookie";import dayjs from"dayjs";import{useEffect}from"react";import{DAY_MS,HOUR_MS,MIN_MS,SEC_MS,YEAR_MS,timer}from"@dr.pogodin/js-utils";import{useGlobalState}from"@dr.pogodin/react-global-state";import{useSsrContext}from"./globalState";/**
2
2
  * This react hook wraps Date.now() function in a SSR friendly way,
3
3
  * ensuring that all calls to useCurrent() within the same render return
4
4
  * exactly the same time (which is retrieved from Date.now() first, and
@@ -17,5 +17,5 @@ export function useCurrent({autorefresh=false,globalStatePath="currentTime",prec
17
17
  * as the default value.
18
18
  */// TODO: Should we request the state type as generic parameter, to be able
19
19
  // to verify the give globalStatePath is correct?
20
- export function useTimezoneOffset(t0){const $=_c(9);let t1;if($[0]!==t0){t1=t0===undefined?{}:t0;$[0]=t0;$[1]=t1}else{t1=$[1]}const{cookieName:t2,globalStatePath:t3}=t1;const cookieName=t2===undefined?"timezoneOffset":t2;const globalStatePath=t3===undefined?"timezoneOffset":t3;const ssrContext=useSsrContext(false);let t4;if($[2]!==cookieName||$[3]!==ssrContext?.req){t4=()=>{const value=cookieName&&ssrContext?.req.cookies[cookieName];return value?parseInt(value):0};$[2]=cookieName;$[3]=ssrContext?.req;$[4]=t4}else{t4=$[4]}const[offset,setOffset]=useGlobalState(globalStatePath,t4);let t5;let t6;if($[5]!==cookieName||$[6]!==setOffset){t5=()=>{const date=new Date;const value_0=date.getTimezoneOffset();setOffset(value_0);if(cookieName){document.cookie=serialize(cookieName,value_0.toString(),{path:"/"})}};t6=[cookieName,setOffset];$[5]=cookieName;$[6]=setOffset;$[7]=t5;$[8]=t6}else{t5=$[7];t6=$[8]}useEffect(t5,t6);return offset}const time={DAY_MS,HOUR_MS,MIN_MS,SEC_MS,YEAR_MS,now:Date.now,timer,useCurrent,useTimezoneOffset};export default Object.assign(dayjs,time);
20
+ export function useTimezoneOffset(t0){const $=_c(9);let t1;if($[0]!==t0){t1=t0===undefined?{}:t0;$[0]=t0;$[1]=t1}else{t1=$[1]}const{cookieName:t2,globalStatePath:t3}=t1;const cookieName=t2===undefined?"timezoneOffset":t2;const globalStatePath=t3===undefined?"timezoneOffset":t3;const ssrContext=useSsrContext(false);let t4;if($[2]!==cookieName||$[3]!==ssrContext?.req){t4=()=>{const value=cookieName&&ssrContext?.req.cookies[cookieName];return value?parseInt(value):0};$[2]=cookieName;$[3]=ssrContext?.req;$[4]=t4}else{t4=$[4]}const[offset,setOffset]=useGlobalState(globalStatePath,t4);let t5;let t6;if($[5]!==cookieName||$[6]!==setOffset){t5=()=>{const date=new Date;const value_0=date.getTimezoneOffset();setOffset(value_0);if(cookieName){document.cookie=stringifySetCookie({name:cookieName,path:"/",value:value_0.toString()})}};t6=[cookieName,setOffset];$[5]=cookieName;$[6]=setOffset;$[7]=t5;$[8]=t6}else{t5=$[7];t6=$[8]}useEffect(t5,t6);return offset}const time={DAY_MS,HOUR_MS,MIN_MS,SEC_MS,YEAR_MS,now:Date.now,timer,useCurrent,useTimezoneOffset};export default Object.assign(dayjs,time);
21
21
  //# sourceMappingURL=time.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"time.js","names":["serialize","dayjs","useEffect","DAY_MS","HOUR_MS","MIN_MS","SEC_MS","YEAR_MS","timer","useGlobalState","useSsrContext","useCurrent","autorefresh","globalStatePath","precision","now","setter","Date","timerId","update","old","neu","Math","abs","setTimeout","clearTimeout","useTimezoneOffset","t0","$","_c","t1","undefined","cookieName","t2","t3","ssrContext","t4","req","value","cookies","parseInt","offset","setOffset","t5","t6","date","value_0","getTimezoneOffset","document","cookie","toString","path","time","Object","assign"],"sources":["../../../../src/shared/utils/time.ts"],"sourcesContent":["import { serialize } from 'cookie';\nimport dayjs from 'dayjs';\nimport { useEffect } from 'react';\n\nimport {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n timer,\n} from '@dr.pogodin/js-utils';\n\nimport { type ForceT, useGlobalState } from '@dr.pogodin/react-global-state';\n\nimport { useSsrContext } from './globalState';\n\n/**\n * This react hook wraps Date.now() function in a SSR friendly way,\n * ensuring that all calls to useCurrent() within the same render return\n * exactly the same time (which is retrieved from Date.now() first, and\n * then stored in the global state to be reused in all other calls), which\n * is also passed and used in the first client side render, and then updated\n * with a finite precision to avoid infinite re-rendering loops.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useCurrent({\n autorefresh = false,\n globalStatePath = 'currentTime',\n precision = 5 * SEC_MS,\n} = {}): number {\n const [now, setter] = useGlobalState<ForceT, number>(\n globalStatePath,\n Date.now,\n );\n useEffect(() => {\n let timerId: NodeJS.Timeout | undefined;\n const update = (): void => {\n setter((old) => {\n const neu = Date.now();\n return Math.abs(neu - old) > precision ? neu : old;\n });\n if (autorefresh) timerId = setTimeout(update, precision);\n };\n update();\n return (): void => {\n if (timerId) clearTimeout(timerId);\n };\n }, [autorefresh, precision, setter]);\n return now;\n}\n\n/**\n * Wraps the standard Date.getTimezoneOffset() method in a SSR-friendly way.\n * This hook retrieves the offset value at the client side and uses a cookie\n * to pass it to the server in subsequent requests from that user. At the server\n * side the value from cookie is used in renders and passed back to the client\n * via the global state. Prior to the value being known (in the very first\n * request from the user, when the cookie is still missing), zero value is used\n * as the default value.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useTimezoneOffset({\n cookieName = 'timezoneOffset',\n globalStatePath = 'timezoneOffset',\n} = {}): number {\n const ssrContext = useSsrContext(false);\n const [offset, setOffset] = useGlobalState<ForceT, number>(\n globalStatePath,\n () => {\n const value = cookieName\n && ssrContext?.req.cookies[cookieName] as string;\n return value ? parseInt(value) : 0;\n },\n );\n useEffect(() => {\n const date = new Date();\n const value = date.getTimezoneOffset();\n setOffset(value);\n if (cookieName) {\n document.cookie = serialize(cookieName, value.toString(), { path: '/' });\n }\n }, [cookieName, setOffset]);\n return offset;\n}\n\nconst time = {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n now: Date.now,\n timer,\n useCurrent,\n useTimezoneOffset,\n};\n\nexport default Object.assign(dayjs, time);\n"],"mappings":"4CAAA,OAASA,SAAS,KAAQ,QAAQ,CAClC,MAAO,CAAAC,KAAK,KAAM,OAAO,CACzB,OAASC,SAAS,KAAQ,OAAO,CAEjC,OACEC,MAAM,CACNC,OAAO,CACPC,MAAM,CACNC,MAAM,CACNC,OAAO,CACPC,KAAK,KACA,sBAAsB,CAE7B,OAAsBC,cAAc,KAAQ,gCAAgC,CAE5E,OAASC,aAAa,qBAEtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA;AACA;AACA,MAAO,SAAS,CAAAC,UAAUA,CAAC,CACzBC,WAAW,CAAG,KAAK,CACnBC,eAAe,CAAG,aAAa,CAC/BC,SAAS,CAAG,CAAC,CAAGR,MAClB,CAAC,CAAG,CAAC,CAAC,CAAU,CACd,KAAM,CAACS,GAAG,CAAEC,MAAM,CAAC,CAAGP,cAAc,CAClCI,eAAe,CACfI,IAAI,CAACF,GACP,CAAC,CACDb,SAAS,CAAC,IAAM,CACd,GAAI,CAAAgB,OAAmC,CACvC,KAAM,CAAAC,MAAM,CAAGA,CAAA,GAAY,CACzBH,MAAM,CAAEI,GAAG,EAAK,CACd,KAAM,CAAAC,GAAG,CAAGJ,IAAI,CAACF,GAAG,CAAC,CAAC,CACtB,MAAO,CAAAO,IAAI,CAACC,GAAG,CAACF,GAAG,CAAGD,GAAG,CAAC,CAAGN,SAAS,CAAGO,GAAG,CAAGD,GAAG,CACpD,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,UAAA,EAAAE,GAAAT,CAAA,KAAAQ,EAAA,MAAAA,EAAA,CAAAR,CAAA,IANH,MAAAa,MAAA,CAAAC,SAAA,EAA4BjC,cAAc,CACxCI,eAAe,CACfuB,EAKF,CAAC,CAAC,IAAAO,EAAA,KAAAC,EAAA,IAAAhB,CAAA,MAAAI,UAAA,EAAAJ,CAAA,MAAAc,SAAA,EACQC,EAAA,CAAAA,CAAA,IACR,MAAAE,IAAA,CAAa,GAAI,CAAA5B,IAAM,CACvB,MAAA6B,OAAA,CAAcD,IAAI,CAAAE,iBAAkB,CAAC,CAAC,CACtCL,SAAS,CAACJ,OAAK,CAAC,CAChB,GAAIN,UAAU,EACZgB,QAAQ,CAAAC,MAAA,CAAUjD,SAAS,CAACgC,UAAU,CAAEM,OAAK,CAAAY,QAAS,CAAC,CAAC,CAAE,CAAAC,IAAA,CAAQ,GAAI,CAAC,CAAxD,CAChB,CACF,CAAEP,EAAA,EAACZ,UAAU,CAAEU,SAAS,CAAC,CAAAd,CAAA,IAAAI,UAAAJ,CAAA,KAAAc,SAAAd,CAAA,KAAAe,EAAAf,CAAA,KAAAgB,EAAA,MAAAD,EAAA,CAAAf,CAAA,GAAAgB,CAAA,GAAAhB,CAAA,IAP1B1B,SAAS,CAACyC,EAOT,CAAEC,EAAuB,CAAC,OACpB,CAAAH,MAAM,CAGf,KAAM,CAAAW,IAAI,CAAG,CACXjD,MAAM,CACNC,OAAO,CACPC,MAAM,CACNC,MAAM,CACNC,OAAO,CACPQ,GAAG,CAAEE,IAAI,CAACF,GAAG,CACbP,KAAK,CACLG,UAAU,CACVe,iBACF,CAAC,CAED,cAAe,CAAA2B,MAAM,CAACC,MAAM,CAACrD,KAAK,CAAEmD,IAAI,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"time.js","names":["stringifySetCookie","dayjs","useEffect","DAY_MS","HOUR_MS","MIN_MS","SEC_MS","YEAR_MS","timer","useGlobalState","useSsrContext","useCurrent","autorefresh","globalStatePath","precision","now","setter","Date","timerId","update","old","neu","Math","abs","setTimeout","clearTimeout","useTimezoneOffset","t0","$","_c","t1","undefined","cookieName","t2","t3","ssrContext","t4","req","value","cookies","parseInt","offset","setOffset","t5","t6","date","value_0","getTimezoneOffset","document","cookie","name","path","toString","time","Object","assign"],"sources":["../../../../src/shared/utils/time.ts"],"sourcesContent":["import { stringifySetCookie } from 'cookie';\nimport dayjs from 'dayjs';\nimport { useEffect } from 'react';\n\nimport {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n timer,\n} from '@dr.pogodin/js-utils';\n\nimport { type ForceT, useGlobalState } from '@dr.pogodin/react-global-state';\n\nimport { useSsrContext } from './globalState';\n\n/**\n * This react hook wraps Date.now() function in a SSR friendly way,\n * ensuring that all calls to useCurrent() within the same render return\n * exactly the same time (which is retrieved from Date.now() first, and\n * then stored in the global state to be reused in all other calls), which\n * is also passed and used in the first client side render, and then updated\n * with a finite precision to avoid infinite re-rendering loops.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useCurrent({\n autorefresh = false,\n globalStatePath = 'currentTime',\n precision = 5 * SEC_MS,\n} = {}): number {\n const [now, setter] = useGlobalState<ForceT, number>(\n globalStatePath,\n Date.now,\n );\n useEffect(() => {\n let timerId: NodeJS.Timeout | undefined;\n const update = (): void => {\n setter((old) => {\n const neu = Date.now();\n return Math.abs(neu - old) > precision ? neu : old;\n });\n if (autorefresh) timerId = setTimeout(update, precision);\n };\n update();\n return (): void => {\n if (timerId) clearTimeout(timerId);\n };\n }, [autorefresh, precision, setter]);\n return now;\n}\n\n/**\n * Wraps the standard Date.getTimezoneOffset() method in a SSR-friendly way.\n * This hook retrieves the offset value at the client side and uses a cookie\n * to pass it to the server in subsequent requests from that user. At the server\n * side the value from cookie is used in renders and passed back to the client\n * via the global state. Prior to the value being known (in the very first\n * request from the user, when the cookie is still missing), zero value is used\n * as the default value.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useTimezoneOffset({\n cookieName = 'timezoneOffset',\n globalStatePath = 'timezoneOffset',\n} = {}): number {\n const ssrContext = useSsrContext(false);\n const [offset, setOffset] = useGlobalState<ForceT, number>(\n globalStatePath,\n () => {\n const value = cookieName\n && ssrContext?.req.cookies[cookieName] as string;\n return value ? parseInt(value) : 0;\n },\n );\n useEffect(() => {\n const date = new Date();\n const value = date.getTimezoneOffset();\n setOffset(value);\n if (cookieName) {\n document.cookie = stringifySetCookie({\n name: cookieName,\n path: '/',\n value: value.toString(),\n });\n }\n }, [cookieName, setOffset]);\n return offset;\n}\n\nconst time = {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n now: Date.now,\n timer,\n useCurrent,\n useTimezoneOffset,\n};\n\nexport default Object.assign(dayjs, time);\n"],"mappings":"4CAAA,OAASA,kBAAkB,KAAQ,QAAQ,CAC3C,MAAO,CAAAC,KAAK,KAAM,OAAO,CACzB,OAASC,SAAS,KAAQ,OAAO,CAEjC,OACEC,MAAM,CACNC,OAAO,CACPC,MAAM,CACNC,MAAM,CACNC,OAAO,CACPC,KAAK,KACA,sBAAsB,CAE7B,OAAsBC,cAAc,KAAQ,gCAAgC,CAE5E,OAASC,aAAa,qBAEtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA;AACA;AACA,MAAO,SAAS,CAAAC,UAAUA,CAAC,CACzBC,WAAW,CAAG,KAAK,CACnBC,eAAe,CAAG,aAAa,CAC/BC,SAAS,CAAG,CAAC,CAAGR,MAClB,CAAC,CAAG,CAAC,CAAC,CAAU,CACd,KAAM,CAACS,GAAG,CAAEC,MAAM,CAAC,CAAGP,cAAc,CAClCI,eAAe,CACfI,IAAI,CAACF,GACP,CAAC,CACDb,SAAS,CAAC,IAAM,CACd,GAAI,CAAAgB,OAAmC,CACvC,KAAM,CAAAC,MAAM,CAAGA,CAAA,GAAY,CACzBH,MAAM,CAAEI,GAAG,EAAK,CACd,KAA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AAM,CAACtD,KAAK,CAAEoD,IAAI,CAAC","ignoreList":[]}
@@ -8,6 +8,7 @@ const globalLibDir = path.resolve(process.execPath, '../../lib/node_modules');
8
8
  const modulesToTransform = [
9
9
  '@dr.pogodin/react-global-state',
10
10
  '@dr.pogodin/react-utils',
11
+ 'cookie',
11
12
  'lodash-es',
12
13
  ];
13
14
 
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.54.0",
2
+ "version": "1.54.2",
3
3
  "bin": {
4
4
  "react-utils-build": "bin/build.js",
5
5
  "react-utils-setup": "bin/setup.js"
@@ -17,11 +17,11 @@
17
17
  "@dr.pogodin/react-helmet": "^3.2.2",
18
18
  "@dr.pogodin/react-themes": "^1.10.5",
19
19
  "@jest/environment": "^30.4.1",
20
- "axios": "^1.18.0",
20
+ "axios": "^1.18.1",
21
21
  "commander": "^15.0.0",
22
22
  "compression": "^1.8.1",
23
23
  "config": "^4.4.1",
24
- "cookie": "^1.1.0",
24
+ "cookie": "^2.0.0",
25
25
  "cookie-parser": "^1.4.7",
26
26
  "core-js": "^3.49.0",
27
27
  "cross-env": "^10.1.0",
@@ -31,7 +31,7 @@
31
31
  "http-status-codes": "^2.3.0",
32
32
  "lodash-es": "^4.18.1",
33
33
  "morgan": "^1.11.0",
34
- "qs": "^6.15.2",
34
+ "qs": "^6.15.3",
35
35
  "raf": "^3.4.1",
36
36
  "react": "^19.2.7",
37
37
  "react-dom": "^19.2.7",
@@ -82,7 +82,7 @@
82
82
  "@types/supertest": "^7.2.0",
83
83
  "@types/webpack": "^5.28.5",
84
84
  "@types/webpack-hot-middleware": "^2.25.12",
85
- "autoprefixer": "^10.5.0",
85
+ "autoprefixer": "^10.5.2",
86
86
  "babel-jest": "^30.4.1",
87
87
  "babel-loader": "^10.1.1",
88
88
  "babel-plugin-add-import-extension": "^1.6.0",