@dr.pogodin/react-utils 1.47.1 → 1.47.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/development/shared/utils/jest/E2eSsrEnv.js +20 -9
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +12 -9
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv.js +19 -9
- package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/package.json +3 -3
|
@@ -29,8 +29,7 @@ import JsdomEnv from 'jest-environment-jsdom';
|
|
|
29
29
|
import { Volume, createFsFromVolume } from 'memfs';
|
|
30
30
|
import webpack from 'webpack';
|
|
31
31
|
/* eslint-enable import/no-extraneous-dependencies */
|
|
32
|
-
|
|
33
|
-
import { setBuildInfo } from "../isomorphy/buildInfo.js";
|
|
32
|
+
|
|
34
33
|
function noop() {
|
|
35
34
|
// NOOP
|
|
36
35
|
}
|
|
@@ -39,7 +38,7 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
39
38
|
* Loads Webpack config, and exposes it to the environment via global
|
|
40
39
|
* webpackConfig object.
|
|
41
40
|
*/
|
|
42
|
-
loadWebpackConfig() {
|
|
41
|
+
async loadWebpackConfig() {
|
|
43
42
|
const optionsString = this.pragmas['webpack-config-options'];
|
|
44
43
|
const options = optionsString ? JSON.parse(optionsString) : {};
|
|
45
44
|
defaults(options, {
|
|
@@ -47,8 +46,8 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
47
46
|
fs: this.global.webpackOutputFs
|
|
48
47
|
});
|
|
49
48
|
const factoryPath = this.pragmas['webpack-config-factory'];
|
|
50
|
-
|
|
51
|
-
|
|
49
|
+
let factory = await import(/* webpackChunkName: "not-a-valid-chunk" */
|
|
50
|
+
path.resolve(this.rootDir, factoryPath));
|
|
52
51
|
factory = 'default' in factory ? factory.default : factory;
|
|
53
52
|
this.global.webpackConfig = factory(options);
|
|
54
53
|
const fs = this.global.webpackOutputFs;
|
|
@@ -64,7 +63,7 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
64
63
|
* @return {Promise}
|
|
65
64
|
*/
|
|
66
65
|
async runWebpack() {
|
|
67
|
-
this.loadWebpackConfig();
|
|
66
|
+
await this.loadWebpackConfig();
|
|
68
67
|
if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');
|
|
69
68
|
const compiler = webpack(this.global.webpackConfig);
|
|
70
69
|
if (!compiler) throw Error('Failed to construct Webpack compiler');
|
|
@@ -106,15 +105,17 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
106
105
|
let cleanup;
|
|
107
106
|
if (options.entry) {
|
|
108
107
|
const p = path.resolve(this.testFolder, options.entry);
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const module = require(p);
|
|
108
|
+
const module = await import(/* webpackChunkName: "not-a-valid-chunk" */
|
|
109
|
+
p);
|
|
112
110
|
if ('cleanup' in module) cleanup = module.cleanup;
|
|
113
111
|
const exportName = options.entryExportName || 'default';
|
|
114
112
|
if (exportName in module) {
|
|
115
113
|
options.Application = module[exportName];
|
|
116
114
|
}
|
|
117
115
|
}
|
|
116
|
+
const {
|
|
117
|
+
default: ssrFactory
|
|
118
|
+
} = await import(/* webpackChunkName: "not-a-valid-chunk" */"../../../server/renderer");
|
|
118
119
|
const renderer = ssrFactory(this.global.webpackConfig, options);
|
|
119
120
|
let status = 200; // OK
|
|
120
121
|
const markup = await new Promise((done, fail) => {
|
|
@@ -185,6 +186,13 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
185
186
|
default:
|
|
186
187
|
root = process.cwd();
|
|
187
188
|
}
|
|
189
|
+
|
|
190
|
+
// BEWARE: Anything imported prior to this register() call seems to be
|
|
191
|
+
// transpiled again by Babel if loaded after this call. This causes very
|
|
192
|
+
// confusing errors when testing the code dependent on some sort of contexts
|
|
193
|
+
// (because loading a module again effectively creates a new context object,
|
|
194
|
+
// which is not recognized by the code expecting another context instance).
|
|
195
|
+
// That's why below we prefer dynamic imports for some React Utils methods.
|
|
188
196
|
register({
|
|
189
197
|
envName: options.babelEnv,
|
|
190
198
|
extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],
|
|
@@ -208,6 +216,9 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
208
216
|
// triggers an error on the subsequent test using the environment.
|
|
209
217
|
// TODO: Look for a cleaner solution.
|
|
210
218
|
require.cache = {};
|
|
219
|
+
const {
|
|
220
|
+
setBuildInfo
|
|
221
|
+
} = await import(/* webpackChunkName: "not-a-valid-chunk" */"../isomorphy/buildInfo");
|
|
211
222
|
setBuildInfo(undefined, true);
|
|
212
223
|
if (this.withSsr) await this.runSsr();
|
|
213
224
|
this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;
|
|
@@ -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;AAC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AAC;IACFjG,QAAQ,CAACkG,MAAM,CAAC,CAAC;IACjB,MAAM,KAAK,CAACL,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"E2eSsrEnv.js","names":["path","defaults","set","register","JsdomEnv","Volume","createFsFromVolume","webpack","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","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","ssrFactory","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","require","cache","setBuildInfo","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\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 async loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n 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 const module = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n p\n ) as NodeJS.Module;\n\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 { default: ssrFactory } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */ 'server/renderer');\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\n // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n 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\n const { setBuildInfo } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */'../isomorphy/buildInfo');\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // 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,SAASC,IAAIA,CAAA,EAAG;EACd;AAAA;AAGF,eAAe,MAAMC,SAAS,SAASL,QAAQ,CAAC;EAa9C;AACF;AACA;AACA;EACE,MAAcM,iBAAiBA,CAAA,EAAG;IAChC,MAAMC,aAAa,GAAG,IAA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ignoreList":[]}
|
|
@@ -14,15 +14,14 @@ import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterat
|
|
|
14
14
|
// TODO: We need to add correct typing for environment options.
|
|
15
15
|
import path from"node:path";import{defaults,set}from"lodash-es";// As this environment is a part of the Jest testing utils,
|
|
16
16
|
// we assume development dependencies are available when it is used.
|
|
17
|
-
/* eslint-disable import/no-extraneous-dependencies */import register from"@babel/register/experimental-worker";import JsdomEnv from"jest-environment-jsdom";import{Volume,createFsFromVolume}from"memfs";import webpack from"webpack";/* eslint-enable import/no-extraneous-dependencies */
|
|
17
|
+
/* eslint-disable import/no-extraneous-dependencies */import register from"@babel/register/experimental-worker";import JsdomEnv from"jest-environment-jsdom";import{Volume,createFsFromVolume}from"memfs";import webpack from"webpack";/* eslint-enable import/no-extraneous-dependencies */function noop(){// NOOP
|
|
18
18
|
}export default class E2eSsrEnv extends JsdomEnv{/**
|
|
19
19
|
* Loads Webpack config, and exposes it to the environment via global
|
|
20
20
|
* webpackConfig object.
|
|
21
|
-
*/loadWebpackConfig(){const optionsString=this.pragmas["webpack-config-options"];const options=optionsString?JSON.parse(optionsString):{};defaults(options,{context:this.testFolder,fs:this.global.webpackOutputFs});const factoryPath=this.pragmas["webpack-config-factory"]
|
|
22
|
-
let factory=require(path.resolve(this.rootDir,factoryPath));factory="default"in factory?factory.default:factory;this.global.webpackConfig=factory(options);const fs=this.global.webpackOutputFs;let buildInfo=`${options.context}/.build-info`;if(fs.existsSync(buildInfo)){buildInfo=fs.readFileSync(buildInfo,"utf8");this.global.buildInfo=JSON.parse(buildInfo)}}/**
|
|
21
|
+
*/async loadWebpackConfig(){const optionsString=this.pragmas["webpack-config-options"];const options=optionsString?JSON.parse(optionsString):{};defaults(options,{context:this.testFolder,fs:this.global.webpackOutputFs});const factoryPath=this.pragmas["webpack-config-factory"];let factory=await import(/* webpackChunkName: "not-a-valid-chunk" */path.resolve(this.rootDir,factoryPath));factory="default"in factory?factory.default:factory;this.global.webpackConfig=factory(options);const fs=this.global.webpackOutputFs;let buildInfo=`${options.context}/.build-info`;if(fs.existsSync(buildInfo)){buildInfo=fs.readFileSync(buildInfo,"utf8");this.global.buildInfo=JSON.parse(buildInfo)}}/**
|
|
23
22
|
* Executes Webpack build.
|
|
24
23
|
* @return {Promise}
|
|
25
|
-
*/async runWebpack(){this.loadWebpackConfig();if(!this.global.webpackConfig)throw Error("Failed to load Webpack config");const compiler=webpack(this.global.webpackConfig);if(!compiler)throw Error("Failed to construct Webpack compiler");// TODO: The "as typeof compiler.outputFileSystem" piece below is
|
|
24
|
+
*/async runWebpack(){await this.loadWebpackConfig();if(!this.global.webpackConfig)throw Error("Failed to load Webpack config");const compiler=webpack(this.global.webpackConfig);if(!compiler)throw Error("Failed to construct Webpack compiler");// TODO: The "as typeof compiler.outputFileSystem" piece below is
|
|
26
25
|
// a workaround for the Webpack regression:
|
|
27
26
|
// https://github.com/webpack/webpack/issues/18242
|
|
28
27
|
compiler.outputFileSystem=this.global.webpackOutputFs;return new Promise((done,fail)=>{compiler.run((err,stats)=>{if(err)fail(err);if(stats?.hasErrors()){// eslint-disable-next-line no-console
|
|
@@ -30,9 +29,7 @@ console.error(stats.toJson().errors);fail(Error("Webpack compilation failed"))}t
|
|
|
30
29
|
// explicitly passed to the server-side renderer alongside the request,
|
|
31
30
|
// so that it can to pick up asset paths for different named chunks.
|
|
32
31
|
this.webpackStats=stats;done()})})}async runSsr(){const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON.parse(optionsString):{};// TODO: This is temporary to shortcut the logging added to SSR.
|
|
33
|
-
options.logger??={debug:noop,info:noop,log:noop,warn:noop};options.buildInfo??=this.global.buildInfo;let cleanup;if(options.entry){const p=path.resolve(this.testFolder,options.entry)
|
|
34
|
-
// eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports
|
|
35
|
-
const module=require(p);if("cleanup"in module)cleanup=module.cleanup;const exportName=options.entryExportName||"default";if(exportName in module){options.Application=module[exportName]}}const renderer=ssrFactory(this.global.webpackConfig,options);let status=200;// OK
|
|
32
|
+
options.logger??={debug:noop,info:noop,log:noop,warn:noop};options.buildInfo??=this.global.buildInfo;let cleanup;if(options.entry){const p=path.resolve(this.testFolder,options.entry);const module=await import(/* webpackChunkName: "not-a-valid-chunk" */p);if("cleanup"in module)cleanup=module.cleanup;const exportName=options.entryExportName||"default";if(exportName in module){options.Application=module[exportName]}}const{default:ssrFactory}=await import(/* webpackChunkName: "not-a-valid-chunk" */"../../../server/renderer");const renderer=ssrFactory(this.global.webpackConfig,options);let status=200;// OK
|
|
36
33
|
const markup=await new Promise((done,fail)=>{void renderer(this.ssrRequest,// TODO: This will do for now, with the current implementation of
|
|
37
34
|
// the renderer, but it will require a rework once the renderer is
|
|
38
35
|
// updated to do streaming.
|
|
@@ -45,7 +42,13 @@ if(error)fail(error);else done("")})});this.global.ssrMarkup=markup;this.global.
|
|
|
45
42
|
set(config.projectConfig,"testEnvironmentOptions.url",`http://localhost${request.url}`);super(config,context);this.global.dom=this.dom;this.global.webpackOutputFs=createFsFromVolume(new Volume);// Extracts necessary settings from config and context.
|
|
46
43
|
const{projectConfig}=config;this.rootDir=projectConfig.rootDir;this.testFolder=path.dirname(context.testPath);this.withSsr=!pragmas["no-ssr"];this.ssrRequest=request;this.pragmas=pragmas;// The usual "babel-jest" transformation setup does not apply to
|
|
47
44
|
// the environment code and imports from it, this workaround enables it.
|
|
48
|
-
const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON.parse(optionsString):{};let root;switch(options.root){case"TEST":root=this.testFolder;break;default:root=process.cwd()}
|
|
45
|
+
const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON.parse(optionsString):{};let root;switch(options.root){case"TEST":root=this.testFolder;break;default:root=process.cwd()}// BEWARE: Anything imported prior to this register() call seems to be
|
|
46
|
+
// transpiled again by Babel if loaded after this call. This causes very
|
|
47
|
+
// confusing errors when testing the code dependent on some sort of contexts
|
|
48
|
+
// (because loading a module again effectively creates a new context object,
|
|
49
|
+
// which is not recognized by the code expecting another context instance).
|
|
50
|
+
// That's why below we prefer dynamic imports for some React Utils methods.
|
|
51
|
+
register({envName:options.babelEnv,extensions:[".js",".jsx",".ts",".tsx",".svg"],root})}async setup(){await super.setup();await this.runWebpack();// NOTE: It is possible that the Webpack run above, and the SSR run below
|
|
49
52
|
// load different versions of the same module (CommonJS, and ES), and it may
|
|
50
53
|
// cause very confusing problems (e.g. see:
|
|
51
54
|
// https://github.com/birdofpreyru/react-utils/issues/413).
|
|
@@ -57,7 +60,7 @@ const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON
|
|
|
57
60
|
// build info to undefined, because ES module version not beeing reset
|
|
58
61
|
// triggers an error on the subsequent test using the environment.
|
|
59
62
|
// TODO: Look for a cleaner solution.
|
|
60
|
-
require.cache={};setBuildInfo(undefined,true);if(this.withSsr)await this.runSsr();this.global.REACT_UTILS_FORCE_CLIENT_SIDE=true}async teardown(){delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;// Resets module cache and @babel/register. Effectively this ensures that
|
|
63
|
+
require.cache={};const{setBuildInfo}=await import(/* webpackChunkName: "not-a-valid-chunk" */"../isomorphy/buildInfo");setBuildInfo(undefined,true);if(this.withSsr)await this.runSsr();this.global.REACT_UTILS_FORCE_CLIENT_SIDE=true}async teardown(){delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;// Resets module cache and @babel/register. Effectively this ensures that
|
|
61
64
|
// the next time an instance of this environment is set up, all modules are
|
|
62
65
|
// transformed by Babel from scratch, thus taking into account the latest
|
|
63
66
|
// Babel config (which may change between different environment instances,
|
|
@@ -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":"mJAAA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA,MAAO,CAAAA,IAAI,KAAM,WAAW,CAI5B,OAASC,QAAQ,CAAEC,GAAG,KAAQ,WAAW,CAIzC;AACA;AACA,sDACA,MAAO,CAAAC,QAAQ,KAAM,qCAAqC,CAE1D,MAAO,CAAAC,QAAQ,KAAM,wBAAwB,CAC7C,OAASC,MAAM,CAAEC,kBAAkB,KAAQ,OAAO,CAClD,MAAO,CAAAC,OAAO,KAA8B,SAAS,CACrD,2DAOO,CAAAC,UAAU,0CAERC,YAAY,iCAErB,QAAS,CAAAC,IAAIA,CAAA,CAAG,CACd;AAAA,CAGF,cAAe,MAAM,CAAAC,SAAS,QAAS,CAAAP,QAAS,CAa9C;AACF;AACA;AACA,KACUQ,iBAAiBA,CAAA,CAAG,CAC1B,KAAM,CAAAC,aAAa,CAAG,IAAI,CAACC,OAAO,CAAC,wBAAwB,CAAW,CAEtE,KAAM,CAAAC,OAAO,CAAIF,aAAa,CAAGG,IAAI,CAACC,KAAK,CAACJ,aAAa,CAAC,CAAG,CAAC,CACvC,CAEvBZ,QAAQ,CAACc,OAAO,CAAE,CAChBG,OAAO,CAAE,IAAI,CAACC,UAAU,CACxBC,EAAE,CAAE,IAAI,CAACC,MAAM,CAACC,eAClB,CAAC,CAAC,CAEF,KAAM,CAAAC,WAAW,CAAG,IAAI,CAACT,OAAO,CAAC,wBAAwB,CAAW,CACpE;AACA,GAAI,CAAAU,OAAO,CAAGC,OAAO,CAACzB,IAAI,CAAC0B,OAAO,CAAC,IAAI,CAACC,OAAO,CAAEJ,WAAW,CAAC,CAGzD,CACJC,O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UAAU,CAAC,CAAC,CAEvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAR,OAAO,CAACoE,KAAK,CAAG,CAAC,CAAC,CAClBpF,YAAY,CAACqF,SAAS,CAAE,IAAI,CAAC,CAE7B,GAAI,IAAI,CAACT,OAAO,CAAE,KAAM,KAAI,CAACpC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC5B,MAAM,CAAC0E,6BAA6B,CAAG,IAC9C,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAkB,CAC9B,MAAO,KAAI,CAAC3E,MAAM,CAAC0E,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAACzE,OAAO,CAACoE,KAAK,CAAC,CAACM,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,CAAA3E,OAAO,CAACoE,KAAK,CAACO,GAAG,CAC1B,CAAC,CAAC,CACFjG,QAAQ,CAACkG,MAAM,CAAC,CAAC,CACjB,KAAM,MAAK,CAACL,QAAQ,CAAC,CACvB,CACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"E2eSsrEnv.js","names":["path","defaults","set","register","JsdomEnv","Volume","createFsFromVolume","webpack","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","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","ssrFactory","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","require","cache","setBuildInfo","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\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 async loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n 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 const module = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n p\n ) as NodeJS.Module;\n\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 { default: ssrFactory } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */ 'server/renderer');\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\n // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n 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\n const { setBuildInfo } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */'../isomorphy/buildInfo');\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // 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":"mJAAA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA,MAAO,CAAAA,IAAI,KAAM,WAAW,CAI5B,OAASC,QAAQ,CAAEC,GAAG,KAAQ,WAAW,CAIzC;AACA;AACA,sDACA,MAAO,CAAAC,QAAQ,KAAM,qCAAqC,CAE1D,MAAO,CAAAC,QAAQ,KAAM,wBAAwB,CAC7C,OAASC,MAAM,CAAEC,kBAAkB,KAAQ,OAAO,CAClD,MAAO,CAAAC,OAAO,KAA8B,SAAS,CACrD,qDAOA,QAAS,CAAAC,IAAIA,CAAA,CAAG,CACd;AAAA,CAGF,cAAe,MAAM,CAAAC,SAAS,QAAS,CAAAL,QAAS,CAa9C;AACF;AACA;AACA,KACE,KAAc,CAAAM,iBAAiBA,CAAA,CAAG,CAChC,KAAM,CAAAC,aAAa,CAAG,IAAI,CAACC,OAAO,CAAC,wBAAwB,CAAW,CAEtE,KAAM,CAAAC,OAAO,CAAIF,aAAa,CAAGG,IAAI,CAACC,KAAK,CAACJ,aAAa,CAAC,CAAG,CAAC,CACvC,CAEvBV,QAAQ,CAACY,OAAO,CAAE,CAChBG,OAAO,CAAE,IAAI,CAACC,UAAU,CACxBC,EAAE,CAAE,IAAI,CAACC,MAAM,CAACC,eAClB,CAAC,CAAC,CAEF,KAAM,CAAAC,WAAW,CAAG,IAAI,CAACT,OAAO,CAAC,wBAAwB,CAAW,CAEpE,GAAI,CAAAU,OAAO,CAAG,KAAM,OAAM,CAAC,2CACzBtB,IAAI,CAACuB,OAAO,CAAC,IAAI,CAACC,OAAO,CAAEH,WAAW,CACxC,CAEE,CAEFC,OAAO,CAAG,SAAS,EAAI,CAAAA,OAAO,CAAGA,OAAO,CAACG,OAAO,CAAGH,OAAO,CAE1D,IAAI,CAACH,MAAM,CAACO,aAAa,CAAGJ,OAAO,CAACT,OAAO,CA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vB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA6D,OAAO,CAACC,KAAK,CAAG,CAAC,CAAC,CAElB,KAAM,CAAEC,YAAa,CAAC,CAAG,KAAM,OAAM,CAAC,mEAAmE,CAAC,CAC1GA,YAAY,CAACC,SAAS,CAAE,IAAI,CAAC,CAE7B,GAAI,IAAI,CAACX,OAAO,CAAE,KAAM,KAAI,CAACrC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC3B,MAAM,CAAC4E,6BAA6B,CAAG,IAC9C,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAkB,CAC9B,MAAO,KAAI,CAAC7E,MAAM,CAAC4E,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAACP,OAAO,CAACC,KAAK,CAAC,CAACO,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,CAAAT,OAAO,CAACC,KAAK,CAACQ,GAAG,CAC1B,CAAC,CAAC,CACFjG,QAAQ,CAACkG,MAAM,CAAC,CAAC,CACjB,KAAM,MAAK,CAACL,QAAQ,CAAC,CACvB,CACF","ignoreList":[]}
|
|
@@ -29,8 +29,6 @@ import { Volume, createFsFromVolume } from 'memfs';
|
|
|
29
29
|
import webpack from 'webpack';
|
|
30
30
|
/* eslint-enable import/no-extraneous-dependencies */
|
|
31
31
|
|
|
32
|
-
import ssrFactory from "../../../server/renderer";
|
|
33
|
-
import { setBuildInfo } from "../isomorphy/buildInfo";
|
|
34
32
|
function noop() {
|
|
35
33
|
// NOOP
|
|
36
34
|
}
|
|
@@ -39,7 +37,7 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
39
37
|
* Loads Webpack config, and exposes it to the environment via global
|
|
40
38
|
* webpackConfig object.
|
|
41
39
|
*/
|
|
42
|
-
loadWebpackConfig() {
|
|
40
|
+
async loadWebpackConfig() {
|
|
43
41
|
const optionsString = this.pragmas['webpack-config-options'];
|
|
44
42
|
const options = optionsString ? JSON.parse(optionsString) : {};
|
|
45
43
|
defaults(options, {
|
|
@@ -47,8 +45,8 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
47
45
|
fs: this.global.webpackOutputFs
|
|
48
46
|
});
|
|
49
47
|
const factoryPath = this.pragmas['webpack-config-factory'];
|
|
50
|
-
|
|
51
|
-
|
|
48
|
+
let factory = await import(/* webpackChunkName: "not-a-valid-chunk" */
|
|
49
|
+
path.resolve(this.rootDir, factoryPath));
|
|
52
50
|
factory = 'default' in factory ? factory.default : factory;
|
|
53
51
|
this.global.webpackConfig = factory(options);
|
|
54
52
|
const fs = this.global.webpackOutputFs;
|
|
@@ -64,7 +62,7 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
64
62
|
* @return {Promise}
|
|
65
63
|
*/
|
|
66
64
|
async runWebpack() {
|
|
67
|
-
this.loadWebpackConfig();
|
|
65
|
+
await this.loadWebpackConfig();
|
|
68
66
|
if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');
|
|
69
67
|
const compiler = webpack(this.global.webpackConfig);
|
|
70
68
|
if (!compiler) throw Error('Failed to construct Webpack compiler');
|
|
@@ -106,15 +104,17 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
106
104
|
let cleanup;
|
|
107
105
|
if (options.entry) {
|
|
108
106
|
const p = path.resolve(this.testFolder, options.entry);
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const module = require(p);
|
|
107
|
+
const module = await import(/* webpackChunkName: "not-a-valid-chunk" */
|
|
108
|
+
p);
|
|
112
109
|
if ('cleanup' in module) cleanup = module.cleanup;
|
|
113
110
|
const exportName = options.entryExportName || 'default';
|
|
114
111
|
if (exportName in module) {
|
|
115
112
|
options.Application = module[exportName];
|
|
116
113
|
}
|
|
117
114
|
}
|
|
115
|
+
const {
|
|
116
|
+
default: ssrFactory
|
|
117
|
+
} = await import(/* webpackChunkName: "not-a-valid-chunk" */"../../../server/renderer");
|
|
118
118
|
const renderer = ssrFactory(this.global.webpackConfig, options);
|
|
119
119
|
let status = 200; // OK
|
|
120
120
|
const markup = await new Promise((done, fail) => {
|
|
@@ -185,6 +185,13 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
185
185
|
default:
|
|
186
186
|
root = process.cwd();
|
|
187
187
|
}
|
|
188
|
+
|
|
189
|
+
// BEWARE: Anything imported prior to this register() call seems to be
|
|
190
|
+
// transpiled again by Babel if loaded after this call. This causes very
|
|
191
|
+
// confusing errors when testing the code dependent on some sort of contexts
|
|
192
|
+
// (because loading a module again effectively creates a new context object,
|
|
193
|
+
// which is not recognized by the code expecting another context instance).
|
|
194
|
+
// That's why below we prefer dynamic imports for some React Utils methods.
|
|
188
195
|
register({
|
|
189
196
|
envName: options.babelEnv,
|
|
190
197
|
extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],
|
|
@@ -208,6 +215,9 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
208
215
|
// triggers an error on the subsequent test using the environment.
|
|
209
216
|
// TODO: Look for a cleaner solution.
|
|
210
217
|
require.cache = {};
|
|
218
|
+
const {
|
|
219
|
+
setBuildInfo
|
|
220
|
+
} = await import(/* webpackChunkName: "not-a-valid-chunk" */"../isomorphy/buildInfo");
|
|
211
221
|
setBuildInfo(undefined, true);
|
|
212
222
|
if (this.withSsr) await this.runSsr();
|
|
213
223
|
this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;
|
|
@@ -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,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,EAAE,EAAE,IAAI,CAACC,MAAM,CAACC;IAClB,CAAC,CAAC;IAEF,MAAMC,WAAW,GAAG,IAAI,CAACT,OAAO,CAAC,wBAAwB,CAAW;IACpE;IACA,IAAIU,OAAO,GAAGC,OAAO,CAACzB,IAAI,CAAC0B,OAAO,CAAC,IAAI,CAACC,OAAO,EAAEJ,WAAW,CAAC,CAGzD;IACJC,OAAO,GAAG,SAAS,IAAIA,OAAO,GAAGA,OAAO,CAACI,OAAO,GAAGJ,OAAO;IAE1D,IAAI,CAACH,MAAM,CAACQ,aAAa,GAAGL,OAAO,CAACT,OAAO,CAAC;IAE5C,MAAMK,EAAE,G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rC,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
|
+
{"version":3,"file":"E2eSsrEnv.js","names":["path","defaults","set","register","JsdomEnv","Volume","createFsFromVolume","webpack","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","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","ssrFactory","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","require","cache","setBuildInfo","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\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 async loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n 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 const module = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n p\n ) as NodeJS.Module;\n\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 { default: ssrFactory } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */ 'server/renderer');\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\n // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n 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\n const { setBuildInfo } = await import(/* webpackChunkName: \"not-a-valid-chunk\" */'../isomorphy/buildInfo');\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // 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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B,OAAO,IAAI,CAAC7E,MAAM,CAAC4E,6BAA6B;;IAEhD;IACA;IACA;IACA;IACA;IACA;IACAE,MAAM,CAACC,IAAI,CAACP,OAAO,CAACC,KAAK,CAAC,CAACO,OAAO,CAAEC,GAAG,IAAK;MAC1C,OAAOT,OAAO,CAACC,KAAK,CAACQ,GAAG,CAAC;IAC3B,CAAC,CAAC;IACFjG,QAAQ,CAACkG,MAAM,CAAC,CAAC;IACjB,MAAM,KAAK,CAACL,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "1.47.
|
|
2
|
+
"version": "1.47.2",
|
|
3
3
|
"bin": {
|
|
4
4
|
"react-utils-build": "bin/build.js",
|
|
5
5
|
"react-utils-setup": "bin/setup.js"
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
"@testing-library/dom": "^10.4.1",
|
|
61
61
|
"@testing-library/react": "^16.3.0",
|
|
62
62
|
"@testing-library/user-event": "^14.6.1",
|
|
63
|
-
"@tsconfig/recommended": "^1.0.
|
|
63
|
+
"@tsconfig/recommended": "^1.0.13",
|
|
64
64
|
"@types/compression": "^1.8.1",
|
|
65
65
|
"@types/config": "^3.3.5",
|
|
66
66
|
"@types/cookie": "^0.6.0",
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
"@types/lodash-es": "^4.17.12",
|
|
72
72
|
"@types/morgan": "^1.9.10",
|
|
73
73
|
"@types/pretty": "^2.0.3",
|
|
74
|
-
"@types/react": "^19.2.
|
|
74
|
+
"@types/react": "^19.2.4",
|
|
75
75
|
"@types/react-dom": "^19.2.3",
|
|
76
76
|
"@types/request-ip": "^0.0.41",
|
|
77
77
|
"@types/serialize-javascript": "^5.0.4",
|