@dr.pogodin/react-utils 1.47.0-alpha.5 → 1.47.0-alpha.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/development/client/getInj.js +11 -0
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/client/index.js +1 -1
- package/build/development/client/index.js.map +1 -1
- package/build/development/index.js +1 -11
- package/build/development/index.js.map +1 -1
- package/build/development/server/index.js +3 -6
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +20 -0
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +6 -0
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/index.js +1 -1
- package/build/development/server/utils/index.js.map +1 -1
- package/build/development/shared/components/Button/index.js +1 -1
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +1 -1
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +1 -1
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +1 -1
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js +1 -1
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +1 -1
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js +1 -1
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +1 -1
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +6 -0
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +5 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +7 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +3 -1
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js +4 -0
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +18 -0
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/webpack.js +4 -0
- package/build/development/shared/utils/webpack.js.map +1 -1
- package/build/production/client/getInj.js +1 -1
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/client/index.js +1 -1
- package/build/production/client/index.js.map +1 -1
- package/build/production/index.js +2 -6
- package/build/production/index.js.map +1 -1
- package/build/production/server/index.js +3 -3
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +1 -1
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +1 -1
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/index.js +1 -1
- package/build/production/server/utils/index.js.map +1 -1
- package/build/production/shared/components/Button/index.js +1 -1
- package/build/production/shared/components/Button/index.js.map +1 -1
- package/build/production/shared/components/Checkbox/index.js +1 -1
- package/build/production/shared/components/Checkbox/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +1 -1
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +1 -1
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js +1 -1
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js +1 -1
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js +1 -1
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +1 -1
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js +2 -2
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js +2 -2
- package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/Switch/index.js +1 -1
- package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +1 -1
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/webpack.js +1 -1
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/types-code/client/index.d.ts +1 -1
- package/build/types-code/index.d.ts +0 -5
- package/build/types-code/server/index.d.ts +4 -9
- package/build/types-code/server/utils/index.d.ts +1 -1
- package/build/web/client/getInj.js +7 -0
- package/build/web/client/getInj.js.map +1 -1
- package/build/web/client/index.js +1 -1
- package/build/web/client/index.js.map +1 -1
- package/build/web/index.js +1 -11
- package/build/web/index.js.map +1 -1
- package/build/web/server/index.js +3 -6
- package/build/web/server/index.js.map +1 -1
- package/build/web/server/renderer.js +10 -0
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/server/server.js +3 -0
- 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 +1 -1
- 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/jest/E2eSsrEnv.js +2 -0
- package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/web/shared/utils/splitComponent.js +9 -0
- package/build/web/shared/utils/splitComponent.js.map +1 -1
- package/build/web/shared/utils/webpack.js +2 -0
- package/build/web/shared/utils/webpack.js.map +1 -1
- package/config/babel/node-ssr.js +7 -1
- package/config/babel/webpack.js +3 -1
- package/config/webpack/app-base.js +4 -7
- package/config/webpack/app-development.js +2 -3
- package/package.json +20 -9
- package/src/client/getInj.ts +0 -71
- package/src/client/index.tsx +0 -45
- package/src/client/init.ts +0 -52
- package/src/index.ts +0 -75
- package/src/server/Cache.ts +0 -61
- package/src/server/index.ts +0 -243
- package/src/server/renderer.tsx +0 -635
- package/src/server/server.ts +0 -330
- 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 -59
- 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 -304
- 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 -284
- package/src/shared/utils/time.ts +0 -101
- package/src/shared/utils/webpack.ts +0 -80
- 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":"E2eSsrEnv.js","names":["path","defaults","set","register","JsdomEnv","Volume","createFsFromVolume","webpack","ssrFactory","setBuildInfo","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","require","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","renderer","status","markup","ssrRequest","cookie","send","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","dirname","testPath","withSsr","root","process","cwd","envName","babelEnv","extensions","setup","cache","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\nimport path from 'node:path';\n\nimport type { Request, Response } from 'express';\n\nimport { defaults, set } from 'lodash-es';\n\nimport type { ReactNode } from 'react';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration } from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport ssrFactory from 'server/renderer';\n\nimport { setBuildInfo } from '../isomorphy/buildInfo';\n\nfunction noop() {\n // NOOP\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n let factory = require(path.resolve(this.rootDir, factoryPath)) as\n (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n if (!compiler) throw Error('Failed to construct Webpack compiler');\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n // TODO: This sure can be replaced by a dynamic import().\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n const module = require(p) as NodeJS.Module;\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\n register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n await super.teardown();\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA,OAAOA,IAAI,MAAM,WAAW;AAI5B,SAASC,QAAQ,EAAEC,GAAG,QAAQ,WAAW;AAIzC;AACA;AACA;AACA,OAAOC,QAAQ,MAAM,qCAAqC;AAE1D,OAAOC,QAAQ,MAAM,wBAAwB;AAC7C,SAASC,MAAM,EAAEC,kBAAkB,QAAQ,OAAO;AAClD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jB,MAAM,KAAK,CAACL,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"E2eSsrEnv.js","names":["path","defaults","set","register","JsdomEnv","Volume","createFsFromVolume","webpack","ssrFactory","setBuildInfo","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","require","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","renderer","status","markup","ssrRequest","cookie","send","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","dirname","testPath","withSsr","root","process","cwd","envName","babelEnv","extensions","setup","cache","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\nimport path from 'node:path';\n\nimport type { Request, Response } from 'express';\n\nimport { defaults, set } from 'lodash-es';\n\nimport type { ReactNode } from 'react';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration } from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport ssrFactory from 'server/renderer';\n\nimport { setBuildInfo } from '../isomorphy/buildInfo';\n\nfunction noop() {\n // NOOP\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n let factory = require(path.resolve(this.rootDir, factoryPath)) as\n (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n if (!compiler) throw Error('Failed to construct Webpack compiler');\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n // TODO: This sure can be replaced by a dynamic import().\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n const module = require(p) as NodeJS.Module;\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\n register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n await super.teardown();\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA,OAAOA,IAAI,MAAM,WAAW;AAI5B,SAASC,QAAQ,EAAEC,GAAG,QAAQ,WAAW;AAIzC;AACA;AACA;AACA,OAAOC,QAAQ,MAAM,qCAAqC;AAE1D,OAAOC,QAAQ,MAAM,wBAAwB;AAC7C,SAASC,MAAM,EAAEC,kBAAkB,QAAQ,OAAO;AAClD,OAAOC,OAAO,MAA8B,SAAS;AACrD;;AAOA,OAAOC,UAAU;AAEjB,SAASC,YAAY;AAErB,SAASC,IAAIA,CAAA,EAAG;EACd;AAAA;AAGF,eAAe,MAAMC,SAAS,SAASP,QAAQ,CAAC;EAa9C;AACF;AACA;AACA;EACUQ,iBAAiBA,CAAA,EAAG;IAC1B,MAAMC,aAAa,GAAG,IAAI,CAACC,OAAO,CAAC,wBAAwB,CAAW;IAEtE,MAAMC,OAAO,GAAIF,aAAa,GAAGG,IAAI,CAACC,KAAK,CAACJ,aAAa,CAAC,GAAG,CAAC,CACvC;IAEvBZ,QAAQ,CAACc,OAAO,EAAE;MAChBG,OAAO,EAAE,IAAI,CAACC,UAAU;MACxBC,E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AAM,EAAE,MAAM,CAAC;MAClDL;IACF,CAAC,CAAC;EACJ;EAEA,MAAMM,KAAKA,CAAA,EAAkB;IAC3B,MAAM,KAAK,CAACA,KAAK,CAAC,CAAC;IACnB,MAAM,IAAI,CAAC3D,UAAU,CAAC,CAAC;;IAEvB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACAR,OAAO,CAACoE,KAAK,GAAG,CAAC,CAAC;IAClBpF,YAAY,CAACqF,SAAS,EAAE,IAAI,CAAC;IAE7B,IAAI,IAAI,CAACT,OAAO,EAAE,MAAM,IAAI,CAACpC,MAAM,CAAC,CAAC;IACrC,IAAI,CAAC5B,MAAM,CAAC0E,6BAA6B,GAAG,IAAI;EAClD;EAEA,MAAMC,QAAQA,CAAA,EAAkB;IAC9B,OAAO,IAAI,CAAC3E,MAAM,CAAC0E,6BAA6B;;IAEhD;IACA;IACA;IACA;IACA;IACA;IACAE,MAAM,CAACC,IAAI,CAACzE,OAAO,CAACoE,KAAK,CAAC,CAACM,OAAO,CAAEC,GAAG,IAAK;MAC1C,OAAO3E,OAAO,CAACoE,KAAK,CAACO,GAAG,CAAC;IAC3B,CAAC,CAAC;IACFjG,QAAQ,CAACkG,MAAM,CAAC,CAAC;IACjB,MAAM,KAAK,CAACL,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
|
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
import "core-js/modules/es.array.push.js";
|
|
2
|
+
import "core-js/modules/es.iterator.constructor.js";
|
|
3
|
+
import "core-js/modules/es.set.difference.v2.js";
|
|
4
|
+
import "core-js/modules/es.set.intersection.v2.js";
|
|
5
|
+
import "core-js/modules/es.set.is-disjoint-from.v2.js";
|
|
6
|
+
import "core-js/modules/es.set.is-subset-of.v2.js";
|
|
7
|
+
import "core-js/modules/es.set.is-superset-of.v2.js";
|
|
8
|
+
import "core-js/modules/es.set.symmetric-difference.v2.js";
|
|
9
|
+
import "core-js/modules/es.set.union.v2.js";
|
|
1
10
|
/* global document */
|
|
2
11
|
|
|
3
12
|
import { Suspense, lazy, useInsertionEffect } from 'react';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"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;AAE9C,SAA4BC,aAAa;A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ACC,QAAQ,CAAC7B,SAAS,CAAC,EAAE4B,MAAM,CAACnB,IAAI,CAACT,SAAS,CAAC;MACzD;;MAEA;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
|
+
{"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;AAE9C,SAA4BC,aAAa;AAEzC,SACEC,cAAc,EACdC,cAAc,EACdC,YAAY;AACO,SAAAC,GAAA,IAAAC,IAAA;AAErB,SAASC,oBAAoBA,CAAA,EAAsC;EACjE,IAAI,CAACL,cAAc,EAAE,OAAOM,SAAS;EAErC,OAAO,CAAC,YAAY;IAClB,MAAM;MAAEC,OAAO,EAAEC;IAAO,CAAC,GAAG,MAAM,MAAM,CAAC,2EAA4E,CAAC;IAEtH,MAAMC,GAAG,GAAG,MAAMD,MAAM,CAAC,CAAC;IAC1B,OAAOC,GAAG,CAACC,YAAY,IAAI,CAAC,CAAC;EAC/B,CAAC,EAAE,CAAC;AACN;AAEA,MAAMC,SAAiC,GAAG,CAAC,CAAC;AAE5C,SAASC,aAAaA,CAAA,EAAG;EACvB,OAAOV,Y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A,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,3 +1,5 @@
|
|
|
1
|
+
import "core-js/modules/es.iterator.constructor.js";
|
|
2
|
+
import "core-js/modules/es.iterator.for-each.js";
|
|
1
3
|
// eslint-disable-next-line import/enforce-node-protocol-usage
|
|
2
4
|
import { createRequire } from 'module';
|
|
3
5
|
import { IS_CLIENT_SIDE, IS_SERVER_SIDE } from "./isomorphy";
|
|
@@ -1 +1 @@
|
|
|
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;AAEtC,SAASC,cAAc,EAAEC,cAAc;AAUvC,IAAIC,OAA+C;AAEnD,IAAID,cAAc,EAAEC,OAAO,GAAGH,aAAa,CAACI,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC;;AAE5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,WAAWA,CACzBC,UAAkB;AAElB;AACA;AACA;AACAC,iBAAgD,EACrB;EAC3B,IAAIR,cAAc,EAAE,OAAO,IAAI;EAE/B,IAAIS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","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;AAEtC,SAASC,cAAc,EAAEC,cAAc;AAUvC,IAAIC,OAA+C;AAEnD,IAAID,cAAc,EAAEC,OAAO,GAAGH,aAAa,CAACI,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC;;AAE5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,WAAWA,CACzBC,UAAkB;AAElB;AACA;AACA;AACAC,iBAAgD,EACrB;EAC3B,IAAIR,cAAc,EAAE,OAAO,IAAI;EAE/B,IAAIS,QAA4B;EAChC,IAAIC,GAAwB;EAC5B,IAAI,OAAOF,iBAAiB,KAAK,QAAQ,EAAE;IACzCC,QAAQ,GAAGD,iBAAiB;EAC9B,CAAC,MAAM;IACLE,GAAG,GAAGF,iBAAiB,IAAI,CAAC,CAAC;IAC7B,CAAC;MAAEC;IAAS,CAAC,GAAGC,GAAG;EACrB;;EAEA;EACA,MAAM;IAAEC;EAAQ,CAAC,GAAGT,OAAO,CAAE,WAAW,CAAkB;EAE1D,MAAMU,IAAI,GAAGH,QAAQ,GAAGE,OAAO,CAACF,QAAQ,EAAEF,UAAU,CAAC,GAAGA,UAAU;EAElE,MAAMM,MAAM,GAAGX,OAAO,CAAEU,IAAI,CAAM;EAElC,IAAI,EAAE,SAAS,IAAIC,MAAM,CAAC,IAAI,CAACA,MAAM,CAACC,OAAO,EAAE,OAAOD,MAAM;EAE5D,MAAM;IAAEC,OAAO,EAAEC,GAAG;IAAE,GAAGC;EAAM,CAAC,GAAGH,MAAM;EAEzC,MAAMI,GAAG,GAAGF,GAAyB;EAErCG,MAAM,CAACC,OAAO,CAACH,KAAK,CAAC,CAACI,OAAO,CAAC,CAAC,CAACC,IAAI,EAAEC,KAAK,CAAC,KAAK;IAC/C,MAAMC,QAAQ,GAAGN,GAAG,CAACI,IAAI,CAA6B;IACtD,IAAIE,QAAQ,KAAKC,SAAS,EAAE;MACzBP,GAAG,CAACI,IAAI,CAA6B,GAAeC,KAAK;IAC5D,CAAC,MAAM,IAAIC,QAAQ,KAAKD,KAAK,EAAE;MAC7B,MAAMG,KAAK,CAAC,4CAA4C,CAAC;IAC3D;EACF,CAAC,CAAC;EACF,OAAOR,GAAG;AACZ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASS,WAAWA,CAACnB,UAAkB,EAAU;EACtD,OAAOA,UAAU;AACnB","ignoreList":[]}
|
package/config/babel/node-ssr.js
CHANGED
|
@@ -48,7 +48,13 @@ const webpack_1 = __importStar(require("./webpack"));
|
|
|
48
48
|
*/
|
|
49
49
|
function newBase(babel, options = {}) {
|
|
50
50
|
var _a;
|
|
51
|
-
const config = (0, webpack_1.default)(babel, Object.assign({
|
|
51
|
+
const config = (0, webpack_1.default)(babel, Object.assign({
|
|
52
|
+
// NOTE: It make sense to have "modules": false here,
|
|
53
|
+
// but it needs a bunch of build configuration updates,
|
|
54
|
+
// and ends-up with conflict of Jest with ES modules (as now
|
|
55
|
+
// Jest relies on babel.config.js, which transpiles everything
|
|
56
|
+
// into CJS).
|
|
57
|
+
modules: 'cjs', targets: 'maintained node versions' }, options));
|
|
52
58
|
const baseAssetsOutputPath = (_a = options.baseAssetsOutputPath) !== null && _a !== void 0 ? _a : '';
|
|
53
59
|
config.plugins.push(['@dr.pogodin/transform-assets', {
|
|
54
60
|
extensions: ['gif', 'jpeg', 'jpg', 'png'],
|
package/config/babel/webpack.js
CHANGED
|
@@ -31,15 +31,17 @@ function newBaseConfig(options) {
|
|
|
31
31
|
],
|
|
32
32
|
}],
|
|
33
33
|
['@babel/transform-runtime', {
|
|
34
|
-
corejs: 3,
|
|
35
34
|
useESModules: true,
|
|
36
35
|
}],
|
|
37
36
|
],
|
|
38
37
|
presets: [
|
|
39
38
|
['@babel/env', {
|
|
39
|
+
bugfixes: true,
|
|
40
|
+
corejs: '3.46',
|
|
40
41
|
// Leaves it to the Webpack to deal with modules.
|
|
41
42
|
modules: (_a = options.modules) !== null && _a !== void 0 ? _a : false,
|
|
42
43
|
targets: (_b = options.targets) !== null && _b !== void 0 ? _b : 'defaults',
|
|
44
|
+
useBuiltIns: 'usage',
|
|
43
45
|
}],
|
|
44
46
|
// TODO: Starting from Babel 8, "automatic" will be the default runtime,
|
|
45
47
|
// thus once upgraded to Babel 8, runtime should be removed from
|
|
@@ -9,10 +9,7 @@ const node_crypto_1 = require("node:crypto");
|
|
|
9
9
|
const node_fs_1 = __importDefault(require("node:fs"));
|
|
10
10
|
const node_path_1 = __importDefault(require("node:path"));
|
|
11
11
|
const sitemap_1 = require("sitemap");
|
|
12
|
-
const
|
|
13
|
-
const defaults_js_1 = __importDefault(require("lodash/defaults.js"));
|
|
14
|
-
const isFunction_js_1 = __importDefault(require("lodash/isFunction.js"));
|
|
15
|
-
const isObject_js_1 = __importDefault(require("lodash/isObject.js"));
|
|
12
|
+
const lodash_es_1 = require("lodash-es");
|
|
16
13
|
const autoprefixer_1 = __importDefault(require("autoprefixer"));
|
|
17
14
|
const mini_css_extract_plugin_1 = __importDefault(require("mini-css-extract-plugin"));
|
|
18
15
|
const webpack_1 = require("webpack");
|
|
@@ -130,7 +127,7 @@ const COREJS_REGEX = /\/core-js/;
|
|
|
130
127
|
*/
|
|
131
128
|
function configFactory(ops) {
|
|
132
129
|
var _a, _b;
|
|
133
|
-
const o = (0,
|
|
130
|
+
const o = (0, lodash_es_1.defaults)((0, lodash_es_1.clone)(ops), {
|
|
134
131
|
babelLoaderOptions: {},
|
|
135
132
|
cssLocalIdent: '[hash:base64:6]',
|
|
136
133
|
outputPath: 'build/web-public',
|
|
@@ -145,7 +142,7 @@ function configFactory(ops) {
|
|
|
145
142
|
const sitemapUrl = node_path_1.default.resolve(o.context, o.sitemap);
|
|
146
143
|
// eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports
|
|
147
144
|
let source = require(sitemapUrl);
|
|
148
|
-
if ((0,
|
|
145
|
+
if ((0, lodash_es_1.isFunction)(source))
|
|
149
146
|
source = source();
|
|
150
147
|
const sm = new sitemap_1.SitemapStream();
|
|
151
148
|
source.forEach((item) => sm.write(item));
|
|
@@ -209,7 +206,7 @@ function configFactory(ops) {
|
|
|
209
206
|
plugins.push(new webpack_1.ProgressPlugin());
|
|
210
207
|
/* Adds InjectManifest plugin from WorkBox, if opted to. */
|
|
211
208
|
if (o.workbox) {
|
|
212
|
-
if (!(0,
|
|
209
|
+
if (!(0, lodash_es_1.isObject)(o.workbox))
|
|
213
210
|
o.workbox = {};
|
|
214
211
|
plugins.push(new workbox_webpack_plugin_1.default.InjectManifest(Object.assign(Object.assign({ swSrc: node_path_1.default.resolve(__dirname, '../workbox/default.js') }, o.workbox), { swDest: '__service-worker.js' })));
|
|
215
212
|
}
|
|
@@ -5,8 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
};
|
|
6
6
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
7
|
exports.default = configFactory;
|
|
8
|
-
const
|
|
9
|
-
const defaults_js_1 = __importDefault(require("lodash/defaults.js"));
|
|
8
|
+
const lodash_es_1 = require("lodash-es");
|
|
10
9
|
const mini_css_extract_plugin_1 = __importDefault(require("mini-css-extract-plugin"));
|
|
11
10
|
const react_refresh_webpack_plugin_1 = __importDefault(require("@pmmmwh/react-refresh-webpack-plugin"));
|
|
12
11
|
const webpack_1 = __importDefault(require("webpack"));
|
|
@@ -18,7 +17,7 @@ const app_base_1 = __importDefault(require("./app-base"));
|
|
|
18
17
|
* @param [ops.dontUseHmr]
|
|
19
18
|
*/
|
|
20
19
|
function configFactory(ops) {
|
|
21
|
-
const o = (0,
|
|
20
|
+
const o = (0, lodash_es_1.defaults)((0, lodash_es_1.clone)(ops), {
|
|
22
21
|
cssLocalIdent: '[package]___[path][name]___[local]___[hash:base64:6]',
|
|
23
22
|
});
|
|
24
23
|
const entry = ['@dr.pogodin/react-utils/build/development/client/init'];
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "1.47.0-alpha.
|
|
2
|
+
"version": "1.47.0-alpha.8",
|
|
3
3
|
"bin": {
|
|
4
4
|
"react-utils-build": "bin/build.js",
|
|
5
5
|
"react-utils-setup": "bin/setup.js"
|
|
@@ -8,13 +8,13 @@
|
|
|
8
8
|
"url": "https://github.com/birdofpreyru/react-utils/issues"
|
|
9
9
|
},
|
|
10
10
|
"dependencies": {
|
|
11
|
-
"@babel/runtime
|
|
11
|
+
"@babel/runtime": "^7.28.4",
|
|
12
12
|
"@dr.pogodin/babel-plugin-react-css-modules": "^6.13.8",
|
|
13
13
|
"@dr.pogodin/csurf": "^1.16.6",
|
|
14
14
|
"@dr.pogodin/js-utils": "^0.1.4",
|
|
15
15
|
"@dr.pogodin/react-global-state": "^0.21.1",
|
|
16
16
|
"@dr.pogodin/react-helmet": "^3.0.4",
|
|
17
|
-
"@dr.pogodin/react-themes": "^1.9.
|
|
17
|
+
"@dr.pogodin/react-themes": "^1.9.4",
|
|
18
18
|
"@jest/environment": "^30.2.0",
|
|
19
19
|
"axios": "^1.13.2",
|
|
20
20
|
"commander": "^14.0.2",
|
|
@@ -120,17 +120,16 @@
|
|
|
120
120
|
"workbox-webpack-plugin": "^7.3.0"
|
|
121
121
|
},
|
|
122
122
|
"engines": {
|
|
123
|
-
"node": ">=
|
|
124
|
-
"npm": ">=10"
|
|
123
|
+
"node": ">=22.21",
|
|
124
|
+
"npm": ">=10.9"
|
|
125
125
|
},
|
|
126
126
|
"main": "./build/production/index.js",
|
|
127
|
-
"source": "./src/index.ts",
|
|
128
127
|
"types": "./build/types-code/index.d.ts",
|
|
129
128
|
"exports": {
|
|
130
129
|
".": {
|
|
131
|
-
"
|
|
130
|
+
"types": "./build/types-code/index.d.ts",
|
|
131
|
+
"webpack": "./build/web/index.js",
|
|
132
132
|
"node": {
|
|
133
|
-
"webpack": "./build/web/index.js",
|
|
134
133
|
"development": "./build/development/index.js",
|
|
135
134
|
"default": "./build/production/index.js"
|
|
136
135
|
},
|
|
@@ -139,12 +138,24 @@
|
|
|
139
138
|
"types": "./build/types-code/index.d.ts"
|
|
140
139
|
}
|
|
141
140
|
},
|
|
141
|
+
"./client": {
|
|
142
|
+
"types": "./build/types-code/client/index.d.ts",
|
|
143
|
+
"default": "./build/web/client/index.js"
|
|
144
|
+
},
|
|
142
145
|
"./config/*": "./config/*.js",
|
|
143
146
|
"./config/eslint/*": "./config/eslint/*.mjs",
|
|
144
147
|
"./config/*.json": "./config/*.json",
|
|
145
148
|
"./global-styles": "./build/web/styles/global.scss",
|
|
146
|
-
"./jest":
|
|
149
|
+
"./jest": {
|
|
150
|
+
"types": "./build/types-code/shared/utils/jest/index.d.ts",
|
|
151
|
+
"default": "./build/production/shared/utils/jest/index.js"
|
|
152
|
+
},
|
|
147
153
|
"./mixins": "./build/web/styles/mixins.scss",
|
|
154
|
+
"./server": {
|
|
155
|
+
"types": "./build/types-code/server/index.d.ts",
|
|
156
|
+
"development": "./build/development/server/index.js",
|
|
157
|
+
"default": "./build/production/server/index.js"
|
|
158
|
+
},
|
|
148
159
|
"./build/development/client/init": "./build/development/client/init.js",
|
|
149
160
|
"./build/production/client/init": "./build/production/client/init.js",
|
|
150
161
|
"./jest-e2e-ssr-env": "./build/production/shared/utils/jest/E2eSsrEnv.js"
|
package/src/client/getInj.ts
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
// Encapsulates retrieval of server-side data injection into HTML template.
|
|
2
|
-
|
|
3
|
-
/* global document */
|
|
4
|
-
|
|
5
|
-
import type { InjT } from 'utils/globalState';
|
|
6
|
-
|
|
7
|
-
import { getBuildInfo } from 'utils/isomorphy/buildInfo';
|
|
8
|
-
|
|
9
|
-
let inj: InjT | Promise<InjT> | undefined;
|
|
10
|
-
|
|
11
|
-
export default function getInj(): InjT | Promise<InjT> {
|
|
12
|
-
inj ??= (async () => {
|
|
13
|
-
const metaElement: HTMLMetaElement | null = typeof document === 'undefined'
|
|
14
|
-
? null : document.querySelector('meta[itemprop="drpruinj"]');
|
|
15
|
-
|
|
16
|
-
if (metaElement) {
|
|
17
|
-
metaElement.remove();
|
|
18
|
-
|
|
19
|
-
// NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be
|
|
20
|
-
// preferred, but it is not supported by older environments yet.
|
|
21
|
-
const data = atob(metaElement.content);
|
|
22
|
-
|
|
23
|
-
// TODO: Our current handling of this encryption / decryption follows
|
|
24
|
-
// a legacy approach, and can be enhanced by using Crypto features.
|
|
25
|
-
// Though, this is not strictly intended to be secure (it is more
|
|
26
|
-
// to obfurscate injected data, rather than really keeping them
|
|
27
|
-
// secure), thus it is fine like this for now.
|
|
28
|
-
const { key } = getBuildInfo();
|
|
29
|
-
|
|
30
|
-
const code = (x: string) => x.charCodeAt(0);
|
|
31
|
-
const dataBuffer = Uint8Array.from(data.slice(16), code);
|
|
32
|
-
const ivBuffer = Uint8Array.from(data.slice(0, 16), code);
|
|
33
|
-
const keyBuffer = Uint8Array.from(atob(key), code);
|
|
34
|
-
|
|
35
|
-
const cKey = await window.crypto.subtle.importKey(
|
|
36
|
-
'raw',
|
|
37
|
-
keyBuffer,
|
|
38
|
-
{ name: 'AES-CBC' },
|
|
39
|
-
false,
|
|
40
|
-
['decrypt'],
|
|
41
|
-
);
|
|
42
|
-
|
|
43
|
-
const buffer = await window.crypto.subtle.decrypt({
|
|
44
|
-
iv: ivBuffer,
|
|
45
|
-
name: 'AES-CBC',
|
|
46
|
-
}, cKey, dataBuffer);
|
|
47
|
-
|
|
48
|
-
const decoder = new TextDecoder();
|
|
49
|
-
|
|
50
|
-
// eslint-disable-next-line no-eval
|
|
51
|
-
const res = eval(`(${decoder.decode(buffer)})`) as InjT;
|
|
52
|
-
|
|
53
|
-
// NOTE: This is important, to be able to return the injection
|
|
54
|
-
// synchronously once it is initialized.
|
|
55
|
-
inj = res;
|
|
56
|
-
|
|
57
|
-
return res;
|
|
58
|
-
} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {
|
|
59
|
-
const res = window.REACT_UTILS_INJECTION;
|
|
60
|
-
delete window.REACT_UTILS_INJECTION;
|
|
61
|
-
return res;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
// Otherwise, a bunch of dependent stuff will easily fail in non-standard
|
|
65
|
-
// environments, where no client-side initialization is performed. Like tests,
|
|
66
|
-
// Docusaurus examples, etc.
|
|
67
|
-
return {};
|
|
68
|
-
})();
|
|
69
|
-
|
|
70
|
-
return inj;
|
|
71
|
-
}
|
package/src/client/index.tsx
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
// Initialization of client-side code.
|
|
2
|
-
/* global document */
|
|
3
|
-
|
|
4
|
-
import type { ComponentType } from 'react';
|
|
5
|
-
import { createRoot, hydrateRoot } from 'react-dom/client';
|
|
6
|
-
import { HelmetProvider } from '@dr.pogodin/react-helmet';
|
|
7
|
-
import { BrowserRouter } from 'react-router';
|
|
8
|
-
|
|
9
|
-
import { GlobalStateProvider } from '@dr.pogodin/react-global-state';
|
|
10
|
-
|
|
11
|
-
import getInj from './getInj';
|
|
12
|
-
|
|
13
|
-
type OptionsT = {
|
|
14
|
-
dontHydrate?: boolean;
|
|
15
|
-
initialState?: unknown;
|
|
16
|
-
};
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Prepares and launches the app at client side.
|
|
20
|
-
* @param Application Root application component
|
|
21
|
-
* @param [options={}] Optional. Additional settings.
|
|
22
|
-
*/
|
|
23
|
-
export default async function Launch(
|
|
24
|
-
Application: ComponentType,
|
|
25
|
-
options: OptionsT = {},
|
|
26
|
-
): Promise<void> {
|
|
27
|
-
const inj = await getInj();
|
|
28
|
-
|
|
29
|
-
const container = document.getElementById('react-view');
|
|
30
|
-
if (!container) throw Error('Failed to find container for React app');
|
|
31
|
-
const scene = (
|
|
32
|
-
<GlobalStateProvider initialState={inj.ISTATE ?? options.initialState}>
|
|
33
|
-
<BrowserRouter>
|
|
34
|
-
<HelmetProvider>
|
|
35
|
-
<Application />
|
|
36
|
-
</HelmetProvider>
|
|
37
|
-
</BrowserRouter>
|
|
38
|
-
</GlobalStateProvider>
|
|
39
|
-
);
|
|
40
|
-
|
|
41
|
-
if (options.dontHydrate) {
|
|
42
|
-
const root = createRoot(container);
|
|
43
|
-
root.render(scene);
|
|
44
|
-
} else hydrateRoot(container, scene);
|
|
45
|
-
}
|
package/src/client/init.ts
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Initialization of client-side environment.
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
/* global window */
|
|
6
|
-
|
|
7
|
-
import { type BuildInfoT, getBuildInfo } from 'utils/isomorphy/buildInfo';
|
|
8
|
-
|
|
9
|
-
const buildInfo = getBuildInfo();
|
|
10
|
-
|
|
11
|
-
// TODO: Should be moved into buildInfo module?
|
|
12
|
-
declare global {
|
|
13
|
-
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
14
|
-
interface Window {
|
|
15
|
-
__DEV_BUILD_INFO__: BuildInfoT | undefined;
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
declare const BUILD_INFO: BuildInfoT | undefined;
|
|
20
|
-
|
|
21
|
-
if (process.env.NODE_ENV !== 'production') {
|
|
22
|
-
// eslint-disable-next-line no-console
|
|
23
|
-
console.warn('Dev mode: "BUILD_INFO" attached to the global "window"');
|
|
24
|
-
|
|
25
|
-
// eslint-disable-next-line no-underscore-dangle
|
|
26
|
-
window.__DEV_BUILD_INFO__ = BUILD_INFO;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */
|
|
30
|
-
const { useServiceWorker } = buildInfo;
|
|
31
|
-
if (useServiceWorker) {
|
|
32
|
-
const { navigator } = window;
|
|
33
|
-
if ('serviceWorker' in navigator) {
|
|
34
|
-
window.addEventListener('load', () => {
|
|
35
|
-
void (async () => {
|
|
36
|
-
try {
|
|
37
|
-
// Note: no matter the "publicPath", we want to serve the service worker
|
|
38
|
-
// from the web app root, to allow it control any and all pages of the
|
|
39
|
-
// web app (otherwise, it will be restricted to the scope of its path).
|
|
40
|
-
// The server takes it into account.
|
|
41
|
-
const reg = await navigator
|
|
42
|
-
.serviceWorker.register('/__service-worker.js');
|
|
43
|
-
// eslint-disable-next-line no-console
|
|
44
|
-
console.log('SW registered:', reg);
|
|
45
|
-
} catch (err) {
|
|
46
|
-
// eslint-disable-next-line no-console
|
|
47
|
-
console.log('SW registration failed:', err);
|
|
48
|
-
}
|
|
49
|
-
})();
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
}
|
package/src/index.ts
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import 'styles/global.scss';
|
|
2
|
-
|
|
3
|
-
import clientModule from './client';
|
|
4
|
-
import { webpack } from './shared/utils';
|
|
5
|
-
|
|
6
|
-
import type * as ServerFactoryM from './server';
|
|
7
|
-
|
|
8
|
-
// It is a safeguard against multiple instances / versions of the library
|
|
9
|
-
// being loaded into environment by mistake (e.g. because of different
|
|
10
|
-
// packages pinning down different exact versions of the lib, thus preventing
|
|
11
|
-
// a proper dedupe and using a single common library version).
|
|
12
|
-
if (global.REACT_UTILS_LIBRARY_LOADED) {
|
|
13
|
-
throw Error('React utils library is already loaded');
|
|
14
|
-
} else global.REACT_UTILS_LIBRARY_LOADED = true;
|
|
15
|
-
|
|
16
|
-
// TODO: This is a rapid workaround to get rid of __dirname. I guess, later
|
|
17
|
-
// we'll re-implement requireWeak() to accept import.meta.url directly, and
|
|
18
|
-
// this workaround won't be needed.
|
|
19
|
-
// eslint-disable-next-line @typescript-eslint/prefer-destructuring
|
|
20
|
-
const dirname = import.meta.dirname;
|
|
21
|
-
|
|
22
|
-
const server = webpack.requireWeak<typeof ServerFactoryM>('./server', dirname);
|
|
23
|
-
|
|
24
|
-
const client = server ? undefined : clientModule;
|
|
25
|
-
|
|
26
|
-
export {
|
|
27
|
-
type AsyncCollectionT,
|
|
28
|
-
type AsyncCollectionLoaderT,
|
|
29
|
-
type AsyncDataEnvelopeT,
|
|
30
|
-
type AsyncDataLoaderT,
|
|
31
|
-
type ForceT,
|
|
32
|
-
type UseAsyncDataOptionsT,
|
|
33
|
-
type UseAsyncDataResT,
|
|
34
|
-
type UseGlobalStateResT,
|
|
35
|
-
type ValueOrInitializerT,
|
|
36
|
-
getGlobalState,
|
|
37
|
-
GlobalStateProvider,
|
|
38
|
-
newAsyncDataEnvelope,
|
|
39
|
-
useAsyncCollection,
|
|
40
|
-
useAsyncData,
|
|
41
|
-
useGlobalState,
|
|
42
|
-
withGlobalStateType,
|
|
43
|
-
} from '@dr.pogodin/react-global-state';
|
|
44
|
-
|
|
45
|
-
export * from 'components';
|
|
46
|
-
|
|
47
|
-
export {
|
|
48
|
-
type BeforeRenderResT,
|
|
49
|
-
type BeforeRenderT,
|
|
50
|
-
type ConfigT,
|
|
51
|
-
type ServerSsrContext,
|
|
52
|
-
type ServerT,
|
|
53
|
-
} from './server';
|
|
54
|
-
|
|
55
|
-
export {
|
|
56
|
-
assertEmptyObject,
|
|
57
|
-
Barrier,
|
|
58
|
-
Cached,
|
|
59
|
-
Emitter,
|
|
60
|
-
getConfig,
|
|
61
|
-
isomorphy,
|
|
62
|
-
getSsrContext,
|
|
63
|
-
type Listener,
|
|
64
|
-
type ObjectKey,
|
|
65
|
-
Semaphore,
|
|
66
|
-
splitComponent,
|
|
67
|
-
type Theme,
|
|
68
|
-
themed,
|
|
69
|
-
ThemeProvider,
|
|
70
|
-
time,
|
|
71
|
-
webpack,
|
|
72
|
-
withRetries,
|
|
73
|
-
} from 'utils';
|
|
74
|
-
|
|
75
|
-
export { client, server };
|