@dr.pogodin/react-utils 1.51.4 → 1.52.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/build.js +0 -2
- package/build/development/server/renderer.js +4 -4
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +1 -1
- package/build/development/server/server.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +5 -3
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv/ssr.js.map +1 -1
- package/build/production/server/renderer.js +5 -4
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +2 -1
- package/build/production/server/server.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +4 -4
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv/ssr.js.map +1 -1
- package/build/web/server/renderer.js +5 -4
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/server/server.js +2 -1
- package/build/web/server/server.js.map +1 -1
- package/build/web/shared/components/WithTooltip/index.js +4 -4
- package/build/web/shared/components/WithTooltip/index.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv/ssr.js.map +1 -1
- package/package.json +7 -7
|
@@ -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","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":"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,KAAQ,kBAAkB,CACxD,OAASC,YAAY,KAAQ,cAAc,CAC3C,MAAO,CAAAC,WAAW,KAAM,sBAAsB,CAE9C,MAAO,CAAAC,OAAO,KAAM,SAAS,CAE7B,OAASC,KAAK,KAAQ,sBAAsB,CAC5C,OAASC,mBAAmB,CAAEC,UAAU,KAAQ,gCAAgC,CAChF,OAAiCC,cAAc,KAAQ,0BAA0B,CAGjF,OAA0BC,YAAY,2CAEtC,MAAO,CAAAC,KAAK,eAEZ;AACA;AAAA,OAAAC,GAAA,IAAAC,IAAA,yBACA,KAAM,CAAEC,MAAM,CAAE,GAAGC,eAAgB,CAAC,CAAGlB,MAAM,CAACmB,IAAI,CAACC,QAAQ,CAACpB,MAAM,CAAC,CAEnE;AACA;AACA;AACA;AAMA;AAMA;AASA,UAAY,CAAAqB,gBAAgB,uBAAhBA,gBAAgB,EAAhBA,gBAAgB,0BAAhBA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,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":[]}
|
|
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","publicConfig","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, ...publicConfig } = 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, publicConfig);\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\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\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 ?? publicConfig,\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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AAM,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":[]}
|
|
@@ -55,6 +55,7 @@ if(!global.location){global.location={href:`${pathToFileURL(process.cwd()).href}
|
|
|
55
55
|
// though.
|
|
56
56
|
server.use((error,req,res,next)=>{// TODO: This is needed to correctly handled any errors thrown after
|
|
57
57
|
// sending initial response to the client.
|
|
58
|
-
if(res.headersSent){next(error);return;}const status=error.status??CODES.INTERNAL_SERVER_ERROR
|
|
58
|
+
if(res.headersSent){next(error);return;}const status=error.status??CODES.INTERNAL_SERVER_ERROR;// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
|
|
59
|
+
const serverSide=status>=CODES.INTERNAL_SERVER_ERROR;// Log server-side errors always, client-side at debug level only.
|
|
59
60
|
options.logger.log(serverSide?"error":"debug",error.toString());let message=error.message||getErrorForCode(status);if(serverSide&&process.env.NODE_ENV==="production"){message=ERRORS.INTERNAL_SERVER_ERROR;}res.status(status).send(message);});}return server;}
|
|
60
61
|
//# sourceMappingURL=server.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":["sep","pathToFileURL","compression","cookieParser","express","helmet","cloneDeep","mapValues","pick","loggerMiddleware","requestIp","favicon","csrf","rendererFactory","CODES","ERRORS","getErrorForCode","newError","defaultCspSettings","directives","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","globalThis","crypto","randomUUID","cspNonce","cspSettings","cspSettingsHook","send","json","limit","urlencoded","extended","cookieSignatureSecret","mw","cookie","ignoreRequest","csrfIgnoreRequest","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","process","cwd","default","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","NOT_FOUND","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport helmet, { type HelmetOptions } from 'helmet';\nimport { cloneDeep, mapValues, pick } from 'lodash-es';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport favicon from 'serve-favicon';\n\nimport type { Configuration } from 'webpack';\n\nimport csrf from '@dr.pogodin/csurf';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => Promise<boolean> | boolean;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n csrfIgnoreRequest?: (req: Request) => boolean;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = globalThis.crypto.randomUUID();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({\n cookie: true,\n ignoreRequest: options.csrfIgnoreRequest,\n }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const { default: webpack } = await import(/* webpackChunkName: \"server-side-code\" */ 'webpack');\n\n const { default: webpackDevMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-dev-middleware'\n );\n\n const { default: webpackHotMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-hot-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":"0IAAA;AACA;AACA,GAEA,OAASA,GAAG,KAAQ,WAAW,CAC/B,OAASC,aAAa,KAAQ,UAAU,CAExC,MAAO,CAAAC,WAAW,KAAM,aAA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A;AACA;AACA;AACA;AACA;AACA9D,MAAM,CAACI,GAAG,CAAC,CACT4D,KAEC,CACD3D,GAAY,CACZC,GAAa,CACbC,IAAkB,GACf,CACH;AACA;AACA,GAAID,GAAG,CAAC2D,WAAW,CAAE,CACnB1D,IAAI,CAACyD,KAAK,CAAC,CACX,OACF,CAEA,KAAM,CAAAE,MAAM,CAAGF,KAAK,CAACE,MAAM,EAAItF,KAAK,CAACuF,qBAAqB,CAC1D,KAAM,CAAAC,UAAU,CAAGF,MAAM,EAAKtF,KAAK,CAACuF,qBAAgC,CAEpE;AACAxE,OAAO,CAACO,MAAM,CAAEmE,GAAG,CAACD,UAAU,CAAG,OAAO,CAAG,OAAO,CAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC,CAErE,GAAI,CAAAC,OAAO,CAAGP,KAAK,CAACO,OAAO,EAAIzF,eAAe,CAACoF,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAIhB,OAAO,CAACoB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDF,OAAO,CAAG1F,MAAM,CAACsF,qBAAqB,CACxC,CAEA7D,GAAG,CAAC4D,MAAM,CAACA,MAAM,CAAC,CAACxC,IAAI,CAAC6C,OAAO,CAAC,CAClC,CAAC,CAAC,CACJ,CAEA,MAAO,CAAAvE,MAAM,CACf","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"server.js","names":["sep","pathToFileURL","compression","cookieParser","express","helmet","cloneDeep","mapValues","pick","loggerMiddleware","requestIp","favicon","csrf","rendererFactory","CODES","ERRORS","getErrorForCode","newError","defaultCspSettings","directives","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","globalThis","crypto","randomUUID","cspNonce","cspSettings","cspSettingsHook","send","json","limit","urlencoded","extended","cookieSignatureSecret","mw","cookie","ignoreRequest","csrfIgnoreRequest","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","process","cwd","default","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","NOT_FOUND","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport helmet, { type HelmetOptions } from 'helmet';\nimport { cloneDeep, mapValues, pick } from 'lodash-es';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport favicon from 'serve-favicon';\n\nimport type { Configuration } from 'webpack';\n\nimport csrf from '@dr.pogodin/csurf';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => Promise<boolean> | boolean;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n csrfIgnoreRequest?: (req: Request) => boolean;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = globalThis.crypto.randomUUID();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({\n cookie: true,\n ignoreRequest: options.csrfIgnoreRequest,\n }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const { default: webpack } = await import(/* webpackChunkName: \"server-side-code\" */ 'webpack');\n\n const { default: webpackDevMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-dev-middleware'\n );\n\n const { default: webpackHotMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-hot-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":"0IAAA;AACA;AACA,GAEA,OAASA,GAAG,KAAQ,WAAW,CAC/B,OAASC,aAAa,KAAQ,UAAU,CAExC,MAAO,CAAAC,WAAW,KAAM,aAAa,CACrC,MAAO,CAAAC,YAAY,KAAM,eAAe,CAExC,MAAO,CAAAC,OAAO,KAKP,SAAS,CAEhB,MAAO,CAAAC,MAAM,KAA8B,QAAQ,CACnD,OAASC,SAAS,CAAEC,SAAS,CAAEC,IAAI,KAAQ,WAAW,CACtD,MAAO,CAAAC,gBAAgB,KAAM,QAAQ,CACrC,MAAO,CAAAC,SAAS,KAAM,YAAY,CAClC,MAAO,CAAAC,OAAO,KAAM,eAAe,CAInC,MAAO,CAAAC,IAAI,KAAM,mBAAmB,CAEpC,MAAO,CAAAC,eAAe,kBAKtB,OACEC,KAAK,CACLC,MAAM,CACNC,eAAe,CACfC,QAAQ,sBAKV;AAMA;AACA;AACA;AACA,GACA,KAAM,CAAAC,kBAAkB,CAAG,CACzBC,UAA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GAAI,CAAAC,OAAO,CAAGP,KAAK,CAACO,OAAO,EAAIzF,eAAe,CAACoF,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAIhB,OAAO,CAACoB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDF,OAAO,CAAG1F,MAAM,CAACsF,qBAAqB,CACxC,CAEA7D,GAAG,CAAC4D,MAAM,CAACA,MAAM,CAAC,CAACxC,IAAI,CAAC6C,OAAO,CAAC,CAClC,CAAC,CAAC,CACJ,CAEA,MAAO,CAAAvE,MAAM,CACf","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/* global window */import{useEffect,useRef,useState}from"react";import{useTheme}from"@dr.pogodin/react-themes";import Tooltip,{PLACEMENTS}from"./Tooltip";import defaultTheme from"./default-theme.scss";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";/**
|
|
1
|
+
/* global window */import{useEffect,useEffectEvent,useRef,useState}from"react";import{useTheme}from"@dr.pogodin/react-themes";import Tooltip,{PLACEMENTS}from"./Tooltip";import defaultTheme from"./default-theme.scss";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";/**
|
|
2
2
|
* Implements a simple to use and themeable tooltip component, _e.g._
|
|
3
3
|
* ```js
|
|
4
4
|
* <WithTooltip tip="This is example tooltip.">
|
|
@@ -11,15 +11,15 @@
|
|
|
11
11
|
* @param tip – Anything React is able to render,
|
|
12
12
|
* _e.g._ a tooltip text. This will be the tooltip content.
|
|
13
13
|
* @param {WithTooltipTheme} props.theme _Ad hoc_ theme.
|
|
14
|
-
*/const WithTooltip=({children,placement=PLACEMENTS.ABOVE_CURSOR,theme,tip})=>{const custom=useTheme("WithTooltip",defaultTheme,theme);const{current:heap}=useRef({lastCursorX:0,lastCursorY:0,timerId:undefined,triggeredByTouch:false});const tooltipRef=useRef(null);const wrapperRef=useRef(null);const[showTooltip,setShowTooltip]=useState(false);const updatePortalPosition=(cursorX,cursorY)=>{if(showTooltip){const wrapperRect=wrapperRef.current.getBoundingClientRect();if(cursorX<wrapperRect.left||cursorX>wrapperRect.right||cursorY<wrapperRect.top||cursorY>wrapperRect.bottom){setShowTooltip(false);}else if(tooltipRef.current){tooltipRef.current.pointTo(cursorX+window.scrollX,cursorY+window.scrollY,placement,wrapperRef.current);}}else{heap.lastCursorX=cursorX;heap.lastCursorY=cursorY;// If tooltip was triggered by a touch, we delay its opening by a bit,
|
|
14
|
+
*/const WithTooltip=({children,placement=PLACEMENTS.ABOVE_CURSOR,theme,tip})=>{const custom=useTheme("WithTooltip",defaultTheme,theme);const{current:heap}=useRef({lastCursorX:0,lastCursorY:0,timerId:undefined,triggeredByTouch:false});const tooltipRef=useRef(null);const wrapperRef=useRef(null);const[showTooltip,setShowTooltip]=useState(false);const getHeap=useEffectEvent(()=>heap);const updatePortalPosition=(cursorX,cursorY)=>{if(showTooltip){const wrapperRect=wrapperRef.current.getBoundingClientRect();if(cursorX<wrapperRect.left||cursorX>wrapperRect.right||cursorY<wrapperRect.top||cursorY>wrapperRect.bottom){setShowTooltip(false);}else if(tooltipRef.current){tooltipRef.current.pointTo(cursorX+window.scrollX,cursorY+window.scrollY,placement,wrapperRef.current);}}else{heap.lastCursorX=cursorX;heap.lastCursorY=cursorY;// If tooltip was triggered by a touch, we delay its opening by a bit,
|
|
15
15
|
// to ensure it was not a touch-click - in the case of touch click we
|
|
16
16
|
// want to do the click, rather than show the tooltip, and the delay
|
|
17
17
|
// gives click handler a chance to abort the tooltip openning.
|
|
18
18
|
if(heap.triggeredByTouch){heap.timerId??=setTimeout(()=>{heap.triggeredByTouch=false;heap.timerId=undefined;setShowTooltip(true);},300);// Otherwise we can just open the tooltip right away.
|
|
19
|
-
}else setShowTooltip(true);}};useEffect(()=>{if(showTooltip&&tip!==null){// This is necessary to ensure that even when a single mouse event
|
|
19
|
+
}else setShowTooltip(true);}};useEffect(()=>{const heap2=getHeap();if(showTooltip&&tip!==null){// This is necessary to ensure that even when a single mouse event
|
|
20
20
|
// arrives to a tool-tipped component, the tooltip is correctly positioned
|
|
21
21
|
// once opened (because similar call above does not have effect until
|
|
22
22
|
// the tooltip is fully mounted, and that is delayed to future rendering
|
|
23
23
|
// cycle due to the implementation).
|
|
24
|
-
if(tooltipRef.current){tooltipRef.current.pointTo(
|
|
24
|
+
if(tooltipRef.current){tooltipRef.current.pointTo(heap2.lastCursorX+window.scrollX,heap2.lastCursorY+window.scrollY,placement,wrapperRef.current);}const listener=()=>{setShowTooltip(false);};window.addEventListener("scroll",listener);return()=>{window.removeEventListener("scroll",listener);};}return undefined;},[placement,showTooltip,tip]);return/*#__PURE__*/_jsxs("div",{className:custom.wrapper,onClick:()=>{if(heap.timerId){clearTimeout(heap.timerId);heap.timerId=undefined;heap.triggeredByTouch=false;}},onMouseLeave:()=>{setShowTooltip(false);},onMouseMove:e=>{updatePortalPosition(e.clientX,e.clientY);},onTouchStart:()=>{heap.triggeredByTouch=true;},ref:wrapperRef,role:"presentation",children:[showTooltip&&tip!==null?/*#__PURE__*/_jsx(Tooltip,{ref:tooltipRef,theme:custom,children:tip}):null,children]});};const e=WithTooltip;e.PLACEMENTS=PLACEMENTS;export default e;
|
|
25
25
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["useEffect","useRef","useState","useTheme","Tooltip","PLACEMENTS","defaultTheme","jsx","_jsx","jsxs","_jsxs","WithTooltip","children","placement","ABOVE_CURSOR","theme","tip","custom","current","heap","lastCursorX","lastCursorY","timerId","undefined","triggeredByTouch","tooltipRef","wrapperRef","showTooltip","setShowTooltip","updatePortalPosition","cursorX","cursorY","wrapperRect","getBoundingClientRect","left","right","top","bottom","pointTo","window","scrollX","scrollY","setTimeout","listener","addEventListener","removeEventListener","className","wrapper","onClick","clearTimeout","onMouseLeave","onMouseMove","e","clientX","clientY","onTouchStart","ref","role"],"sources":["../../../../../src/shared/components/WithTooltip/index.tsx"],"sourcesContent":["/* global window */\n\nimport {\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport Tooltip, {\n PLACEMENTS,\n type ThemeKeysT as TooltipThemeKeysT,\n} from './Tooltip';\n\nimport defaultTheme from './default-theme.scss';\n\ntype PropsT = {\n children?: ReactNode;\n placement?: PLACEMENTS;\n theme?: Theme<'wrapper' | TooltipThemeKeysT>;\n tip?: ReactNode;\n};\n\ntype TooltipRefT = {\n pointTo: (\n x: number,\n y: number,\n placement: PLACEMENTS,\n wrapperRef: HTMLDivElement,\n ) => void;\n};\n\ntype HeapT = {\n lastCursorX: number;\n lastCursorY: number;\n timerId?: NodeJS.Timeout;\n triggeredByTouch: boolean;\n};\n\n/**\n * Implements a simple to use and themeable tooltip component, _e.g._\n * ```js\n * <WithTooltip tip=\"This is example tooltip.\">\n * <p>Hover to see the tooltip.</p>\n * </WithTooltip>\n * ```\n * **Children:** Children are rendered in the place of `<WithTooltip>`,\n * and when hovered the tooltip is shown. By default the wrapper itself is\n * `<div>` block with `display: inline-block`.\n * @param tip – Anything React is able to render,\n * _e.g._ a tooltip text. This will be the tooltip content.\n * @param {WithTooltipTheme} props.theme _Ad hoc_ theme.\n */\nconst WithTooltip: FunctionComponent<PropsT> = ({\n children,\n placement = PLACEMENTS.ABOVE_CURSOR,\n theme,\n tip,\n}) => {\n const custom = useTheme('WithTooltip', defaultTheme, theme);\n\n const { current: heap } = useRef<HeapT>({\n lastCursorX: 0,\n lastCursorY: 0,\n timerId: undefined,\n triggeredByTouch: false,\n });\n const tooltipRef = useRef<TooltipRefT>(null);\n const wrapperRef = useRef<HTMLDivElement>(null);\n const [showTooltip, setShowTooltip] = useState(false);\n\n const updatePortalPosition = (cursorX: number, cursorY: number) => {\n if (showTooltip) {\n const wrapperRect = wrapperRef.current!.getBoundingClientRect();\n if (\n cursorX < wrapperRect.left\n || cursorX > wrapperRect.right\n || cursorY < wrapperRect.top\n || cursorY > wrapperRect.bottom\n ) {\n setShowTooltip(false);\n } else if (tooltipRef.current) {\n tooltipRef.current.pointTo(\n cursorX + window.scrollX,\n cursorY + window.scrollY,\n placement,\n wrapperRef.current!,\n );\n }\n } else {\n heap.lastCursorX = cursorX;\n heap.lastCursorY = cursorY;\n\n // If tooltip was triggered by a touch, we delay its opening by a bit,\n // to ensure it was not a touch-click - in the case of touch click we\n // want to do the click, rather than show the tooltip, and the delay\n // gives click handler a chance to abort the tooltip openning.\n if (heap.triggeredByTouch) {\n heap.timerId ??= setTimeout(() => {\n heap.triggeredByTouch = false;\n heap.timerId = undefined;\n setShowTooltip(true);\n }, 300);\n\n // Otherwise we can just open the tooltip right away.\n } else setShowTooltip(true);\n }\n };\n\n useEffect(() => {\n if (showTooltip && tip !== null) {\n // This is necessary to ensure that even when a single mouse event\n // arrives to a tool-tipped component, the tooltip is correctly positioned\n // once opened (because similar call above does not have effect until\n // the tooltip is fully mounted, and that is delayed to future rendering\n // cycle due to the implementation).\n if (tooltipRef.current) {\n tooltipRef.current.pointTo(\n
|
|
1
|
+
{"version":3,"file":"index.js","names":["useEffect","useEffectEvent","useRef","useState","useTheme","Tooltip","PLACEMENTS","defaultTheme","jsx","_jsx","jsxs","_jsxs","WithTooltip","children","placement","ABOVE_CURSOR","theme","tip","custom","current","heap","lastCursorX","lastCursorY","timerId","undefined","triggeredByTouch","tooltipRef","wrapperRef","showTooltip","setShowTooltip","getHeap","updatePortalPosition","cursorX","cursorY","wrapperRect","getBoundingClientRect","left","right","top","bottom","pointTo","window","scrollX","scrollY","setTimeout","heap2","listener","addEventListener","removeEventListener","className","wrapper","onClick","clearTimeout","onMouseLeave","onMouseMove","e","clientX","clientY","onTouchStart","ref","role"],"sources":["../../../../../src/shared/components/WithTooltip/index.tsx"],"sourcesContent":["/* global window */\n\nimport {\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useEffectEvent,\n useRef,\n useState,\n} from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport Tooltip, {\n PLACEMENTS,\n type ThemeKeysT as TooltipThemeKeysT,\n} from './Tooltip';\n\nimport defaultTheme from './default-theme.scss';\n\ntype PropsT = {\n children?: ReactNode;\n placement?: PLACEMENTS;\n theme?: Theme<'wrapper' | TooltipThemeKeysT>;\n tip?: ReactNode;\n};\n\ntype TooltipRefT = {\n pointTo: (\n x: number,\n y: number,\n placement: PLACEMENTS,\n wrapperRef: HTMLDivElement,\n ) => void;\n};\n\ntype HeapT = {\n lastCursorX: number;\n lastCursorY: number;\n timerId?: NodeJS.Timeout;\n triggeredByTouch: boolean;\n};\n\n/**\n * Implements a simple to use and themeable tooltip component, _e.g._\n * ```js\n * <WithTooltip tip=\"This is example tooltip.\">\n * <p>Hover to see the tooltip.</p>\n * </WithTooltip>\n * ```\n * **Children:** Children are rendered in the place of `<WithTooltip>`,\n * and when hovered the tooltip is shown. By default the wrapper itself is\n * `<div>` block with `display: inline-block`.\n * @param tip – Anything React is able to render,\n * _e.g._ a tooltip text. This will be the tooltip content.\n * @param {WithTooltipTheme} props.theme _Ad hoc_ theme.\n */\nconst WithTooltip: FunctionComponent<PropsT> = ({\n children,\n placement = PLACEMENTS.ABOVE_CURSOR,\n theme,\n tip,\n}) => {\n const custom = useTheme('WithTooltip', defaultTheme, theme);\n\n const { current: heap } = useRef<HeapT>({\n lastCursorX: 0,\n lastCursorY: 0,\n timerId: undefined,\n triggeredByTouch: false,\n });\n const tooltipRef = useRef<TooltipRefT>(null);\n const wrapperRef = useRef<HTMLDivElement>(null);\n const [showTooltip, setShowTooltip] = useState(false);\n\n const getHeap = useEffectEvent(() => heap);\n\n const updatePortalPosition = (cursorX: number, cursorY: number) => {\n if (showTooltip) {\n const wrapperRect = wrapperRef.current!.getBoundingClientRect();\n if (\n cursorX < wrapperRect.left\n || cursorX > wrapperRect.right\n || cursorY < wrapperRect.top\n || cursorY > wrapperRect.bottom\n ) {\n setShowTooltip(false);\n } else if (tooltipRef.current) {\n tooltipRef.current.pointTo(\n cursorX + window.scrollX,\n cursorY + window.scrollY,\n placement,\n wrapperRef.current!,\n );\n }\n } else {\n heap.lastCursorX = cursorX;\n heap.lastCursorY = cursorY;\n\n // If tooltip was triggered by a touch, we delay its opening by a bit,\n // to ensure it was not a touch-click - in the case of touch click we\n // want to do the click, rather than show the tooltip, and the delay\n // gives click handler a chance to abort the tooltip openning.\n if (heap.triggeredByTouch) {\n heap.timerId ??= setTimeout(() => {\n heap.triggeredByTouch = false;\n heap.timerId = undefined;\n setShowTooltip(true);\n }, 300);\n\n // Otherwise we can just open the tooltip right away.\n } else setShowTooltip(true);\n }\n };\n\n useEffect(() => {\n const heap2 = getHeap();\n\n if (showTooltip && tip !== null) {\n // This is necessary to ensure that even when a single mouse event\n // arrives to a tool-tipped component, the tooltip is correctly positioned\n // once opened (because similar call above does not have effect until\n // the tooltip is fully mounted, and that is delayed to future rendering\n // cycle due to the implementation).\n if (tooltipRef.current) {\n tooltipRef.current.pointTo(\n heap2.lastCursorX + window.scrollX,\n heap2.lastCursorY + window.scrollY,\n placement,\n wrapperRef.current!,\n );\n }\n\n const listener = () => {\n setShowTooltip(false);\n };\n window.addEventListener('scroll', listener);\n return () => {\n window.removeEventListener('scroll', listener);\n };\n }\n return undefined;\n }, [\n placement,\n showTooltip,\n tip,\n ]);\n\n return (\n <div\n className={custom.wrapper}\n onClick={() => {\n if (heap.timerId) {\n clearTimeout(heap.timerId);\n heap.timerId = undefined;\n heap.triggeredByTouch = false;\n }\n }}\n onMouseLeave={() => {\n setShowTooltip(false);\n }}\n onMouseMove={(e) => {\n updatePortalPosition(e.clientX, e.clientY);\n }}\n onTouchStart={() => {\n heap.triggeredByTouch = true;\n }}\n ref={wrapperRef}\n role=\"presentation\"\n >\n {\n showTooltip && tip !== null\n ? <Tooltip ref={tooltipRef} theme={custom}>{tip}</Tooltip>\n : null\n }\n {children}\n </div>\n );\n};\n\ntype ExportT = {\n PLACEMENTS: typeof PLACEMENTS;\n} & typeof WithTooltip;\n\nconst e: ExportT = WithTooltip as Export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","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssr.js","names":["readFileSync","registerHooks","basename","dirname","resolve","fileURLToPath","transformSync","ssrFactory","noop","run","options","root","ssrRequest","testFolder","webpackConfig","load","url","context","nextLoad","startsWith","includes","match","path","code","cwd","envName","babelEnv","filename","format","shortCircuit","source","entry","p","babelModule","module","__esModule","default","exportName","entryExportName","Application","renderer","status","csrfToken","markup","Promise","done","fail","cookie","send","set","value","error","process","on","message"],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/ssr.ts"],"sourcesContent":["/* eslint-disable import/dynamic-import-chunkname, import/no-extraneous-dependencies */\n\nimport { readFileSync } from 'node:fs';\nimport { registerHooks } from 'node:module';\nimport { basename, dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { Request, Response } from 'express';\nimport type {
|
|
1
|
+
{"version":3,"file":"ssr.js","names":["readFileSync","registerHooks","basename","dirname","resolve","fileURLToPath","transformSync","ssrFactory","noop","run","options","root","ssrRequest","testFolder","webpackConfig","load","url","context","nextLoad","startsWith","includes","match","path","code","cwd","envName","babelEnv","filename","format","shortCircuit","source","entry","p","babelModule","module","__esModule","default","exportName","entryExportName","Application","renderer","status","csrfToken","markup","Promise","done","fail","cookie","send","set","value","error","process","on","message"],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/ssr.ts"],"sourcesContent":["/* eslint-disable import/dynamic-import-chunkname, import/no-extraneous-dependencies */\n\nimport { readFileSync } from 'node:fs';\nimport { registerHooks } from 'node:module';\nimport { basename, dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { Request, Response } from 'express';\nimport type { Configuration } from 'webpack';\n\nimport { transformSync } from '@babel/core';\n\nimport ssrFactory from 'server/renderer';\n\nexport type LaunchT = {\n // TODO: Should it be typed as the renderer's options type?\n options: Record<string, unknown>;\n\n root: string;\n ssrRequest: object;\n testFolder: string;\n webpackConfig: Configuration;\n};\n\nexport type ResultT = {\n markup: string;\n status: number;\n};\n\nfunction noop() {\n // NOOP\n}\n\nasync function run({\n options,\n root,\n ssrRequest,\n testFolder,\n webpackConfig,\n}: LaunchT) {\n // NOTE: It looks like @babel/register does not work for us here, because\n // it only supports transpiling of modules loaded with require(), so here\n // is, presumably, a temporary workaround relying on the new NodeJS module\n // API, and Babel's core, to transpile all modules loaded further into\n // CommonJS. I guess, later we'll be able to get rid of this, as Babel\n // register supports runtime transformation of modules loaded with import().\n registerHooks({\n load(url, context, nextLoad) {\n if (\n url.startsWith('file://')\n && !url.includes('/node_modules/')\n && !url.includes('/config/babel/')\n && url.match(/\\.(js|jsx|ts|tsx|svg)$/)\n ) {\n const path = fileURLToPath(url);\n let code = readFileSync(path, 'utf8');\n code = transformSync(code, {\n cwd: dirname(path),\n envName: options.babelEnv as string,\n filename: basename(path),\n root,\n })?.code ?? '';\n return {\n format: 'commonjs',\n shortCircuit: true,\n source: code,\n };\n }\n\n return nextLoad(url, context);\n },\n });\n\n if (options.entry) {\n const p = resolve(testFolder, options.entry as string);\n const babelModule = await import(p) as NodeJS.Module;\n\n // TODO: This is basically a hotfix hack, which works both for the library\n // itself, and for dependent projects... (those tested so far). It sure has\n // to be reworked later.\n /* eslint-disable no-underscore-dangle */\n const module = (\n '__esModule' in babelModule\n && typeof babelModule.__esModule === 'boolean'\n && babelModule.__esModule\n && 'default' in babelModule\n ? babelModule.default : babelModule\n ) as NodeJS.Module;\n /* eslint-enable no-underscore-dangle */\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n // eslint-disable-next-line no-param-reassign\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName];\n // eslint-disable-next-line no-param-reassign\n } else options.Application = module;\n }\n\n const renderer = ssrFactory(webpackConfig, options);\n let status = 200; // OK\n\n // eslint-disable-next-line no-param-reassign\n (ssrRequest as Request).csrfToken = () => '';\n\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n process.send?.({ markup, status } satisfies ResultT);\n}\n\nprocess.on('message', (message: LaunchT) => {\n void run(message);\n});\n"],"mappings":"AAAA,uFAEA,OAASA,YAAY,KAAQ,SAAS,CACtC,OAASC,aAAa,KAAQ,aAAa,CAC3C,OAASC,QAAQ,CAAEC,OAAO,CAAEC,OAAO,KAAQ,WAAW,CACtD,OAASC,aAAa,KAAQ,UAAU,CAKxC,OAASC,aAAa,KAAQ,aAAa,CAE3C,MAAO,CAAAC,UAAU,mCAiBjB,QAAS,CAAAC,IAAIA,CAAA,CAAG,CACd;AAAA,CAGF,cAAe,CAAAC,GAAGA,CAAC,CACjBC,OAAO,CACPC,IAAI,CACJC,UAAU,CACVC,UAAU,CACVC,aACO,CAAC,CAAE,CACV;AACA;AACA;AACA;AACA;AACA;AACAb,aAAa,CAAC,CACZc,IAAIA,CAACC,GAAG,CAAEC,OAAO,CAAEC,QAAQ,CAAE,CAC3B,GACEF,GAAG,CAACG,UAAU,CAAC,SAAS,CAAC,EACtB,CAACH,GAAG,CAACI,QAAQ,CAAC,gBAAgB,CAAC,EAC/B,CAACJ,GAAG,CAACI,QAAQ,CAAC,gBAAgB,CAAC,EAC/BJ,GAAG,CAACK,KAAK,CAAC,wBAAwB,CAAC,CACtC,CACA,KAAM,CAAAC,IAAI,CAAGjB,aAAa,CAACW,GAAG,CAAC,CAC/B,GAAI,CAAAO,IAAI,CAAGvB,YAAY,CAACsB,IAAI,CAAE,MAAM,CAAC,CACrCC,IAAI,CAAGjB,aAAa,CAACiB,IAAI,CAAE,CACzBC,GAAG,CAAErB,OAAO,CAACmB,IAAI,CAAC,CAClBG,OAAO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D,IAAK,CAAAN,QAAQ,CACX5B,UAAU,CAEV;AACA;AACA;AACC,CACCmC,MAAM,CAAEvC,IAAI,CACZwC,IAAI,CAAEH,IAAI,CACVI,GAAG,CAAEzC,IAAI,CACTiC,MAAM,CAAGS,KAAa,EAAK,CACzBT,MAAM,CAAGS,KAAK,CAChB,CACF,CAAC,CAEAC,KAAK,EAAK,CACT;AACA;AACA,GAAIA,KAAK,CAAEL,IAAI,CAACK,KAAc,CAAC,CAAC,IAC3B,CAAAN,IAAI,CAAC,EAAE,CAAC,CACf,CACF,CAAC,CACH,CAAC,CAAC,CAEFO,OAAO,CAACJ,IAAI,GAAG,CAAEL,MAAM,CAAEF,MAAO,CAAmB,CAAC,CACtD,CAEAW,OAAO,CAACC,EAAE,CAAC,SAAS,CAAGC,OAAgB,EAAK,CAC1C,IAAK,CAAA7C,GAAG,CAAC6C,OAAO,CAAC,CACnB,CAAC,CAAC","ignoreList":[]}
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "1.
|
|
2
|
+
"version": "1.52.1",
|
|
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.15.
|
|
20
|
+
"axios": "^1.15.2",
|
|
21
21
|
"commander": "^14.0.3",
|
|
22
22
|
"compression": "^1.8.1",
|
|
23
23
|
"config": "^4.4.1",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"raf": "^3.4.1",
|
|
36
36
|
"react": "^19.2.5",
|
|
37
37
|
"react-dom": "^19.2.5",
|
|
38
|
-
"react-router": "^7.14.
|
|
38
|
+
"react-router": "^7.14.2",
|
|
39
39
|
"request-ip": "^3.3.0",
|
|
40
40
|
"rimraf": "^6.1.3",
|
|
41
41
|
"serialize-javascript": "^7.0.5",
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"@babel/register": "^7.28.6",
|
|
56
56
|
"@dr.pogodin/babel-plugin-transform-assets": "^1.2.6",
|
|
57
57
|
"@dr.pogodin/babel-preset-svgr": "^1.9.3",
|
|
58
|
-
"@dr.pogodin/eslint-configs": "^0.2.
|
|
58
|
+
"@dr.pogodin/eslint-configs": "^0.2.12",
|
|
59
59
|
"@pmmmwh/react-refresh-webpack-plugin": "^0.6.2",
|
|
60
60
|
"@standard-schema/spec": "^1.1.0",
|
|
61
61
|
"@testing-library/dom": "^10.4.1",
|
|
@@ -96,7 +96,7 @@
|
|
|
96
96
|
"mini-css-extract-plugin": "^2.10.2",
|
|
97
97
|
"mockdate": "^3.0.5",
|
|
98
98
|
"nodelist-foreach-polyfill": "^1.2.0",
|
|
99
|
-
"postcss": "^8.5.
|
|
99
|
+
"postcss": "^8.5.12",
|
|
100
100
|
"postcss-loader": "^8.2.1",
|
|
101
101
|
"postcss-scss": "^4.0.9",
|
|
102
102
|
"pretty": "^2.0.0",
|
|
@@ -106,11 +106,11 @@
|
|
|
106
106
|
"sass-loader": "^16.0.7",
|
|
107
107
|
"sitemap": "^9.0.1",
|
|
108
108
|
"source-map-loader": "^5.0.0",
|
|
109
|
-
"stylelint": "^17.
|
|
109
|
+
"stylelint": "^17.9.1",
|
|
110
110
|
"stylelint-config-standard-scss": "^17.0.0",
|
|
111
111
|
"supertest": "^7.2.2",
|
|
112
112
|
"tsc-alias": "1.8.16",
|
|
113
|
-
"tstyche": "^7.
|
|
113
|
+
"tstyche": "^7.1.0",
|
|
114
114
|
"typed-scss-modules": "^8.1.1",
|
|
115
115
|
"typescript": "^5.9.3",
|
|
116
116
|
"webpack": "^5.106.2",
|