@dr.pogodin/react-utils 1.50.1 → 1.51.0
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/bin/build.js +15 -4
- package/build/development/server/renderer.js +13 -8
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/shared/utils/jest/{E2eSsrEnv.js → E2eSsrEnv/index.js} +34 -97
- package/build/development/shared/utils/jest/E2eSsrEnv/index.js.map +1 -0
- package/build/development/shared/utils/jest/E2eSsrEnv/register.js +6 -0
- package/build/development/shared/utils/jest/E2eSsrEnv/register.js.map +1 -0
- package/build/development/shared/utils/jest/E2eSsrEnv/ssr.js +59 -0
- package/build/development/shared/utils/jest/E2eSsrEnv/ssr.js.map +1 -0
- package/build/production/server/renderer.js +3 -1
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv/index.js +45 -0
- package/build/production/shared/utils/jest/E2eSsrEnv/index.js.map +1 -0
- package/build/production/shared/utils/jest/E2eSsrEnv/register.js +3 -0
- package/build/production/shared/utils/jest/E2eSsrEnv/register.js.map +1 -0
- package/build/production/shared/utils/jest/E2eSsrEnv/ssr.js +11 -0
- package/build/production/shared/utils/jest/E2eSsrEnv/ssr.js.map +1 -0
- package/build/types-code/server/renderer.d.ts +8 -1
- package/build/types-code/shared/utils/jest/{E2eSsrEnv.d.ts → E2eSsrEnv/index.d.ts} +2 -2
- package/build/types-code/shared/utils/jest/E2eSsrEnv/register.d.ts +1 -0
- package/build/types-code/shared/utils/jest/E2eSsrEnv/ssr.d.ts +12 -0
- package/build/web/server/renderer.js +3 -1
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv/index.js +45 -0
- package/build/web/shared/utils/jest/E2eSsrEnv/index.js.map +1 -0
- package/build/web/shared/utils/jest/E2eSsrEnv/register.js +3 -0
- package/build/web/shared/utils/jest/E2eSsrEnv/register.js.map +1 -0
- package/build/web/shared/utils/jest/E2eSsrEnv/ssr.js +11 -0
- package/build/web/shared/utils/jest/E2eSsrEnv/ssr.js.map +1 -0
- package/config/webpack/app-base.js +1 -30
- package/package.json +17 -17
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +0 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +0 -70
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +0 -1
- package/build/web/shared/utils/jest/E2eSsrEnv.js +0 -70
- package/build/web/shared/utils/jest/E2eSsrEnv.js.map +0 -1
- /package/{tstyche.config.json → tstyche.json} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.js","names":["Buffer","createCipheriv","randomBytes","fs","path","Writable","brotliCompress","brotliDecompress","config","cloneDeep","defaults","get","mapValues","prerenderToNodeStream","StaticRouter","serializeJs","winston","timer","GlobalStateProvider","SsrContext","HelmetProvider","setBuildInfo","Cache","jsx","_jsx","SECRET","sanitizedConfig","util","toObject","SCRIPT_LOCATIONS","ServerSsrContext","chunks","status","constructor","req","chunkGroups","initialState","getBuildInfo","context","url","resolve","JSON","parse","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","iv","cipher","from","isBrotliAcceptable","acceptable","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","beforeRender","Promise","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","outputPath","publicPath","output","manifestLink","existsSync","cache","staticCacheController","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","helmet","webpackStats","locals","toJson","all","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","reject","helmetContext","state","children","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","logMsg","log","redirectTo","redirect","ready","pipe","destroy","write","chunk","_","payload","CONFIG","ISTATE","ignoreFunction","unsafe","INJ","concat","update","final","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { type Cipheriv, createCipheriv, randomBytes } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport config from 'config';\nimport type { Request, RequestHandler } from 'express';\n\nimport {\n cloneDeep,\n defaults,\n get,\n mapValues,\n} from 'lodash-es';\n\nimport type { ComponentType } from 'react';\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { timer } from '@dr.pogodin/js-utils';\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { type HelmetDataContext, HelmetProvider } from '@dr.pogodin/react-helmet';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport Cache from './Cache';\n\n// @ts-expect-error \"Property 'SECRET' does not exist on type 'IConfig'.\"\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst { SECRET, ...sanitizedConfig } = config.util.toObject(config);\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (level: string, message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LeveledLogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nexport class ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n redirectTo?: string;\n\n req: Request;\n\n status: number = 200;\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) ?? ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8')) as BuildInfoT;\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8')) as Record<string, string[]>;\n } catch {\n // TODO: Should we message the error here somehow?\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random, Base64-encoded key is expected).\n * @return Returns a tuple of:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string): [cipher: Cipheriv, iv: Buffer] {\n const iv = randomBytes(16);\n const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);\n return [cipher, iv];\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param req\n */\nexport function isBrotliAcceptable(req: Request): boolean {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (const op of ops) {\n const [type, priority] = op.trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<ScriptT | string> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (const script of scripts) {\n if (typeof script === 'string') {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (script.location in res) res[script.location] += script.code;\n else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}): winston.Logger {\n const { format, transports } = winston;\n return winston.createLogger({\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n stack,\n timestamp,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\n transports: [new transports.Console()],\n });\n}\n\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: unknown;\n};\n\nexport type BeforeRenderT = (\n req: Request,\n config: ConfigT,\n) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n staticCacheSize?: number;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` – the cache key for the response;\n * - `maxage?: number` – the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults({ ...options }, {\n beforeRender: async () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context!);\n setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { path: outputPath, publicPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath as string}manifest.json\">` : '';\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface BufferWithNonce extends ArrayBuffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n // TODO: Look at it later.\n // eslint-disable-next-line complexity\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n\n // TODO: It should be implemented more careful.\n h = h.replace(regex, (req as unknown as {\n nonce: string;\n }).nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const brr = ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT);\n const { configToInject, extraScripts, initialState } = await brr;\n\n const [cipher, iv] = prepareCipher(buildInfo.key);\n\n let helmet: HelmetDataContext['helmet'];\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats') as Stats | undefined;\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name)\n ?? [],\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: NodeJS.ReadableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n rejectArg(arg as Error);\n };\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n const helmetContext = {} as HelmetDataContext;\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\n const timeout = ops.ssrTimeout! + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject ?? sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n\n const INJ = Buffer.concat([\n iv,\n cipher.update(payload, 'utf8'),\n cipher.final(),\n ]).toString('base64');\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) {\n assets.forEach((asset) => {\n chunkSet.add(asset);\n });\n }\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath as string}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath as string}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon\n ? '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet?.title.toString() ?? ''}\n ${helmet?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmet?.link.toString() ?? ''}${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n const b = buffer as unknown as BufferWithNonce;\n b.nonce = (req as unknown as {\n nonce: string;\n }).nonce;\n cache!.add({ buffer: b, status }, cacheRef.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":"ukBAAA;AACA;AACA,GAEA,OAASA,MAAM,KAAQ,aAAa,CACpC,OAAwBC,cAAc,CAAEC,WAAW,KAAQ,aAAa,CACxE,MAAO,CAAAC,EAAE,KAAM,SAAS,CACxB,MAAO,CAAAC,IAAI,KAAM,WAAW,CAC5B,OAASC,QAAQ,KAAQ,aAAa,CACtC,OAASC,cAAc,CAAEC,gBAAgB,KAAQ,WAAW,CAE5D,MAAO,CAAAC,MAAM,KAAM,QAAQ,CAG3B,OACEC,SAAS,CACTC,QAAQ,CACRC,GAAG,CACHC,SAAS,KACJ,WAAW,CAGlB,OAASC,qBAAqB,K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CAAED,MAAM,CAACC,KAAK,CAAC,CAAC,IACpB,CACH,KAAM,CAAAoF,CAAC,CAAGzF,MAAoC,CAC9CyF,CAAC,CAAC9E,KAAK,CAAI3F,GAAG,CAEX2F,KAAK,CACRpB,KAAK,CAAEwF,GAAG,CAAC,CAAE/E,MAAM,CAAEyF,CAAC,CAAE3K,MAAO,CAAC,CAAEgF,QAAQ,CAAChE,GAAG,CAAEkE,MAAM,CAAC5B,MAAM,CAAC,CAC9D+B,IAAI,CAAC,CAAC,CACR,CACF,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA;AACA;AACA;AACAvE,GAAG,CAACsE,IAAI,CAACI,IAAI,CAAC,CAChB,CAAE,MAAOD,KAAK,CAAE,CACdX,IAAI,CAACW,KAAK,CAAC,CACb,CACF,CAAC,CACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"renderer.js","names":["Buffer","createCipheriv","randomBytes","fs","path","Writable","brotliCompress","brotliDecompress","config","cloneDeep","defaults","get","mapValues","prerenderToNodeStream","StaticRouter","serializeJs","winston","timer","GlobalStateProvider","SsrContext","HelmetProvider","setBuildInfo","Cache","jsx","_jsx","SECRET","sanitizedConfig","util","toObject","SCRIPT_LOCATIONS","ServerSsrContext","chunks","status","constructor","req","chunkGroups","initialState","getBuildInfo","context","url","resolve","JSON","parse","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","iv","cipher","from","isBrotliAcceptable","acceptable","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","deduceChunkGroups","stats","toJson","all","namedChunkGroups","item","assets","map","name","factory","webpackConfig","options","beforeRender","Promise","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","outputPath","publicPath","output","manifestLink","existsSync","cache","staticCacheController","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","helmet","webpackStats","locals","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","reject","helmetContext","state","children","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","logMsg","log","redirectTo","redirect","ready","pipe","destroy","write","chunk","_","payload","CONFIG","ISTATE","ignoreFunction","unsafe","INJ","concat","update","final","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { type Cipheriv, createCipheriv, randomBytes } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport config from 'config';\nimport type { Request, RequestHandler } from 'express';\n\nimport {\n cloneDeep,\n defaults,\n get,\n mapValues,\n} from 'lodash-es';\n\nimport type { ComponentType } from 'react';\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { timer } from '@dr.pogodin/js-utils';\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { type HelmetDataContext, HelmetProvider } from '@dr.pogodin/react-helmet';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport Cache from './Cache';\n\n// @ts-expect-error \"Property 'SECRET' does not exist on type 'IConfig'.\"\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst { SECRET, ...sanitizedConfig } = config.util.toObject(config);\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (level: string, message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LeveledLogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nexport class ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n redirectTo?: string;\n\n req: Request;\n\n status: number = 200;\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) ?? ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8')) as BuildInfoT;\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8')) as Record<string, string[]>;\n } catch {\n // TODO: Should we message the error here somehow?\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random, Base64-encoded key is expected).\n * @return Returns a tuple of:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string): [cipher: Cipheriv, iv: Buffer] {\n const iv = randomBytes(16);\n const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);\n return [cipher, iv];\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param req\n */\nexport function isBrotliAcceptable(req: Request): boolean {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (const op of ops) {\n const [type, priority] = op.trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<ScriptT | string> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (const script of scripts) {\n if (typeof script === 'string') {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (script.location in res) res[script.location] += script.code;\n else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}): winston.Logger {\n const { format, transports } = winston;\n return winston.createLogger({\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n stack,\n timestamp,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\n transports: [new transports.Console()],\n });\n}\n\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: unknown;\n};\n\nexport type BeforeRenderT = (\n req: Request,\n config: ConfigT,\n) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\n/**\n * Deduces the map of code chunk groups from the Webpack compilation Stats.\n */\nexport function deduceChunkGroups(stats: Stats): ChunkGroupsT {\n return mapValues(\n stats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name) ?? [],\n );\n}\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n\n /** Allows to pass chunk groups explicitly, at the renderer creation time;\n * intended for test purposes. */\n chunkGroups?: ChunkGroupsT;\n\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n staticCacheSize?: number;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` – the cache key for the response;\n * - `maxage?: number` – the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults({ ...options }, {\n beforeRender: async () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context!);\n setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { path: outputPath, publicPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath as string}manifest.json\">` : '';\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface BufferWithNonce extends ArrayBuffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n // TODO: Look at it later.\n // eslint-disable-next-line complexity\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n\n // TODO: It should be implemented more careful.\n h = h.replace(regex, (req as unknown as {\n nonce: string;\n }).nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const brr = ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT);\n const { configToInject, extraScripts, initialState } = await brr;\n\n const [cipher, iv] = prepareCipher(buildInfo.key);\n\n let helmet: HelmetDataContext['helmet'];\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats') as Stats | undefined;\n if (webpackStats) chunkGroups = deduceChunkGroups(webpackStats);\n else if (options.chunkGroups) ({ chunkGroups } = options);\n else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: NodeJS.ReadableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n rejectArg(arg as Error);\n };\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n const helmetContext = {} as HelmetDataContext;\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\n const timeout = ops.ssrTimeout! + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject ?? sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n\n const INJ = Buffer.concat([\n iv,\n cipher.update(payload, 'utf8'),\n cipher.final(),\n ]).toString('base64');\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) {\n assets.forEach((asset) => {\n chunkSet.add(asset);\n });\n }\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath as string}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath as string}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon\n ? '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet?.title.toString() ?? ''}\n ${helmet?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmet?.link.toString() ?? ''}${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n const b = buffer as unknown as BufferWithNonce;\n b.nonce = (req as unknown as {\n nonce: string;\n }).nonce;\n cache!.add({ buffer: b, status }, cacheRef.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":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;AACA;AACA,iDAAiDb,GAAG;AACpD;AACA;AACA,cAAcY,oBAAoB,CAAC1K,gBAAgB,CAACkC,SAAS,CAAC;AAC9D,mCAAmCiF,aAAa;AAChD,cAAcqD,iBAAiB;AAC/B,cAAcE,oBAAoB,CAAC1K,gBAAgB,CAACmC,OAAO,CAAC;AAC5D;AACA,gBAAgB,CAEV,KAAM,CAAAhC,MAAM,CAAGiH,UAAU,CAACjH,MAAM,EAAI,GAAG,CACvC,GAAIA,MAAM,GAAK,GAAG,CAAEc,GAAG,CAACd,MAAM,CAACA,MAAM,CAAC,CAEtC,GAAIyF,QAAQ,EAAIzF,MAAM,CAAG,GAAG,CAAE,CAC5B;AACA;AACA,KAAM,IAAI,CAAAsE,OAAO,CAAO,CAACwB,IAAI,CAAEC,MAAM,GAAK,CACxCzH,cAAc,CAAC2H,IAAI,CAAE,CAACD,KAAK,CAAEL,MAAM,GAAK,CACtC,GAAIK,KAAK,CAAED,MAAM,CAACC,KAAK,CAAC,CAAC,IACpB,CACH,KAAM,CAAA6E,CAAC,CAAGlF,MAAoC,CAC9CkF,CAAC,CAACvE,KAAK,CAAIpG,GAAG,CAEXoG,KAAK,CACRpB,KAAK,CAAEiF,GAAG,CAAC,CAAExE,MAAM,CAAEkF,CAAC,CAAE7K,MAAO,CAAC,CAAEyF,QAAQ,CAACzE,GAAG,CAAE2E,MAAM,CAACrC,MAAM,CAAC,CAC9DwC,IAAI,CAAC,CAAC,CACR,CACF,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA;AACA;AACA;AACAhF,GAAG,CAAC+E,IAAI,CAACI,IAAI,CAAC,CAChB,CAAE,MAAOD,KAAK,CAAE,CACdX,IAAI,CAACW,KAAK,CAAC,CACb,CACF,CAAC,CACH","ignoreList":[]}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.json.parse.js";/**
|
|
2
|
+
* Jest environment for end-to-end SSR and client-side testing. It relies on
|
|
3
|
+
* the standard react-utils mechanics to execute SSR of given scene, and also
|
|
4
|
+
* Webpack build of the code for client-side execution, it further exposes
|
|
5
|
+
* Jsdom environment for the client-side testing of the outcomes.
|
|
6
|
+
*/// BEWARE: The module is not imported into the JU module / the main assembly of
|
|
7
|
+
// the library, because doing so easily breaks stuff:
|
|
8
|
+
// 1) This module depends on Node-specific modules, which would make JU
|
|
9
|
+
// incompatible with JsDom if included into JU.
|
|
10
|
+
// 2) If this module is weakly imported from somewhere else in the lib,
|
|
11
|
+
// it seems to randomly break tests using it for a different reason,
|
|
12
|
+
// probably some sort of a require-loop, or some issues with weak
|
|
13
|
+
// require in that scenario.
|
|
14
|
+
// TODO: We need to add correct typing for environment options.
|
|
15
|
+
// As this environment is a part of the Jest testing utils,
|
|
16
|
+
// we assume development dependencies are available when it is used.
|
|
17
|
+
/* eslint-disable import/no-extraneous-dependencies */import{fork}from"node:child_process";import path from"node:path";import JsdomEnv from"jest-environment-jsdom";import{defaults,set}from"lodash-es";import{Volume,createFsFromVolume}from"memfs";import webpack from"webpack";import{deduceChunkGroups}from"../../../../server/renderer";import{setBuildInfo}from"../../isomorphy/buildInfo";export default class E2eSsrEnv extends JsdomEnv{/**
|
|
18
|
+
* Loads Webpack config, and exposes it to the environment via global
|
|
19
|
+
* webpackConfig object.
|
|
20
|
+
*/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);}}/**
|
|
21
|
+
* Executes Webpack build.
|
|
22
|
+
* @return {Promise}
|
|
23
|
+
*/async runWebpack(){await this.loadWebpackConfig();if(!this.global.webpackConfig)throw Error("Failed to load Webpack config");const compiler=webpack(this.global.webpackConfig);// TODO: The "as typeof compiler.outputFileSystem" piece below is
|
|
24
|
+
// a workaround for the Webpack regression:
|
|
25
|
+
// https://github.com/webpack/webpack/issues/18242
|
|
26
|
+
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
|
|
27
|
+
console.error(stats.toJson().errors);fail(Error("Webpack compilation failed"));}this.global.webpackStats=stats?.toJson();// Keeps reference to the raw Webpack stats object, which should be
|
|
28
|
+
// explicitly passed to the server-side renderer alongside the request,
|
|
29
|
+
// so that it can to pick up asset paths for different named chunks.
|
|
30
|
+
this.webpackStats=stats;done();});});}async runSsr(){const cp=fork(`${import.meta.dirname}/ssr.ts`,[],{// NOTE: This ensures the forked "ssr.ts" module is pre-processed by
|
|
31
|
+
// Babel, which is necessary to correctly resolve paths to modules it
|
|
32
|
+
// loads, as we rely on Babel aliasing module paths; and we need to have
|
|
33
|
+
// a little "register.ts" module (rather than just a command-line argument)
|
|
34
|
+
// because we need to specify to Babel that ".ts", ".tsx", etc. files
|
|
35
|
+
// need to be processed, in addition to the standard JS modules.
|
|
36
|
+
execArgv:["-r",`${import.meta.dirname}/register.ts`]});const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON.parse(optionsString):{};options.buildInfo??=this.global.buildInfo;if(!this.webpackStats)throw Error("Missing Webpack stats");options.chunkGroups=deduceChunkGroups(this.webpackStats);return new Promise(resolve=>{cp.on("message",message=>{this.global.ssrMarkup=message.markup;this.global.ssrOptions=options;this.global.ssrStatus=message.status;cp.kill();resolve();});if(!this.global.webpackConfig)throw Error("Missing Webpack config");cp.send({options,root:options.root==="TEST"?this.testFolder:process.cwd(),ssrRequest:this.ssrRequest,testFolder:this.testFolder,webpackConfig:this.global.webpackConfig});});}constructor(config,context){const pragmas=context.docblockPragmas;const requestString=pragmas["ssr-request"];const request=requestString?JSON.parse(requestString):{};request.url??="/";// This ensures the initial JsDom URL matches the value we use for SSR.
|
|
37
|
+
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.
|
|
38
|
+
const{projectConfig}=config;this.rootDir=projectConfig.rootDir;this.testFolder=path.dirname(context.testPath);this.withSsr=!pragmas["no-ssr"];this.ssrRequest=request;this.pragmas=pragmas;}async setup(){await super.setup();await this.runWebpack();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
|
|
39
|
+
// the next time an instance of this environment is set up, all modules are
|
|
40
|
+
// transformed by Babel from scratch, thus taking into account the latest
|
|
41
|
+
// Babel config (which may change between different environment instances,
|
|
42
|
+
// which does not seem to be taken into account by Babel / Node caches
|
|
43
|
+
// automatically).
|
|
44
|
+
Object.keys(require.cache).forEach(key=>{delete require.cache[key];});await super.teardown();}}
|
|
45
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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":"4IAAA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA,sDAEA,OAASA,IAAI,KAAQ,oBAAoB,CACzC,MAAO,CAAAC,IAAI,KAAM,WAAW,CAE5B,MAAO,CAAAC,QAAQ,KAAM,wBAAwB,CAC7C,OAASC,QAAQ,CAAEC,GAAG,KAAQ,WAAW,CACzC,OAASC,MAAM,CAAEC,kBAAkB,KAAQ,OAAO,CAClD,MAAO,CAAAC,OAAO,KAA0C,SAAS,CAOjE,OAASC,iBAAiB,mCAE1B,OAASC,YAAY,iCAIrB,cAAe,MAAM,CAAAC,SAAS,QAAS,CAAAR,QAAS,CAa9C;AACF;AACA;AACA,KACE,KAAc,CAAAS,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,CAEvBT,QAAQ,CAACW,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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CAACqD,UAAU,CAAGK,OAAO,CACzB,IAAI,CAAC1D,OAAO,CAAGA,OAAO,CACxB,CAEA,KAAM,CAAAgE,KAAKA,CAAA,CAAkB,CAC3B,KAAM,MAAK,CAACA,KAAK,CAAC,CAAC,CACnB,KAAM,KAAI,CAAC9C,UAAU,CAAC,CAAC,CAEvBtB,YAAY,CAACqE,SAAS,CAAE,IAAI,CAAC,CAE7B,GAAI,IAAI,CAACF,OAAO,CAAE,KAAM,KAAI,CAAC7B,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC3B,MAAM,CAAC2D,6BAA6B,CAAG,IAAI,CAClD,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAkB,CAC9B,MAAO,KAAI,CAAC5D,MAAM,CAAC2D,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAACC,OAAO,CAACC,KAAK,CAAC,CAACC,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,CAAAH,OAAO,CAACC,KAAK,CAACE,GAAG,CAAC,CAC3B,CAAC,CAAC,CAEF,KAAM,MAAK,CAACN,QAAQ,CAAC,CAAC,CACxB,CACF","ignoreList":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"register.js","names":["register","extensions"],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/register.ts"],"sourcesContent":["// eslint-disable-next-line import/no-extraneous-dependencies\nimport register from '@babel/register';\n\nregister({\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n});\n"],"mappings":"AAAA;AACA,MAAO,CAAAA,QAAQ,KAAM,iBAAiB,CAEtCA,QAAQ,CAAC,CACPC,UAAU,CAAE,CAAC,KAAK,CAAE,MAAM,CAAE,KAAK,CAAE,MAAM,CAAE,MAAM,CACnD,CAAC,CAAC","ignoreList":[]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/* eslint-disable import/dynamic-import-chunkname, import/no-extraneous-dependencies */import{resolve}from"node:path";import register from"@babel/register";function noop(){// NOOP
|
|
2
|
+
}async function run({options,root,ssrRequest,testFolder,webpackConfig}){register({envName:options.babelEnv,extensions:[".js",".jsx",".ts",".tsx",".svg"],root});if(options.entry){const p=resolve(testFolder,options.entry);const module=await import(p);const exportName=options.entryExportName||"default";if(exportName in module){// eslint-disable-next-line no-param-reassign
|
|
3
|
+
options.Application=module[exportName];}}const{default:ssrFactory}=await import("../../../../server/renderer");const renderer=ssrFactory(webpackConfig,options);let status=200;// OK
|
|
4
|
+
// eslint-disable-next-line no-param-reassign
|
|
5
|
+
ssrRequest.csrfToken=()=>"";const markup=await new Promise((done,fail)=>{void renderer(ssrRequest,// TODO: This will do for now, with the current implementation of
|
|
6
|
+
// the renderer, but it will require a rework once the renderer is
|
|
7
|
+
// updated to do streaming.
|
|
8
|
+
{cookie:noop,send:done,set:noop,status:value=>{status=value;}},error=>{// TODO: Strictly speaking, that error as Error casting is not all
|
|
9
|
+
// correct, but it works, so no need to spend time on it right now.
|
|
10
|
+
if(error)fail(error);else done("");});});process.send?.({markup,status});}process.on("message",message=>{void run(message);});
|
|
11
|
+
//# sourceMappingURL=ssr.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ssr.js","names":["resolve","register","noop","run","options","root","ssrRequest","testFolder","webpackConfig","envName","babelEnv","extensions","entry","p","module","exportName","entryExportName","Application","default","ssrFactory","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 { resolve } from 'node:path';\n\nimport type { Request, Response } from 'express';\nimport type { ReactNode } from 'react';\nimport type { Configuration } from 'webpack';\n\nimport register from '@babel/register';\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 register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n\n if (options.entry) {\n const p = resolve(testFolder, options.entry as string);\n const module = await import(p) as NodeJS.Module;\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 }\n }\n\n const { default: ssrFactory } = await import('server/renderer');\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,OAASA,OAAO,KAAQ,WAAW,CAMnC,MAAO,CAAAC,QAAQ,KAAM,iBAAiB,CAiBtC,QAAS,CAAAC,IAAIA,CAAA,CAAG,CACd;AAAA,CAGF,cAAe,CAAAC,GAAGA,CAAC,CACjBC,OAAO,CACPC,IAAI,CACJC,UAAU,CACVC,UAAU,CACVC,aACO,CAAC,CAAE,CACVP,QAAQ,CAAC,CACPQ,OAAO,CAAEL,OAAO,CAACM,QAAkB,CACnCC,UAAU,CAAE,CAAC,KAAK,CAAE,MAAM,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CAACC,EAAE,CAAC,SAAS,CAAGC,OAAgB,EAAK,CAC1C,IAAK,CAAA/B,GAAG,CAAC+B,OAAO,CAAC,CACnB,CAAC,CAAC","ignoreList":[]}
|
|
@@ -126,7 +126,7 @@ const COREJS_REGEX = /\/core-js/;
|
|
|
126
126
|
* - **`timestamp`** — The value set for `BUILD_TIMESTAMP`.
|
|
127
127
|
*/
|
|
128
128
|
function configFactory(ops) {
|
|
129
|
-
var _a
|
|
129
|
+
var _a;
|
|
130
130
|
const o = (0, lodash_es_1.defaults)((0, lodash_es_1.clone)(ops), {
|
|
131
131
|
babelLoaderOptions: {},
|
|
132
132
|
cssLocalIdent: '[hash:base64:6]',
|
|
@@ -316,14 +316,6 @@ function configFactory(ops) {
|
|
|
316
316
|
fonts: node_path_1.default.resolve(o.context, 'src/assets/fonts'),
|
|
317
317
|
styles: node_path_1.default.resolve(o.context, 'src/styles'),
|
|
318
318
|
},
|
|
319
|
-
// NOTE: This is primarily motivated by the issue #413
|
|
320
|
-
// https://github.com/birdofpreyru/react-utils/issues/413
|
|
321
|
-
// caused by react-router exporting different package builds
|
|
322
|
-
// for "import" and "default" conditions, resulting in Webpack
|
|
323
|
-
// picking up different module versions for import() and require()
|
|
324
|
-
// imports. Adding "import" with the highest priorty below forces
|
|
325
|
-
// the "import" to be used, working around the problem.
|
|
326
|
-
conditionNames: ['import', '...'],
|
|
327
319
|
extensions: [
|
|
328
320
|
'.ts',
|
|
329
321
|
'.tsx',
|
|
@@ -336,26 +328,5 @@ function configFactory(ops) {
|
|
|
336
328
|
symlinks: false,
|
|
337
329
|
},
|
|
338
330
|
};
|
|
339
|
-
// TODO: Can we do anything better about it? Otherwise, we potentially
|
|
340
|
-
// have to alias all Babel's runtime helpers, otherwise if it tries to
|
|
341
|
-
// use a new helper it breaks (probably only production) build in a very
|
|
342
|
-
// confusing, hard to debug way. Not sure what to do, as the problem with
|
|
343
|
-
// RR exports is still there, and we still can't fully move to ES modules
|
|
344
|
-
// because Jest and other tools. Also such aliases easily break E2E tests
|
|
345
|
-
// with Jest (with our setup), that's why they are avoided when NODE_ENV
|
|
346
|
-
// is test (but it might be not the solution that always helps).
|
|
347
|
-
//
|
|
348
|
-
// NOTE: The "conditionNames" workaround below messes up the loading of
|
|
349
|
-
// Babel's runtime helper for require of CJS and ES styles of modules
|
|
350
|
-
// (without this alias it is resolved to
|
|
351
|
-
// @babel/runtime/helpers/esm/interopRequireDefault, which has
|
|
352
|
-
// the hepler function attached to "default" export).
|
|
353
|
-
if (process.env.NODE_ENV !== 'test') {
|
|
354
|
-
const aliases = (_b = res.resolve) === null || _b === void 0 ? void 0 : _b.alias;
|
|
355
|
-
aliases['@babel/runtime/helpers/defineProperty']
|
|
356
|
-
= node_path_1.default.resolve(o.context, 'node_modules/@babel/runtime/helpers/defineProperty');
|
|
357
|
-
aliases['@babel/runtime/helpers/interopRequireDefault']
|
|
358
|
-
= node_path_1.default.resolve(o.context, 'node_modules/@babel/runtime/helpers/interopRequireDefault');
|
|
359
|
-
}
|
|
360
331
|
return res;
|
|
361
332
|
}
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "1.
|
|
2
|
+
"version": "1.51.0",
|
|
3
3
|
"bin": {
|
|
4
4
|
"react-utils-build": "bin/build.js",
|
|
5
5
|
"react-utils-setup": "bin/setup.js"
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"@dr.pogodin/react-helmet": "^3.1.1",
|
|
18
18
|
"@dr.pogodin/react-themes": "^1.10.3",
|
|
19
19
|
"@jest/environment": "^30.3.0",
|
|
20
|
-
"axios": "^1.
|
|
20
|
+
"axios": "^1.15.0",
|
|
21
21
|
"commander": "^14.0.3",
|
|
22
22
|
"compression": "^1.8.1",
|
|
23
23
|
"config": "^4.4.1",
|
|
@@ -29,13 +29,13 @@
|
|
|
29
29
|
"express": "^5.2.1",
|
|
30
30
|
"helmet": "^8.1.0",
|
|
31
31
|
"http-status-codes": "^2.3.0",
|
|
32
|
-
"lodash-es": "^4.
|
|
32
|
+
"lodash-es": "^4.18.1",
|
|
33
33
|
"morgan": "^1.10.1",
|
|
34
|
-
"qs": "^6.15.
|
|
34
|
+
"qs": "^6.15.1",
|
|
35
35
|
"raf": "^3.4.1",
|
|
36
|
-
"react": "^19.2.
|
|
37
|
-
"react-dom": "^19.2.
|
|
38
|
-
"react-router": "^7.
|
|
36
|
+
"react": "^19.2.5",
|
|
37
|
+
"react-dom": "^19.2.5",
|
|
38
|
+
"react-router": "^7.14.0",
|
|
39
39
|
"request-ip": "^3.3.0",
|
|
40
40
|
"rimraf": "^6.1.3",
|
|
41
41
|
"serialize-javascript": "^7.0.5",
|
|
@@ -56,13 +56,14 @@
|
|
|
56
56
|
"@babel/register": "^7.28.6",
|
|
57
57
|
"@dr.pogodin/babel-plugin-transform-assets": "^1.2.6",
|
|
58
58
|
"@dr.pogodin/babel-preset-svgr": "^1.9.3",
|
|
59
|
-
"@dr.pogodin/eslint-configs": "^0.2.
|
|
59
|
+
"@dr.pogodin/eslint-configs": "^0.2.10",
|
|
60
60
|
"@pmmmwh/react-refresh-webpack-plugin": "^0.6.2",
|
|
61
61
|
"@standard-schema/spec": "^1.1.0",
|
|
62
62
|
"@testing-library/dom": "^10.4.1",
|
|
63
63
|
"@testing-library/react": "^16.3.2",
|
|
64
64
|
"@testing-library/user-event": "^14.6.1",
|
|
65
65
|
"@tsconfig/recommended": "^1.0.13",
|
|
66
|
+
"@types/babel__register": "^7.17.3",
|
|
66
67
|
"@types/compression": "^1.8.1",
|
|
67
68
|
"@types/config": "^3.3.5",
|
|
68
69
|
"@types/cookie": "^0.6.0",
|
|
@@ -96,13 +97,13 @@
|
|
|
96
97
|
"mini-css-extract-plugin": "^2.10.2",
|
|
97
98
|
"mockdate": "^3.0.5",
|
|
98
99
|
"nodelist-foreach-polyfill": "^1.2.0",
|
|
99
|
-
"postcss": "^8.5.
|
|
100
|
+
"postcss": "^8.5.9",
|
|
100
101
|
"postcss-loader": "^8.2.1",
|
|
101
102
|
"postcss-scss": "^4.0.9",
|
|
102
103
|
"pretty": "^2.0.0",
|
|
103
104
|
"react-refresh": "^0.18.0",
|
|
104
105
|
"resolve-url-loader": "^5.0.0",
|
|
105
|
-
"sass": "^1.
|
|
106
|
+
"sass": "^1.99.0",
|
|
106
107
|
"sass-loader": "^16.0.7",
|
|
107
108
|
"sitemap": "^9.0.1",
|
|
108
109
|
"source-map-loader": "^5.0.0",
|
|
@@ -110,11 +111,11 @@
|
|
|
110
111
|
"stylelint-config-standard-scss": "^17.0.0",
|
|
111
112
|
"supertest": "^7.2.2",
|
|
112
113
|
"tsc-alias": "1.8.16",
|
|
113
|
-
"tstyche": "^
|
|
114
|
+
"tstyche": "^7.0.0",
|
|
114
115
|
"typed-scss-modules": "^8.1.1",
|
|
115
116
|
"typescript": "^5.9.3",
|
|
116
|
-
"webpack": "^5.
|
|
117
|
-
"webpack-dev-middleware": "^8.0.
|
|
117
|
+
"webpack": "^5.106.0",
|
|
118
|
+
"webpack-dev-middleware": "^8.0.3",
|
|
118
119
|
"webpack-hot-middleware": "^2.26.1",
|
|
119
120
|
"webpack-merge": "^6.0.1",
|
|
120
121
|
"workbox-core": "^7.4.0",
|
|
@@ -160,7 +161,7 @@
|
|
|
160
161
|
},
|
|
161
162
|
"./build/development/client/init": "./build/development/client/init.js",
|
|
162
163
|
"./build/production/client/init": "./build/production/client/init.js",
|
|
163
|
-
"./jest-e2e-ssr-env": "./build/production/shared/utils/jest/E2eSsrEnv.js"
|
|
164
|
+
"./jest-e2e-ssr-env": "./build/production/shared/utils/jest/E2eSsrEnv/index.js"
|
|
164
165
|
},
|
|
165
166
|
"homepage": "https://dr.pogodin.studio/docs/react-utils/index.html",
|
|
166
167
|
"author": "Dr. Sergey Pogodin <doc@pogodin.studio> (https://dr.pogodin.studio)",
|
|
@@ -189,10 +190,9 @@
|
|
|
189
190
|
"build": "rimraf build && npm run build:scripts && npm run build:configs && node bin/build -t library",
|
|
190
191
|
"build:configs": "tsc --project tsconfig.configs.json",
|
|
191
192
|
"build:scripts": "babel ./bin-ts-src --config-file ./babel.scripts.config.js --out-dir bin -x .ts",
|
|
192
|
-
"jest:
|
|
193
|
-
"jest:2": "NODE_CONFIG_ENV=test jest --no-cache -w 1 --config config/jest/default.js --shard=2/2",
|
|
193
|
+
"jest:logic": "NODE_CONFIG_ENV=test jest --no-cache -w 1 --config config/jest/default.js",
|
|
194
194
|
"jest:types": "tstyche",
|
|
195
|
-
"jest": "npm run jest:types && npm run jest:
|
|
195
|
+
"jest": "npm run jest:types && npm run jest:logic",
|
|
196
196
|
"lint": "npm run lint:code && npm run lint:scss",
|
|
197
197
|
"lint:code": "eslint --cache",
|
|
198
198
|
"lint:scss": "stylelint -- **/*.{css,scss}",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"E2eSsrEnv.js","names":["path","JsdomEnv","defaults","set","Volume","createFsFromVolume","webpack","register","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\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 path from 'node:path';\n\nimport type { Request, Response } from 'express';\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport type { ReactNode } from 'react';\nimport webpack, { type Configuration } from 'webpack';\n\nimport register from '@babel/register/experimental-worker';\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\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":";;;0CAAA;AACA;AACA;AACA;AACA;AACA,6CALA,CAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAEA,OAAOA,IAAI,MAAM,WAAW;AAG5B,OAAOC,QAAQ,MAAM,wBAAwB;AAC7C,SAASC,QA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IAAI,CAACP,OAAO,CAACC,KAAK,CAAC,CAACO,OAAO,CAAEC,GAAG,IAAK;MAC1C,OAAOT,OAAO,CAACC,KAAK,CAACQ,GAAG,CAAC;IAC3B,CAAC,CAAC;IACF7F,QAAQ,CAAC8F,MAAM,CAAC,CAAC;IACjB,MAAM,KAAK,CAACL,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.json.parse.js";/**
|
|
2
|
-
* Jest environment for end-to-end SSR and client-side testing. It relies on
|
|
3
|
-
* the standard react-utils mechanics to execute SSR of given scene, and also
|
|
4
|
-
* Webpack build of the code for client-side execution, it further exposes
|
|
5
|
-
* Jsdom environment for the client-side testing of the outcomes.
|
|
6
|
-
*/// BEWARE: The module is not imported into the JU module / the main assembly of
|
|
7
|
-
// the library, because doing so easily breaks stuff:
|
|
8
|
-
// 1) This module depends on Node-specific modules, which would make JU
|
|
9
|
-
// incompatible with JsDom if included into JU.
|
|
10
|
-
// 2) If this module is weakly imported from somewhere else in the lib,
|
|
11
|
-
// it seems to randomly break tests using it for a different reason,
|
|
12
|
-
// probably some sort of a require-loop, or some issues with weak
|
|
13
|
-
// require in that scenario.
|
|
14
|
-
// TODO: We need to add correct typing for environment options.
|
|
15
|
-
// As this environment is a part of the Jest testing utils,
|
|
16
|
-
// we assume development dependencies are available when it is used.
|
|
17
|
-
/* eslint-disable import/no-extraneous-dependencies */import path from"node:path";import JsdomEnv from"jest-environment-jsdom";import{defaults,set}from"lodash-es";import{Volume,createFsFromVolume}from"memfs";import webpack from"webpack";import register from"@babel/register/experimental-worker";function noop(){// NOOP
|
|
18
|
-
}export default class E2eSsrEnv extends JsdomEnv{/**
|
|
19
|
-
* Loads Webpack config, and exposes it to the environment via global
|
|
20
|
-
* webpackConfig object.
|
|
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);}}/**
|
|
22
|
-
* Executes Webpack build.
|
|
23
|
-
* @return {Promise}
|
|
24
|
-
*/async runWebpack(){await this.loadWebpackConfig();if(!this.global.webpackConfig)throw Error("Failed to load Webpack config");const compiler=webpack(this.global.webpackConfig);// TODO: The "as typeof compiler.outputFileSystem" piece below is
|
|
25
|
-
// a workaround for the Webpack regression:
|
|
26
|
-
// https://github.com/webpack/webpack/issues/18242
|
|
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
|
|
28
|
-
console.error(stats.toJson().errors);fail(Error("Webpack compilation failed"));}this.global.webpackStats=stats?.toJson();// Keeps reference to the raw Webpack stats object, which should be
|
|
29
|
-
// explicitly passed to the server-side renderer alongside the request,
|
|
30
|
-
// so that it can to pick up asset paths for different named chunks.
|
|
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.
|
|
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
|
|
33
|
-
const markup=await new Promise((done,fail)=>{void renderer(this.ssrRequest,// TODO: This will do for now, with the current implementation of
|
|
34
|
-
// the renderer, but it will require a rework once the renderer is
|
|
35
|
-
// updated to do streaming.
|
|
36
|
-
{cookie:noop,send:done,set:noop,status:value=>{status=value;},// This is how up-to-date Webpack stats are passed to the server in
|
|
37
|
-
// development mode, and we use this here always, instead of having
|
|
38
|
-
// to pass some information via filesystem.
|
|
39
|
-
locals:{webpack:{devMiddleware:{stats:this.webpackStats}}}},error=>{// TODO: Strictly speaking, that error as Error casting is not all
|
|
40
|
-
// correct, but it works, so no need to spend time on it right now.
|
|
41
|
-
if(error)fail(error);else done("");});});this.global.ssrMarkup=markup;this.global.ssrOptions=options;this.global.ssrStatus=status;if(cleanup)cleanup();}constructor(config,context){const pragmas=context.docblockPragmas;const requestString=pragmas["ssr-request"];const request=requestString?JSON.parse(requestString):{};request.url??="/";request.csrfToken=noop;// This ensures the initial JsDom URL matches the value we use for SSR.
|
|
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.
|
|
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
|
|
44
|
-
// the environment code and imports from it, this workaround enables it.
|
|
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
|
|
52
|
-
// load different versions of the same module (CommonJS, and ES), and it may
|
|
53
|
-
// cause very confusing problems (e.g. see:
|
|
54
|
-
// https://github.com/birdofpreyru/react-utils/issues/413).
|
|
55
|
-
// It seems we can't reset the cache of ES modules, and Jest's module reset
|
|
56
|
-
// does not reset modules loaded in this enviroment module, and also only
|
|
57
|
-
// replacing entire cache object by and empty {} seems to help (in contrast
|
|
58
|
-
// to deleting all entries by their keys, as it is done within .teardown()
|
|
59
|
-
// method below). Thus, for now we do this as a hotfix, and we also reset
|
|
60
|
-
// build info to undefined, because ES module version not beeing reset
|
|
61
|
-
// triggers an error on the subsequent test using the environment.
|
|
62
|
-
// TODO: Look for a cleaner solution.
|
|
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
|
|
64
|
-
// the next time an instance of this environment is set up, all modules are
|
|
65
|
-
// transformed by Babel from scratch, thus taking into account the latest
|
|
66
|
-
// Babel config (which may change between different environment instances,
|
|
67
|
-
// which does not seem to be taken into account by Babel / Node caches
|
|
68
|
-
// automatically).
|
|
69
|
-
Object.keys(require.cache).forEach(key=>{delete require.cache[key];});register.revert();await super.teardown();}}
|
|
70
|
-
//# sourceMappingURL=E2eSsrEnv.js.map
|