@dr.pogodin/react-utils 1.47.0-alpha.1 → 1.47.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/babel.config.js +1 -1
- package/babel.module.config.js +11 -0
- package/bin/build.js +8 -4
- package/bin/setup.js +2 -3
- package/build/development/client/getInj.js +57 -44
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/client/index.js +15 -21
- package/build/development/client/index.js.map +1 -1
- package/build/development/client/init.js +2 -6
- package/build/development/client/init.js.map +1 -1
- package/build/development/index.js +3 -183
- package/build/development/index.js.map +1 -1
- package/build/development/server/Cache.js +1 -8
- package/build/development/server/Cache.js.map +1 -1
- package/build/development/server/index.js +22 -50
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +83 -92
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +58 -62
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/errors.js +8 -31
- package/build/development/server/utils/errors.js.map +1 -1
- package/build/development/server/utils/index.js +2 -9
- package/build/development/server/utils/index.js.map +1 -1
- package/build/development/shared/components/Button/index.js +9 -16
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +6 -13
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/GenericLink/index.js +4 -10
- package/build/development/shared/components/GenericLink/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +11 -18
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Link.js +6 -13
- package/build/development/shared/components/Link.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +16 -22
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/NavLink.js +6 -13
- package/build/development/shared/components/NavLink.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js +7 -14
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +15 -22
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js +7 -14
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js +12 -18
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +16 -23
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +10 -17
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/index.js +16 -130
- package/build/development/shared/components/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +18 -19
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +24 -28
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +19 -19
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +12 -17
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/components/selectors/common.js +1 -7
- package/build/development/shared/components/selectors/common.js.map +1 -1
- package/build/development/shared/components/selectors/index.js +3 -27
- package/build/development/shared/components/selectors/index.js.map +1 -1
- package/build/development/shared/utils/config.js +40 -21
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/globalState.js +3 -8
- package/build/development/shared/utils/globalState.js.map +1 -1
- package/build/development/shared/utils/index.js +12 -89
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/isomorphy/buildInfo.js +2 -9
- package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/development/shared/utils/isomorphy/environment-check.js +2 -8
- package/build/development/shared/utils/isomorphy/environment-check.js.map +1 -1
- package/build/development/shared/utils/isomorphy/index.js +7 -32
- package/build/development/shared/utils/isomorphy/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js +24 -31
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/development/shared/utils/jest/global.js +1 -7
- package/build/development/shared/utils/jest/global.js.map +1 -1
- package/build/development/shared/utils/jest/index.js +20 -44
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +54 -46
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/time.js +22 -31
- package/build/development/shared/utils/time.js.map +1 -1
- package/build/development/shared/utils/webpack.js +17 -16
- package/build/development/shared/utils/webpack.js.map +1 -1
- package/build/production/client/getInj.js +13 -11
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/client/index.js +3 -3
- package/build/production/client/index.js.map +1 -1
- package/build/production/client/init.js +2 -2
- package/build/production/client/init.js.map +1 -1
- package/build/production/index.js +2 -6
- package/build/production/index.js.map +1 -1
- package/build/production/server/Cache.js +3 -3
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/index.js +8 -8
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +24 -25
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +9 -11
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/errors.js +9 -9
- package/build/production/server/utils/errors.js.map +1 -1
- package/build/production/server/utils/index.js +2 -1
- package/build/production/server/utils/index.js.map +1 -1
- package/build/production/shared/components/Button/index.js +4 -4
- package/build/production/shared/components/Button/index.js.map +1 -1
- package/build/production/shared/components/Checkbox/index.js +1 -1
- package/build/production/shared/components/Checkbox/index.js.map +1 -1
- package/build/production/shared/components/GenericLink/index.js +4 -4
- package/build/production/shared/components/GenericLink/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +5 -5
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Link.js +3 -3
- package/build/production/shared/components/Link.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +7 -7
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/NavLink.js +2 -2
- package/build/production/shared/components/NavLink.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js +2 -2
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js +5 -5
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js +2 -2
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js +4 -4
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +4 -4
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +4 -4
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/index.js +3 -1
- package/build/production/shared/components/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +2 -2
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js +2 -2
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js +4 -4
- package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/Switch/index.js +1 -1
- package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/production/shared/components/selectors/common.js +2 -2
- package/build/production/shared/components/selectors/common.js.map +1 -1
- package/build/production/shared/components/selectors/index.js +1 -1
- package/build/production/shared/components/selectors/index.js.map +1 -1
- package/build/production/shared/utils/config.js +8 -6
- package/build/production/shared/utils/config.js.map +1 -1
- package/build/production/shared/utils/globalState.js +2 -2
- package/build/production/shared/utils/globalState.js.map +1 -1
- package/build/production/shared/utils/index.js +1 -1
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/isomorphy/buildInfo.js +3 -3
- package/build/production/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/production/shared/utils/isomorphy/environment-check.js +3 -3
- package/build/production/shared/utils/isomorphy/environment-check.js.map +1 -1
- package/build/production/shared/utils/isomorphy/index.js +4 -4
- package/build/production/shared/utils/isomorphy/index.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +14 -14
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/jest/global.js +1 -1
- package/build/production/shared/utils/jest/global.js.map +1 -1
- package/build/production/shared/utils/jest/index.js +11 -11
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +11 -22
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/time.js +3 -3
- package/build/production/shared/utils/time.js.map +1 -1
- package/build/production/shared/utils/webpack.js +6 -6
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/types-code/client/getInj.d.ts +1 -2
- package/build/types-code/client/index.d.ts +1 -1
- package/build/types-code/index.d.ts +1 -7
- package/build/types-code/server/index.d.ts +6 -11
- package/build/types-code/server/utils/index.d.ts +1 -1
- package/build/types-code/shared/utils/config.d.ts +4 -2
- package/build/types-code/shared/utils/index.d.ts +2 -2
- package/build/types-code/shared/utils/splitComponent.d.ts +6 -4
- package/build/web/client/getInj.js +55 -44
- package/build/web/client/getInj.js.map +1 -1
- package/build/web/client/index.js +15 -21
- package/build/web/client/index.js.map +1 -1
- package/build/web/client/init.js +2 -4
- package/build/web/client/init.js.map +1 -1
- package/build/web/index.js +1 -15
- package/build/web/index.js.map +1 -1
- package/build/web/server/index.js +12 -21
- package/build/web/server/index.js.map +1 -1
- package/build/web/server/renderer.js +34 -40
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/server/server.js +14 -11
- package/build/web/server/server.js.map +1 -1
- package/build/web/server/utils/index.js +1 -1
- package/build/web/server/utils/index.js.map +1 -1
- package/build/web/shared/components/Button/index.js +1 -1
- package/build/web/shared/components/Button/index.js.map +1 -1
- package/build/web/shared/components/Checkbox/index.js +1 -1
- package/build/web/shared/components/Checkbox/index.js.map +1 -1
- package/build/web/shared/components/Input/index.js +1 -1
- package/build/web/shared/components/Input/index.js.map +1 -1
- package/build/web/shared/components/Modal/index.js +3 -3
- package/build/web/shared/components/Modal/index.js.map +1 -1
- package/build/web/shared/components/PageLayout/index.js +1 -1
- package/build/web/shared/components/PageLayout/index.js.map +1 -1
- package/build/web/shared/components/TextArea/index.js +1 -1
- package/build/web/shared/components/TextArea/index.js.map +1 -1
- package/build/web/shared/components/Throbber/index.js +1 -1
- package/build/web/shared/components/Throbber/index.js.map +1 -1
- package/build/web/shared/components/WithTooltip/index.js +1 -1
- package/build/web/shared/components/WithTooltip/index.js.map +1 -1
- package/build/web/shared/components/YouTubeVideo/index.js +1 -1
- package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +3 -0
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js +3 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js +4 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/Switch/index.js +2 -1
- package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/web/shared/utils/config.js +38 -14
- package/build/web/shared/utils/config.js.map +1 -1
- package/build/web/shared/utils/index.js +2 -2
- package/build/web/shared/utils/index.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv.js +3 -2
- package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/web/shared/utils/splitComponent.js +27 -20
- package/build/web/shared/utils/splitComponent.js.map +1 -1
- package/build/web/shared/utils/webpack.js +13 -7
- package/build/web/shared/utils/webpack.js.map +1 -1
- package/config/babel/node-ssr.js +12 -6
- package/config/babel/webpack.js +6 -1
- package/config/jest/default.js +8 -2
- package/config/jest/setup.js +8 -1
- package/config/webpack/app-base.js +23 -15
- package/config/webpack/app-development.js +2 -3
- package/config/webpack/lib-base.js +1 -2
- package/package.json +35 -25
- package/types.d.ts +1 -6
- package/node-entry.js +0 -15
- package/src/client/getInj.ts +0 -51
- package/src/client/index.tsx +0 -43
- package/src/client/init.ts +0 -52
- package/src/index.ts +0 -79
- package/src/server/Cache.ts +0 -61
- package/src/server/index.ts +0 -249
- package/src/server/renderer.tsx +0 -653
- package/src/server/server.ts +0 -332
- package/src/server/utils/errors.ts +0 -122
- package/src/server/utils/index.ts +0 -3
- package/src/shared/components/Button/index.tsx +0 -130
- package/src/shared/components/Button/style.scss +0 -54
- package/src/shared/components/Checkbox/index.tsx +0 -53
- package/src/shared/components/Checkbox/theme.scss +0 -63
- package/src/shared/components/GenericLink/index.tsx +0 -141
- package/src/shared/components/GenericLink/style.scss +0 -3
- package/src/shared/components/Input/index.tsx +0 -96
- package/src/shared/components/Input/theme.scss +0 -52
- package/src/shared/components/Link.tsx +0 -25
- package/src/shared/components/Modal/base-theme.scss +0 -38
- package/src/shared/components/Modal/index.tsx +0 -177
- package/src/shared/components/Modal/styles.scss +0 -3
- package/src/shared/components/NavLink.tsx +0 -18
- package/src/shared/components/PageLayout/base-theme.scss +0 -30
- package/src/shared/components/PageLayout/index.tsx +0 -51
- package/src/shared/components/TextArea/index.tsx +0 -139
- package/src/shared/components/TextArea/style.scss +0 -68
- package/src/shared/components/Throbber/index.tsx +0 -28
- package/src/shared/components/Throbber/theme.scss +0 -26
- package/src/shared/components/WithTooltip/Tooltip.tsx +0 -274
- package/src/shared/components/WithTooltip/default-theme.scss +0 -36
- package/src/shared/components/WithTooltip/index.tsx +0 -186
- package/src/shared/components/YouTubeVideo/base.scss +0 -15
- package/src/shared/components/YouTubeVideo/index.tsx +0 -73
- package/src/shared/components/YouTubeVideo/throbber.scss +0 -11
- package/src/shared/components/index.ts +0 -20
- package/src/shared/components/selectors/CustomDropdown/Options/index.tsx +0 -124
- package/src/shared/components/selectors/CustomDropdown/Options/style.scss +0 -6
- package/src/shared/components/selectors/CustomDropdown/index.tsx +0 -146
- package/src/shared/components/selectors/CustomDropdown/theme.scss +0 -118
- package/src/shared/components/selectors/NativeDropdown/index.tsx +0 -90
- package/src/shared/components/selectors/NativeDropdown/theme.scss +0 -81
- package/src/shared/components/selectors/Switch/index.tsx +0 -74
- package/src/shared/components/selectors/Switch/theme.scss +0 -39
- package/src/shared/components/selectors/common.ts +0 -57
- package/src/shared/components/selectors/index.ts +0 -8
- package/src/shared/utils/config.ts +0 -28
- package/src/shared/utils/globalState.ts +0 -44
- package/src/shared/utils/index.ts +0 -45
- package/src/shared/utils/isomorphy/buildInfo.ts +0 -50
- package/src/shared/utils/isomorphy/environment-check.ts +0 -18
- package/src/shared/utils/isomorphy/index.ts +0 -36
- package/src/shared/utils/jest/E2eSsrEnv.ts +0 -305
- package/src/shared/utils/jest/global.ts +0 -17
- package/src/shared/utils/jest/index.ts +0 -215
- package/src/shared/utils/splitComponent.tsx +0 -275
- package/src/shared/utils/time.ts +0 -101
- package/src/shared/utils/webpack.ts +0 -74
- package/src/styles/_global/reset.css +0 -52
- package/src/styles/_mixins/fonts.scss +0 -40
- package/src/styles/_mixins/media.scss +0 -150
- package/src/styles/_mixins/typography.scss +0 -83
- package/src/styles/global.scss +0 -11
- package/src/styles/mixins.scss +0 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitComponent.js","names":["_react","require","_jsUtils","_globalState","_isomorphy","_jsxRuntime","clientChunkGroups","IS_CLIENT_SIDE","default","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","resolved","Component","Wrapper","children","ref","rest","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","_jsx","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\n// Note: At the client side we can get chunk groups immediately when loading\n// the module; at the server-side we only can get them within React render flow.\n// Thus, we set and use the following variable at the client-side, and then when\n// needed on the server side, we'll fetch it differently.\nlet clientChunkGroups: ChunkGroupsT;\n\nif (IS_CLIENT_SIDE) {\n // TODO: Rewrite to avoid these overrides of ESLint rules.\n /* eslint-disable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n clientChunkGroups = require('client/getInj').default().CHUNK_GROUPS ?? {};\n /* eslint-enable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) assertChunkName(chunkName, clientChunkGroups);\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":";;;;;;;;AAEA,IAAAA,MAAA,GAAAC,OAAA;AAUA,IAAAC,QAAA,GAAAD,OAAA;AAEA,IAAAE,YAAA,GAAAF,OAAA;AAEA,IAAAG,UAAA,GAAAH,OAAA;AASA,IAAAI,WAAA,GAAAJ,OAAA;AAzBA;;AAsBA;AACA;AACA;AACA;;AACA,IAAIK,iBAA+B;AAEnC,IAAIC,yBAAc,EAAE;EAClB;EACA;AACF;AACA;AACA;EACED,iBAAiB,GAAGL,OAAO,sBAAgB,CAAC,CAACO,OAAO,CAAC,CAAC,CAACC,YAAY,IAAI,CAAC,CAAC;EACzE;AACF;AACA;AACA;AACA;AAEA,MAAMC,SAAiC,GAAG,CAAC,CAAC;AAE5C,SAASC,aAAaA,CAAA,EAAG;EACvB,OAAO,IAAAC,uBAAY,EAAC,CAAC,CAACC,UAAU;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,cAAcA,CACrBC,IAA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
+
{"version":3,"file":"splitComponent.js","names":["Suspense","lazy","useInsertionEffect","Barrier","getSsrContext","IS_CLIENT_SIDE","IS_SERVER_SIDE","getBuildInfo","jsx","_jsx","getClientChunkGroups","undefined","default","getInj","inj","CHUNK_GROUPS","refCounts","getPublicPath","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","clientChunkGroups","resolved","Component","Wrapper","children","ref","rest","chunks","includes","CodeSplit","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\nfunction getClientChunkGroups(): Promise<ChunkGroupsT> | undefined {\n if (!IS_CLIENT_SIDE) return undefined;\n\n return (async () => {\n const { default: getInj } = await import(/* webpackChunkName: \"react-utils-client-side-code\" */ '../../client/getInj');\n\n const inj = await getInj();\n return inj.CHUNK_GROUPS ?? {};\n })();\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\ntype GenericComponentPropsT = {\n children?: ReactNode;\n ref?: RefObject<unknown>;\n\n // NOTE: This is necessary, as without it this type (with only optional\n // fields) will be conisdered as \"weak\" by TypeScript, and it will be\n // a error to assign to it any type that does not use \"children\", or \"ref\".\n [propName: string]: unknown;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends GenericComponentPropsT,\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const clientChunkGroups = await getClientChunkGroups();\n\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n assertChunkName(chunkName, clientChunkGroups);\n }\n\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;;AAEA,SAKEA,QAAQ,EACRC,IAAI,EACJC,kBAAkB,QACb,OAAO;AAEd,SAASC,OAAO,QAAQ,sBAAsB;AAAA,SAElBC,aAAa;AAAA,SAGvCC,cAAc,EACdC,cAAc,EACdC,YAAY;AACO,SAAAC,GAAA,IAAAC,IAAA;AAErB,SAASC,oB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A;MACA;MACA5C,kBAAkB,CAAC,MAAM;QACvB,IAAI,CAACiE,iBAAiB,EAAE,MAAM9B,KAAK,CAAC,gBAAgB,CAAC;QACrD,KAAKW,eAAe,CAACF,SAAS,EAAEqB,iBAAiB,EAAE,IAAI,CAAC;QACxD,OAAO,MAAM;UACXR,eAAe,CAACb,SAAS,EAAEqB,iBAAiB,CAAC;QAC/C,CAAC;MACH,CAAC,EAAE,EAAE,CAAC;MAEN,oBACE1D,IAAA,CAAC4D;MACC;MAAA;QAAA,GACKI,IAAI;QACTD,GAAG,EAAEA,GAAI;QAAAD,QAAA,EAERA;MAAQ,CACA,CAAC;IAEhB,CAAC;IAED,OAAO;MAAE3D,OAAO,EAAE0D;IAAQ,CAAC;EAC7B,CAAC,CAAC;EAEF,MAAMM,SAAmD,GAAGA,CAAC;IAC3DL,QAAQ;IACR,GAAGE;EACY,CAAC,kBAChBhE,IAAA,CAACT,QAAQ;IAAC6E,QAAQ,EAAEZ,WAAY;IAAAM,QAAA,eAC9B9D,IAAA,CAACyD;IACC;IAAA;MAAA,GACIO,IAAI;MAAAF,QAAA,EAEPA;IAAQ,CACI;EAAC,CACR,CACX;EAED,OAAOK,SAAS;AAClB","ignoreList":[]}
|
|
@@ -1,18 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
}
|
|
7
|
-
exports.default = void 0;
|
|
8
|
-
exports.useCurrent = useCurrent;
|
|
9
|
-
exports.useTimezoneOffset = useTimezoneOffset;
|
|
10
|
-
var _cookie = require("cookie");
|
|
11
|
-
var _react = require("react");
|
|
12
|
-
var _dayjs = _interopRequireDefault(require("dayjs"));
|
|
13
|
-
var _jsUtils = require("@dr.pogodin/js-utils");
|
|
14
|
-
var _reactGlobalState = require("@dr.pogodin/react-global-state");
|
|
15
|
-
var _globalState = require("./globalState");
|
|
1
|
+
import { serialize } from 'cookie';
|
|
2
|
+
import { useEffect } from 'react';
|
|
3
|
+
import dayjs from 'dayjs';
|
|
4
|
+
import { DAY_MS, HOUR_MS, MIN_MS, SEC_MS, YEAR_MS, timer } from '@dr.pogodin/js-utils';
|
|
5
|
+
import { useGlobalState } from '@dr.pogodin/react-global-state';
|
|
6
|
+
import { getSsrContext } from "./globalState.js";
|
|
16
7
|
/**
|
|
17
8
|
* This react hook wraps Date.now() function in a SSR friendly way,
|
|
18
9
|
* ensuring that all calls to useCurrent() within the same render return
|
|
@@ -23,13 +14,13 @@ var _globalState = require("./globalState");
|
|
|
23
14
|
*/
|
|
24
15
|
// TODO: Should we request the state type as generic parameter, to be able
|
|
25
16
|
// to verify the give globalStatePath is correct?
|
|
26
|
-
function useCurrent({
|
|
17
|
+
export function useCurrent({
|
|
27
18
|
autorefresh = false,
|
|
28
19
|
globalStatePath = 'currentTime',
|
|
29
|
-
precision = 5 *
|
|
20
|
+
precision = 5 * SEC_MS
|
|
30
21
|
} = {}) {
|
|
31
|
-
const [now, setter] =
|
|
32
|
-
|
|
22
|
+
const [now, setter] = useGlobalState(globalStatePath, Date.now);
|
|
23
|
+
useEffect(() => {
|
|
33
24
|
let timerId;
|
|
34
25
|
const update = () => {
|
|
35
26
|
setter(old => {
|
|
@@ -57,21 +48,21 @@ function useCurrent({
|
|
|
57
48
|
*/
|
|
58
49
|
// TODO: Should we request the state type as generic parameter, to be able
|
|
59
50
|
// to verify the give globalStatePath is correct?
|
|
60
|
-
function useTimezoneOffset({
|
|
51
|
+
export function useTimezoneOffset({
|
|
61
52
|
cookieName = 'timezoneOffset',
|
|
62
53
|
globalStatePath = 'timezoneOffset'
|
|
63
54
|
} = {}) {
|
|
64
|
-
const ssrContext =
|
|
65
|
-
const [offset, setOffset] =
|
|
55
|
+
const ssrContext = getSsrContext(false);
|
|
56
|
+
const [offset, setOffset] = useGlobalState(globalStatePath, () => {
|
|
66
57
|
const value = cookieName && ssrContext?.req.cookies[cookieName];
|
|
67
58
|
return value ? parseInt(value) : 0;
|
|
68
59
|
});
|
|
69
|
-
|
|
60
|
+
useEffect(() => {
|
|
70
61
|
const date = new Date();
|
|
71
62
|
const value = date.getTimezoneOffset();
|
|
72
63
|
setOffset(value);
|
|
73
64
|
if (cookieName) {
|
|
74
|
-
document.cookie =
|
|
65
|
+
document.cookie = serialize(cookieName, value.toString(), {
|
|
75
66
|
path: '/'
|
|
76
67
|
});
|
|
77
68
|
}
|
|
@@ -79,15 +70,15 @@ function useTimezoneOffset({
|
|
|
79
70
|
return offset;
|
|
80
71
|
}
|
|
81
72
|
const time = {
|
|
82
|
-
DAY_MS
|
|
83
|
-
HOUR_MS
|
|
84
|
-
MIN_MS
|
|
85
|
-
SEC_MS
|
|
86
|
-
YEAR_MS
|
|
73
|
+
DAY_MS,
|
|
74
|
+
HOUR_MS,
|
|
75
|
+
MIN_MS,
|
|
76
|
+
SEC_MS,
|
|
77
|
+
YEAR_MS,
|
|
87
78
|
now: Date.now,
|
|
88
|
-
timer
|
|
79
|
+
timer,
|
|
89
80
|
useCurrent,
|
|
90
81
|
useTimezoneOffset
|
|
91
82
|
};
|
|
92
|
-
|
|
83
|
+
export default Object.assign(dayjs, time);
|
|
93
84
|
//# sourceMappingURL=time.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"time.js","names":["
|
|
1
|
+
{"version":3,"file":"time.js","names":["serialize","useEffect","dayjs","DAY_MS","HOUR_MS","MIN_MS","SEC_MS","YEAR_MS","timer","useGlobalState","getSsrContext","useCurrent","autorefresh","globalStatePath","precision","now","setter","Date","timerId","update","old","neu","Math","abs","setTimeout","clearTimeout","useTimezoneOffset","cookieName","ssrContext","offset","setOffset","value","req","cookies","parseInt","date","getTimezoneOffset","document","cookie","toString","path","time","Object","assign"],"sources":["../../../../src/shared/utils/time.ts"],"sourcesContent":["import { serialize } from 'cookie';\nimport { useEffect } from 'react';\nimport dayjs from 'dayjs';\n\nimport {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n timer,\n} from '@dr.pogodin/js-utils';\n\nimport { type ForceT, useGlobalState } from '@dr.pogodin/react-global-state';\n\nimport { getSsrContext } from './globalState';\n\n/**\n * This react hook wraps Date.now() function in a SSR friendly way,\n * ensuring that all calls to useCurrent() within the same render return\n * exactly the same time (which is retrieved from Date.now() first, and\n * then stored in the global state to be reused in all other calls), which\n * is also passed and used in the first client side render, and then updated\n * with a finite precision to avoid infinite re-rendering loops.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useCurrent({\n autorefresh = false,\n globalStatePath = 'currentTime',\n precision = 5 * SEC_MS,\n} = {}): number {\n const [now, setter] = useGlobalState<ForceT, number>(\n globalStatePath,\n Date.now,\n );\n useEffect(() => {\n let timerId: NodeJS.Timeout | undefined;\n const update = (): void => {\n setter((old) => {\n const neu = Date.now();\n return Math.abs(neu - old) > precision ? neu : old;\n });\n if (autorefresh) timerId = setTimeout(update, precision);\n };\n update();\n return (): void => {\n if (timerId) clearTimeout(timerId);\n };\n }, [autorefresh, precision, setter]);\n return now;\n}\n\n/**\n * Wraps the standard Date.getTimezoneOffset() method in a SSR-friendly way.\n * This hook retrieves the offset value at the client side and uses a cookie\n * to pass it to the server in subsequent requests from that user. At the server\n * side the value from cookie is used in renders and passed back to the client\n * via the global state. Prior to the value being known (in the very first\n * request from the user, when the cookie is still missing), zero value is used\n * as the default value.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useTimezoneOffset({\n cookieName = 'timezoneOffset',\n globalStatePath = 'timezoneOffset',\n} = {}): number {\n const ssrContext = getSsrContext(false);\n const [offset, setOffset] = useGlobalState<ForceT, number>(\n globalStatePath,\n () => {\n const value = cookieName\n && ssrContext?.req.cookies[cookieName] as string;\n return value ? parseInt(value) : 0;\n },\n );\n useEffect(() => {\n const date = new Date();\n const value = date.getTimezoneOffset();\n setOffset(value);\n if (cookieName) {\n document.cookie = serialize(cookieName, value.toString(), { path: '/' });\n }\n }, [cookieName, setOffset]);\n return offset;\n}\n\nconst time = {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n now: Date.now,\n timer,\n useCurrent,\n useTimezoneOffset,\n};\n\nexport default Object.assign(dayjs, time);\n"],"mappings":"AAAA,SAASA,SAAS,QAAQ,QAAQ;AAClC,SAASC,SAAS,QAAQ,OAAO;AACjC,OAAOC,KAAK,MAAM,OAAO;AAEzB,SACEC,MAAM,EACNC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,OAAO,EACPC,KAAK,QACA,sBAAsB;AAE7B,SAAsBC,cAAc,QAAQ,gCAAgC;AAAA,SAEnEC,aAAa;AAEtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,UAAUA,CAAC;EACzBC,WAAW,GAAG,KAAK;EACnBC,eAAe,GAAG,aAAa;EAC/BC,SAAS,GAAG,CAAC,GAAGR;AAClB,CAAC,GAAG,CAAC,CAAC,EAAU;EACd,MAAM,CAACS,GAAG,EAAEC,MAAM,CAAC,GAAGP,cAAc,CAClCI,eAAe,EACfI,IAAI,CAACF,GACP,CAAC;EACDd,SAAS,CAAC,MAAM;IACd,IAAIiB,OAAmC;IACvC,MAAMC,MAAM,GAAGA,CAAA,KAAY;MACzBH,MAAM,CAAEI,GAAG,IAAK;QACd,MAAMC,GAAG,GAAGJ,IAAI,CAACF,GAAG,CAAC,CAAC;QACtB,OAAOO,IAAI,CAACC,GAAG,CAACF,GAAG,GAAGD,GAAG,CAAC,GAAGN,SAAS,GAAGO,GAAG,GAAGD,GAAG;MACpD,CAAC,CAAC;MACF,IAAIR,WAAW,EAAEM,OAAO,GAAGM,UAAU,CAACL,MAAM,EAAEL,SAAS,CAAC;IAC1D,CAAC;IACDK,MAAM,CAAC,CAAC;IACR,OAAO,MAAY;MACjB,IAAID,OAAO,EAAEO,YAAY,CAACP,OAAO,CAAC;IACpC,CAAC;EACH,CAAC,EAAE,CAACN,WAAW,EAAEE,SAAS,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1
|
+
import "core-js/modules/es.iterator.constructor.js";
|
|
2
|
+
import "core-js/modules/es.iterator.for-each.js";
|
|
3
|
+
import "core-js/modules/es.iterator.constructor.js";
|
|
4
|
+
import "core-js/modules/es.iterator.for-each.js";
|
|
5
|
+
// eslint-disable-next-line import/enforce-node-protocol-usage
|
|
6
|
+
import { createRequire } from 'module';
|
|
7
|
+
import { IS_CLIENT_SIDE, IS_SERVER_SIDE } from "./isomorphy/index.js";
|
|
8
|
+
let require;
|
|
9
|
+
if (IS_SERVER_SIDE) require = createRequire(import.meta.url);
|
|
2
10
|
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.requireWeak = requireWeak;
|
|
7
|
-
exports.resolveWeak = resolveWeak;
|
|
8
|
-
var _isomorphy = require("./isomorphy");
|
|
9
11
|
/**
|
|
10
12
|
* Requires the specified module without including it into the bundle during
|
|
11
13
|
* Webpack build.
|
|
@@ -13,12 +15,12 @@ var _isomorphy = require("./isomorphy");
|
|
|
13
15
|
* @param [basePath]
|
|
14
16
|
* @return Required module.
|
|
15
17
|
*/
|
|
16
|
-
function requireWeak(modulePath,
|
|
18
|
+
export function requireWeak(modulePath,
|
|
17
19
|
// TODO: For now `basePath` can be provided directly as a string here,
|
|
18
20
|
// for backward compatibility. Deprecate it in future, if any other
|
|
19
21
|
// breaking changes are done for requireWeak().
|
|
20
22
|
basePathOrOptions) {
|
|
21
|
-
if (
|
|
23
|
+
if (IS_CLIENT_SIDE) return null;
|
|
22
24
|
let basePath;
|
|
23
25
|
let ops;
|
|
24
26
|
if (typeof basePathOrOptions === 'string') {
|
|
@@ -30,15 +32,12 @@ basePathOrOptions) {
|
|
|
30
32
|
} = ops);
|
|
31
33
|
}
|
|
32
34
|
|
|
33
|
-
// eslint-disable-next-line no-eval
|
|
34
|
-
const req = eval('require');
|
|
35
|
-
|
|
36
35
|
// eslint-disable-next-line @typescript-eslint/unbound-method
|
|
37
36
|
const {
|
|
38
37
|
resolve
|
|
39
|
-
} =
|
|
38
|
+
} = require('node:path');
|
|
40
39
|
const path = basePath ? resolve(basePath, modulePath) : modulePath;
|
|
41
|
-
const module =
|
|
40
|
+
const module = require(path);
|
|
42
41
|
if (!('default' in module) || !module.default) return module;
|
|
43
42
|
const {
|
|
44
43
|
default: def,
|
|
@@ -47,7 +46,9 @@ basePathOrOptions) {
|
|
|
47
46
|
const res = def;
|
|
48
47
|
Object.entries(named).forEach(([name, value]) => {
|
|
49
48
|
const assigned = res[name];
|
|
50
|
-
if (assigned
|
|
49
|
+
if (assigned === undefined) {
|
|
50
|
+
res[name] = value;
|
|
51
|
+
} else if (assigned !== value) {
|
|
51
52
|
throw Error('Conflict between default and named exports');
|
|
52
53
|
}
|
|
53
54
|
});
|
|
@@ -62,7 +63,7 @@ basePathOrOptions) {
|
|
|
62
63
|
* @param {string} modulePath
|
|
63
64
|
* @return {string} Absolute or relative path to the module.
|
|
64
65
|
*/
|
|
65
|
-
function resolveWeak(modulePath) {
|
|
66
|
+
export function resolveWeak(modulePath) {
|
|
66
67
|
return modulePath;
|
|
67
68
|
}
|
|
68
69
|
//# sourceMappingURL=webpack.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webpack.js","names":["
|
|
1
|
+
{"version":3,"file":"webpack.js","names":["createRequire","IS_CLIENT_SIDE","IS_SERVER_SIDE","require","import","meta","url","requireWeak","modulePath","basePathOrOptions","basePath","ops","resolve","path","module","default","def","named","res","Object","entries","forEach","name","value","assigned","undefined","Error","resolveWeak"],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import type PathNS from 'node:path';\n\n// eslint-disable-next-line import/enforce-node-protocol-usage\nimport { createRequire } from 'module';\n\nimport { IS_CLIENT_SIDE, IS_SERVER_SIDE } from './isomorphy';\n\ntype RequireWeakOptionsT = {\n basePath?: string;\n};\n\ntype RequireWeakResT<T> = T extends { default: infer D }\n ? (D extends null | undefined ? T : D & Omit<T, 'default'>)\n : T;\n\nlet require: ((url: string) => unknown) | undefined;\n\nif (IS_SERVER_SIDE) require = createRequire(import.meta.url);\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak<T extends object>(\n modulePath: string,\n\n // TODO: For now `basePath` can be provided directly as a string here,\n // for backward compatibility. Deprecate it in future, if any other\n // breaking changes are done for requireWeak().\n basePathOrOptions?: string | RequireWeakOptionsT,\n): RequireWeakResT<T> | null {\n if (IS_CLIENT_SIDE) return null;\n\n let basePath: string | undefined;\n let ops: RequireWeakOptionsT;\n if (typeof basePathOrOptions === 'string') {\n basePath = basePathOrOptions;\n } else {\n ops = basePathOrOptions ?? {};\n ({ basePath } = ops);\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { resolve } = require!('node:path') as typeof PathNS;\n\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n\n const module = require!(path) as T;\n\n if (!('default' in module) || !module.default) return module as RequireWeakResT<T>;\n\n const { default: def, ...named } = module;\n\n const res = def as RequireWeakResT<T>;\n\n Object.entries(named).forEach(([name, value]) => {\n const assigned = res[name as keyof RequireWeakResT<T>];\n if (assigned === undefined) {\n (res[name as keyof RequireWeakResT<T>] as unknown) = value;\n } else if (assigned !== value) {\n throw Error('Conflict between default and named exports');\n }\n });\n return res;\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":";;;;AAEA;AACA,SAASA,aAAa,QAAQ,QAAQ;AAAA,SAE7BC,cAAc,EAAEC,cAAc;AAUvC,IAAIC,OAA+C;AAEnD,IAAID,cAAc,EAAEC,OAAO,GAAGH,aAAa,CAACI,MAAM,CAACC,IAAI,CAACC,GA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AACA;AACA;AACA;AACA,OAAO,SAASS,WAAWA,CAACnB,UAAkB,EAAU;EACtD,OAAOA,UAAU;AACnB","ignoreList":[]}
|
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
"
|
|
2
|
-
/* global document
|
|
3
|
-
// is
|
|
4
|
-
|
|
5
|
-
//
|
|
6
|
-
// is
|
|
7
|
-
//
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
1
|
+
import"core-js/modules/es.array-buffer.detached.js";import"core-js/modules/es.array-buffer.transfer.js";import"core-js/modules/es.array-buffer.transfer-to-fixed-length.js";import"core-js/modules/es.array-buffer.detached.js";import"core-js/modules/es.array-buffer.transfer.js";import"core-js/modules/es.array-buffer.transfer-to-fixed-length.js";import"core-js/modules/es.typed-array.to-reversed.js";import"core-js/modules/es.typed-array.to-sorted.js";import"core-js/modules/es.typed-array.with.js";import"core-js/modules/web.dom-exception.stack.js";// Encapsulates retrieval of server-side data injection into HTML template.
|
|
2
|
+
/* global document */import{getBuildInfo}from"../shared/utils/isomorphy/buildInfo.js";let inj;export default function getInj(){inj??=(async()=>{const metaElement=typeof document==="undefined"?null:document.querySelector("meta[itemprop=\"drpruinj\"]");if(metaElement){metaElement.remove();// NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be
|
|
3
|
+
// preferred, but it is not supported by older environments yet.
|
|
4
|
+
const data=atob(metaElement.content);// TODO: Our current handling of this encryption / decryption follows
|
|
5
|
+
// a legacy approach, and can be enhanced by using Crypto features.
|
|
6
|
+
// Though, this is not strictly intended to be secure (it is more
|
|
7
|
+
// to obfurscate injected data, rather than really keeping them
|
|
8
|
+
// secure), thus it is fine like this for now.
|
|
9
|
+
const{key}=getBuildInfo();const code=x=>x.charCodeAt(0);const dataBuffer=Uint8Array.from(data.slice(16),code);const ivBuffer=Uint8Array.from(data.slice(0,16),code);const keyBuffer=Uint8Array.from(atob(key),code);const cKey=await window.crypto.subtle.importKey("raw",keyBuffer,{name:"AES-CBC"},false,["decrypt"]);const buffer=await window.crypto.subtle.decrypt({iv:ivBuffer,name:"AES-CBC"},cKey,dataBuffer);const decoder=new TextDecoder;// eslint-disable-next-line no-eval
|
|
10
|
+
const res=eval(`(${decoder.decode(buffer)})`);// NOTE: This is important, to be able to return the injection
|
|
11
|
+
// synchronously once it is initialized.
|
|
12
|
+
inj=res;return res}else if(typeof window!=="undefined"&&window.REACT_UTILS_INJECTION){const res=window.REACT_UTILS_INJECTION;delete window.REACT_UTILS_INJECTION;return res}// Otherwise, a bunch of dependent stuff will easily fail in non-standard
|
|
11
13
|
// environments, where no client-side initialization is performed. Like tests,
|
|
12
14
|
// Docusaurus examples, etc.
|
|
13
|
-
|
|
15
|
+
return{}})();return inj}
|
|
14
16
|
//# sourceMappingURL=getInj.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getInj.js","names":["
|
|
1
|
+
{"version":3,"file":"getInj.js","names":["getBuildInfo","inj","getInj","metaElement","document","querySelector","remove","data","atob","content","key","code","x","charCodeAt","dataBuffer","Uint8Array","from","slice","ivBuffer","keyBuffer","cKey","window","crypto","subtle","importKey","name","buffer","decrypt","iv","decoder","TextDecoder","res","eval","decode","REACT_UTILS_INJECTION"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nlet inj: InjT | Promise<InjT> | undefined;\n\nexport default function getInj(): InjT | Promise<InjT> {\n inj ??= (async () => {\n const metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\n if (metaElement) {\n metaElement.remove();\n\n // NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be\n // preferred, but it is not supported by older environments yet.\n const data = atob(metaElement.content);\n\n // TODO: Our current handling of this encryption / decryption follows\n // a legacy approach, and can be enhanced by using Crypto features.\n // Though, this is not strictly intended to be secure (it is more\n // to obfurscate injected data, rather than really keeping them\n // secure), thus it is fine like this for now.\n const { key } = getBuildInfo();\n\n const code = (x: string) => x.charCodeAt(0);\n const dataBuffer = Uint8Array.from(data.slice(16), code);\n const ivBuffer = Uint8Array.from(data.slice(0, 16), code);\n const keyBuffer = Uint8Array.from(atob(key), code);\n\n const cKey = await window.crypto.subtle.importKey(\n 'raw',\n keyBuffer,\n { name: 'AES-CBC' },\n false,\n ['decrypt'],\n );\n\n const buffer = await window.crypto.subtle.decrypt({\n iv: ivBuffer,\n name: 'AES-CBC',\n }, cKey, dataBuffer);\n\n const decoder = new TextDecoder();\n\n // eslint-disable-next-line no-eval\n const res = eval(`(${decoder.decode(buffer)})`) as InjT;\n\n // NOTE: This is important, to be able to return the injection\n // synchronously once it is initialized.\n inj = res;\n\n return res;\n } else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n const res = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n return res;\n }\n\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n return {};\n })();\n\n return inj;\n}\n"],"mappings":"oiBAAA;AAEA,4BAISA,YAAY,8CAErB,GAAI,CAAAC,GAAqC,CAEzC,cAAe,SAAS,CAAAC,MAAMA,CAAA,CAAyB,CACrDD,GAAG,GAAK,CAAC,SAAY,CACnB,KAAM,CAAAE,WAAmC,CAAG,MAAO,CAAAC,QAAQ,GAAK,WAAW,CACvE,IAAI,CAAGA,QAAQ,CAACC,aAAa,CAAC,6BAA2B,CAAC,CAE9D,GAAIF,WAAW,CAAE,CACfA,WAAW,CAACG,MAAM,CAAC,CAAC,CAEpB;AACA;AACA,KAAM,CAAAC,IAAI,CAAGC,IAAI,CAACL,WAAW,CAACM,OAAO,CAAC,CAEtC;AACA;AACA;AACA;AACA;AACA,KAAM,CAAEC,GAAI,CAAC,CAAGV,YAAY,CAAC,CAAC,CAE9B,KAAM,CAAAW,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AC,EAAE,CAAC,CAEJ,MAAO,CAAA9B,GACT","ignoreList":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
/* global document
|
|
1
|
+
// Initialization of client-side code.
|
|
2
|
+
/* global document */import{createRoot,hydrateRoot}from"react-dom/client";import{HelmetProvider}from"@dr.pogodin/react-helmet";import{BrowserRouter}from"react-router";import{GlobalStateProvider}from"@dr.pogodin/react-global-state";import getInj from"./getInj.js";import{jsx as _jsx}from"react/jsx-runtime";/**
|
|
3
3
|
* Prepares and launches the app at client side.
|
|
4
4
|
* @param Application Root application component
|
|
5
5
|
* @param [options={}] Optional. Additional settings.
|
|
6
|
-
*/function
|
|
6
|
+
*/export async function launchClient(Application,options={}){const inj=await getInj();const container=document.getElementById("react-view");if(!container)throw Error("Failed to find container for React app");const scene=/*#__PURE__*/_jsx(GlobalStateProvider,{initialState:inj.ISTATE??options.initialState,children:/*#__PURE__*/_jsx(BrowserRouter,{children:/*#__PURE__*/_jsx(HelmetProvider,{children:/*#__PURE__*/_jsx(Application,{})})})});if(options.dontHydrate){const root=createRoot(container);root.render(scene)}else hydrateRoot(container,scene)}
|
|
7
7
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["
|
|
1
|
+
{"version":3,"file":"index.js","names":["createRoot","hydrateRoot","HelmetProvider","BrowserRouter","GlobalStateProvider","getInj","jsx","_jsx","launchClient","Application","options","inj","container","document","getElementById","Error","scene","initialState","ISTATE","children","dontHydrate","root","render"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport type { ComponentType } from 'react';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { BrowserRouter } from 'react-router';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: unknown;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport async function launchClient(\n Application: ComponentType,\n options: OptionsT = {},\n): Promise<void> {\n const inj = await getInj();\n\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={inj.ISTATE ?? options.initialState}>\n <BrowserRouter>\n <HelmetProvider>\n <Application />\n </HelmetProvider>\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":"AAAA;AACA,qBAGA,OAASA,UAAU,CAAEC,WAAW,KAAQ,kBAAkB,CAC1D,OAASC,cAAc,KAAQ,0BAA0B,CACzD,OAASC,aAAa,KAAQ,cAAc,CAE5C,OAASC,mBAAmB,KAAQ,gCAAgC,OAE7D,CAAAC,MAAM,mBAAiB,OAAAC,GAAA,IAAAC,IAAA,yBAO9B;AACA;AACA;AACA;AACA,GACA,MAAO,eAAe,CAAAC,YAAYA,CAChCC,WAA0B,CAC1BC,OAAiB,CAAG,CAAC,CAAC,CACP,CACf,KAAM,CAAAC,GAAG,CAAG,KAAM,CAAAN,MAAM,CAAC,CAAC,CAE1B,KAAM,CAAAO,SAAS,CAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC,CACvD,GAAI,CAACF,SAAS,CAAE,KAAM,CAAAG,KAAK,CAAC,wCAAwC,CAAC,CACrE,KAAM,CAAAC,KAAK,cACTT,IAAA,CAACH,mBAAmB,EAACa,YAAY,CAAEN,GAAG,CAACO,MAAM,EAAIR,OAAO,CAACO,YAAa,CAAAE,QAAA,cACpEZ,IAAA,CAACJ,aAAa,EAAAgB,QAAA,cACZZ,IAAA,CAACL,cAAc,EAAAiB,QAAA,cACbZ,IAAA,CAACE,WAAW,GAAE,CAAC,CACD,CAAC,CACJ,CAAC,CACG,CACtB,CAED,GAAIC,OAAO,CAACU,WAAW,CAAE,CACvB,KAAM,CAAAC,IAAI,CAAGrB,UAAU,CAACY,SAAS,CAAC,CAClCS,IAAI,CAACC,MAAM,CAACN,KAAK,CACnB,CAAC,IAAM,CAAAf,WAAW,CAACW,SAAS,CAAEI,KAAK,CACrC","ignoreList":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
2
|
* Initialization of client-side environment.
|
|
3
|
-
*//* global window */const buildInfo=
|
|
3
|
+
*//* global window */import{getBuildInfo}from"../shared/utils/isomorphy/buildInfo.js";const buildInfo=getBuildInfo();// TODO: Should be moved into buildInfo module?
|
|
4
4
|
if(process.env.NODE_ENV!=="production"){// eslint-disable-next-line no-console
|
|
5
5
|
console.warn("Dev mode: \"BUILD_INFO\" attached to the global \"window\"");// eslint-disable-next-line no-underscore-dangle
|
|
6
6
|
window.__DEV_BUILD_INFO__=BUILD_INFO}/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */const{useServiceWorker}=buildInfo;if(useServiceWorker){const{navigator}=window;if("serviceWorker"in navigator){window.addEventListener("load",()=>{void(async()=>{try{// Note: no matter the "publicPath", we want to serve the service worker
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.js","names":["
|
|
1
|
+
{"version":3,"file":"init.js","names":["getBuildInfo","buildInfo","process","env","NODE_ENV","console","warn","window","__DEV_BUILD_INFO__","BUILD_INFO","useServiceWorker","navigator","addEventListener","reg","serviceWorker","register","log","err"],"sources":["../../../src/client/init.ts"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global window */\n\nimport { type BuildInfoT, getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nconst buildInfo = getBuildInfo();\n\n// TODO: Should be moved into buildInfo module?\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n __DEV_BUILD_INFO__: BuildInfoT | undefined;\n }\n}\n\ndeclare const BUILD_INFO: BuildInfoT | undefined;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.warn('Dev mode: \"BUILD_INFO\" attached to the global \"window\"');\n\n // eslint-disable-next-line no-underscore-dangle\n window.__DEV_BUILD_INFO__ = BUILD_INFO;\n}\n\n/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */\nconst { useServiceWorker } = buildInfo;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', () => {\n void (async () => {\n try {\n // Note: no matter the \"publicPath\", we want to serve the service worker\n // from the web app root, to allow it control any and all pages of the\n // web app (otherwise, it will be restricted to the scope of its path).\n // The server takes it into account.\n const reg = await navigator\n .serviceWorker.register('/__service-worker.js');\n // eslint-disable-next-line no-console\n console.log('SW registered:', reg);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.log('SW registration failed:', err);\n }\n })();\n });\n }\n}\n"],"mappings":"AAAA;AACA;AACA,GAEA,0BAE0BA,YAAY,8CAEtC,KAAM,CAAAC,SAAS,CAAGD,YAAY,CAAC,CAAC,CAEhC;AAUA,GAAIE,OAAO,CAACC,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACzC;AACAC,OAAO,CAACC,IAAI,CAAC,4DAAwD,CAAC,CAEtE;AACAC,MAAM,CAACC,kBAAkB,CAAGC,UAC9B,CAEA,yEACA,KAAM,CAAEC,gBAAiB,CAAC,CAAGT,SAAS,CACtC,GAAIS,gBAAgB,CAAE,CACpB,KAAM,CAAEC,SAAU,CAAC,CAAGJ,MAAM,CAC5B,GAAI,eAAe,EAAI,CAAAI,SAAS,CAAE,CAChCJ,MAAM,CAACK,gBAAgB,CAAC,MAAM,CAAE,IAAM,CACpC,IAAK,CAAC,SAAY,CAChB,GAAI,CACF;AACA;AACA;AACA;AACA,KAAM,CAAAC,GAAG,CAAG,KAAM,CAAAF,SAAS,CACxBG,aAAa,CAACC,QAAQ,CAAC,sBAAsB,CAAC,CACjD;AACAV,OAAO,CAACW,GAAG,CAAC,gBAAgB,CAAEH,GAAG,CACnC,CAAE,MAAOI,GAAG,CAAE,CACZ;AACAZ,OAAO,CAACW,GAAG,CAAC,yBAAyB,CAAEC,GAAG,CAC5C,CACF,CAAC,EAAE,CACL,CAAC,CACH,CACF","ignoreList":[]}
|
|
@@ -1,10 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
// It is a safeguard against multiple instances / versions of the library
|
|
2
2
|
// being loaded into environment by mistake (e.g. because of different
|
|
3
3
|
// packages pinning down different exact versions of the lib, thus preventing
|
|
4
4
|
// a proper dedupe and using a single common library version).
|
|
5
|
-
if(global.REACT_UTILS_LIBRARY_LOADED){throw Error("React utils library is already loaded")}else global.REACT_UTILS_LIBRARY_LOADED=true
|
|
6
|
-
// we'll re-implement requireWeak() to accept import.meta.url directly, and
|
|
7
|
-
// this workaround won't be needed.
|
|
8
|
-
let dirname=require("url").pathToFileURL(__filename).toString();dirname=dirname.slice(5,dirname.lastIndexOf("/"));const server=exports.server=_utils.webpack.requireWeak("./server",dirname);const client=exports.client=server?undefined// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
9
|
-
:require("./client").default;
|
|
5
|
+
if(global.REACT_UTILS_LIBRARY_LOADED){throw Error("React utils library is already loaded")}else global.REACT_UTILS_LIBRARY_LOADED=true;export{getGlobalState,GlobalStateProvider,newAsyncDataEnvelope,useAsyncCollection,useAsyncData,useGlobalState,withGlobalStateType}from"@dr.pogodin/react-global-state";export*from"./shared/components/index.js";export{assertEmptyObject,Barrier,Cached,Emitter,getConfig,isomorphy,getSsrContext,Semaphore,splitComponent,themed,ThemeProvider,time,webpack,withRetries}from"./shared/utils/index.js";
|
|
10
6
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["
|
|
1
|
+
{"version":3,"file":"index.js","names":["global","REACT_UTILS_LIBRARY_LOADED","Error","getGlobalState","GlobalStateProvider","newAsyncDataEnvelope","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType","assertEmptyObject","Barrier","Cached","Emitter","getConfig","isomorphy","getSsrContext","Semaphore","splitComponent","themed","ThemeProvider","time","webpack","withRetries"],"sources":["../../src/index.ts"],"sourcesContent":["// It is a safeguard against multiple instances / versions of the library\n// being loaded into environment by mistake (e.g. because of different\n// packages pinning down different exact versions of the lib, thus preventing\n// a proper dedupe and using a single common library version).\nif (global.REACT_UTILS_LIBRARY_LOADED) {\n throw Error('React utils library is already loaded');\n} else global.REACT_UTILS_LIBRARY_LOADED = true;\n\nexport {\n type AsyncCollectionT,\n type AsyncCollectionLoaderT,\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type ForceT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateResT,\n type ValueOrInitializerT,\n getGlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n withGlobalStateType,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\n\nexport {\n type BeforeRenderResT,\n type BeforeRenderT,\n type ConfigT,\n type ServerSsrContext,\n type ServerT,\n} from './server';\n\nexport {\n assertEmptyObject,\n Barrier,\n Cached,\n Emitter,\n getConfig,\n isomorphy,\n getSsrContext,\n type Listener,\n type ObjectKey,\n Semaphore,\n splitComponent,\n type Theme,\n themed,\n ThemeProvider,\n time,\n webpack,\n withRetries,\n} from 'utils';\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA,GAAIA,MAAM,CAACC,0BAA0B,CAAE,CACrC,KAAM,CAAAC,KAAK,CAAC,uCAAuC,CACrD,CAAC,IAAM,CAAAF,MAAM,CAACC,0BAA0B,CAAG,IAAI,CAE/C,OAUEE,cAAc,CACdC,mBAAmB,CACnBC,oBAAoB,CACpBC,kBAAkB,CAClBC,YAAY,CACZC,cAAc,CACdC,mBAAmB,KACd,gCAAgC,kDAarCC,iBAAiB,CACjBC,OAAO,CACPC,MAAM,CACNC,OAAO,CACPC,SAAS,CACTC,SAAS,CACTC,aAAa,CAGbC,SAAS,CACTC,cAAc,CAEdC,MAAM,CACNC,aAAa,CACbC,IAAI,CACJC,OAAO,CACPC,WAAW","ignoreList":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
2
|
* Implements the static cache.
|
|
3
|
-
*/class Cache{items={};size=0;constructor(maxSize){this.maxSize=maxSize}/**
|
|
3
|
+
*/export default class Cache{items={};size=0;constructor(maxSize){this.maxSize=maxSize}/**
|
|
4
4
|
* Cache lookup.
|
|
5
5
|
* @param key Item key to look for.
|
|
6
6
|
* @param [maxage=Number.MAX_VALUE] Optional. The maximum age of
|
|
@@ -12,5 +12,5 @@
|
|
|
12
12
|
* @param data Item to add.
|
|
13
13
|
* @param key Key to store the item at.
|
|
14
14
|
* @param size Byte size of the item.
|
|
15
|
-
*/add(data,key,size){const cached=this.items[key];if(cached)this.size-=cached.size;this.items[key]={data,size,timestamp:Date.now()};this.size+=size;if(this.size>this.maxSize){const entries=Object.entries(this.items);entries.sort((a,b)=>a[1].timestamp-b[1].timestamp);for(const entry of entries){const[itemKey,item]=entry;delete this.items[itemKey];this.size-=item.size;if(this.size<this.maxSize/2)break}}}}
|
|
15
|
+
*/add(data,key,size){const cached=this.items[key];if(cached)this.size-=cached.size;this.items[key]={data,size,timestamp:Date.now()};this.size+=size;if(this.size>this.maxSize){const entries=Object.entries(this.items);entries.sort((a,b)=>a[1].timestamp-b[1].timestamp);for(const entry of entries){const[itemKey,item]=entry;delete this.items[itemKey];this.size-=item.size;if(this.size<this.maxSize/2)break}}}}
|
|
16
16
|
//# sourceMappingURL=Cache.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Cache.js","names":["Cache","items","size","constructor","maxSize","get","key","maxage","Number","MAX_VALUE","item","Date","now","timestamp","data","add","cached","entries","Object","sort","a","b","entry","itemKey"
|
|
1
|
+
{"version":3,"file":"Cache.js","names":["Cache","items","size","constructor","maxSize","get","key","maxage","Number","MAX_VALUE","item","Date","now","timestamp","data","add","cached","entries","Object","sort","a","b","entry","itemKey"],"sources":["../../../src/server/Cache.ts"],"sourcesContent":["type CachedItemT<DatumT> = {\n data: DatumT;\n size: number;\n timestamp: number;\n};\n\n/**\n * Implements the static cache.\n */\nexport default class Cache<DatumT> {\n private items: Record<string, CachedItemT<DatumT>> = {};\n\n private size = 0;\n\n constructor(private maxSize: number) { }\n\n /**\n * Cache lookup.\n * @param key Item key to look for.\n * @param [maxage=Number.MAX_VALUE] Optional. The maximum age of\n * cached item to serve. Default to infinite.\n * @returns Cached item, or null if the item is absent in cache,\n * or stale.\n */\n get({\n key,\n maxage = Number.MAX_VALUE,\n }: {\n key: string;\n maxage?: number;\n }): DatumT | null {\n const item = this.items[key];\n return item && Date.now() - item.timestamp < maxage ? item.data : null;\n }\n\n /**\n * Adds item to cache.\n * @param data Item to add.\n * @param key Key to store the item at.\n * @param size Byte size of the item.\n */\n add(data: DatumT, key: string, size: number): void {\n const cached = this.items[key];\n if (cached) this.size -= cached.size;\n\n this.items[key] = { data, size, timestamp: Date.now() };\n this.size += size;\n\n if (this.size > this.maxSize) {\n const entries = Object.entries(this.items);\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp);\n\n for (const entry of entries) {\n const [itemKey, item] = entry;\n delete this.items[itemKey];\n this.size -= item.size;\n if (this.size < this.maxSize / 2) break;\n }\n }\n }\n}\n"],"mappings":"AAMA;AACA;AACA,GACA,cAAe,MAAM,CAAAA,KAAc,CACzBC,KAAK,CAAwC,CAAC,CAAC,CAE/CC,IAAI,CAAG,CAAC,CAEhBC,WAAWA,CAASC,OAAe,CAAE,MAAjBA,OAAe,CAAfA,OAAmB,CAEvC;AACF;AACA;AACA;AACA;AACA;AACA;AACA,KACEC,GAAGA,CAAC,CACFC,GAAG,CACHC,MAAM,CAAGC,MAAM,CAACC,SAIlB,CAAC,CAAiB,CAChB,KAAM,CAAAC,IAAI,CAAG,IAAI,CAACT,KAAK,CAACK,GAAG,CAAC,C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-line import/no-unassigned-import
|
|
2
|
+
import"source-map-support/register.js";import http from"node:http";import https from"node:https";import{cloneDeep,defaults}from"lodash-es";// Polyfill required by ReactJS.
|
|
3
3
|
// TODO: Double-check, if it is still required by React v19?
|
|
4
4
|
// eslint-disable-next-line import/no-unassigned-import
|
|
5
|
-
|
|
5
|
+
import"raf/polyfill.js";import serverFactory,{getDefaultCspSettings}from"./server.js";import{SCRIPT_LOCATIONS,newDefaultLogger}from"./renderer.js";export*from"./utils/index.js";export{getDefaultCspSettings,SCRIPT_LOCATIONS};/**
|
|
6
6
|
* Normalizes a port into a number, string, or false.
|
|
7
7
|
* TODO: Drop this function?
|
|
8
8
|
* @param value Port name or number.
|
|
9
|
-
* @return Port number (Number), name (String)
|
|
10
|
-
*/function normalizePort(value){const port=(
|
|
9
|
+
* @return Port number (Number), name (String).
|
|
10
|
+
*/function normalizePort(value){const port=typeof value==="string"?parseInt(value):value;if(Number.isFinite(port))return port;/* port number */return value;/* named pipe */}/**
|
|
11
11
|
* Creates and launches web-server for ReactJS application. Allows zero
|
|
12
12
|
* or detailed configuration, supports server-side rendering,
|
|
13
13
|
* and development tools, including Hot Module Reloading (HMR).
|
|
@@ -124,8 +124,8 @@
|
|
|
124
124
|
* @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,
|
|
125
125
|
* defaults to 1 second.
|
|
126
126
|
* @return Resolves to an object with created Express and HTTP servers.
|
|
127
|
-
*/async function launchServer(webpackConfig,options={}){/* Options normalization. */const ops=(
|
|
128
|
-
ops.port=normalizePort(ops.port||process.env.PORT||3000);(
|
|
127
|
+
*/export async function launchServer(webpackConfig,options={}){/* Options normalization. */const ops=cloneDeep(options);// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
|
128
|
+
ops.port=normalizePort(ops.port||process.env.PORT||3000);defaults(ops,{httpsRedirect:true});// TODO: Need a separate type for normalized options, which guarantees
|
|
129
129
|
// the logger is set!
|
|
130
|
-
ops.logger??=
|
|
130
|
+
ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});/* Creates servers, resolves and sets the port. */const expressServer=await serverFactory(webpackConfig,ops);let httpServer;if(ops.https){httpServer=https.createServer({cert:ops.https.cert,key:ops.https.key},expressServer)}else httpServer=http.createServer(expressServer);/* Sets error handler for HTTP(S) server. */httpServer.on("error",error=>{if(error.syscall!=="listen")throw error;const bind=typeof ops.port==="string"?`Pipe ${ops.port}`:`Port ${ops.port}`;/* Human-readable message for some specific listen errors. */switch(error.code){case"EACCES":ops.logger.error(`${bind} requires elevated privileges`);return process.exit(1);case"EADDRINUSE":ops.logger.error(`${bind} is already in use`);return process.exit(1);case undefined:default:throw error}});/* Listening event handler for HTTP(S) server. */httpServer.on("listening",()=>{const addr=httpServer.address();const bind=typeof addr==="string"?`pipe ${addr}`:`port ${addr.port}`;ops.logger.info(`Server listening on ${bind} in ${process.env.NODE_ENV} mode`)});httpServer.listen(ops.port);return{expressServer,httpServer}}
|
|
131
131
|
//# sourceMappingURL=index.js.map
|