@dr.pogodin/react-utils 1.47.0-alpha.3 → 1.47.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/development/client/getInj.js +48 -37
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/client/index.js +3 -2
- package/build/development/client/index.js.map +1 -1
- package/build/development/index.js +3 -3
- package/build/development/index.js.map +1 -1
- package/build/development/server/renderer.js +12 -30
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +2 -2
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/utils/config.js +37 -9
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/index.js +2 -2
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +2 -1
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/production/client/getInj.js +12 -10
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/client/index.js +1 -1
- package/build/production/client/index.js.map +1 -1
- package/build/production/index.js +2 -1
- package/build/production/index.js.map +1 -1
- package/build/production/server/renderer.js +6 -9
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +2 -2
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/utils/config.js +8 -4
- package/build/production/shared/utils/config.js.map +1 -1
- package/build/production/shared/utils/index.js +1 -1
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +1 -1
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/types-code/client/getInj.d.ts +1 -2
- package/build/types-code/client/index.d.ts +1 -1
- package/build/types-code/index.d.ts +1 -1
- package/build/types-code/shared/utils/config.d.ts +4 -2
- package/build/types-code/shared/utils/index.d.ts +2 -2
- package/build/types-code/shared/utils/splitComponent.d.ts +6 -4
- package/build/web/client/getInj.js +48 -37
- package/build/web/client/getInj.js.map +1 -1
- package/build/web/client/index.js +3 -2
- package/build/web/client/index.js.map +1 -1
- package/build/web/index.js +3 -3
- package/build/web/index.js.map +1 -1
- package/build/web/server/renderer.js +12 -30
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/shared/components/Modal/index.js +2 -2
- package/build/web/shared/components/Modal/index.js.map +1 -1
- package/build/web/shared/utils/config.js +36 -10
- package/build/web/shared/utils/config.js.map +1 -1
- package/build/web/shared/utils/index.js +2 -2
- package/build/web/shared/utils/index.js.map +1 -1
- package/build/web/shared/utils/splitComponent.js +2 -1
- package/build/web/shared/utils/splitComponent.js.map +1 -1
- package/config/jest/setup.js +8 -1
- package/config/webpack/app-base.js +2 -2
- package/config/webpack/lib-base.js +0 -1
- package/package.json +2 -4
- package/src/client/getInj.ts +60 -40
- package/src/client/index.tsx +5 -3
- package/src/index.ts +3 -3
- package/src/server/renderer.tsx +16 -35
- package/src/shared/components/Modal/index.tsx +2 -2
- package/src/shared/utils/config.ts +48 -12
- package/src/shared/utils/index.ts +2 -2
- package/src/shared/utils/splitComponent.tsx +14 -2
- package/types.d.ts +1 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.js","names":["fs","path","Writable","brotliCompress","brotliDecompress","winston","GlobalStateProvider","SsrContext","timer","cloneDeep","defaults","get","mapValues","config","forge","prerenderToNodeStream","HelmetProvider","StaticRouter","serializeJs","setBuildInfo","Cache","jsx","_jsx","SECRET","sanitizedConfig","SCRIPT_LOCATIONS","ServerSsrContext","chunks","status","constructor","req","chunkGroups","initialState","getBuildInfo","context","url","resolve","JSON","parse","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","Promise","reject","random","getBytes","err","iv","cipher","createCipher","start","isBrotliAcceptable","acceptable","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","publicPath","outputPath","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","all","helmet","webpackStats","locals","toJson","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","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","update","util","createBuffer","finish","INJ","encode64","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 fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport type { Request, RequestHandler } from 'express';\nimport type { ComponentType } from 'react';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\n\nimport {\n cloneDeep,\n defaults,\n get,\n mapValues,\n} from 'lodash-es';\n\nimport config from 'config';\nimport forge from 'node-forge';\n\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { type HelmetDataContext, HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\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;\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 key is expected, see\n * node-forge documentation, in case of doubts).\n * @return Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nasync function prepareCipher(key: string): Promise<{\n cipher: forge.cipher.BlockCipher;\n iv: string;\n}> {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\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<string | ScriptT> = []) {\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 timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\n transports: [new transports.Console()],\n });\n}\n\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: unknown;\n};\n\nexport type BeforeRenderT = (\n req: Request,\n config: ConfigT,\n) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n staticCacheSize?: number;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\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 { publicPath, path: outputPath } = 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\n const [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n // NOTE: Written this way to avoid triggering the \"await-thenable\"\n // ESLint rule.\n brr instanceof Promise ? brr : Promise.resolve(brr),\n\n prepareCipher(buildInfo.key),\n ]);\n\n let helmet: HelmetDataContext['helmet'];\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats') as Stats | undefined;\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name)\n ?? [],\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: NodeJS.ReadableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n rejectArg(arg as Error);\n };\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n const helmetContext = {} as HelmetDataContext;\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\n const timeout = ops.ssrTimeout! + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject ?? sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\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) assets.forEach((asset) => chunkSet.add(asset));\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":"AAAA;AACA;AACA;;AAEA,OAAOA,EAAE,MAAM,SAAS;AACxB,OAAOC,IAAI,MAAM,WAAW;AAC5B,SAASC,QAAQ,QAAQ,aAAa;AACtC,SAASC,cAAc,EAAEC,gBAAgB,QAAQ,WAAW;AAK5D,OAAOC,OAAO,MAAM,SAAS;AAE7B,SAASC,mBAAmB,EAAEC,UAAU,QAAQ,gCAAgC;AAChF,SAASC,KAAK,QAAQ,sBAAsB;AAE5C,SACEC,SAAS,EACTC,QAAQ,EACRC,GAAG,EACHC,SAAS,QACJ,WAAW;AAElB,OAAOC,MAAM,MAAM,QAAQ;AAC3B,OAAOC,KAAK,MAAM,YAAY;AAE9B,SAASC,qBAAqB,QAAQ,kBAAkB;AACxD,SAAiCC,cAAc,QAAQ,0BAA0B;AACjF,SAASC,YAAY,QAAQ,cAAc;AAC3C,OAAOC,WAAW,MAAM,sBAAsB;AAC9C,SAA0BC,YAAY;AAItC,OAAOC,KAAK;;AAEZ;AACA;AAAA,SAAAC,GAAA,IAAAC,IAAA;AACA,MAAM;EAAEC,MAAM;EAAE,GAAGC;AAAgB,CAAC,GAAGX,MAAM;;AAE7C;AACA;AACA;AACA;;AAMA;;AAMA;;AASA,WAAYY,gBAAgB,0BAAhBA,gBAAgB;EAAhBA,gBAAgB;EAAhBA,gBAAgB;EAAhBA,gBAAgB;EAAA,OAAhBA,gBAAgB;AAAA;AAM5B,OAAO,MAAMC,gBAAgB,SACnBnB,UAAU,CACa;EAG/BoB,MAAM,GAAa,EAAE;EAMrBC,MAAM,GAAW,GAAG;EAEpBC,WAAWA,CACTC,GAAY,EACZC,WAAyB,EACzBC,YAAqB,EACrB;IACA,KAAK,CAACvB,SAAS,CAACuB,YAAY,CAAC,IAAK,CAAC,CAAY,CAAC;IAChD,IAAI,CAACD,WAAW,GAAGA,WAAW;IAC9B,IA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AAM,IAAI,GAAG;MACvC,IAAIA,MAAM,KAAK,GAAG,EAAEc,GAAG,CAACd,MAAM,CAACA,MAAM,CAAC;MAEtC,IAAIqF,QAAQ,IAAIrF,MAAM,GAAG,GAAG,EAAE;QAC5B;QACA;QACA,MAAM,IAAIiB,OAAO,CAAO,CAACyE,IAAI,EAAEC,MAAM,KAAK;UACxCpH,cAAc,CAACsH,IAAI,EAAE,CAACD,KAAK,EAAEL,MAAM,KAAK;YACtC,IAAIK,KAAK,EAAED,MAAM,CAACC,KAAK,CAAC,CAAC,KACpB;cACH,MAAMqF,CAAC,GAAG1F,MAAoC;cAC9C0F,CAAC,CAAC/E,KAAK,GAAIhG,GAAG,CAEXgG,KAAK;cACRpB,KAAK,CAAEyF,GAAG,CAAC;gBAAEhF,MAAM,EAAE0F,CAAC;gBAAEjL;cAAO,CAAC,EAAEqF,QAAQ,CAACrE,GAAG,EAAEuE,MAAM,CAAC3B,MAAM,CAAC;cAC9D8B,IAAI,CAAC,CAAC;YACR;UACF,CAAC,CAAC;QACJ,CAAC,CAAC;MACJ;;MAEA;MACA;MACA;MACA5E,GAAG,CAAC2E,IAAI,CAACI,IAAI,CAAC;IAChB,CAAC,CAAC,OAAOD,KAAK,EAAE;MACdX,IAAI,CAACW,KAAK,CAAC;IACb;EACF,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"renderer.js","names":["Buffer","createCipheriv","randomBytes","fs","path","Writable","brotliCompress","brotliDecompress","winston","GlobalStateProvider","SsrContext","timer","cloneDeep","defaults","get","mapValues","config","prerenderToNodeStream","HelmetProvider","StaticRouter","serializeJs","setBuildInfo","Cache","jsx","_jsx","SECRET","sanitizedConfig","SCRIPT_LOCATIONS","ServerSsrContext","chunks","status","constructor","req","chunkGroups","initialState","getBuildInfo","context","url","resolve","JSON","parse","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","iv","cipher","from","isBrotliAcceptable","acceptable","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","beforeRender","Promise","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","helmet","webpackStats","locals","toJson","all","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","reject","helmetContext","state","children","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","logMsg","log","redirectTo","redirect","ready","pipe","destroy","write","chunk","_","payload","CONFIG","ISTATE","ignoreFunction","unsafe","INJ","concat","update","final","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { type Cipheriv, createCipheriv, randomBytes } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport type { Request, RequestHandler } from 'express';\nimport type { ComponentType } from 'react';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\n\nimport {\n cloneDeep,\n defaults,\n get,\n mapValues,\n} from 'lodash-es';\n\nimport config from 'config';\n\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { type HelmetDataContext, HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\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;\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<string | ScriptT> = []) {\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 timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\n transports: [new transports.Console()],\n });\n}\n\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: unknown;\n};\n\nexport type BeforeRenderT = (\n req: Request,\n config: ConfigT,\n) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n staticCacheSize?: number;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\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 { publicPath, path: outputPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath as string}manifest.json\">` : '';\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface BufferWithNonce extends ArrayBuffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n // TODO: Look at it later.\n // eslint-disable-next-line complexity\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n\n // TODO: It should be implemented more careful.\n h = h.replace(regex, (req as unknown as {\n nonce: string;\n }).nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const brr = ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT);\n const { configToInject, extraScripts, initialState } = await brr;\n\n const [cipher, iv] = prepareCipher(buildInfo.key);\n\n let helmet: HelmetDataContext['helmet'];\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats') as Stats | undefined;\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name)\n ?? [],\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: NodeJS.ReadableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n rejectArg(arg as Error);\n };\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n const helmetContext = {} as HelmetDataContext;\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\n const timeout = ops.ssrTimeout! + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject ?? sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n\n const INJ = Buffer.concat([\n iv,\n cipher.update(payload, 'utf8'),\n cipher.final(),\n ]).toString('base64');\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\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, l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K;cACRpB,KAAK,CAAEwF,GAAG,CAAC;gBAAE/E,MAAM,EAAEyF,CAAC;gBAAE3K;cAAO,CAAC,EAAEgF,QAAQ,CAAChE,GAAG,EAAEkE,MAAM,CAAC5B,MAAM,CAAC;cAC9D+B,IAAI,CAAC,CAAC;YACR;UACF,CAAC,CAAC;QACJ,CAAC,CAAC;MACJ;;MAEA;MACA;MACA;MACAvE,GAAG,CAACsE,IAAI,CAACI,IAAI,CAAC;IAChB,CAAC,CAAC,OAAOD,KAAK,EAAE;MACdX,IAAI,CAACW,KAAK,CAAC;IACb;EACF,CAAC;AACH","ignoreList":[]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useEffect, useMemo, useRef } from 'react';
|
|
2
|
-
import
|
|
2
|
+
import { createPortal } from 'react-dom';
|
|
3
3
|
import themed from '@dr.pogodin/react-themes';
|
|
4
4
|
import baseTheme from "./base-theme.scss";
|
|
5
5
|
import S from "./styles.scss";
|
|
@@ -69,7 +69,7 @@ const BaseModal = ({
|
|
|
69
69
|
,
|
|
70
70
|
tabIndex: 0
|
|
71
71
|
}), []);
|
|
72
|
-
return /*#__PURE__*/
|
|
72
|
+
return /*#__PURE__*/createPortal(/*#__PURE__*/_jsxs("div", {
|
|
73
73
|
children: [focusLast, /*#__PURE__*/_jsx("div", {
|
|
74
74
|
"aria-label": "Cancel",
|
|
75
75
|
className: theme.overlay,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["useEffect","useMemo","useRef","
|
|
1
|
+
{"version":3,"file":"index.js","names":["useEffect","useMemo","useRef","createPortal","themed","baseTheme","S","jsx","_jsx","jsxs","_jsxs","BaseModal","cancelOnScrolling","children","containerStyle","dontDisableScrolling","onCancel","overlayStyle","style","testId","testIdForOverlay","theme","containerRef","overlayRef","window","addEventListener","removeEventListener","document","body","classList","add","scrollingDisabledByModal","remove","focusLast","onFocus","elems","current","querySelectorAll","i","length","focus","activeElement","tabIndex","className","overlay","process","env","NODE_ENV","undefined","onClick","e","stopPropagation","onKeyDown","key","ref","node","role","container","onWheel","event"],"sources":["../../../../../src/shared/components/Modal/index.tsx"],"sourcesContent":["import {\n type CSSProperties,\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useMemo,\n useRef,\n} from 'react';\n\nimport { createPortal } from 'react-dom';\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport baseTheme from './base-theme.scss';\nimport S from './styles.scss';\n\ntype PropsT = {\n cancelOnScrolling?: boolean;\n children?: ReactNode;\n dontDisableScrolling?: boolean;\n onCancel?: () => void;\n overlayStyle?: CSSProperties;\n style?: CSSProperties;\n testId?: string;\n testIdForOverlay?: string;\n theme: Theme<'container' | 'overlay'>;\n\n /** @deprecated */\n containerStyle?: CSSProperties;\n};\n\n/**\n * The `<Modal>` component implements a simple themeable modal window, wrapped\n * into the default theme. `<BaseModal>` exposes the base non-themed component.\n * **Children:** Component children are rendered as the modal content.\n * @param {object} props Component properties. Beside props documented below,\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties) are supported as well.\n * @param {function} [props.onCancel] The callback to trigger when user\n * clicks outside the modal, or presses Escape. It is expected to hide the\n * modal.\n * @param {ModalTheme} [props.theme] _Ad hoc_ theme.\n */\nconst BaseModal: FunctionComponent<PropsT> = ({\n cancelOnScrolling,\n children,\n containerStyle,\n dontDisableScrolling,\n onCancel,\n overlayStyle,\n style,\n testId,\n testIdForOverlay,\n theme,\n}) => {\n const containerRef = useRef<HTMLDivElement | null>(null);\n const overlayRef = useRef<HTMLDivElement | null>(null);\n\n // Sets up modal cancellation of scrolling, if opted-in.\n useEffect(() => {\n if (cancelOnScrolling && onCancel) {\n window.addEventListener('scroll', onCancel);\n window.addEventListener('wheel', onCancel);\n }\n return () => {\n if (cancelOnScrolling && onCancel) {\n window.removeEventListener('scroll', onCancel);\n window.removeEventListener('wheel', onCancel);\n }\n };\n }, [cancelOnScrolling, onCancel]);\n\n // Disables window scrolling, if it is not opted-out.\n useEffect(() => {\n if (!dontDisableScrolling) {\n document.body.classList.add(S.scrollingDisabledByModal);\n }\n return () => {\n if (!dontDisableScrolling) {\n document.body.classList.remove(S.scrollingDisabledByModal);\n }\n };\n }, [dontDisableScrolling]);\n\n const focusLast = useMemo(() => (\n <div\n onFocus={() => {\n const elems = containerRef.current!.querySelectorAll('*');\n for (let i = elems.length - 1; i >= 0; --i) {\n (elems[i] as HTMLElement).focus();\n if (document.activeElement === elems[i]) return;\n }\n overlayRef.current?.focus();\n }}\n // TODO: Have a look at this later.\n // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex\n tabIndex={0}\n />\n ), []);\n\n return createPortal(\n (\n <div>\n {focusLast}\n <div\n aria-label=\"Cancel\"\n className={theme.overlay}\n data-testid={\n process.env.NODE_ENV === 'production'\n ? undefined : testIdForOverlay\n }\n onClick={(e) => {\n if (onCancel) {\n onCancel();\n e.stopPropagation();\n }\n }}\n onKeyDown={(e) => {\n if (e.key === 'Escape' && onCancel) {\n onCancel();\n e.stopPropagation();\n }\n }}\n ref={(node) => {\n if (node && node !== overlayRef.current) {\n overlayRef.current = node;\n node.focus();\n }\n }}\n role=\"button\"\n style={overlayStyle}\n tabIndex={0}\n />\n {\n // NOTE: These rules are disabled because our intention is to keep\n // the element non-interactive (thus not on the keyboard focus chain),\n // and it has `onClick` handler merely to stop propagation of click\n // events to its parent container. This is needed because, for example\n // when the modal is wrapped into an interactive element we don't want\n // any clicks inside the modal to bubble-up to that parent element\n // (because visually and logically the modal dialog does not belong\n // to its parent container, where it technically belongs from\n // the HTML mark-up perpective).\n }\n <div // eslint-disable-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions\n aria-modal=\"true\"\n className={theme.container}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onClick={(e) => {\n e.stopPropagation();\n }}\n onWheel={(event) => {\n event.stopPropagation();\n }}\n ref={containerRef}\n role=\"dialog\"\n style={style ?? containerStyle}\n >\n {children}\n </div>\n <div\n onFocus={() => {\n overlayRef.current?.focus();\n }}\n // TODO: Have a look at this later.\n // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex\n tabIndex={0}\n />\n {focusLast}\n </div>\n ),\n document.body,\n );\n};\n\nexport default themed(BaseModal, 'Modal', baseTheme);\n\n/* Non-themed version of the Modal. */\nexport { BaseModal };\n"],"mappings":"AAAA,SAIEA,SAAS,EACTC,OAAO,EACPC,MAAM,QACD,OAAO;AAEd,SAASC,YAAY,QAAQ,WAAW;AACxC,OAAOC,MAAM,MAAsB,0BAA0B;AAE7D,OAAOC,SAAS;AAChB,OAAOC,CAAC;AAAsB,SAAAC,GAAA,IAAAC,IAAA,EAAAC,IAAA,IAAAC,KAAA;AAiB9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,SAAoC,GAAGA,CAAC;EAC5CC,iBAAiB;EACjBC,QAAQ;EACRC,cAAc;EACdC,oBAAoB;EACpBC,QAAQ;EACRC,YAAY;EACZC,KAAK;EACLC,MAAM;EACNC,gBAAgB;EAChBC;AACF,CAAC,KAAK;EACJ,MAAMC,YAAY,GAAGpB,MAAM,CAAwB,IAAI,CAAC;EACxD,MAAMqB,UAAU,GAAGrB,MAAM,CAAwB,IAAI,CAAC;;EAEtD;EACAF,SAAS,CAAC,MAAM;IACd,IAAIY,iBAAiB,IAAII,QAAQ,EAAE;MACjCQ,MAAM,CAACC,gBAAgB,CAAC,QAAQ,EAAET,QAAQ,CAAC;MAC3CQ,MAAM,CAACC,gBAAgB,CAAC,OAAO,EAAET,QAAQ,CAAC;IAC5C;IACA,OAAO,MAAM;MACX,IAAIJ,iBAAiB,IAAII,QAAQ,EAAE;QACjCQ,MAAM,CAACE,mBAAmB,CAAC,QAAQ,EAAEV,QAAQ,CAAC;QAC9CQ,MAAM,CAACE,mBAAmB,CAAC,OAAO,EAAEV,QAAQ,CAAC;MAC/C;IACF,CAAC;EACH,CAAC,EAAE,CAACJ,iBAAiB,EAAE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AAS,CAAC;;AAEpD;AACA,SAASM,SAAS","ignoreList":[]}
|
|
@@ -4,16 +4,42 @@ import { parse } from 'cookie';
|
|
|
4
4
|
import clientGetInj from "../../client/getInj";
|
|
5
5
|
import { IS_CLIENT_SIDE } from "./isomorphy/environment-check";
|
|
6
6
|
import { requireWeak } from "./webpack";
|
|
7
|
+
let config;
|
|
7
8
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Injects CSRF token into config (on client-side only).
|
|
11
|
+
*
|
|
12
|
+
* BEWARE: It mutates the argument, and also returns it as the result,
|
|
13
|
+
* for chaining.
|
|
14
|
+
*/
|
|
15
|
+
function injectCsrfToken(cfg) {
|
|
16
|
+
// The safeguard for "document" is necessary because in non-Node environments,
|
|
17
|
+
// like React Native, IS_CLIENT_SIDE is "true", however "document" and a bunch
|
|
18
|
+
// of other browser-world features are not available.
|
|
19
|
+
if (IS_CLIENT_SIDE && typeof document !== 'undefined') {
|
|
20
|
+
// eslint-disable-next-line no-param-reassign
|
|
21
|
+
cfg.CSRF = parse(document.cookie).csrfToken;
|
|
22
|
+
}
|
|
23
|
+
return cfg;
|
|
24
|
+
}
|
|
25
|
+
export function getConfig(sync) {
|
|
26
|
+
if (!config) {
|
|
27
|
+
if (IS_CLIENT_SIDE) {
|
|
28
|
+
const inj = clientGetInj();
|
|
29
|
+
config = inj instanceof Promise ? inj.then(injection => {
|
|
30
|
+
const res = injectCsrfToken(injection.CONFIG ?? {});
|
|
31
|
+
config = res;
|
|
32
|
+
return res;
|
|
33
|
+
}) : injectCsrfToken(inj.CONFIG ?? {});
|
|
34
|
+
} else {
|
|
35
|
+
const weak = requireWeak('config');
|
|
36
|
+
if (!weak) throw Error('Internal error');
|
|
37
|
+
config = weak;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (sync && config instanceof Promise) {
|
|
41
|
+
throw Error('The config is not available yet');
|
|
42
|
+
}
|
|
43
|
+
return config;
|
|
17
44
|
}
|
|
18
|
-
export default config;
|
|
19
45
|
//# sourceMappingURL=config.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","names":["parse","clientGetInj","IS_CLIENT_SIDE","requireWeak","config","
|
|
1
|
+
{"version":3,"file":"config.js","names":["parse","clientGetInj","IS_CLIENT_SIDE","requireWeak","config","injectCsrfToken","cfg","document","CSRF","cookie","csrfToken","getConfig","sync","inj","Promise","then","injection","res","CONFIG","weak","Error"],"sources":["../../../../src/shared/utils/config.ts"],"sourcesContent":["/* global document */\n\nimport { parse } from 'cookie';\n\nimport clientGetInj from '../../client/getInj';\n\nimport { IS_CLIENT_SIDE } from './isomorphy/environment-check';\nimport { requireWeak } from './webpack';\n\ntype ConfigT = Record<string, unknown>;\n\nlet config: ConfigT | Promise<ConfigT> | undefined;\n\n/**\n * Injects CSRF token into config (on client-side only).\n *\n * BEWARE: It mutates the argument, and also returns it as the result,\n * for chaining.\n */\nfunction injectCsrfToken(cfg: ConfigT): ConfigT {\n // The safeguard for \"document\" is necessary because in non-Node environments,\n // like React Native, IS_CLIENT_SIDE is \"true\", however \"document\" and a bunch\n // of other browser-world features are not available.\n if (IS_CLIENT_SIDE && typeof document !== 'undefined') {\n // eslint-disable-next-line no-param-reassign\n cfg.CSRF = parse(document.cookie).csrfToken;\n }\n\n return cfg;\n}\n\nexport function getConfig(sync: true): ConfigT;\n\nexport function getConfig(sync?: boolean): ConfigT | Promise<ConfigT>;\n\nexport function getConfig(sync?: boolean): ConfigT | Promise<ConfigT> {\n if (!config) {\n if (IS_CLIENT_SIDE) {\n const inj = clientGetInj();\n config = inj instanceof Promise\n ? inj.then((injection) => {\n const res = injectCsrfToken(injection.CONFIG ?? {});\n config = res;\n return res;\n })\n : injectCsrfToken(inj.CONFIG ?? {});\n } else {\n const weak = requireWeak<ConfigT>('config');\n if (!weak) throw Error('Internal error');\n config = weak;\n }\n }\n\n if (sync && (config instanceof Promise)) {\n throw Error('The config is not available yet');\n }\n\n return config;\n}\n"],"mappings":"AAAA;;AAEA,SAASA,KAAK,QAAQ,QAAQ;AAE9B,OAAOC,YAAY;AAEnB,SAASC,cAAc;AACvB,SAASC,WAAW;AAIpB,IAAIC,MAA8C;;AAElD;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,eAAeA,CAACC,GAAY,EAAW;EAC9C;EACA;EACA;EACA,IAAIJ,cAAc,IAAI,OAAOK,QAAQ,KAAK,WAAW,EAAE;IACrD;IACAD,GAAG,CAACE,IAAI,GAAGR,KAAK,CAACO,QAAQ,CAACE,MAAM,CAAC,CAACC,SAAS;EAC7C;EAEA,OAAOJ,GAAG;AACZ;AAMA,OAAO,SAASK,SAASA,CAACC,IAAc,EAA8B;EACpE,IAAI,CAACR,MAAM,EAAE;IACX,IAAIF,cAAc,EAAE;MAClB,MAAMW,GAAG,GAAGZ,YAAY,CAAC,CAAC;MAC1BG,MAAM,GAAGS,GAAG,YAAYC,OAAO,GAC3BD,GAAG,CAACE,IAAI,CAAEC,SAAS,IAAK;QACxB,MAAMC,GAAG,GAAGZ,eAAe,CAACW,SAAS,CAACE,MAAM,IAAI,CAAC,CAAC,CAAC;QACnDd,MAAM,GAAGa,GAAG;QACZ,OAAOA,GAAG;MACZ,CAAC,CAAC,GACAZ,eAAe,CAACQ,GAAG,CAACK,MAAM,IAAI,CAAC,CAAC,CAAC;IACvC,CAAC,MAAM;MACL,MAAMC,IAAI,GAAGhB,WAAW,CAAU,QAAQ,CAAC;MAC3C,IAAI,CAACgB,IAAI,EAAE,MAAMC,KAAK,CAAC,gBAAgB,CAAC;MACxChB,MAAM,GAAGe,IAAI;IACf;EACF;EAEA,IAAIP,IAAI,IAAKR,MAAM,YAAYU,OAAQ,EAAE;IACvC,MAAMM,KAAK,CAAC,iCAAiC,CAAC;EAChD;EAEA,OAAOhB,MAAM;AACf","ignoreList":[]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import themedImpl, { COMPOSE, PRIORITY, ThemeProvider } from '@dr.pogodin/react-themes';
|
|
2
|
-
import
|
|
2
|
+
import { getConfig } from "./config";
|
|
3
3
|
import * as isomorphy from "./isomorphy";
|
|
4
4
|
import time from "./time";
|
|
5
5
|
import * as webpack from "./webpack";
|
|
@@ -9,5 +9,5 @@ export { default as splitComponent } from "./splitComponent";
|
|
|
9
9
|
const themed = themedImpl;
|
|
10
10
|
themed.COMPOSE = COMPOSE;
|
|
11
11
|
themed.PRIORITY = PRIORITY;
|
|
12
|
-
export {
|
|
12
|
+
export { getConfig, isomorphy, themed, ThemeProvider, time, webpack };
|
|
13
13
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["themedImpl","COMPOSE","PRIORITY","ThemeProvider","
|
|
1
|
+
{"version":3,"file":"index.js","names":["themedImpl","COMPOSE","PRIORITY","ThemeProvider","getConfig","isomorphy","time","webpack","assertEmptyObject","Barrier","Cached","Emitter","Semaphore","withRetries","getSsrContext","default","splitComponent","themed"],"sources":["../../../../src/shared/utils/index.ts"],"sourcesContent":["import themedImpl, {\n COMPOSE,\n PRIORITY,\n type Theme,\n ThemeProvider,\n} from '@dr.pogodin/react-themes';\n\nimport { getConfig } from './config';\nimport * as isomorphy from './isomorphy';\nimport time from './time';\nimport * as webpack from './webpack';\n\nexport {\n assertEmptyObject,\n type Listener,\n type ObjectKey,\n Barrier,\n Cached,\n Emitter,\n Semaphore,\n withRetries,\n} from '@dr.pogodin/js-utils';\n\nexport { getSsrContext } from './globalState';\nexport { default as splitComponent } from './splitComponent';\n\ntype ThemedT = typeof themedImpl & {\n COMPOSE: typeof COMPOSE;\n PRIORITY: typeof PRIORITY;\n};\n\nconst themed: ThemedT = themedImpl as ThemedT;\n\nthemed.COMPOSE = COMPOSE;\nthemed.PRIORITY = PRIORITY;\n\nexport {\n type Theme,\n getConfig,\n isomorphy,\n themed,\n ThemeProvider,\n time,\n webpack,\n};\n"],"mappings":"AAAA,OAAOA,UAAU,IACfC,OAAO,EACPC,QAAQ,EAERC,aAAa,QACR,0BAA0B;AAEjC,SAASC,SAAS;AAClB,OAAO,KAAKC,SAAS;AACrB,OAAOC,IAAI;AACX,OAAO,KAAKC,OAAO;AAEnB,SACEC,iBAAiB,EAGjBC,OAAO,EACPC,MAAM,EACNC,OAAO,EACPC,SAAS,EACTC,WAAW,QACN,sBAAsB;AAE7B,SAASC,aAAa;AACtB,SAASC,OAAO,IAAIC,cAAc;AAOlC,MAAMC,MAAe,GAAGjB,UAAqB;AAE7CiB,MAAM,CAAChB,OAAO,GAAGA,OAAO;AACxBgB,MAAM,CAACf,QAAQ,GAAGA,QAAQ;AAE1B,SAEEE,SAAS,EACTC,SAAS,EACTY,MAAM,EACNd,aAAa,EACbG,IAAI,EACJC,OAAO","ignoreList":[]}
|
|
@@ -11,7 +11,8 @@ function getClientChunkGroups() {
|
|
|
11
11
|
const {
|
|
12
12
|
default: getInj
|
|
13
13
|
} = await import(/* webpackChunkName: "react-utils-client-side-code" */"../../client/getInj");
|
|
14
|
-
|
|
14
|
+
const inj = await getInj();
|
|
15
|
+
return inj.CHUNK_GROUPS ?? {};
|
|
15
16
|
})();
|
|
16
17
|
}
|
|
17
18
|
const refCounts = {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitComponent.js","names":["Suspense","lazy","useInsertionEffect","Barrier","getSsrContext","IS_CLIENT_SIDE","IS_SERVER_SIDE","getBuildInfo","jsx","_jsx","getClientChunkGroups","undefined","default","getInj","CHUNK_GROUPS","refCounts","getPublicPath","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","clientChunkGroups","resolved","Component","Wrapper","children","ref","rest","chunks","includes","CodeSplit","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\nfunction getClientChunkGroups(): Promise<ChunkGroupsT> | undefined {\n if (!IS_CLIENT_SIDE) return undefined;\n\n return (async () => {\n const { default: getInj } = await import(/* webpackChunkName: \"react-utils-client-side-code\" */ '../../client/getInj');\n return getInj().CHUNK_GROUPS ?? {};\n })();\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const clientChunkGroups = await getClientChunkGroups();\n\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n assertChunkName(chunkName, clientChunkGroups);\n }\n\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":"AAAA;;AAEA,SAKEA,QAAQ,EACRC,IAAI,EACJC,kBAAkB,QACb,OAAO;AAEd,SAASC,OAAO,QAAQ,sBAAsB;AAE9C,SAA4BC,aAAa;AAEzC,SACEC,cAAc,EACdC,cAAc,EACdC,YAAY;AACO,SAAAC,GAAA,IAAAC,IAAA;AAErB,SAASC,oBAAoBA,CAAA,EAAsC;EACjE,IAAI,CAACL,cAAc,EAAE,OAAOM,SAAS;EAErC,OAAO,CAAC,YAAY;IAClB,MAAM;MAAEC,OAAO,EAAEC;IAAO,CAAC,GAAG,MAAM,MAAM,CAAC,2EAA4E,CAAC;IACtH,OAAOA,MAAM,CAAC,CAAC,CAACC,YAAY,IAAI,CAAC,CAAC;EACpC,CAAC,EAAE,CAAC;AACN;AAEA,MAAMC,SAAiC,GAAG,CAAC,CAAC;AAE5C,SAASC,aAAaA,CAAA,EAAG;EACvB,OAAOT,YAAY,CAAC,CAAC,CAACU,UAAU;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,cAAcA,CACrBC,IAAY,EACZC,YAAyB,EACzBC,QAAiB,EACU;EAC3B,IAAIC,GAA8B;EAClC,MAAMC,IAAI,GAAG,GAAGP,aAAa,CAAC,CAAC,IAAIG,IAAI,EAAE;E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7D,IAAA,CAACwD;IACC;IAAA;MAAA,GACIO,IAAI;MAAAF,QAAA,EAEPA;IAAQ,CACI;EAAC,CACR,CACX;EAED,OAAOK,SAAS;AAClB","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"splitComponent.js","names":["Suspense","lazy","useInsertionEffect","Barrier","getSsrContext","IS_CLIENT_SIDE","IS_SERVER_SIDE","getBuildInfo","jsx","_jsx","getClientChunkGroups","undefined","default","getInj","inj","CHUNK_GROUPS","refCounts","getPublicPath","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","clientChunkGroups","resolved","Component","Wrapper","children","ref","rest","chunks","includes","CodeSplit","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\nfunction getClientChunkGroups(): Promise<ChunkGroupsT> | undefined {\n if (!IS_CLIENT_SIDE) return undefined;\n\n return (async () => {\n const { default: getInj } = await import(/* webpackChunkName: \"react-utils-client-side-code\" */ '../../client/getInj');\n\n const inj = await getInj();\n return inj.CHUNK_GROUPS ?? {};\n })();\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\ntype GenericComponentPropsT = {\n children?: ReactNode;\n ref?: RefObject<unknown>;\n\n // NOTE: This is necessary, as without it this type (with only optional\n // fields) will be conisdered as \"weak\" by TypeScript, and it will be\n // a error to assign to it any type that does not use \"children\", or \"ref\".\n [propName: string]: unknown;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends GenericComponentPropsT,\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const clientChunkGroups = await getClientChunkGroups();\n\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n assertChunkName(chunkName, clientChunkGroups);\n }\n\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":"AAAA;;AAEA,SAKEA,QAAQ,EACRC,IAAI,EACJC,kBAAkB,QACb,OAAO;AAEd,SAASC,OAAO,QAAQ,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C;QACvC,IAAI,CAAC2B,MAAM,CAACC,QAAQ,CAAC7B,SAAS,CAAC,EAAE4B,MAAM,CAACnB,IAAI,CAACT,SAAS,CAAC;MACzD;;MAEA;MACA;MACA5C,kBAAkB,CAAC,MAAM;QACvB,IAAI,CAACiE,iBAAiB,EAAE,MAAM9B,KAAK,CAAC,gBAAgB,CAAC;QACrD,KAAKW,eAAe,CAACF,SAAS,EAAEqB,iBAAiB,EAAE,IAAI,CAAC;QACxD,OAAO,MAAM;UACXR,eAAe,CAACb,SAAS,EAAEqB,iBAAiB,CAAC;QAC/C,CAAC;MACH,CAAC,EAAE,EAAE,CAAC;MAEN,oBACE1D,IAAA,CAAC4D;MACC;MAAA;QAAA,GACKI,IAAI;QACTD,GAAG,EAAEA,GAAI;QAAAD,QAAA,EAERA;MAAQ,CACA,CAAC;IAEhB,CAAC;IAED,OAAO;MAAE3D,OAAO,EAAE0D;IAAQ,CAAC;EAC7B,CAAC,CAAC;EAEF,MAAMM,SAAmD,GAAGA,CAAC;IAC3DL,QAAQ;IACR,GAAGE;EACY,CAAC,kBAChBhE,IAAA,CAACT,QAAQ;IAAC6E,QAAQ,EAAEZ,WAAY;IAAAM,QAAA,eAC9B9D,IAAA,CAACyD;IACC;IAAA;MAAA,GACIO,IAAI;MAAAF,QAAA,EAEPA;IAAQ,CACI;EAAC,CACR,CACX;EAED,OAAOK,SAAS;AAClB","ignoreList":[]}
|
package/config/jest/setup.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
/* global globalThis, require */
|
|
1
|
+
/* global globalThis, require, window */
|
|
2
|
+
|
|
3
|
+
import { subtle } from 'node:crypto';
|
|
2
4
|
|
|
3
5
|
// eslint-disable-next-line import/no-unassigned-import
|
|
4
6
|
import 'raf/polyfill';
|
|
@@ -11,3 +13,8 @@ if (!globalThis.TextEncoder || !globalThis.TextDecoder) {
|
|
|
11
13
|
globalThis.TextEncoder = TextEncoder;
|
|
12
14
|
globalThis.TextDecoder = TextDecoder;
|
|
13
15
|
}
|
|
16
|
+
|
|
17
|
+
// Polyfill of crypto.subtle in JSDOM environments.
|
|
18
|
+
if (typeof window !== 'undefined') {
|
|
19
|
+
window.crypto.subtle = subtle;
|
|
20
|
+
}
|
|
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
};
|
|
6
6
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
7
|
exports.default = configFactory;
|
|
8
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
9
|
const node_fs_1 = __importDefault(require("node:fs"));
|
|
9
10
|
const node_path_1 = __importDefault(require("node:path"));
|
|
10
11
|
const sitemap_1 = require("sitemap");
|
|
@@ -14,7 +15,6 @@ const isFunction_js_1 = __importDefault(require("lodash/isFunction.js"));
|
|
|
14
15
|
const isObject_js_1 = __importDefault(require("lodash/isObject.js"));
|
|
15
16
|
const autoprefixer_1 = __importDefault(require("autoprefixer"));
|
|
16
17
|
const mini_css_extract_plugin_1 = __importDefault(require("mini-css-extract-plugin"));
|
|
17
|
-
const node_forge_1 = __importDefault(require("node-forge"));
|
|
18
18
|
const webpack_1 = require("webpack");
|
|
19
19
|
const workbox_webpack_plugin_1 = __importDefault(require("workbox-webpack-plugin"));
|
|
20
20
|
const utils_1 = require("@dr.pogodin/babel-plugin-react-css-modules/utils");
|
|
@@ -179,7 +179,7 @@ function configFactory(ops) {
|
|
|
179
179
|
// build info object in case nothing could be loaded.
|
|
180
180
|
buildInfo !== null && buildInfo !== void 0 ? buildInfo : (buildInfo = Object.freeze({
|
|
181
181
|
/* A random 32-bit key, that can be used for encryption. */
|
|
182
|
-
key:
|
|
182
|
+
key: (0, node_crypto_1.randomBytes)(32).toString('base64'),
|
|
183
183
|
/* Public path used during build. */
|
|
184
184
|
publicPath: o.publicPath,
|
|
185
185
|
/* `true` if client-side code should setup a service worker. */
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "1.47.0-alpha.
|
|
2
|
+
"version": "1.47.0-alpha.4",
|
|
3
3
|
"bin": {
|
|
4
4
|
"react-utils-build": "bin/build.js",
|
|
5
5
|
"react-utils-setup": "bin/setup.js"
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"@dr.pogodin/react-helmet": "^3.0.4",
|
|
17
17
|
"@dr.pogodin/react-themes": "^1.9.3",
|
|
18
18
|
"@jest/environment": "^30.2.0",
|
|
19
|
-
"axios": "^1.13.
|
|
19
|
+
"axios": "^1.13.2",
|
|
20
20
|
"commander": "^14.0.2",
|
|
21
21
|
"compression": "^1.8.1",
|
|
22
22
|
"config": "^4.1.1",
|
|
@@ -29,7 +29,6 @@
|
|
|
29
29
|
"http-status-codes": "^2.3.0",
|
|
30
30
|
"lodash-es": "^4.17.21",
|
|
31
31
|
"morgan": "^1.10.1",
|
|
32
|
-
"node-forge": "^1.3.1",
|
|
33
32
|
"qs": "^6.14.0",
|
|
34
33
|
"raf": "^3.4.1",
|
|
35
34
|
"react": "^19.2.0",
|
|
@@ -71,7 +70,6 @@
|
|
|
71
70
|
"@types/lodash": "^4.17.20",
|
|
72
71
|
"@types/lodash-es": "^4.17.12",
|
|
73
72
|
"@types/morgan": "^1.9.10",
|
|
74
|
-
"@types/node-forge": "^1.3.14",
|
|
75
73
|
"@types/pretty": "^2.0.3",
|
|
76
74
|
"@types/react": "^19.2.2",
|
|
77
75
|
"@types/react-dom": "^19.2.2",
|