@dr.pogodin/react-utils 1.46.2 → 1.47.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/babel.config.js +1 -0
  2. package/babel.libweb.config.js +16 -0
  3. package/bin/build.js +16 -10
  4. package/bin/setup.js +11 -8
  5. package/build/development/client/getInj.js.map +1 -1
  6. package/build/development/client/index.js.map +1 -1
  7. package/build/development/client/init.js.map +1 -1
  8. package/build/development/index.js +7 -1
  9. package/build/development/index.js.map +1 -1
  10. package/build/development/server/Cache.js.map +1 -1
  11. package/build/development/server/index.js +13 -8
  12. package/build/development/server/index.js.map +1 -1
  13. package/build/development/server/renderer.js +15 -8
  14. package/build/development/server/renderer.js.map +1 -1
  15. package/build/development/server/server.js +7 -5
  16. package/build/development/server/server.js.map +1 -1
  17. package/build/development/shared/components/Button/index.js +6 -6
  18. package/build/development/shared/components/Button/index.js.map +1 -1
  19. package/build/development/shared/components/Checkbox/index.js +8 -8
  20. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  21. package/build/development/shared/components/GenericLink/index.js +5 -1
  22. package/build/development/shared/components/GenericLink/index.js.map +1 -1
  23. package/build/development/shared/components/Input/index.js +10 -9
  24. package/build/development/shared/components/Input/index.js.map +1 -1
  25. package/build/development/shared/components/Link.js.map +1 -1
  26. package/build/development/shared/components/Modal/index.js +8 -6
  27. package/build/development/shared/components/Modal/index.js.map +1 -1
  28. package/build/development/shared/components/NavLink.js.map +1 -1
  29. package/build/development/shared/components/PageLayout/index.js +6 -6
  30. package/build/development/shared/components/PageLayout/index.js.map +1 -1
  31. package/build/development/shared/components/TextArea/index.js +13 -9
  32. package/build/development/shared/components/TextArea/index.js.map +1 -1
  33. package/build/development/shared/components/Throbber/index.js +6 -6
  34. package/build/development/shared/components/Throbber/index.js.map +1 -1
  35. package/build/development/shared/components/WithTooltip/Tooltip.js +1 -0
  36. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  37. package/build/development/shared/components/WithTooltip/index.js +7 -7
  38. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  39. package/build/development/shared/components/YouTubeVideo/index.js +9 -9
  40. package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
  41. package/build/development/shared/components/index.js.map +1 -1
  42. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  43. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  44. package/build/development/shared/components/selectors/CustomDropdown/index.js +11 -11
  45. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  46. package/build/development/shared/components/selectors/NativeDropdown/index.js +12 -12
  47. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  48. package/build/development/shared/components/selectors/Switch/index.js +7 -7
  49. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  50. package/build/development/shared/utils/config.js.map +1 -1
  51. package/build/development/shared/utils/globalState.js.map +1 -1
  52. package/build/development/shared/utils/index.js.map +1 -1
  53. package/build/development/shared/utils/jest/E2eSsrEnv.js +14 -10
  54. package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  55. package/build/development/shared/utils/splitComponent.js +1 -0
  56. package/build/development/shared/utils/splitComponent.js.map +1 -1
  57. package/build/development/shared/utils/time.js.map +1 -1
  58. package/build/production/client/getInj.js.map +1 -1
  59. package/build/production/client/index.js.map +1 -1
  60. package/build/production/client/init.js.map +1 -1
  61. package/build/production/index.js +4 -1
  62. package/build/production/index.js.map +1 -1
  63. package/build/production/server/Cache.js.map +1 -1
  64. package/build/production/server/index.js +5 -5
  65. package/build/production/server/index.js.map +1 -1
  66. package/build/production/server/renderer.js +7 -7
  67. package/build/production/server/renderer.js.map +1 -1
  68. package/build/production/server/server.js +4 -4
  69. package/build/production/server/server.js.map +1 -1
  70. package/build/production/shared/components/Button/index.js +1 -1
  71. package/build/production/shared/components/Button/index.js.map +1 -1
  72. package/build/production/shared/components/Checkbox/index.js +1 -1
  73. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  74. package/build/production/shared/components/GenericLink/index.js +2 -2
  75. package/build/production/shared/components/GenericLink/index.js.map +1 -1
  76. package/build/production/shared/components/Input/index.js +1 -1
  77. package/build/production/shared/components/Input/index.js.map +1 -1
  78. package/build/production/shared/components/Link.js.map +1 -1
  79. package/build/production/shared/components/Modal/index.js +1 -1
  80. package/build/production/shared/components/Modal/index.js.map +1 -1
  81. package/build/production/shared/components/NavLink.js.map +1 -1
  82. package/build/production/shared/components/PageLayout/index.js +1 -1
  83. package/build/production/shared/components/PageLayout/index.js.map +1 -1
  84. package/build/production/shared/components/TextArea/index.js +1 -1
  85. package/build/production/shared/components/TextArea/index.js.map +1 -1
  86. package/build/production/shared/components/Throbber/index.js +1 -1
  87. package/build/production/shared/components/Throbber/index.js.map +1 -1
  88. package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
  89. package/build/production/shared/components/WithTooltip/index.js +1 -1
  90. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  91. package/build/production/shared/components/YouTubeVideo/index.js +1 -1
  92. package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
  93. package/build/production/shared/components/index.js.map +1 -1
  94. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
  95. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  96. package/build/production/shared/components/selectors/CustomDropdown/index.js +1 -1
  97. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  98. package/build/production/shared/components/selectors/NativeDropdown/index.js +1 -1
  99. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  100. package/build/production/shared/components/selectors/Switch/index.js +1 -1
  101. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  102. package/build/production/shared/utils/config.js.map +1 -1
  103. package/build/production/shared/utils/globalState.js.map +1 -1
  104. package/build/production/shared/utils/index.js.map +1 -1
  105. package/build/production/shared/utils/jest/E2eSsrEnv.js +8 -7
  106. package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
  107. package/build/production/shared/utils/splitComponent.js.map +1 -1
  108. package/build/production/shared/utils/time.js.map +1 -1
  109. package/build/web/client/getInj.js +54 -0
  110. package/build/web/client/getInj.js.map +1 -0
  111. package/build/web/client/index.js +38 -0
  112. package/build/web/client/index.js.map +1 -0
  113. package/build/web/client/init.js +49 -0
  114. package/build/web/client/init.js.map +1 -0
  115. package/build/web/index.js +25 -0
  116. package/build/web/index.js.map +1 -0
  117. package/build/web/server/Cache.js +54 -0
  118. package/build/web/server/Cache.js.map +1 -0
  119. package/build/web/server/index.js +211 -0
  120. package/build/web/server/index.js.map +1 -0
  121. package/build/web/server/renderer.js +516 -0
  122. package/build/web/server/renderer.js.map +1 -0
  123. package/build/web/server/server.js +231 -0
  124. package/build/web/server/server.js.map +1 -0
  125. package/build/web/server/utils/errors.js +103 -0
  126. package/build/web/server/utils/errors.js.map +1 -0
  127. package/build/web/server/utils/index.js +4 -0
  128. package/build/web/server/utils/index.js.map +1 -0
  129. package/build/web/shared/components/Button/index.js +90 -0
  130. package/build/web/shared/components/Button/index.js.map +1 -0
  131. package/build/web/shared/components/Button/style.scss +54 -0
  132. package/build/web/shared/components/Checkbox/index.js +35 -0
  133. package/build/web/shared/components/Checkbox/index.js.map +1 -0
  134. package/build/web/shared/components/Checkbox/theme.scss +63 -0
  135. package/build/web/shared/components/GenericLink/index.js +107 -0
  136. package/build/web/shared/components/GenericLink/index.js.map +1 -0
  137. package/build/web/shared/components/GenericLink/style.scss +3 -0
  138. package/build/web/shared/components/Input/index.js +71 -0
  139. package/build/web/shared/components/Input/index.js.map +1 -0
  140. package/build/web/shared/components/Input/theme.scss +52 -0
  141. package/build/web/shared/components/Link.js +20 -0
  142. package/build/web/shared/components/Link.js.map +1 -0
  143. package/build/web/shared/components/Modal/base-theme.scss +38 -0
  144. package/build/web/shared/components/Modal/index.js +128 -0
  145. package/build/web/shared/components/Modal/index.js.map +1 -0
  146. package/build/web/shared/components/Modal/styles.scss +3 -0
  147. package/build/web/shared/components/NavLink.js +13 -0
  148. package/build/web/shared/components/NavLink.js.map +1 -0
  149. package/build/web/shared/components/PageLayout/base-theme.scss +30 -0
  150. package/build/web/shared/components/PageLayout/index.js +38 -0
  151. package/build/web/shared/components/PageLayout/index.js.map +1 -0
  152. package/build/web/shared/components/TextArea/index.js +106 -0
  153. package/build/web/shared/components/TextArea/index.js.map +1 -0
  154. package/build/web/shared/components/TextArea/style.scss +68 -0
  155. package/build/web/shared/components/Throbber/index.js +26 -0
  156. package/build/web/shared/components/Throbber/index.js.map +1 -0
  157. package/build/web/shared/components/Throbber/theme.scss +26 -0
  158. package/build/web/shared/components/WithTooltip/Tooltip.js +226 -0
  159. package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -0
  160. package/build/web/shared/components/WithTooltip/default-theme.scss +36 -0
  161. package/build/web/shared/components/WithTooltip/index.js +117 -0
  162. package/build/web/shared/components/WithTooltip/index.js.map +1 -0
  163. package/build/web/shared/components/YouTubeVideo/base.scss +15 -0
  164. package/build/web/shared/components/YouTubeVideo/index.js +56 -0
  165. package/build/web/shared/components/YouTubeVideo/index.js.map +1 -0
  166. package/build/web/shared/components/YouTubeVideo/throbber.scss +11 -0
  167. package/build/web/shared/components/index.js +18 -0
  168. package/build/web/shared/components/index.js.map +1 -0
  169. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +79 -0
  170. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -0
  171. package/build/web/shared/components/selectors/CustomDropdown/Options/style.scss +6 -0
  172. package/build/web/shared/components/selectors/CustomDropdown/index.js +120 -0
  173. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -0
  174. package/build/web/shared/components/selectors/CustomDropdown/theme.scss +118 -0
  175. package/build/web/shared/components/selectors/NativeDropdown/index.js +82 -0
  176. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -0
  177. package/build/web/shared/components/selectors/NativeDropdown/theme.scss +81 -0
  178. package/build/web/shared/components/selectors/Switch/index.js +49 -0
  179. package/build/web/shared/components/selectors/Switch/index.js.map +1 -0
  180. package/build/web/shared/components/selectors/Switch/theme.scss +39 -0
  181. package/build/web/shared/components/selectors/common.js +12 -0
  182. package/build/web/shared/components/selectors/common.js.map +1 -0
  183. package/build/web/shared/components/selectors/index.js +4 -0
  184. package/build/web/shared/components/selectors/index.js.map +1 -0
  185. package/build/web/shared/utils/config.js +21 -0
  186. package/build/web/shared/utils/config.js.map +1 -0
  187. package/build/web/shared/utils/globalState.js +15 -0
  188. package/build/web/shared/utils/globalState.js.map +1 -0
  189. package/build/web/shared/utils/index.js +13 -0
  190. package/build/web/shared/utils/index.js.map +1 -0
  191. package/build/web/shared/utils/isomorphy/buildInfo.js +44 -0
  192. package/build/web/shared/utils/isomorphy/buildInfo.js.map +1 -0
  193. package/build/web/shared/utils/isomorphy/environment-check.js +17 -0
  194. package/build/web/shared/utils/isomorphy/environment-check.js.map +1 -0
  195. package/build/web/shared/utils/isomorphy/index.js +36 -0
  196. package/build/web/shared/utils/isomorphy/index.js.map +1 -0
  197. package/build/web/shared/utils/jest/E2eSsrEnv.js +230 -0
  198. package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -0
  199. package/build/web/shared/utils/jest/global.js +4 -0
  200. package/build/web/shared/utils/jest/global.js.map +1 -0
  201. package/build/web/shared/utils/jest/index.js +165 -0
  202. package/build/web/shared/utils/jest/index.js.map +1 -0
  203. package/build/web/shared/utils/splitComponent.js +221 -0
  204. package/build/web/shared/utils/splitComponent.js.map +1 -0
  205. package/build/web/shared/utils/time.js +85 -0
  206. package/build/web/shared/utils/time.js.map +1 -0
  207. package/build/web/shared/utils/webpack.js +61 -0
  208. package/build/web/shared/utils/webpack.js.map +1 -0
  209. package/build/web/styles/_global/reset.css +52 -0
  210. package/build/web/styles/_mixins/fonts.scss +40 -0
  211. package/build/web/styles/_mixins/media.scss +150 -0
  212. package/build/web/styles/_mixins/typography.scss +83 -0
  213. package/build/web/styles/global.scss +11 -0
  214. package/build/web/styles/mixins.scss +6 -0
  215. package/config/babel/node-ssr.js +5 -2
  216. package/config/webpack/app-base.js +10 -7
  217. package/config/webpack/app-development.js +3 -2
  218. package/package.json +16 -27
  219. package/src/index.ts +7 -1
  220. package/src/server/index.ts +6 -8
  221. package/src/server/renderer.tsx +7 -9
  222. package/src/server/server.ts +3 -5
  223. package/src/shared/components/Modal/base-theme.scss +1 -1
  224. package/src/shared/components/PageLayout/base-theme.scss +1 -1
  225. package/src/shared/utils/jest/E2eSsrEnv.ts +8 -1
  226. package/build/development/__chunk_groups__.json +0 -6
  227. package/build/development/style.css +0 -909
  228. package/build/development/web.bundle.js +0 -752
  229. package/build/production/__chunk_groups__.json +0 -6
  230. package/build/production/style.css +0 -2
  231. package/build/production/style.css.map +0 -1
  232. package/build/production/web.bundle.js +0 -3
  233. package/build/production/web.bundle.js.LICENSE.txt +0 -9
  234. package/build/production/web.bundle.js.map +0 -1
  235. package/dev-styles.js +0 -1
  236. package/null.js +0 -1
  237. package/prod-styles.js +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"splitComponent.js","names":["_react","require","_jsUtils","_globalState","_isomorphy","_jsxRuntime","clientChunkGroups","IS_CLIENT_SIDE","default","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","resolved","Component","Wrapper","children","ref","rest","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","jsx","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\n// Note: At the client side we can get chunk groups immediately when loading\n// the module; at the server-side we only can get them within React render flow.\n// Thus, we set and use the following variable at the client-side, and then when\n// needed on the server side, we'll fetch it differently.\nlet clientChunkGroups: ChunkGroupsT;\n\nif (IS_CLIENT_SIDE) {\n // TODO: Rewrite to avoid these overrides of ESLint rules.\n /* eslint-disable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n clientChunkGroups = require('client/getInj').default().CHUNK_GROUPS ?? {};\n /* eslint-enable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) assertChunkName(chunkName, clientChunkGroups);\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":"qLAEA,IAAAA,MAAA,CAAAC,OAAA,UAUA,IAAAC,QAAA,CAAAD,OAAA,yBAEA,IAAAE,YAAA,CAAAF,OAAA,kBAEA,IAAAG,UAAA,CAAAH,OAAA,gBAIqB,IAAAI,WAAA,CAAAJ,OAAA,sBApBrB,qBAsBA;AACA;AACA;AACA;AACA,GAAI,CAAAK,iBAA+B,CAEnC,GAAIC,yBAAc,CAAE,CAClB;AACA;AACF;AACA;AACA,iDACED,iBAAiB,CAAGL,OAAO,sBAAgB,CAAC,CAACO,OAAO,CAAC,CAAC,CAACC,YAAY,EAAI,CAAC,CAAC,CACzE;AACF;AACA;AACA,iDACA,CAEA,KAAM,CAAAC,SAAiC,CAAG,CAAC,CAAC,CAE5C,QAAS,CAAAC,aAAaA,CAAA,CAAG,CACvB,MAAO,GAAAC,uBAAY,EAAC,CAAC,CAACC,UACxB,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,CAAAC,cAAcA,CACrBC,IAAY,CACZC,YAAyB,CACzBC,QAAiB,CACU,CAC3B,GAAI,CAAAC,GAA8B,CAClC,KAAM,CAAAC,IAAI,CAAG,GAAGR,aAAa,CAAC,CAAC,IAAII,IAAI,EAAE,CACzC,KAAM,CAAAK,QAAQ,CAAG,GAAGC,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version":3,"file":"splitComponent.js","names":["_react","require","_jsUtils","_globalState","_isomorphy","_jsxRuntime","clientChunkGroups","IS_CLIENT_SIDE","default","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","resolved","Component","Wrapper","children","ref","rest","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","_jsx","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\n// Note: At the client side we can get chunk groups immediately when loading\n// the module; at the server-side we only can get them within React render flow.\n// Thus, we set and use the following variable at the client-side, and then when\n// needed on the server side, we'll fetch it differently.\nlet clientChunkGroups: ChunkGroupsT;\n\nif (IS_CLIENT_SIDE) {\n // TODO: Rewrite to avoid these overrides of ESLint rules.\n /* eslint-disable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n clientChunkGroups = require('client/getInj').default().CHUNK_GROUPS ?? {};\n /* eslint-enable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) assertChunkName(chunkName, clientChunkGroups);\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":"qLAEA,IAAAA,MAAA,CAAAC,OAAA,UAUA,IAAAC,QAAA,CAAAD,OAAA,yBAEA,IAAAE,YAAA,CAAAF,OAAA,kBAEA,IAAAG,UAAA,CAAAH,OAAA,gBASA,IAAAI,WAAA,CAAAJ,OAAA,sBAzBA,qBAsBA;AACA;AACA;AACA;AACA,GAAI,CAAAK,iBAA+B,CAEnC,GAAIC,y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E,EAAE,CAAC,CAEN,mBACE,GAAAqE,eAAA,EAACV,SACC;AAAA,KACKI,IAAI,CACTD,GAAG,CAAEA,GAAI,CAAAD,QAAA,CAERA,QAAQ,CACA,CAEf,CAAC,CAED,MAAO,CAAE3D,OAAO,CAAE0D,OAAQ,CAC5B,CAAC,CAAC,CAEF,KAAM,CAAAU,SAAmD,CAAGA,CAAC,CAC3DT,QAAQ,CACR,GAAGE,IACY,CAAC,gBAChB,GAAAM,eAAA,EAACE,eAAQ,EAACC,QAAQ,CAAEjB,WAAY,CAAAM,QAAA,cAC9B,GAAAQ,eAAA,EAACb,aACC;AAAA,KACIO,IAAI,CAAAF,QAAA,CAEPA,QAAQ,CACI,CAAC,CACR,CACX,CAED,MAAO,CAAAS,SACT","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"time.js","names":["_cookie","require","_react","_dayjs","_interopRequireDefault","_jsUtils","_reactGlobalState","_globalState","useCurrent","autorefresh","globalStatePath","precision","SEC_MS","now","setter","useGlobalState","Date","useEffect","timerId","update","old","neu","Math","abs","setTimeout","clearTimeout","useTimezoneOffset","cookieName","ssrContext","getSsrContext","offset","setOffset","value","req","cookies","parseInt","date","getTimezoneOffset","document","cookie","serialize","toString","path","time","DAY_MS","HOUR_MS","MIN_MS","YEAR_MS","timer","_default","exports","default","Object","assign","dayjs"],"sources":["../../../../src/shared/utils/time.ts"],"sourcesContent":["import { serialize } from 'cookie';\nimport { useEffect } from 'react';\nimport dayjs from 'dayjs';\n\nimport {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n timer,\n} from '@dr.pogodin/js-utils';\n\nimport { type ForceT, useGlobalState } from '@dr.pogodin/react-global-state';\n\nimport { getSsrContext } from './globalState';\n\n/**\n * This react hook wraps Date.now() function in a SSR friendly way,\n * ensuring that all calls to useCurrent() within the same render return\n * exactly the same time (which is retrieved from Date.now() first, and\n * then stored in the global state to be reused in all other calls), which\n * is also passed and used in the first client side render, and then updated\n * with a finite precision to avoid infinite re-rendering loops.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useCurrent({\n autorefresh = false,\n globalStatePath = 'currentTime',\n precision = 5 * SEC_MS,\n} = {}): number {\n const [now, setter] = useGlobalState<ForceT, number>(\n globalStatePath,\n Date.now,\n );\n useEffect(() => {\n let timerId: NodeJS.Timeout | undefined;\n const update = (): void => {\n setter((old) => {\n const neu = Date.now();\n return Math.abs(neu - old) > precision ? neu : old;\n });\n if (autorefresh) timerId = setTimeout(update, precision);\n };\n update();\n return (): void => {\n if (timerId) clearTimeout(timerId);\n };\n }, [autorefresh, precision, setter]);\n return now;\n}\n\n/**\n * Wraps the standard Date.getTimezoneOffset() method in a SSR-friendly way.\n * This hook retrieves the offset value at the client side and uses a cookie\n * to pass it to the server in subsequent requests from that user. At the server\n * side the value from cookie is used in renders and passed back to the client\n * via the global state. Prior to the value being known (in the very first\n * request from the user, when the cookie is still missing), zero value is used\n * as the default value.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useTimezoneOffset({\n cookieName = 'timezoneOffset',\n globalStatePath = 'timezoneOffset',\n} = {}): number {\n const ssrContext = getSsrContext(false);\n const [offset, setOffset] = useGlobalState<ForceT, number>(\n globalStatePath,\n () => {\n const value = cookieName\n && ssrContext?.req.cookies[cookieName] as string;\n return value ? parseInt(value) : 0;\n },\n );\n useEffect(() => {\n const date = new Date();\n const value = date.getTimezoneOffset();\n setOffset(value);\n if (cookieName) {\n document.cookie = serialize(cookieName, value.toString(), { path: '/' });\n }\n }, [cookieName, setOffset]);\n return offset;\n}\n\nconst time = {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n now: Date.now,\n timer,\n useCurrent,\n useTimezoneOffset,\n};\n\nexport default Object.assign(dayjs, time);\n"],"mappings":"0PAAA,IAAAA,OAAA,CAAAC,OAAA,WACA,IAAAC,MAAA,CAAAD,OA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U,CAAG,GAAAC,0BAAa,EAAC,KAAK,CAAC,CACvC,KAAM,CAACC,MAAM,CAAEC,SAAS,CAAC,CAAG,GAAAhB,gCAAc,EACxCL,eAAe,CACf,IAAM,CACJ,KAAM,CAAAsB,KAAK,CAAGL,UAAU,EACnBC,UAAU,EAAEK,GAAG,CAACC,OAAO,CAACP,UAAU,CAAW,CAClD,MAAO,CAAAK,KAAK,CAAGG,QAAQ,CAACH,KAAK,CAAC,CAAG,CACnC,CACF,CAAC,CACD,GAAAf,gBAAS,EAAC,IAAM,CACd,KAAM,CAAAmB,IAAI,CAAG,GAAI,CAAApB,IAAM,CACvB,KAAM,CAAAgB,KAAK,CAAGI,IAAI,CAACC,iBAAiB,CAAC,CAAC,CACtCN,SAAS,CAACC,KAAK,CAAC,CAChB,GAAIL,UAAU,CAAE,CACdW,QAAQ,CAACC,MAAM,CAAG,GAAAC,iBAAS,EAACb,UAAU,CAAEK,KAAK,CAACS,QAAQ,CAAC,CAAC,CAAE,CAAEC,IAAI,CAAE,GAAI,CAAC,CACzE,CACF,CAAC,CAAE,CAACf,UAAU,CAAEI,SAAS,CAAC,CAAC,CAC3B,MAAO,CAAAD,MACT,CAEA,KAAM,CAAAa,IAAI,CAAG,CACXC,MAAM,CAANA,eAAM,CACNC,OAAO,CAAPA,gBAAO,CACPC,MAAM,CAANA,eAAM,CACNlC,MAAM,CAANA,eAAM,CACNmC,OAAO,CAAPA,gBAAO,CACPlC,GAAG,CAAEG,IAAI,CAACH,GAAG,CACbmC,KAAK,CAALA,cAAK,CACLxC,UAAU,CACVkB,iBACF,CAAC,CAAC,IAAAuB,QAAA,CAAAC,OAAA,CAAAC,OAAA,CAEaC,MAAM,CAACC,MAAM,CAACC,cAAK,CAAEX,IAAI,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"time.js","names":["_cookie","require","_react","_dayjs","_interopRequireDefault","_jsUtils","_reactGlobalState","_globalState","useCurrent","autorefresh","globalStatePath","precision","SEC_MS","now","setter","useGlobalState","Date","useEffect","timerId","update","old","neu","Math","abs","setTimeout","clearTimeout","useTimezoneOffset","cookieName","ssrContext","getSsrContext","offset","setOffset","value","req","cookies","parseInt","date","getTimezoneOffset","document","cookie","serialize","toString","path","time","DAY_MS","HOUR_MS","MIN_MS","YEAR_MS","timer","_default","exports","default","Object","assign","dayjs"],"sources":["../../../../src/shared/utils/time.ts"],"sourcesContent":["import { serialize } from 'cookie';\nimport { useEffect } from 'react';\nimport dayjs from 'dayjs';\n\nimport {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n timer,\n} from '@dr.pogodin/js-utils';\n\nimport { type ForceT, useGlobalState } from '@dr.pogodin/react-global-state';\n\nimport { getSsrContext } from './globalState';\n\n/**\n * This react hook wraps Date.now() function in a SSR friendly way,\n * ensuring that all calls to useCurrent() within the same render return\n * exactly the same time (which is retrieved from Date.now() first, and\n * then stored in the global state to be reused in all other calls), which\n * is also passed and used in the first client side render, and then updated\n * with a finite precision to avoid infinite re-rendering loops.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useCurrent({\n autorefresh = false,\n globalStatePath = 'currentTime',\n precision = 5 * SEC_MS,\n} = {}): number {\n const [now, setter] = useGlobalState<ForceT, number>(\n globalStatePath,\n Date.now,\n );\n useEffect(() => {\n let timerId: NodeJS.Timeout | undefined;\n const update = (): void => {\n setter((old) => {\n const neu = Date.now();\n return Math.abs(neu - old) > precision ? neu : old;\n });\n if (autorefresh) timerId = setTimeout(update, precision);\n };\n update();\n return (): void => {\n if (timerId) clearTimeout(timerId);\n };\n }, [autorefresh, precision, setter]);\n return now;\n}\n\n/**\n * Wraps the standard Date.getTimezoneOffset() method in a SSR-friendly way.\n * This hook retrieves the offset value at the client side and uses a cookie\n * to pass it to the server in subsequent requests from that user. At the server\n * side the value from cookie is used in renders and passed back to the client\n * via the global state. Prior to the value being known (in the very first\n * request from the user, when the cookie is still missing), zero value is used\n * as the default value.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useTimezoneOffset({\n cookieName = 'timezoneOffset',\n globalStatePath = 'timezoneOffset',\n} = {}): number {\n const ssrContext = getSsrContext(false);\n const [offset, setOffset] = useGlobalState<ForceT, number>(\n globalStatePath,\n () => {\n const value = cookieName\n && ssrContext?.req.cookies[cookieName] as string;\n return value ? parseInt(value) : 0;\n },\n );\n useEffect(() => {\n const date = new Date();\n const value = date.getTimezoneOffset();\n setOffset(value);\n if (cookieName) {\n document.cookie = serialize(cookieName, value.toString(), { path: '/' });\n }\n }, [cookieName, setOffset]);\n return offset;\n}\n\nconst time = {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n now: Date.now,\n timer,\n useCurrent,\n useTimezoneOffset,\n};\n\nexport default Object.assign(dayjs, time);\n"],"mappings":"0PAAA,IAAAA,OAAA,CAAAC,OAAA,WACA,IAAAC,MAAA,CAAAD,OAAA,UACA,IAAAE,MAAA,CAAAC,sBAAA,CAAAH,OAAA,WAEA,IAAAI,QAAA,CAAAJ,OAAA,yBASA,IAAAK,iBAAA,CAAAL,OAAA,mCAEA,IAAAM,YAAA,CAAAN,OAAA,kBAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA;AACA;AACO,QAAS,CAAAO,UAAUA,CAAC,CACzBC,WAAW,CAAG,KAAK,CACnBC,eAAe,CAAG,aAAa,CAC/BC,SAAS,CAAG,CAAC,CAAGC,eAClB,CAAC,CAAG,CAAC,CAAC,CAAU,CACd,KAAM,CAACC,GAAG,CAAEC,MAAM,CAAC,CAAG,GAAAC,gCAAc,EAClCL,eAAe,CACfM,IAAI,CAACH,GACP,CAAC,CACD,GAAAI,gBAAS,EAAC,IAAM,CACd,GAAI,CAAAC,OAAmC,CACvC,KAAM,CAAAC,MAAM,CAAGA,CAAA,GAAY,CACzBL,MAAM,CAAEM,GAAG,EAAK,CACd,KAAM,CAAAC,GAAG,CAAGL,IAAI,C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AE,GAAI,CAAC,CACzE,CACF,CAAC,CAAE,CAACf,UAAU,CAAEI,SAAS,CAAC,CAAC,CAC3B,MAAO,CAAAD,MACT,CAEA,KAAM,CAAAa,IAAI,CAAG,CACXC,MAAM,CAANA,eAAM,CACNC,OAAO,CAAPA,gBAAO,CACPC,MAAM,CAANA,eAAM,CACNlC,MAAM,CAANA,eAAM,CACNmC,OAAO,CAAPA,gBAAO,CACPlC,GAAG,CAAEG,IAAI,CAACH,GAAG,CACbmC,KAAK,CAALA,cAAK,CACLxC,UAAU,CACVkB,iBACF,CAAC,KAAAuB,QAAA,CAAAC,OAAA,CAAAC,OAAA,CAEcC,MAAM,CAACC,MAAM,CAACC,cAAK,CAAEX,IAAI,CAAC","ignoreList":[]}
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = getInj;
8
+ var _forge = _interopRequireDefault(require("node-forge/lib/forge"));
9
+ require("node-forge/lib/aes");
10
+ var _buildInfo = require("../shared/utils/isomorphy/buildInfo");
11
+ // Encapsulates retrieval of server-side data injection into HTML template.
12
+
13
+ /* global document */
14
+
15
+ // Note: this way, only required part of "node-forge": AES, and some utils,
16
+ // is bundled into client-side code.
17
+
18
+ // eslint-disable-next-line import/no-unassigned-import
19
+
20
+ // Safeguard is needed here, because the server-side version of Docusaurus docs
21
+ // is compiled (at least now) with settings suggesting it is a client-side
22
+ // environment, but there is no document.
23
+ let inj = {};
24
+ const metaElement = typeof document === 'undefined' ? null : document.querySelector('meta[itemprop="drpruinj"]');
25
+ if (metaElement) {
26
+ metaElement.remove();
27
+ let data = _forge.default.util.decode64(metaElement.content);
28
+ const {
29
+ key
30
+ } = (0, _buildInfo.getBuildInfo)();
31
+ const d = _forge.default.cipher.createDecipher('AES-CBC', key);
32
+ d.start({
33
+ iv: data.slice(0, key.length)
34
+ });
35
+ d.update(_forge.default.util.createBuffer(data.slice(key.length)));
36
+ d.finish();
37
+ data = _forge.default.util.decodeUtf8(d.output.data);
38
+
39
+ // TODO: Double-check, if there is a safer alternative to parse it?
40
+ // eslint-disable-next-line no-eval
41
+ inj = eval(`(${data})`);
42
+ } else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {
43
+ inj = window.REACT_UTILS_INJECTION;
44
+ delete window.REACT_UTILS_INJECTION;
45
+ } else {
46
+ // Otherwise, a bunch of dependent stuff will easily fail in non-standard
47
+ // environments, where no client-side initialization is performed. Like tests,
48
+ // Docusaurus examples, etc.
49
+ inj = {};
50
+ }
51
+ function getInj() {
52
+ return inj;
53
+ }
54
+ //# sourceMappingURL=getInj.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getInj.js","names":["_forge","_interopRequireDefault","require","_buildInfo","inj","metaElement","document","querySelector","remove","data","forge","util","decode64","content","key","getBuildInfo","d","cipher","createDecipher","start","iv","slice","length","update","createBuffer","finish","decodeUtf8","output","eval","window","REACT_UTILS_INJECTION","getInj"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\n\n// eslint-disable-next-line import/no-unassigned-import\nimport 'node-forge/lib/aes';\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\n// Safeguard is needed here, because the server-side version of Docusaurus docs\n// is compiled (at least now) with settings suggesting it is a client-side\n// environment, but there is no document.\nlet inj: InjT = {};\n\nconst metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\nif (metaElement) {\n metaElement.remove();\n let data = forge.util.decode64(metaElement.content);\n\n const { key } = getBuildInfo();\n const d = forge.cipher.createDecipher('AES-CBC', key);\n d.start({ iv: data.slice(0, key.length) });\n d.update(forge.util.createBuffer(data.slice(key.length)));\n d.finish();\n\n data = forge.util.decodeUtf8(d.output.data);\n\n // TODO: Double-check, if there is a safer alternative to parse it?\n // eslint-disable-next-line no-eval\n inj = eval(`(${data})`) as InjT;\n} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n inj = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n} else {\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n inj = {};\n}\n\nexport default function getInj(): InjT {\n return inj;\n}\n"],"mappings":";;;;;;;AAMA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AAGAA,OAAA;AAIA,IAAAC,UAAA,GAAAD,OAAA;AAbA;;AAEA;;AAEA;AACA;;AAGA;;AAOA;AACA;AACA;AACA,IAAIE,GAAS,GAAG,CAAC,CAAC;AAElB,MAAMC,WAAmC,GAAG,OAAOC,QAAQ,KAAK,WAAW,GACvE,IAAI,GAAGA,QAAQ,CAACC,aAAa,CAAC,2BAA2B,CAAC;AAE9D,IAAIF,WAAW,EAAE;EACfA,WAAW,CAACG,MAAM,CAAC,CAAC;EACpB,IAAIC,IAAI,GAAGC,cAAK,CAACC,IAAI,CAACC,QAAQ,CAACP,WAAW,CAACQ,OAAO,CAAC;EAEnD,MAAM;IAAEC;EAAI,CAAC,GAAG,IAAAC,uBAAY,EAAC,CAAC;EAC9B,MAAMC,CAAC,GAAGN,cAAK,CAACO,MAAM,CAACC,cAAc,CAAC,SAAS,EAAEJ,GAAG,CAAC;EACrDE,CAAC,CAACG,KAAK,CAAC;IAAEC,EAAE,EAAEX,IAAI,CAACY,KAAK,CAAC,CAAC,EAAEP,GAAG,CAACQ,MAAM;EAAE,CAAC,CAAC;EAC1CN,CAAC,CAACO,MAAM,CAACb,cAAK,CAACC,IAAI,CAACa,YAAY,CAACf,IAAI,CAACY,KAAK,CAACP,GAAG,CAACQ,MAAM,CAAC,CAAC,CAAC;EACzDN,CAAC,CAACS,MAAM,CAAC,CAAC;EAEVhB,IAAI,GAAGC,cAAK,CAACC,IAAI,CAACe,UAAU,CAACV,CAAC,CAACW,MAAM,CAAClB,IAAI,CAAC;;EAE3C;EACA;EACAL,GAAG,GAAGwB,IAAI,CAAC,IAAInB,IAAI,GAAG,CAAS;AACjC,CAAC,MAAM,IAAI,OAAOoB,MAAM,KAAK,WAAW,IAAIA,MAAM,CAACC,qBAAqB,EAAE;EACxE1B,GAAG,GAAGyB,MAAM,CAACC,qBAAqB;EAClC,OAAOD,MAAM,CAACC,qBAAqB;AACrC,CAAC,MAAM;EACL;EACA;EACA;EACA1B,GAAG,GAAG,CAAC,CAAC;AACV;AAEe,SAAS2B,MAAMA,CAAA,EAAS;EACrC,OAAO3B,GAAG;AACZ","ignoreList":[]}
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = Launch;
8
+ var _client = require("react-dom/client");
9
+ var _reactHelmet = require("@dr.pogodin/react-helmet");
10
+ var _reactRouter = require("react-router");
11
+ var _reactGlobalState = require("@dr.pogodin/react-global-state");
12
+ var _getInj = _interopRequireDefault(require("./getInj"));
13
+ var _jsxRuntime = require("react/jsx-runtime");
14
+ // Initialization of client-side code.
15
+ /* global document */
16
+
17
+ /**
18
+ * Prepares and launches the app at client side.
19
+ * @param Application Root application component
20
+ * @param [options={}] Optional. Additional settings.
21
+ */
22
+ function Launch(Application, options = {}) {
23
+ const container = document.getElementById('react-view');
24
+ if (!container) throw Error('Failed to find container for React app');
25
+ const scene = /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactGlobalState.GlobalStateProvider, {
26
+ initialState: (0, _getInj.default)().ISTATE ?? options.initialState,
27
+ children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactRouter.BrowserRouter, {
28
+ children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactHelmet.HelmetProvider, {
29
+ children: /*#__PURE__*/(0, _jsxRuntime.jsx)(Application, {})
30
+ })
31
+ })
32
+ });
33
+ if (options.dontHydrate) {
34
+ const root = (0, _client.createRoot)(container);
35
+ root.render(scene);
36
+ } else (0, _client.hydrateRoot)(container, scene);
37
+ }
38
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["_client","require","_reactHelmet","_reactRouter","_reactGlobalState","_getInj","_interopRequireDefault","_jsxRuntime","Launch","Application","options","container","document","getElementById","Error","scene","jsx","GlobalStateProvider","initialState","getInj","ISTATE","children","BrowserRouter","HelmetProvider","dontHydrate","root","createRoot","render","hydrateRoot"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport type { ComponentType } from 'react';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { BrowserRouter } from 'react-router';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: unknown;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n): void {\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={getInj().ISTATE ?? options.initialState}>\n <BrowserRouter>\n <HelmetProvider>\n <Application />\n </HelmetProvider>\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":";;;;;;;AAIA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,YAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAF,OAAA;AAEA,IAAAG,iBAAA,GAAAH,OAAA;AAEA,IAAAI,OAAA,GAAAC,sBAAA,CAAAL,OAAA;AAA8B,IAAAM,WAAA,GAAAN,OAAA;AAV9B;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACe,SAASO,MAAMA,CAC5BC,WAA0B,EAC1BC,OAAiB,GAAG,CAAC,CAAC,EAChB;EACN,MAAMC,SAAS,GAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC;EACvD,IAAI,CAACF,SAAS,EAAE,MAAMG,KAAK,CAAC,wCAAwC,CAAC;EACrE,MAAMC,KAAK,gBACT,IAAAR,WAAA,CAAAS,GAAA,EAACZ,iBAAA,CAAAa,mBAAmB;IAACC,YAAY,EAAE,IAAAC,eAAM,EAAC,CAAC,CAACC,MAAM,IAAIV,OAAO,CAACQ,YAAa;IAAAG,QAAA,eACzE,IAAAd,WAAA,CAAAS,GAAA,EAACb,YAAA,CAAAmB,aAAa;MAAAD,QAAA,eACZ,IAAAd,WAAA,CAAAS,GAAA,EAACd,YAAA,CAAAqB,cAAc;QAAAF,QAAA,eACb,IAAAd,WAAA,CAAAS,GAAA,EAACP,WAAW,IAAE;MAAC,CACD;IAAC,CACJ;EAAC,CACG,CACtB;EAED,IAAIC,OAAO,CAACc,WAAW,EAAE;IACvB,MAAMC,IAAI,GAAG,IAAAC,kBAAU,EAACf,SAAS,CAAC;IAClCc,IAAI,CAACE,MAAM,CAACZ,KAAK,CAAC;EACpB,CAAC,MAAM,IAAAa,mBAAW,EAACjB,SAAS,EAAEI,KAAK,CAAC;AACtC","ignoreList":[]}
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+
3
+ var _buildInfo = require("../shared/utils/isomorphy/buildInfo");
4
+ /**
5
+ * Initialization of client-side environment.
6
+ */
7
+
8
+ /* global window */
9
+
10
+ const buildInfo = (0, _buildInfo.getBuildInfo)();
11
+
12
+ // TODO: Should be moved into buildInfo module?
13
+
14
+ if (process.env.NODE_ENV !== 'production') {
15
+ // eslint-disable-next-line no-console
16
+ console.warn('Dev mode: "BUILD_INFO" attached to the global "window"');
17
+
18
+ // eslint-disable-next-line no-underscore-dangle
19
+ window.__DEV_BUILD_INFO__ = BUILD_INFO;
20
+ }
21
+
22
+ /* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */
23
+ const {
24
+ useServiceWorker
25
+ } = buildInfo;
26
+ if (useServiceWorker) {
27
+ const {
28
+ navigator
29
+ } = window;
30
+ if ('serviceWorker' in navigator) {
31
+ window.addEventListener('load', () => {
32
+ void (async () => {
33
+ try {
34
+ // Note: no matter the "publicPath", we want to serve the service worker
35
+ // from the web app root, to allow it control any and all pages of the
36
+ // web app (otherwise, it will be restricted to the scope of its path).
37
+ // The server takes it into account.
38
+ const reg = await navigator.serviceWorker.register('/__service-worker.js');
39
+ // eslint-disable-next-line no-console
40
+ console.log('SW registered:', reg);
41
+ } catch (err) {
42
+ // eslint-disable-next-line no-console
43
+ console.log('SW registration failed:', err);
44
+ }
45
+ })();
46
+ });
47
+ }
48
+ }
49
+ //# sourceMappingURL=init.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.js","names":["_buildInfo","require","buildInfo","getBuildInfo","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":";;AAMA,IAAAA,UAAA,GAAAC,OAAA;AANA;AACA;AACA;;AAEA;;AAIA,MAAMC,SAAS,GAAG,IAAAC,uBAAY,EAAC,CAAC;;AAEhC;;AAUA,IAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;EACzC;EACAC,OAAO,CAACC,IAAI,CAAC,wDAAwD,CAAC;;EAEtE;EACAC,MAAM,CAACC,kBAAkB,GAAGC,UAAU;AACxC;;AAEA;AACA,MAAM;EAAEC;AAAiB,CAAC,GAAGV,SAAS;AACtC,IAAIU,gBAAgB,EAAE;EACpB,MAAM;IAAEC;EAAU,CAAC,GAAGJ,MAAM;EAC5B,IAAI,eAAe,IAAII,SAAS,EAAE;IAChCJ,MAAM,CAACK,gBAAgB,CAAC,MAAM,EAAE,MAAM;MACpC,KAAK,CAAC,YAAY;QAChB,IAAI;UACF;UACA;UACA;UACA;UACA,MAAMC,GAAG,GAAG,MAAMF,SAAS,CACxBG,aAAa,CAACC,QAAQ,CAAC,sBAAsB,CAAC;UACjD;UACAV,OAAO,CAACW,GAAG,CAAC,gBAAgB,EAAEH,GAAG,CAAC;QACpC,CAAC,CAAC,OAAOI,GAAG,EAAE;UACZ;UACAZ,OAAO,CAACW,GAAG,CAAC,yBAAyB,EAAEC,GAAG,CAAC;QAC7C;MACF,CAAC,EAAE,CAAC;IACN,CAAC,CAAC;EACJ;AACF","ignoreList":[]}
@@ -0,0 +1,25 @@
1
+ import "./styles/global.scss";
2
+ import { webpack } from "./shared/utils";
3
+ // It is a safeguard against multiple instances / versions of the library
4
+ // being loaded into environment by mistake (e.g. because of different
5
+ // packages pinning down different exact versions of the lib, thus preventing
6
+ // a proper dedupe and using a single common library version).
7
+ if (global.REACT_UTILS_LIBRARY_LOADED) {
8
+ throw Error('React utils library is already loaded');
9
+ } else global.REACT_UTILS_LIBRARY_LOADED = true;
10
+
11
+ // TODO: This is a rapid workaround to get rid of __dirname. I guess, later
12
+ // we'll re-implement requireWeak() to accept import.meta.url directly, and
13
+ // this workaround won't be needed.
14
+ let dirname = import.meta.url;
15
+ dirname = dirname.slice(5, dirname.lastIndexOf('/'));
16
+ const server = webpack.requireWeak('./server', dirname);
17
+ const client = server ? undefined
18
+
19
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
20
+ : require("./client").default;
21
+ export { getGlobalState, GlobalStateProvider, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState, withGlobalStateType } from '@dr.pogodin/react-global-state';
22
+ export * from "./shared/components";
23
+ export { assertEmptyObject, config, Barrier, Cached, Emitter, isomorphy, getSsrContext, Semaphore, splitComponent, themed, ThemeProvider, time, webpack, withRetries } from "./shared/utils";
24
+ export { client, server };
25
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["webpack","global","REACT_UTILS_LIBRARY_LOADED","Error","dirname","import","meta","url","slice","lastIndexOf","server","requireWeak","client","undefined","require","default","getGlobalState","GlobalStateProvider","newAsyncDataEnvelope","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType","assertEmptyObject","config","Barrier","Cached","Emitter","isomorphy","getSsrContext","Semaphore","splitComponent","themed","ThemeProvider","time","withRetries"],"sources":["../../src/index.ts"],"sourcesContent":["import 'styles/global.scss';\n\nimport { webpack } from 'utils';\n\nimport type * as ClientM from './client';\nimport type * as ServerFactoryM from './server';\n\n// 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\n// TODO: This is a rapid workaround to get rid of __dirname. I guess, later\n// we'll re-implement requireWeak() to accept import.meta.url directly, and\n// this workaround won't be needed.\nlet dirname = import.meta.url;\ndirname = dirname.slice(5, dirname.lastIndexOf('/'));\n\nconst server = webpack.requireWeak<typeof ServerFactoryM>('./server', dirname);\n\nconst client = server\n ? undefined\n\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n : (require('./client') as typeof ClientM).default;\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 config,\n Barrier,\n Cached,\n Emitter,\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\nexport { client, server };\n"],"mappings":"AAAA;AAEA,SAASA,OAAO;AAKhB;AACA;AACA;AACA;AACA,IAAIC,MAAM,CAACC,0BAA0B,EAAE;EACrC,MAAMC,KAAK,CAAC,uCAAuC,CAAC;AACtD,CAAC,MAAMF,MAAM,CAACC,0BAA0B,GAAG,IAAI;;AAE/C;AACA;AACA;AACA,IAAIE,OAAO,GAAGC,MAAM,CAACC,IAAI,CAACC,GAAG;AAC7BH,OAAO,GAAGA,OAAO,CAACI,KAAK,CAAC,CAAC,EAAEJ,OAAO,CAACK,WAAW,CAAC,GAAG,CAAC,CAAC;AAEpD,MAAMC,MAAM,GAAGV,OAAO,CAACW,WAAW,CAAwB,UAAU,EAAEP,OAAO,CAAC;AAE9E,MAAMQ,MAAM,GAAGF,MAAM,GACjBG;;AAEF;AAAA,EACGC,OAAO,WAAW,CAAC,CAAoBC,OAAO;AAEnD,SAUEC,cAAc,EACdC,mBAAmB,EACnBC,oBAAoB,EACpBC,kBAAkB,EAClBC,YAAY,EACZC,cAAc,EACdC,mBAAmB,QACd,gCAAgC;AAEvC;AAUA,SACEC,iBAAiB,EACjBC,MAAM,EACNC,OAAO,EACPC,MAAM,EACNC,OAAO,EACPC,SAAS,EACTC,aAAa,EAGbC,SAAS,EACTC,cAAc,EAEdC,MAAM,EACNC,aAAa,EACbC,IAAI,EACJlC,OAAO,EACPmC,WAAW;AAGb,SAASvB,MAAM,EAAEF,MAAM","ignoreList":[]}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Implements the static cache.
3
+ */
4
+ export default class Cache {
5
+ items = {};
6
+ size = 0;
7
+ constructor(maxSize) {
8
+ this.maxSize = maxSize;
9
+ }
10
+
11
+ /**
12
+ * Cache lookup.
13
+ * @param key Item key to look for.
14
+ * @param [maxage=Number.MAX_VALUE] Optional. The maximum age of
15
+ * cached item to serve. Default to infinite.
16
+ * @returns Cached item, or null if the item is absent in cache,
17
+ * or stale.
18
+ */
19
+ get({
20
+ key,
21
+ maxage = Number.MAX_VALUE
22
+ }) {
23
+ const item = this.items[key];
24
+ return item && Date.now() - item.timestamp < maxage ? item.data : null;
25
+ }
26
+
27
+ /**
28
+ * Adds item to cache.
29
+ * @param data Item to add.
30
+ * @param key Key to store the item at.
31
+ * @param size Byte size of the item.
32
+ */
33
+ add(data, key, size) {
34
+ const cached = this.items[key];
35
+ if (cached) this.size -= cached.size;
36
+ this.items[key] = {
37
+ data,
38
+ size,
39
+ timestamp: Date.now()
40
+ };
41
+ this.size += size;
42
+ if (this.size > this.maxSize) {
43
+ const entries = Object.entries(this.items);
44
+ entries.sort((a, b) => a[1].timestamp - b[1].timestamp);
45
+ for (const entry of entries) {
46
+ const [itemKey, item] = entry;
47
+ delete this.items[itemKey];
48
+ this.size -= item.size;
49
+ if (this.size < this.maxSize / 2) break;
50
+ }
51
+ }
52
+ }
53
+ }
54
+ //# sourceMappingURL=Cache.js.map
@@ -0,0 +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"],"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;AACA,eAAe,MAAMA,KAAK,CAAS;EACzBC,KAAK,GAAwC,CAAC,CAAC;EAE/CC,IAAI,GAAG,CAAC;EAEhBC,WAAWA,CAASC,OAAe,EAAE;IAAA,KAAjBA,OAAe,GAAfA,OAAe;EAAI;;EAEvC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;EACEC,GAAGA,CAAC;IACFC,GAAG;IACHC,MAAM,GAAGC,MAAM,CAACC;EAIlB,CAAC,EAAiB;IAChB,MAAMC,IAAI,GAAG,IAAI,CAACT,KAAK,CAACK,GAAG,CAAC;IAC5B,OAAOI,IAAI,IAAIC,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGF,IAAI,CAACG,SAAS,GAAGN,MAAM,GAAGG,IAAI,CAACI,IAAI,GAAG,IAAI;EACxE;;EAEA;AACF;AACA;AACA;AACA;AACA;EACEC,GAAGA,CAACD,IAAY,EAAER,GAAW,EAAEJ,IAAY,EAAQ;IACjD,MAAMc,MAAM,GAAG,IAAI,CAACf,KAAK,CAACK,GAAG,CAAC;IAC9B,IAAIU,MAAM,EAAE,IAAI,CAACd,IAAI,IAAIc,MAAM,CAACd,IAAI;IAEpC,IAAI,CAACD,KAAK,CAACK,GAAG,CAAC,GAAG;MAAEQ,IAAI;MAAEZ,IAAI;MAAEW,SAAS,EAAEF,IAAI,CAACC,GAAG,CAAC;IAAE,CAAC;IACvD,IAAI,CAACV,IAAI,IAAIA,IAAI;IAEjB,IAAI,IAAI,CAACA,IAAI,GAAG,IAAI,CAACE,OAAO,EAAE;MAC5B,MAAMa,OAAO,GAAGC,MAAM,CAACD,OAAO,CAAC,IAAI,CAAChB,KAAK,CAAC;MAC1CgB,OAAO,CAACE,IAAI,CAAC,CAACC,CAAC,EAAEC,CAAC,KAAKD,CAAC,CAAC,CAAC,CAAC,CAACP,SAAS,GAAGQ,CAAC,CAAC,CAAC,CAAC,CAACR,SAAS,CAAC;MAEvD,KAAK,MAAMS,KAAK,IAAIL,OAAO,EAAE;QAC3B,MAAM,CAACM,OAAO,EAAEb,IAAI,CAAC,GAAGY,KAAK;QAC7B,OAAO,IAAI,CAACrB,KAAK,CAACsB,OAAO,CAAC;QAC1B,IAAI,CAACrB,IAAI,IAAIQ,IAAI,CAACR,IAAI;QACtB,IAAI,IAAI,CAACA,IAAI,GAAG,IAAI,CAACE,OAAO,GAAG,CAAC,EAAE;MACpC;IACF;EACF;AACF","ignoreList":[]}
@@ -0,0 +1,211 @@
1
+ // eslint-disable-next-line import/no-unassigned-import
2
+ import 'source-map-support/register';
3
+ import http from 'node:http';
4
+ import https from 'node:https';
5
+ import cloneDeep from 'lodash/cloneDeep';
6
+ import defaults from 'lodash/defaults';
7
+ import isFinite from 'lodash/isFinite';
8
+ import isNumber from 'lodash/isNumber';
9
+ import isString from 'lodash/isString';
10
+ import toNumber from 'lodash/toNumber';
11
+
12
+ // Polyfill required by ReactJS.
13
+ // TODO: Double-check, if it is still required by React v19?
14
+ // eslint-disable-next-line import/no-unassigned-import
15
+ import 'raf/polyfill';
16
+ import serverFactory, { getDefaultCspSettings } from "./server";
17
+ import { SCRIPT_LOCATIONS, newDefaultLogger } from "./renderer";
18
+ import { errors } from "./utils";
19
+ export { errors, getDefaultCspSettings };
20
+
21
+ /**
22
+ * Normalizes a port into a number, string, or false.
23
+ * TODO: Drop this function?
24
+ * @param value Port name or number.
25
+ * @return Port number (Number), name (String), or false.
26
+ */
27
+ function normalizePort(value) {
28
+ const port = toNumber(value);
29
+ if (isFinite(port)) return port; /* port number */
30
+ if (!isNumber(port)) return value; /* named pipe */
31
+ return false;
32
+ }
33
+ /**
34
+ * Creates and launches web-server for ReactJS application. Allows zero
35
+ * or detailed configuration, supports server-side rendering,
36
+ * and development tools, including Hot Module Reloading (HMR).
37
+ *
38
+ * NOTE: Many of options defined below are passed down to the server and
39
+ * renderer factories, and their declared default values are set in those
40
+ * factories, rather than here.
41
+ *
42
+ * @param {object} webpackConfig Webpack configuration used to build
43
+ * the frontend bundle. In production mode the server will read out of it
44
+ * `context`, `publicPath`, and a few other parameters, necessary to locate
45
+ * and serve the app bundle. In development mode the server will use entire
46
+ * provided config to build the app bundle in memory, and further watch and
47
+ * update it via HMR.
48
+ * @param {object} [options] Additional parameters.
49
+ * @param {Component} [options.Application] The root ReactJS component of
50
+ * the app to use for the server-side rendering. When not provided
51
+ * the server-side rendering is disabled.
52
+ * @param {function} [options.beforeExpressJsError] Asynchronous callback
53
+ * (`(server) => Promise<boolean>`) to be executed just before the default error
54
+ * handler is added to ExpressJS server. If the callback is provided and its
55
+ * result resolves to a truthy value, `react-utils` won't attach the default
56
+ * error handler.
57
+ * @param {function} [options.beforeExpressJsSetup] Asynchronous callback
58
+ * (`(server) => Promise) to be executed right after ExpressJS server creation,
59
+ * before any configuration is performed.
60
+ * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before
61
+ * the server-side rendering. For each incoming request, it will be executed
62
+ * just before the HTML markup is generated at the server. It allows to load
63
+ * and provide the data necessary for server-side rendering, and also to inject
64
+ * additional configuration and scripts into the generated HTML code.
65
+ * @param {boolean} [options.noCsp] Set `true` to disable
66
+ * Content-Security-Policy (CSP) headers altogether.
67
+ * @param {function} [options.cspSettingsHook] A hook allowing
68
+ * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)
69
+ * settings for [helmet](https://github.com/helmetjs/helmet)'s
70
+ * `contentSecurityPolicy` middleware on per-request basis.
71
+ *
72
+ * If provided it should be a with signature: \
73
+ * `(defaultSettings: object, req: object)` &rArr; `object` \
74
+ * which gets the default settings (also used without the hook),
75
+ * and the incoming request object. The hook response will be passed
76
+ * as options to the helmet `contentSecurityPolicy` middleware.
77
+ *
78
+ * Currently, the default settings is the following object in production
79
+ * environment:
80
+ * ```js
81
+ * {
82
+ * directives: {
83
+ * defaultSrc: ["'self'"],
84
+ * baseUri: ["'self'"],
85
+ * blockAllMixedContent: [],
86
+ * fontSrc: ["'self'", 'https:', 'data:'],
87
+ * frameAncestors: ["'self'"],
88
+ * frameSrc: ["'self'", 'https://*.youtube.com'],
89
+ * imgSrc: ["'self'", 'data:'],
90
+ * objectSrc: ["'none'"],
91
+ * scriptSrc: ["'self'", "'unsafe-eval'", `'nonce-UNIQUE_NONCE_VALUE'`],
92
+ * scriptSrcAttr: ["'none'"],
93
+ * styleSrc: ["'self'", 'https:', "'unsafe-inline'"],
94
+ * upgradeInsecureRequests: [] // Removed in dev mode.
95
+ * }
96
+ * }
97
+ * ```
98
+ * It matches the default value used by Helmet with a few updates:
99
+ * - YouTube host is whitelisted in the `frameSrc` directive to ensure
100
+ * the {@link YouTubeVideo} component works.
101
+ * - An unique per-request nonce is added to `scriptSrc` directive to
102
+ * whitelist auxiliary scripts injected by react-utils. The actual nonce
103
+ * value can be fetched by host code via `.nonce` field of `req` argument
104
+ * of `.beforeRender` hook.
105
+ * - `upgradeInsecureRequests` directive is removed in development mode,
106
+ * to simplify local testing with http requests.
107
+ * @param {string} [options.defaultLoggerLogLevel='info'] Log level for
108
+ * the default logger, which is created if no `logger` option provided.
109
+ * @param {boolean} [options.devMode] Pass in `true` to start the server in
110
+ * development mode.
111
+ * @param {string} [options.favicon] Path to the favicon to use by the server.
112
+ * By default no favicon is used.
113
+ * @param {object} [options.https] If provided, HTTPS server will be started,
114
+ * instead of HTTP otherwise. The object should provide SSL certificate and key
115
+ * via two string fields: `cert`, and `key`.
116
+ * @param {string} [options.https.cert] SSL Certificate.
117
+ * @param {string} [options.https.key] SSL key.
118
+ * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable
119
+ * automatic redirection of all incoming HTTP requests to HTTPS.
120
+ *
121
+ * To smoothly use it at `localhost` you need to run the server in HTTPS mode,
122
+ * and also properly create and install a self-signed SSL sertificate on your
123
+ * system. This article is helpful:
124
+ * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)
125
+ * @param {Logger} [options.logger] The logger to use at server side.
126
+ * By default [`winston`](https://www.npmjs.com/package/winston) logger
127
+ * with console transport is used. The logger you provide, or the default
128
+ * `winston` logger otherwise, will be attached to the created ExpressJS server
129
+ * object.
130
+ * @param {function} [options.onExpressJsSetup] An async callback
131
+ * (`(server) => Promise`) to be triggered when most of the server
132
+ * configuration is completed, just before the server-side renderer,
133
+ * and the default error handler are attached. You can use it to mount
134
+ * custom API routes. The server-side logger can be accessed as `server.logger`.
135
+ * @param {number|string} [options.port=3000] The port to start the server on.
136
+ * @param {number} [options.staticCacheSize=1.e7] The maximum
137
+ * static cache size in bytes. Defaults to ~10 MB.
138
+ * @param {function} [options.staticCacheController] When given, it activates,
139
+ * and controls the static caching of generated HTML markup. When this function
140
+ * is provided, on each incoming request it is triggered with the request
141
+ * passed in as the argument. To attempt to serve the response from the cache
142
+ * it should return the object with the following fields:
143
+ * - `key: string` &ndash; the cache key for the response;
144
+ * - `maxage?: number` &ndash; the maximum age of cached result in ms.
145
+ * If undefined - infinite age is assumed.
146
+ * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.
147
+ * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,
148
+ * defaults to 1 second.
149
+ * @return Resolves to an object with created Express and HTTP servers.
150
+ */
151
+ export default async function launchServer(webpackConfig, options = {}) {
152
+ /* Options normalization. */
153
+ const ops = cloneDeep(options);
154
+
155
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
156
+ ops.port = normalizePort(ops.port || process.env.PORT || 3000);
157
+ defaults(ops, {
158
+ httpsRedirect: true
159
+ });
160
+
161
+ // TODO: Need a separate type for normalized options, which guarantees
162
+ // the logger is set!
163
+ ops.logger ??= newDefaultLogger({
164
+ defaultLogLevel: ops.defaultLoggerLogLevel
165
+ });
166
+
167
+ /* Creates servers, resolves and sets the port. */
168
+ const expressServer = await serverFactory(webpackConfig, ops);
169
+ let httpServer;
170
+ if (ops.https) {
171
+ httpServer = https.createServer({
172
+ cert: ops.https.cert,
173
+ key: ops.https.key
174
+ }, expressServer);
175
+ } else httpServer = http.createServer(expressServer);
176
+
177
+ /* Sets error handler for HTTP(S) server. */
178
+ httpServer.on('error', error => {
179
+ if (error.syscall !== 'listen') throw error;
180
+ const bind = isString(ops.port) ? `Pipe ${ops.port}` : `Port ${ops.port}`;
181
+
182
+ /* Human-readable message for some specific listen errors. */
183
+ switch (error.code) {
184
+ case 'EACCES':
185
+ ops.logger.error(`${bind} requires elevated privileges`);
186
+ return process.exit(1);
187
+ case 'EADDRINUSE':
188
+ ops.logger.error(`${bind} is already in use`);
189
+ return process.exit(1);
190
+ case undefined:
191
+ default:
192
+ throw error;
193
+ }
194
+ });
195
+
196
+ /* Listening event handler for HTTP(S) server. */
197
+ httpServer.on('listening', () => {
198
+ const addr = httpServer.address();
199
+ const bind = isString(addr) ? `pipe ${addr}` : `port ${addr.port}`;
200
+ ops.logger.info(`Server listening on ${bind} in ${process.env.NODE_ENV} mode`);
201
+ });
202
+ httpServer.listen(ops.port);
203
+ return {
204
+ expressServer,
205
+ httpServer
206
+ };
207
+ }
208
+ launchServer.SCRIPT_LOCATIONS = SCRIPT_LOCATIONS;
209
+ launchServer.getDefaultCspSettings = getDefaultCspSettings;
210
+ launchServer.errors = errors;
211
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["http","https","cloneDeep","defaults","isFinite","isNumber","isString","toNumber","serverFactory","getDefaultCspSettings","SCRIPT_LOCATIONS","newDefaultLogger","errors","normalizePort","value","port","launchServer","webpackConfig","options","ops","process","env","PORT","httpsRedirect","logger","defaultLogLevel","defaultLoggerLogLevel","expressServer","httpServer","createServer","cert","key","on","error","syscall","bind","code","exit","undefined","addr","address","info","NODE_ENV","listen"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport cloneDeep from 'lodash/cloneDeep';\nimport defaults from 'lodash/defaults';\nimport isFinite from 'lodash/isFinite';\nimport isNumber from 'lodash/isNumber';\nimport isString from 'lodash/isString';\nimport toNumber from 'lodash/toNumber';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill';\n\nimport type { Configuration } from 'webpack';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport { errors } from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport { errors, getDefaultCspSettings, type ServerT };\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String), or false.\n */\nfunction normalizePort(value: number | string) {\n const port = toNumber(value);\n if (isFinite(port)) return port; /* port number */\n if (!isNumber(port)) return value; /* named pipe */\n return false;\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` &rArr; `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel='info'] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @return Resolves to an object with created Express and HTTP servers.\n */\nexport default async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = isString(ops.port) ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger!.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger!.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address()!;\n const bind = isString(addr) ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger!.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n\nlaunchServer.SCRIPT_LOCATIONS = SCRIPT_LOCATIONS;\nlaunchServer.getDefaultCspSettings = getDefaultCspSettings;\nlaunchServer.errors = errors;\n"],"mappings":"AAAA;AACA,OAAO,6BAA6B;AAEpC,OAAOA,IAAI,MAAM,WAAW;AAC5B,OAAOC,KAAK,MAAM,YAAY;AAE9B,OAAOC,SAAS,MAAM,kBAAkB;AACxC,OAAOC,QAAQ,MAAM,iBAAiB;AACtC,OAAOC,QAAQ,MAAM,iBAAiB;AACtC,OAAOC,QAAQ,MAAM,iBAAiB;AACtC,OAAOC,QAAQ,MAAM,iBAAiB;AACtC,OAAOC,QAAQ,MAAM,iBAAiB;;AAEtC;AACA;AACA;AACA,OAAO,cAAc;AAIrB,OAAOC,aAAa,IAGlBC,qBAAqB;AAGvB,SAASC,gBAAgB,EAAEC,gBAAgB;AAE3C,SAASC,MAAM;AASf,SAASA,MAAM,EAAEH,qBAAqB;;AAEtC;AACA;AACA;AACA;AACA;AACA;AACA,SAASI,aAAaA,CAACC,KAAsB,EAAE;EAC7C,MAAMC,IAAI,GAAGR,QAAQ,CAACO,KAAK,CAAC;EAC5B,IAAIV,QAAQ,CAACW,IAAI,CAAC,EAAE,OAAOA,IAAI,CAAC,CAAC;EACjC,IAAI,CAACV,QAAQ,CAACU,IAAI,CAAC,EAAE,OAAOD,KAAK,CAAC,CAAC;EACnC,OAAO,KAAK;AACd;AAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A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