@dr.pogodin/react-utils 1.51.1 → 1.51.3
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/server/server.js +1 -2
- package/build/development/server/server.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv/index.js +77 -12
- package/build/development/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv/ssr.js +38 -12
- package/build/development/shared/utils/jest/E2eSsrEnv/ssr.js.map +1 -1
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/production/server/server.js +2 -2
- package/build/production/server/server.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv/index.js +40 -10
- package/build/production/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv/ssr.js +13 -3
- package/build/production/shared/utils/jest/E2eSsrEnv/ssr.js.map +1 -1
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/types-code/shared/utils/jest/index.d.ts +1 -1
- package/build/web/server/server.js +2 -2
- package/build/web/server/server.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv/index.js +40 -10
- package/build/web/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv/ssr.js +13 -3
- package/build/web/shared/utils/jest/E2eSsrEnv/ssr.js.map +1 -1
- package/build/web/shared/utils/jest/index.js.map +1 -1
- package/config/jest/default.js +0 -1
- package/config/jest/setup.js +5 -0
- package/package.json +8 -9
|
@@ -14,7 +14,6 @@ import { cloneDeep, mapValues, pick } from "lodash-es";
|
|
|
14
14
|
import loggerMiddleware from "morgan";
|
|
15
15
|
import requestIp from "request-ip";
|
|
16
16
|
import favicon from "serve-favicon";
|
|
17
|
-
import { v4 as uuid } from "uuid";
|
|
18
17
|
import csrf from "@dr.pogodin/csurf";
|
|
19
18
|
import rendererFactory from "./renderer.js";
|
|
20
19
|
import { CODES, ERRORS, getErrorForCode, newError } from "./utils/errors.js"; // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
@@ -91,7 +90,7 @@ export default async function factory(webpackConfig, options) {
|
|
|
91
90
|
if (!options.noCsp) {
|
|
92
91
|
server.use((req, res, next) => {
|
|
93
92
|
const req2 = req;
|
|
94
|
-
req2.nonce =
|
|
93
|
+
req2.nonce = globalThis.crypto.randomUUID(); // TODO: This is deprecated, but it is kept for now for backward
|
|
95
94
|
// compatibility. Should be removed sometime later.
|
|
96
95
|
req2.cspNonce = req2.nonce; // The deep clone is necessary here to ensure that default value can't be
|
|
97
96
|
// mutated during request processing.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":["sep","pathToFileURL","compression","cookieParser","express","helmet","cloneDeep","mapValues","pick","loggerMiddleware","requestIp","favicon","v4","uuid","csrf","rendererFactory","CODES","ERRORS","getErrorForCode","newError","defaultCspSettings","directives","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","cspNonce","cspSettings","cspSettingsHook","send","json","limit","urlencoded","extended","cookieSignatureSecret","mw","cookie","ignoreRequest","csrfIgnoreRequest","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","process","cwd","default","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","NOT_FOUND","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport helmet, { type HelmetOptions } from 'helmet';\nimport { cloneDeep, mapValues, pick } from 'lodash-es';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport favicon from 'serve-favicon';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Configuration } from 'webpack';\n\nimport csrf from '@dr.pogodin/csurf';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => Promise<boolean> | boolean;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n csrfIgnoreRequest?: (req: Request) => boolean;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({\n cookie: true,\n ignoreRequest: options.csrfIgnoreRequest,\n }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const { default: webpack } = await import(/* webpackChunkName: \"server-side-code\" */ 'webpack');\n\n const { default: webpackDevMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-dev-middleware'\n );\n\n const { default: webpackHotMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-hot-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":";;;+CAAA;AACA;AACA;AAEA,SAASA,GAAG,QAAQ,WAAW;AAC/B,SAASC,aAAa,QAAQ,UAAU;AAExC,OAAOC,WAAW,MAAM,aAAa;AACrC,OAAOC,YAAY,MAAM,eAAe;AAExC,OAAOC,OAAO,MAKP,SAAS;AAEhB,OAAOC,MAAM,MAA8B,QAAQ;AACnD,SAASC,SAAS,EAAEC,SAAS,EAAEC,IAAI,QAAQ,WAAW;AACtD,OAAOC,gBAAgB,MAAM,QAAQ;AACrC,OAAOC,SAAS,MAAM,YAAY;AAClC,OAAOC,OAAO,MAAM,eAAe;AACnC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAIjC,OAAOC,IAAI,MAAM,mBAAmB;AAEpC,OAAOC,eAAe;AAAA,SAMpBC,KAAK,EACLC,MAAM,EACNC,eAAe,EACfC,QAAQ,6BAKV;AAMA;AACA;AACA;AACA;AACA,MAAMC,kBAAkB,GAAG;EACzBC,UAAU,EAAEd,SAAS,CACnBF,MAAM,CAACiB,qBAAqB,CAACC,oBAAoB,CAAC,CAAC;EAEnD;EACA;EACA;EACA;EACCC,KAAK,IAAMA,KAAK,CAAcC,MAAM,CAAEC,IAAY,IAAKA,IAAI,KAAK,QAAQ,CAC3E;AACF,CAAC;AACDN,kBAAkB,CAACC,UAAU,CAAC,WAAW,CAAC,GAAG,CAC3C,QAAQ;AAER;AACA;AACA,uBAAuB,CACxB;AAED;EACE,MAAMA,UAAU,GAAGD,kBAAkB,CAACC,UAAU,CAAC,YAAY,CAAC;EAC9D,IAAIA,UAAU,EAAEA,UAAU,CAACM,IAAI,CAAC,eAAe,CAAC,CAAC,KAC5CP,kBAAkB,CAACC,UAAU,CAAC,YAA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BAAoB,EAAE;IAChCD,6BAA6B,GAAG,MAAMhE,OAAO,CAACiE,oBAAoB,CAAC5D,MAAM,CAAC;EAC5E,CAEA;EACA,IAAI,CAAC2D,6BAA6B,EAAE;IAClC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA3D,MAAM,CAACI,GAAG,CAAC,CACTyD,KAEC,EACDxD,GAAY,EACZC,GAAa,EACbC,IAAkB,KACf;MACH;MACA;MACA,IAAID,GAAG,CAACwD,WAAW,EAAE;QACnBvD,IAAI,CAACsD,KAAK,CAAC;QACX;MACF;MAEA,MAAME,MAAM,GAAGF,KAAK,CAACE,MAAM,IAAInF,KAAK,CAACoF,qBAAqB;MAC1D,MAAMC,UAAU,GAAGF,MAAM,IAAKnF,KAAK,CAACoF,qBAAgC,CAEpE;MACArE,OAAO,CAACO,MAAM,CAAEgE,GAAG,CAACD,UAAU,GAAG,OAAO,GAAG,OAAO,EAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC;MAErE,IAAIC,OAAO,GAAGP,KAAK,CAACO,OAAO,IAAItF,eAAe,CAACiF,MAAM,CAAC;MACtD,IAAIE,UAAU,IAAIhB,OAAO,CAACoB,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACvDF,OAAO,GAAGvF,MAAM,CAACmF,qBAAqB;MACxC;MAEA1D,GAAG,CAACyD,MAAM,CAACA,MAAM,CAAC,CAACxC,IAAI,CAAC6C,OAAO,CAAC;IAClC,CAAC,CAAC;EACJ;EAEA,OAAOpE,MAAM;AACf","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"server.js","names":["sep","pathToFileURL","compression","cookieParser","express","helmet","cloneDeep","mapValues","pick","loggerMiddleware","requestIp","favicon","csrf","rendererFactory","CODES","ERRORS","getErrorForCode","newError","defaultCspSettings","directives","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","globalThis","crypto","randomUUID","cspNonce","cspSettings","cspSettingsHook","send","json","limit","urlencoded","extended","cookieSignatureSecret","mw","cookie","ignoreRequest","csrfIgnoreRequest","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","process","cwd","default","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","NOT_FOUND","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport helmet, { type HelmetOptions } from 'helmet';\nimport { cloneDeep, mapValues, pick } from 'lodash-es';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport favicon from 'serve-favicon';\n\nimport type { Configuration } from 'webpack';\n\nimport csrf from '@dr.pogodin/csurf';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => Promise<boolean> | boolean;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n csrfIgnoreRequest?: (req: Request) => boolean;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = globalThis.crypto.randomUUID();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({\n cookie: true,\n ignoreRequest: options.csrfIgnoreRequest,\n }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const { default: webpack } = await import(/* webpackChunkName: \"server-side-code\" */ 'webpack');\n\n const { default: webpackDevMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-dev-middleware'\n );\n\n const { default: webpackHotMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-hot-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":";;;+CAAA;AACA;AACA;AAEA,SAASA,GAAG,QAAQ,WAAW;AAC/B,SAASC,aAAa,QAAQ,UAAU;AAExC,OAAOC,WAAW,MAAM,aAAa;AACrC,OAAOC,YAAY,MAAM,eAAe;AAExC,OAAOC,OAAO,MAKP,SAAS;AAEhB,OAAOC,MAAM,MAA8B,QAAQ;AACnD,SAASC,SAAS,EAAEC,SAAS,EAAEC,IAAI,QAAQ,WAAW;AACtD,OAAOC,gBAAgB,MAAM,QAAQ;AACrC,OAAOC,SAAS,MAAM,YAAY;AAClC,OAAOC,OAAO,MAAM,eAAe;AAInC,OAAOC,IAAI,MAAM,mBAAmB;AAEpC,OAAOC,eAAe;AAAA,SAMpBC,KAAK,EACLC,MAAM,EACNC,eAAe,EACfC,QAAQ,6BAKV;AAMA;AACA;AACA;AACA;AACA,MAAMC,kBA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B,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACvDF,OAAO,GAAG1F,MAAM,CAACsF,qBAAqB;MACxC;MAEA7D,GAAG,CAAC4D,MAAM,CAACA,MAAM,CAAC,CAACxC,IAAI,CAAC6C,OAAO,CAAC;IAClC,CAAC,CAAC;EACJ;EAEA,OAAOvE,MAAM;AACf","ignoreList":[]}
|
|
@@ -19,13 +19,29 @@ import "core-js/modules/es.json.parse.js"; /**
|
|
|
19
19
|
// we assume development dependencies are available when it is used.
|
|
20
20
|
/* eslint-disable import/no-extraneous-dependencies */
|
|
21
21
|
import { fork } from "node:child_process";
|
|
22
|
+
import { access } from "node:fs/promises";
|
|
22
23
|
import path from "node:path";
|
|
23
24
|
import JsdomEnv from "jest-environment-jsdom";
|
|
24
25
|
import { defaults, set } from "lodash-es";
|
|
25
26
|
import { Volume, createFsFromVolume } from "memfs";
|
|
26
27
|
import webpack from "webpack";
|
|
28
|
+
import register from "@babel/register/experimental-worker";
|
|
27
29
|
import { deduceChunkGroups } from "../../../../server/renderer.js";
|
|
28
|
-
|
|
30
|
+
async function findModule(module) {
|
|
31
|
+
try {
|
|
32
|
+
const res = `${module}.ts`;
|
|
33
|
+
await access(res);
|
|
34
|
+
return res;
|
|
35
|
+
} catch {// NOOP
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
const res = `${module}.js`;
|
|
39
|
+
await access(res);
|
|
40
|
+
return res;
|
|
41
|
+
} catch {// NOOP
|
|
42
|
+
}
|
|
43
|
+
throw Error(`Module "${module}" was not found, neither as TS, nor as JS`);
|
|
44
|
+
}
|
|
29
45
|
export default class E2eSsrEnv extends JsdomEnv {
|
|
30
46
|
/**
|
|
31
47
|
* Loads Webpack config, and exposes it to the environment via global
|
|
@@ -76,21 +92,30 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
76
92
|
});
|
|
77
93
|
}
|
|
78
94
|
async runSsr() {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
95
|
+
// NOTE: These are TS modules in the source code, and they turn into JS
|
|
96
|
+
// modules in the distributed code, after Babel compilation. As we rely
|
|
97
|
+
// on them for the forked NodeJS process, we need to resolve the correct
|
|
98
|
+
// extentions ourselves (as NodeJS will hit the given paths, without any
|
|
99
|
+
// additional resolutions / transformations).
|
|
100
|
+
const regModulePath = await findModule(`${import.meta.dirname}/register`);
|
|
101
|
+
const ssrModulePath = await findModule(`${import.meta.dirname}/ssr`);
|
|
102
|
+
const cp = fork(ssrModulePath, [], {
|
|
103
|
+
// NOTE: We have to preload this "register" module, to setup Babel
|
|
104
|
+
// transformation for the loaded "ssr.ts" module itself (I believe,
|
|
105
|
+
// it is relevant only when the source code is executed within
|
|
106
|
+
// the library codebase itself, as the distributed code already
|
|
107
|
+
// has "ssr.ts" transpiled).
|
|
108
|
+
execArgv: ["-r", regModulePath]
|
|
87
109
|
});
|
|
88
110
|
const optionsString = this.pragmas["ssr-options"];
|
|
89
111
|
const options = optionsString ? JSON.parse(optionsString) : {};
|
|
90
112
|
options.buildInfo ??= this.global.buildInfo;
|
|
91
113
|
if (!this.webpackStats) throw Error("Missing Webpack stats");
|
|
92
114
|
options.chunkGroups = deduceChunkGroups(this.webpackStats);
|
|
93
|
-
return new Promise(resolve => {
|
|
115
|
+
return new Promise((resolve, reject) => {
|
|
116
|
+
cp.on("exit", code => {
|
|
117
|
+
if (code) reject(Error("SSR process crashed"));
|
|
118
|
+
});
|
|
94
119
|
cp.on("message", message => {
|
|
95
120
|
this.global.ssrMarkup = message.markup;
|
|
96
121
|
this.global.ssrOptions = options;
|
|
@@ -124,11 +149,50 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
124
149
|
this.testFolder = path.dirname(context.testPath);
|
|
125
150
|
this.withSsr = !pragmas["no-ssr"];
|
|
126
151
|
this.ssrRequest = request;
|
|
127
|
-
this.pragmas = pragmas;
|
|
152
|
+
this.pragmas = pragmas; // The usual "babel-jest" transformation setup does not apply to
|
|
153
|
+
// the environment code and imports from it, this workaround enables it.
|
|
154
|
+
const optionsString = this.pragmas["ssr-options"];
|
|
155
|
+
const options = optionsString ? JSON.parse(optionsString) : {};
|
|
156
|
+
let root;
|
|
157
|
+
switch (options.root) {
|
|
158
|
+
case "TEST":
|
|
159
|
+
root = this.testFolder;
|
|
160
|
+
break;
|
|
161
|
+
default:
|
|
162
|
+
root = process.cwd();
|
|
163
|
+
} // BEWARE: Anything imported prior to this register() call seems to be
|
|
164
|
+
// transpiled again by Babel if loaded after this call. This causes very
|
|
165
|
+
// confusing errors when testing the code dependent on some sort of contexts
|
|
166
|
+
// (because loading a module again effectively creates a new context object,
|
|
167
|
+
// which is not recognized by the code expecting another context instance).
|
|
168
|
+
// That's why below we prefer dynamic imports for some React Utils methods.
|
|
169
|
+
// BEWARE: Although we also do the registration inside SSR testing code,
|
|
170
|
+
// we still need it here to correctly process imported Webpack configurations
|
|
171
|
+
// (which are imported directly from this module).
|
|
172
|
+
register({
|
|
173
|
+
envName: options.babelEnv,
|
|
174
|
+
extensions: [".js", ".jsx", ".ts", ".tsx", ".svg"],
|
|
175
|
+
root
|
|
176
|
+
});
|
|
128
177
|
}
|
|
129
178
|
async setup() {
|
|
130
179
|
await super.setup();
|
|
131
|
-
await this.runWebpack();
|
|
180
|
+
await this.runWebpack(); // NOTE: It is possible that the Webpack run above, and the SSR run below
|
|
181
|
+
// load different versions of the same module (CommonJS, and ES), and it may
|
|
182
|
+
// cause very confusing problems (e.g. see:
|
|
183
|
+
// https://github.com/birdofpreyru/react-utils/issues/413).
|
|
184
|
+
// It seems we can't reset the cache of ES modules, and Jest's module reset
|
|
185
|
+
// does not reset modules loaded in this enviroment module, and also only
|
|
186
|
+
// replacing entire cache object by and empty {} seems to help (in contrast
|
|
187
|
+
// to deleting all entries by their keys, as it is done within .teardown()
|
|
188
|
+
// method below). Thus, for now we do this as a hotfix, and we also reset
|
|
189
|
+
// build info to undefined, because ES module version not beeing reset
|
|
190
|
+
// triggers an error on the subsequent test using the environment.
|
|
191
|
+
// TODO: Look for a cleaner solution.
|
|
192
|
+
require.cache = {}; // eslint-disable-next-line import/dynamic-import-chunkname
|
|
193
|
+
const {
|
|
194
|
+
setBuildInfo
|
|
195
|
+
} = await import("../../isomorphy/buildInfo");
|
|
132
196
|
setBuildInfo(undefined, true);
|
|
133
197
|
if (this.withSsr) await this.runSsr();
|
|
134
198
|
this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;
|
|
@@ -143,6 +207,7 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
143
207
|
Object.keys(require.cache).forEach(key => {
|
|
144
208
|
delete require.cache[key];
|
|
145
209
|
});
|
|
210
|
+
register.revert();
|
|
146
211
|
await super.teardown();
|
|
147
212
|
}
|
|
148
213
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["fork","path","JsdomEnv","defaults","set","Volume","createFsFromVolume","webpack","deduceChunkGroups","setBuildInfo","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","cp","import","meta","dirname","execArgv","chunkGroups","on","message","ssrMarkup","markup","ssrOptions","ssrStatus","status","kill","send","root","process","cwd","ssrRequest","constructor","config","docblockPragmas","requestString","request","url","projectConfig","dom","testPath","withSsr","setup","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","require","cache","forEach","key"],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/index.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\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 */\n\nimport { fork } from 'node:child_process';\nimport path from 'node:path';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration, type Stats } from 'webpack';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport { deduceChunkGroups } from 'server/renderer';\n\nimport { setBuildInfo } from '../../isomorphy/buildInfo';\n\nimport type { LaunchT, ResultT } from './ssr';\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?: Stats;\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\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 cp = fork(`${import.meta.dirname}/ssr.ts`, [], {\n // NOTE: This ensures the forked \"ssr.ts\" module is pre-processed by\n // Babel, which is necessary to correctly resolve paths to modules it\n // loads, as we rely on Babel aliasing module paths; and we need to have\n // a little \"register.ts\" module (rather than just a command-line argument)\n // because we need to specify to Babel that \".ts\", \".tsx\", etc. files\n // need to be processed, in addition to the standard JS modules.\n execArgv: ['-r', `${import.meta.dirname}/register.ts`],\n });\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve) => {\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\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\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\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\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\n await super.teardown();\n }\n}\n"],"mappings":";;;0CAAA;AACA;AACA;AACA;AACA;AACA,6CALA,CAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAEA,SAASA,IAAI,QAAQ,oBAAoB;AACzC,OAAOC,IAAI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BAA6B,CAEhD;IACA;IACA;IACA;IACA;IACA;IACAE,MAAM,CAACC,IAAI,CAACC,OAAO,CAACC,KAAK,CAAC,CAACC,OAAO,CAAEC,GAAG,IAAK;MAC1C,OAAOH,OAAO,CAACC,KAAK,CAACE,GAAG,CAAC;IAC3B,CAAC,CAAC;IAEF,MAAM,KAAK,CAACN,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["fork","access","path","JsdomEnv","defaults","set","Volume","createFsFromVolume","webpack","register","deduceChunkGroups","findModule","module","res","Error","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","regModulePath","import","meta","dirname","ssrModulePath","cp","execArgv","chunkGroups","reject","on","code","message","ssrMarkup","markup","ssrOptions","ssrStatus","status","kill","send","root","process","cwd","ssrRequest","constructor","config","docblockPragmas","requestString","request","url","projectConfig","dom","testPath","withSsr","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/index.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\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 */\n\nimport { fork } from 'node:child_process';\nimport { access } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration, type Stats } from 'webpack';\n\nimport register from '@babel/register/experimental-worker';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport { deduceChunkGroups } from 'server/renderer';\n\nimport type { LaunchT, ResultT } from './ssr';\n\nasync function findModule(module: string): Promise<string> {\n try {\n const res = `${module}.ts`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n try {\n const res = `${module}.js`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n throw Error(`Module \"${module}\" was not found, neither as TS, nor as JS`);\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?: Stats;\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\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 // NOTE: These are TS modules in the source code, and they turn into JS\n // modules in the distributed code, after Babel compilation. As we rely\n // on them for the forked NodeJS process, we need to resolve the correct\n // extentions ourselves (as NodeJS will hit the given paths, without any\n // additional resolutions / transformations).\n const regModulePath = await findModule(`${import.meta.dirname}/register`);\n const ssrModulePath = await findModule(`${import.meta.dirname}/ssr`);\n\n const cp = fork(ssrModulePath, [], {\n // NOTE: We have to preload this \"register\" module, to setup Babel\n // transformation for the loaded \"ssr.ts\" module itself (I believe,\n // it is relevant only when the source code is executed within\n // the library codebase itself, as the distributed code already\n // has \"ssr.ts\" transpiled).\n execArgv: ['-r', regModulePath],\n });\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve, reject) => {\n cp.on('exit', (code) => {\n if (code) reject(Error('SSR process crashed'));\n });\n\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\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\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 // BEWARE: Although we also do the registration inside SSR testing code,\n // we still need it here to correctly process imported Webpack configurations\n // (which are imported directly from this module).\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 // eslint-disable-next-line import/dynamic-import-chunkname\n const { setBuildInfo } = await import('../../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\n await super.teardown();\n }\n}\n"],"mappings":";;;0CAAA;AACA;AACA;AACA;AACA;AACA,6CALA,CAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAEA,SAASA,IAAI,QAAQ,oBAAoB;AACzC,SAASC,MAAM,QAAQ,kBAAkB;AACzC,OAAOC,IAAI,MAAM,WAAW;AAE5B,OAAOC,QAAQ,MAAM,wBAAwB;AAC7C,SAASC,QAAQ,EAAEC,GAAG,QAAQ,WAAW;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oE,6BAA6B,GAAG,IAAI;EAClD;EAEA,MAAMC,QAAQA,CAAA,EAAkB;IAC9B,OAAO,IAAI,CAACrE,MAAM,CAACoE,6BAA6B,CAEhD;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;IACFzF,QAAQ,CAAC0F,MAAM,CAAC,CAAC;IAEjB,MAAM,KAAK,CAACL,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
|
-
/* eslint-disable import/dynamic-import-chunkname, import/no-extraneous-dependencies */import {
|
|
2
|
-
import
|
|
1
|
+
/* eslint-disable import/dynamic-import-chunkname, import/no-extraneous-dependencies */import { readFileSync } from "node:fs";
|
|
2
|
+
import { registerHooks } from "node:module";
|
|
3
|
+
import { basename, dirname, resolve } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { transformSync } from "@babel/core";
|
|
6
|
+
import ssrFactory from "../../../../server/renderer.js";
|
|
3
7
|
function noop() {// NOOP
|
|
4
8
|
}
|
|
5
9
|
async function run({
|
|
@@ -9,23 +13,45 @@ async function run({
|
|
|
9
13
|
testFolder,
|
|
10
14
|
webpackConfig
|
|
11
15
|
}) {
|
|
12
|
-
register
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
+
// NOTE: It looks like @babel/register does not work for us here, because
|
|
17
|
+
// it only supports transpiling of modules loaded with require(), so here
|
|
18
|
+
// is, presumably, a temporary workaround relying on the new NodeJS module
|
|
19
|
+
// API, and Babel's core, to transpile all modules loaded further into
|
|
20
|
+
// CommonJS. I guess, later we'll be able to get rid of this, as Babel
|
|
21
|
+
// register supports runtime transformation of modules loaded with import().
|
|
22
|
+
registerHooks({
|
|
23
|
+
load(url, context, nextLoad) {
|
|
24
|
+
if (url.startsWith("file://") && !url.includes("/node_modules/") && !url.includes("/config/babel/") && url.match(/\.(js|jsx|ts|tsx|svg)$/)) {
|
|
25
|
+
const path = fileURLToPath(url);
|
|
26
|
+
let code = readFileSync(path, "utf8");
|
|
27
|
+
code = transformSync(code, {
|
|
28
|
+
cwd: dirname(path),
|
|
29
|
+
envName: options.babelEnv,
|
|
30
|
+
filename: basename(path),
|
|
31
|
+
root
|
|
32
|
+
})?.code ?? "";
|
|
33
|
+
return {
|
|
34
|
+
format: "commonjs",
|
|
35
|
+
shortCircuit: true,
|
|
36
|
+
source: code
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
return nextLoad(url, context);
|
|
40
|
+
}
|
|
16
41
|
});
|
|
17
42
|
if (options.entry) {
|
|
18
43
|
const p = resolve(testFolder, options.entry);
|
|
19
|
-
const
|
|
44
|
+
const babelModule = await import(p); // TODO: This is basically a hotfix hack, which works both for the library
|
|
45
|
+
// itself, and for dependent projects... (those tested so far). It sure has
|
|
46
|
+
// to be reworked later.
|
|
47
|
+
/* eslint-disable no-underscore-dangle */
|
|
48
|
+
const module = "__esModule" in babelModule && typeof babelModule.__esModule === "boolean" && babelModule.__esModule && "default" in babelModule ? babelModule.default : babelModule; /* eslint-enable no-underscore-dangle */
|
|
20
49
|
const exportName = options.entryExportName || "default";
|
|
21
50
|
if (exportName in module) {
|
|
22
51
|
// eslint-disable-next-line no-param-reassign
|
|
23
|
-
options.Application = module[exportName];
|
|
24
|
-
}
|
|
52
|
+
options.Application = module[exportName]; // eslint-disable-next-line no-param-reassign
|
|
53
|
+
} else options.Application = module;
|
|
25
54
|
}
|
|
26
|
-
const {
|
|
27
|
-
default: ssrFactory
|
|
28
|
-
} = await import("../../../../server/renderer");
|
|
29
55
|
const renderer = ssrFactory(webpackConfig, options);
|
|
30
56
|
let status = 200; // OK
|
|
31
57
|
// eslint-disable-next-line no-param-reassign
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssr.js","names":["resolve","
|
|
1
|
+
{"version":3,"file":"ssr.js","names":["readFileSync","registerHooks","basename","dirname","resolve","fileURLToPath","transformSync","ssrFactory","noop","run","options","root","ssrRequest","testFolder","webpackConfig","load","url","context","nextLoad","startsWith","includes","match","path","code","cwd","envName","babelEnv","filename","format","shortCircuit","source","entry","p","babelModule","module","__esModule","default","exportName","entryExportName","Application","renderer","status","csrfToken","markup","Promise","done","fail","cookie","send","set","value","error","process","on","message"],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/ssr.ts"],"sourcesContent":["/* eslint-disable import/dynamic-import-chunkname, import/no-extraneous-dependencies */\n\nimport { readFileSync } from 'node:fs';\nimport { registerHooks } from 'node:module';\nimport { basename, dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { Request, Response } from 'express';\nimport type { ReactNode } from 'react';\nimport type { Configuration } from 'webpack';\n\nimport { transformSync } from '@babel/core';\n\nimport ssrFactory from 'server/renderer';\n\nexport type LaunchT = {\n // TODO: Should it be typed as the renderer's options type?\n options: Record<string, unknown>;\n\n root: string;\n ssrRequest: object;\n testFolder: string;\n webpackConfig: Configuration;\n};\n\nexport type ResultT = {\n markup: string;\n status: number;\n};\n\nfunction noop() {\n // NOOP\n}\n\nasync function run({\n options,\n root,\n ssrRequest,\n testFolder,\n webpackConfig,\n}: LaunchT) {\n // NOTE: It looks like @babel/register does not work for us here, because\n // it only supports transpiling of modules loaded with require(), so here\n // is, presumably, a temporary workaround relying on the new NodeJS module\n // API, and Babel's core, to transpile all modules loaded further into\n // CommonJS. I guess, later we'll be able to get rid of this, as Babel\n // register supports runtime transformation of modules loaded with import().\n registerHooks({\n load(url, context, nextLoad) {\n if (\n url.startsWith('file://')\n && !url.includes('/node_modules/')\n && !url.includes('/config/babel/')\n && url.match(/\\.(js|jsx|ts|tsx|svg)$/)\n ) {\n const path = fileURLToPath(url);\n let code = readFileSync(path, 'utf8');\n code = transformSync(code, {\n cwd: dirname(path),\n envName: options.babelEnv as string,\n filename: basename(path),\n root,\n })?.code ?? '';\n return {\n format: 'commonjs',\n shortCircuit: true,\n source: code,\n };\n }\n\n return nextLoad(url, context);\n },\n });\n\n if (options.entry) {\n const p = resolve(testFolder, options.entry as string);\n const babelModule = await import(p) as NodeJS.Module;\n\n // TODO: This is basically a hotfix hack, which works both for the library\n // itself, and for dependent projects... (those tested so far). It sure has\n // to be reworked later.\n /* eslint-disable no-underscore-dangle */\n const module = (\n '__esModule' in babelModule\n && typeof babelModule.__esModule === 'boolean'\n && babelModule.__esModule\n && 'default' in babelModule\n ? babelModule.default : babelModule\n ) as NodeJS.Module;\n /* eslint-enable no-underscore-dangle */\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n // eslint-disable-next-line no-param-reassign\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n // eslint-disable-next-line no-param-reassign\n } else options.Application = module;\n }\n\n const renderer = ssrFactory(webpackConfig, options);\n let status = 200; // OK\n\n // eslint-disable-next-line no-param-reassign\n (ssrRequest as Request).csrfToken = () => '';\n\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n 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 } 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 process.send?.({ markup, status } satisfies ResultT);\n}\n\nprocess.on('message', (message: LaunchT) => {\n void run(message);\n});\n"],"mappings":"AAAA,uFAEA,SAASA,YAAY,QAAQ,SAAS;AACtC,SAASC,aAAa,QAAQ,aAAa;AAC3C,SAASC,QAAQ,EAAEC,OAAO,EAAEC,OAAO,QAAQ,WAAW;AACtD,SAASC,aAAa,QAAQ,UAAU;AAMxC,SAASC,aAAa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"file":"index.js","names":["mockdate","act","createRoot","render","default","getGlobal","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","jest","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","unmount","remove","snapshot","expect","toMatchSnapshot","options","promise","await","Error","Promise","resolve","then","nodes","asFragment","childNodes","length"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global jest, document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): string {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: React.ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve) => {\n void promise.then(() => {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"8CAAA,6BACA;AASA,OAAOA,QAAQ,MAAM,UAAU;AAC/B,SAA4CC,GAAG,QAAQ,OAAO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,UAAU;QAC1CX,MAAM,CAACS,KAAK,CAACG,MAAM,GAAG,CAAC,GAAG,CAAC,GAAGH,KAAK,CAAC,GAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC;QAClEM,OAAO,CAACnC,GAAI,CAAC;MACf,CAAC,CAAC;IACJ,CAAC,CAAC;EACJ;EAEA,MAAMqC,KAAK,GAAGrC,GAAG,CAACsC,UAAU,CAAC,CAAC,CAACC,UAAU;EACzCX,MAAM,CAACS,KAAK,CAACG,MAAM,GAAG,CAAC,GAAG,CAAC,GAAGH,KAAK,CAAC,GAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC;EAClE,OAAO7B,GAAG;AACZ","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["mockdate","act","createRoot","render","default","getGlobal","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","jest","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","unmount","remove","snapshot","expect","toMatchSnapshot","options","promise","await","Error","Promise","resolve","then","nodes","asFragment","childNodes","length"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global jest, document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): `${string}-${string}-${string}-${string}-${string}` {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: React.ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve) => {\n void promise.then(() => {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"8CAAA,6BACA;AASA,OAAOA,QAAQ,MAAM,UAAU;AAC/B,SAA4CC,GAAG,QAAQ,OAAO;AAC9D,SAAoBC,UAAU,QAAQ,kBAAkB;AAExD,SAA4BC,MAAM,QAAQ,wBAAwB,CAElE;AACA;AACA;AACA;AACA,SAASF,GAAG;AAEZ,SAASG,OAAO,IAAIC,SAAS;AAE7BC,MAAM,CAACC,wBAAwB,GAAG,IAAI;AAEtC,MAAMC,uBAAuB,GAAGC,OAAO,CAACC,QAAQ,CAEhD;AACA;AACA;AACA;AACA,OAAO,SAASC,cAAcA,CAAA,EAAS;EACrCC,MAAM,CAACC,cAAc,CAACJ,OAAO,EAAE,UAAU,EAAE;IAAEK,KAAK,EAAEC;EAAU,CAAC,CAAC;AAClE,CAEA;AACA;AACA;AACA,OAAO,SAASC,gBAAgBA,CAAA,EAAS;EACvCJ,MAAM,CAACC,cAAc,CAACJ,OAAO,EAAE,UAAU,EAAE;IACzCK,KAAK,EAAEN,uBAAuB;IAC9BS,QAAQ,EAAE;EACZ,CAAC,CAAC;AACJ,CAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,WAAWA,CAACC,IAAI,GAAG,CAAC,EAAuD;EACzF,MAAMC,CAAC,GAAGD,IAAI,CAACE,QAAQ,C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AA2B,EAC3BW,OAA+B,EACO;EACtC,IAAI9B,GAA6B,CAEjC;EACA;EACA;EACA;EACA;EACA;EACA,MAAM+B,OAAO,GAAG/D,GAAG,CAAC,MAAM;IACxBgC,GAAG,GAAG9B,MAAM,CAACiD,OAAO,CAAC;IACrB,OAAOW,OAAO,EAAEE,KAAK;EACvB,CAAC,CAAC;EAEF,IAAIhC,GAAG,KAAKlB,SAAS,EAAE,MAAMmD,KAAK,CAAC,eAAe,CAAC;EACnD,IAAIH,OAAO,EAAEE,KAAK,EAAE;IAClB;IACA;IACA;IACA;IACA,OAAO,IAAIE,OAAO,CAAEC,OAAO,IAAK;MAC9B,KAAKJ,OAAO,CAACK,IAAI,CAAC,MAAM;QACtB;QACA;QACA,MAAMC,KAAK,GAAGrC,GAAG,CAAEsC,UAAU,CAAC,CAAC,CAACC,UAAU;QAC1CX,MAAM,CAACS,KAAK,CAACG,MAAM,GAAG,CAAC,GAAG,CAAC,GAAGH,KAAK,CAAC,GAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC;QAClEM,OAAO,CAACnC,GAAI,CAAC;MACf,CAAC,CAAC;IACJ,CAAC,CAAC;EACJ;EAEA,MAAMqC,KAAK,GAAGrC,GAAG,CAACsC,UAAU,CAAC,CAAC,CAACC,UAAU;EACzCX,MAAM,CAACS,KAAK,CAACG,MAAM,GAAG,CAAC,GAAG,CAAC,GAAGH,KAAK,CAAC,GAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC;EAClE,OAAO7B,GAAG;AACZ","ignoreList":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import"core-js/modules/es.iterator.filter.js";import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";/**
|
|
2
2
|
* Creation of standard ExpressJS server for ReactJS apps.
|
|
3
|
-
*/import{sep}from"node:path";import{pathToFileURL}from"node:url";import compression from"compression";import cookieParser from"cookie-parser";import express from"express";import helmet from"helmet";import{cloneDeep,mapValues,pick}from"lodash-es";import loggerMiddleware from"morgan";import requestIp from"request-ip";import favicon from"serve-favicon";import
|
|
3
|
+
*/import{sep}from"node:path";import{pathToFileURL}from"node:url";import compression from"compression";import cookieParser from"cookie-parser";import express from"express";import helmet from"helmet";import{cloneDeep,mapValues,pick}from"lodash-es";import loggerMiddleware from"morgan";import requestIp from"request-ip";import favicon from"serve-favicon";import csrf from"@dr.pogodin/csurf";import rendererFactory from"./renderer.js";import{CODES,ERRORS,getErrorForCode,newError}from"./utils/errors.js";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
4
4
|
/**
|
|
5
5
|
* Default Content Security Policy settings.
|
|
6
6
|
* @ignore
|
|
@@ -27,7 +27,7 @@ delete defaultCspSettings.directives["upgrade-insecure-requests"];/**
|
|
|
27
27
|
* }} A deep copy of default CSP settings object used by `react-utils`,
|
|
28
28
|
* with the exception of `nonce-xxx` clause in `script-src` directive,
|
|
29
29
|
* which is added dynamically for each request.
|
|
30
|
-
*/export function getDefaultCspSettings(){return cloneDeep(defaultCspSettings);}export default async function factory(webpackConfig,options){const rendererOps=pick(options,["Application","beforeRender","favicon","logger","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=rendererFactory(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=express();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server);}if(options.logger)server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;res.redirect(url);return;}next();});}server.use(compression());server.use(helmet({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{const req2=req;req2.nonce=
|
|
30
|
+
*/export function getDefaultCspSettings(){return cloneDeep(defaultCspSettings);}export default async function factory(webpackConfig,options){const rendererOps=pick(options,["Application","beforeRender","favicon","logger","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=rendererFactory(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=express();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server);}if(options.logger)server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;res.redirect(url);return;}next();});}server.use(compression());server.use(helmet({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{const req2=req;req2.nonce=globalThis.crypto.randomUUID();// TODO: This is deprecated, but it is kept for now for backward
|
|
31
31
|
// compatibility. Should be removed sometime later.
|
|
32
32
|
req2.cspNonce=req2.nonce;// The deep clone is necessary here to ensure that default value can't be
|
|
33
33
|
// mutated during request processing.
|