@dr.pogodin/react-utils 1.57.0 → 1.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/development/server/Cache.js +7 -7
- package/build/development/server/Cache.js.map +1 -1
- package/build/development/server/index.js +6 -3
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +18 -7
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +12 -6
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/errors.js +10 -10
- package/build/development/server/utils/errors.js.map +1 -1
- package/build/development/shared/components/Button/index.js +1 -1
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +5 -5
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +3 -3
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +3 -0
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +3 -3
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js +2 -2
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +3 -1
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +4 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +7 -4
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +3 -3
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +2 -2
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv/index.js +7 -6
- package/build/development/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/development/shared/utils/jest/index.js +2 -1
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +10 -8
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/webpack.js +2 -1
- package/build/development/shared/utils/webpack.js.map +1 -1
- package/build/production/server/Cache.js +3 -3
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/index.js +1 -1
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +9 -9
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +6 -6
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/errors.js +1 -1
- package/build/production/server/utils/errors.js.map +1 -1
- package/build/production/shared/components/Button/index.js +1 -1
- package/build/production/shared/components/Button/index.js.map +1 -1
- package/build/production/shared/components/Checkbox/index.js +1 -1
- package/build/production/shared/components/Checkbox/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +1 -1
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +1 -1
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js +1 -1
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +2 -2
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js +2 -2
- package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/Switch/index.js +1 -1
- package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/production/shared/utils/config.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv/index.js +2 -2
- package/build/production/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/production/shared/utils/jest/index.js +2 -2
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +3 -3
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/webpack.js +3 -2
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/types-code/shared/utils/config.d.ts +1 -1
- package/build/web/server/Cache.js +3 -3
- package/build/web/server/Cache.js.map +1 -1
- package/build/web/server/index.js +1 -1
- package/build/web/server/index.js.map +1 -1
- package/build/web/server/renderer.js +9 -9
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/server/server.js +6 -6
- package/build/web/server/server.js.map +1 -1
- package/build/web/server/utils/errors.js +1 -1
- package/build/web/server/utils/errors.js.map +1 -1
- package/build/web/shared/components/Button/index.js +1 -1
- package/build/web/shared/components/Button/index.js.map +1 -1
- package/build/web/shared/components/Checkbox/index.js +1 -1
- package/build/web/shared/components/Checkbox/index.js.map +1 -1
- package/build/web/shared/components/Input/index.js +1 -1
- package/build/web/shared/components/Input/index.js.map +1 -1
- package/build/web/shared/components/Modal/index.js +1 -1
- package/build/web/shared/components/Modal/index.js.map +1 -1
- package/build/web/shared/components/TextArea/index.js +1 -1
- package/build/web/shared/components/TextArea/index.js.map +1 -1
- package/build/web/shared/components/WithTooltip/Tooltip.js +1 -1
- package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/web/shared/components/WithTooltip/index.js +2 -2
- package/build/web/shared/components/WithTooltip/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js +2 -2
- package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/Switch/index.js +1 -1
- package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/web/shared/utils/config.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv/index.js +2 -2
- package/build/web/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/web/shared/utils/jest/index.js +2 -2
- package/build/web/shared/utils/jest/index.js.map +1 -1
- package/build/web/shared/utils/splitComponent.js +3 -3
- package/build/web/shared/utils/splitComponent.js.map +1 -1
- package/build/web/shared/utils/webpack.js +3 -2
- package/build/web/shared/utils/webpack.js.map +1 -1
- package/config/babel/webpack.js +6 -1
- package/config/webpack/app-base.js +16 -6
- package/config/webpack/app-development.js +2 -0
- package/package.json +21 -19
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import _JSON$parse from"core-js-pure/
|
|
1
|
+
import _JSON$parse from"core-js-pure/features/json/parse.js";import _JSON$stringify from"core-js-pure/features/json/stringify.js";/**
|
|
2
2
|
* ExpressJS middleware for server-side rendering of a ReactJS app.
|
|
3
3
|
*/import{Buffer}from"node:buffer";import{createCipheriv,randomBytes}from"node:crypto";import fs from"node:fs";import path from"node:path";import{Writable}from"node:stream";import{brotliCompress,brotliDecompress}from"node:zlib";import config from"config";import{cloneDeep,defaults,get,mapValues}from"lodash-es";import{prerenderToNodeStream}from"react-dom/static";import{StaticRouter}from"react-router";import serializeJs from"serialize-javascript";import winston from"winston";import{timer}from"@dr.pogodin/js-utils";import{GlobalStateProvider,SsrContext}from"@dr.pogodin/react-global-state";import{HelmetProvider}from"@dr.pogodin/react-helmet";import{setBuildInfo}from"../shared/utils/isomorphy/buildInfo.js";import Cache from"./Cache.js";// @ts-expect-error "Property 'SECRET' does not exist on type 'IConfig'."
|
|
4
4
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
@@ -89,16 +89,16 @@ res=null;}return res;}/**
|
|
|
89
89
|
*/export default function factory(webpackConfig,options){const ops=defaults({...options},{beforeRender:async()=>Promise.resolve({}),maxSsrRounds:10,ssrTimeout:1000,staticCacheSize:1.e7});// Note: in normal use the default logger is created and set in the root
|
|
90
90
|
// server function, and this initialization is for testing uses, where
|
|
91
91
|
// renderer is imported directly.
|
|
92
|
-
ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});const buildInfo=ops.buildInfo??getBuildInfo(webpackConfig.context);setBuildInfo(buildInfo);// publicPath from webpack.output has a trailing slash at the end.
|
|
93
|
-
const{path:outputPath,publicPath}=webpackConfig.output;const manifestLink=fs.existsSync(`${outputPath}/manifest.json`)?`<link rel="manifest" href="${publicPath}manifest.json">`:"";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
94
|
-
const cache=ops.staticCacheController?new Cache(ops.staticCacheSize):null;const CHUNK_GROUPS=readChunkGroupsJson(outputPath);// TODO: Look at it later.
|
|
92
|
+
ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});if(!webpackConfig.context)throw Error("Missing Webpack context");const buildInfo=ops.buildInfo??getBuildInfo(webpackConfig.context);setBuildInfo(buildInfo);if(!webpackConfig.output)throw Error("Missing Webpack output config");// publicPath from webpack.output has a trailing slash at the end.
|
|
93
|
+
const{path:outputPath,publicPath}=webpackConfig.output;if(!outputPath)throw Error("Missing output path");const manifestLink=fs.existsSync(`${outputPath}/manifest.json`)?`<link rel="manifest" href="${publicPath}manifest.json">`:"";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
94
|
+
if(ops.staticCacheSize===undefined)throw Error("Missing staticCacheSize");const cache=ops.staticCacheController?new Cache(ops.staticCacheSize):null;const CHUNK_GROUPS=readChunkGroupsJson(outputPath);// TODO: Look at it later.
|
|
95
95
|
// eslint-disable-next-line complexity
|
|
96
96
|
return async(req,res,next)=>{try{// Ensures any caches always revalidate HTML markup before reuse.
|
|
97
|
-
res.set("Cache-Control","no-cache");res.cookie("csrfToken",req.csrfToken());let cacheRef;if(cache){cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){const{buffer,status}=data;if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");if(status!==200)res.status(status);res.send(buffer);}else{await new Promise((done,failed)=>{brotliDecompress(buffer,(error,html)=>{if(error)failed(error);else{let h=html.toString();if(!ops.noCsp){// TODO: Starting from Node v15 we'll be able to use string's
|
|
97
|
+
res.set("Cache-Control","no-cache");res.cookie("csrfToken",req.csrfToken());let cacheRef;if(cache){if(!ops.staticCacheController)throw Error("Missing staticCacheController");cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){const{buffer,status}=data;if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");if(status!==200)res.status(status);res.send(buffer);}else{await new Promise((done,failed)=>{brotliDecompress(buffer,(error,html)=>{if(error)failed(error);else{let h=html.toString();if(!ops.noCsp){// TODO: Starting from Node v15 we'll be able to use string's
|
|
98
98
|
// .replaceAll() method instead relying on reg. expression for
|
|
99
99
|
// global matching.
|
|
100
100
|
const regex=new RegExp(buffer.nonce,"g");// TODO: It should be implemented more careful.
|
|
101
|
-
h=h.replace(regex,req.nonce);}if(status!==200)res.status(status);res.send(h);done();}});});}return;}}}const brr=ops.beforeRender(req,publicConfig);const{configToInject,extraScripts,initialState}=await brr;const[cipher,iv]=prepareCipher(buildInfo.key);let helmetState;// Gets the mapping between code chunk names and their asset files.
|
|
101
|
+
h=h.replace(regex,req.nonce);}if(status!==200)res.status(status);res.send(h);done();}});});}return;}}}if(!ops.beforeRender)throw Error("Missing beforeRender");const brr=ops.beforeRender(req,publicConfig);const{configToInject,extraScripts,initialState}=await brr;const[cipher,iv]=prepareCipher(buildInfo.key);let helmetState;// Gets the mapping between code chunk names and their asset files.
|
|
102
102
|
// These data come from the Webpack compilation, either from the stats
|
|
103
103
|
// attached to the request (in dev mode), or from a file output during
|
|
104
104
|
// the build (in prod mode).
|
|
@@ -122,10 +122,10 @@ if(!error)resolveArg(arg);};const reject=arg=>{if(error!==undefined&&error!==arg
|
|
|
122
122
|
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
|
|
123
123
|
rejectArg(arg);};// TODO: prerenderToNodeStream has (abort) "signal" option,
|
|
124
124
|
// and we should wire it up to the SSR timeout below.
|
|
125
|
-
void prerenderToNodeStream(/*#__PURE__*/_jsx(GlobalStateProvider,{initialState:ssrContext.state,ssrContext:ssrContext,children:/*#__PURE__*/_jsx(StaticRouter,{location:req.url,children:/*#__PURE__*/_jsx(HelmetProvider,{onServerState:state=>{helmetState=state;},children:/*#__PURE__*/_jsx(App2,{})})})}),{onError:reject}).then(result=>{resolve(result.prelude);},reject);});let ssrRound=0;let bailed=false;for(;ssrRound<ops.maxSsrRounds;++ssrRound){stream=await renderPass();if(!ssrContext.dirty)break;const timeout=ops.ssrTimeout+ssrStart-Date.now();bailed=timeout<=0||!(await Promise.race([Promise.allSettled(ssrContext.pending),timer(timeout).then(()=>false)]));if(bailed)break;}let logMsg;if(ssrContext.dirty){// NOTE: In the case of incomplete SSR one more round is necessary
|
|
125
|
+
void prerenderToNodeStream(/*#__PURE__*/_jsx(GlobalStateProvider,{initialState:ssrContext.state,ssrContext:ssrContext,children:/*#__PURE__*/_jsx(StaticRouter,{location:req.url,children:/*#__PURE__*/_jsx(HelmetProvider,{onServerState:state=>{helmetState=state;},children:/*#__PURE__*/_jsx(App2,{})})})}),{onError:reject}).then(result=>{resolve(result.prelude);},reject);});let ssrRound=0;let bailed=false;if(ops.maxSsrRounds===undefined)throw Error("Missing maxSsrRounds");for(;ssrRound<ops.maxSsrRounds;++ssrRound){stream=await renderPass();if(!ssrContext.dirty)break;if(ops.ssrTimeout===undefined)throw Error("Missing SSR timeout");const timeout=ops.ssrTimeout+ssrStart-Date.now();bailed=timeout<=0||!(await Promise.race([Promise.allSettled(ssrContext.pending),timer(timeout).then(()=>false)]));if(bailed)break;}let logMsg;if(ssrContext.dirty){// NOTE: In the case of incomplete SSR one more round is necessary
|
|
126
126
|
// to ensure the correct hydration when some pending promises have
|
|
127
127
|
// resolved and placed their data into the initial global state.
|
|
128
|
-
stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} second(s)`:`SSR bailed out after ${ops.maxSsrRounds} round(s)`;}else logMsg=`SSR completed in ${ssrRound+1} round(s)`;ops.logger.log(ssrContext.dirty?"warn":"info",logMsg);if(ssrContext.redirectTo){res.redirect(ssrContext.status,ssrContext.redirectTo);return;}await new Promise(ready=>{stream.pipe(new Writable({destroy:ready,write:(chunk,_,done)=>{appHtmlMarkup+=chunk.toString();done();}}));});}/* Encrypts data to be injected into HTML.
|
|
128
|
+
stream=await renderPass();if(ops.ssrTimeout===undefined)throw Error("Missing SSR timeout");logMsg=bailed?`SSR timed out after ${ops.ssrTimeout.toString()} second(s)`:`SSR bailed out after ${ops.maxSsrRounds.toString()} round(s)`;}else logMsg=`SSR completed in ${(ssrRound+1).toString()} round(s)`;if(!ops.logger)throw Error("Missing logger");ops.logger.log(ssrContext.dirty?"warn":"info",logMsg);if(ssrContext.redirectTo){res.redirect(ssrContext.status,ssrContext.redirectTo);return;}await new Promise(ready=>{stream.pipe(new Writable({destroy:ready,write:(chunk,_,done)=>{appHtmlMarkup+=chunk.toString();done();}}));});}/* Encrypts data to be injected into HTML.
|
|
129
129
|
* Keep in mind, that this encryption is no way secure: as the JS bundle
|
|
130
130
|
* contains decryption key and is able to decode it at the client side.
|
|
131
131
|
* Hovewer, for a number of reasons, encryption of injected data is still
|
|
@@ -168,7 +168,7 @@ stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} s
|
|
|
168
168
|
</body>
|
|
169
169
|
</html>`;const status=ssrContext.status||200;if(status!==200)res.status(status);if(cacheRef&&status<500){// Note: waiting for the caching to complete is not strictly necessary,
|
|
170
170
|
// but it greately simplifies testing, and error reporting.
|
|
171
|
-
await new Promise((done,failed)=>{brotliCompress(html,(error,buffer)=>{if(error)failed(error);else{const b=buffer;b.nonce=req.nonce;cache.add({buffer:b,status},cacheRef.key,buffer.length);done();}});});}// Note: as caching code above may throw in some cases, sending response
|
|
171
|
+
await new Promise((done,failed)=>{brotliCompress(html,(error,buffer)=>{if(error)failed(error);else{const b=buffer;b.nonce=req.nonce;if(cache===null)throw Error("Missing cache");cache.add({buffer:b,status},cacheRef.key,buffer.length);done();}});});}// Note: as caching code above may throw in some cases, sending response
|
|
172
172
|
// before it completes will likely hide the error, making it difficult
|
|
173
173
|
// to debug. Thus, at least for now, lets send response after it.
|
|
174
174
|
res.send(html);}catch(error){next(error);}};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.js","names":[],"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 { HelmetProvider, type HelmetServerState } 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 private pRedirectTo?: string;\n private pStatus: number = 200;\n\n req: Request;\n\n get redirectTo(): string | undefined {\n return this.pRedirectTo;\n }\n\n get status(): number {\n return this.pStatus;\n }\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 /**\n * Sets status code and `redirectTo` value.\n */\n setStatus(status: number, redirectTo?: string): void {\n this.pRedirectTo = redirectTo;\n this.pStatus = status;\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 helmetState: HelmetServerState | undefined;\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 // TODO: I guess, if we refactor the rendering pass function\n // (promise) using less Promises, but Barrier instead - it might\n // become a better understandable.\n const resolve = (arg: NodeJS.ReadableStream) => {\n // NOTE: The error might be set via the `onError` handler passed\n // into the prerenderToNodeStream() call below (which will reject\n // the rendering pass promise), after which the this resolve()\n // will be called from .then() handler, and we should just ignore\n // it, and do nothing.\n if (!error) 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 // TODO: Perhaps assert \"arg instanceof Error\"?\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 void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider\n onServerState={(state) => {\n helmetState = state;\n }}\n >\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then(\n (result) => {\n resolve(result.prelude);\n },\n reject,\n );\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 // NOTE: It is not a mistake that the \"/favicon.ico\" path is hard-coded\n // here! Note, that during the server setup the \"favicon\" middleware is\n // configured to serve the given `ops.favicon` from the \"/favicon.ico\"\n // path.\n ? '<link rel=\"icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmetState?.title.toString() ?? ''}\n ${helmetState?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmetState?.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":"8HAAA;AACA;AACA,GAEA,OAAS,MAAM,KAAQ,aAAa,CACpC,OAAwB,cAAc,CAAE,WAAW,KAAQ,aAAa,CACxE,MAAO,GAAE,KAAM,SAAS,CACxB,MAAO,KAAI,KAAM,WAAW,CAC5B,OAAS,QAAQ,KAAQ,aAAa,CACtC,OAAS,cAAc,CAAE,gBAAgB,KAAQ,WAAW,CAE5D,MAAO,OAAM,KAAM,QAAQ,CAG3B,OACE,SAAS,CACT,QAAQ,CACR,GAAG,CACH,SAAS,KACJ,WAAW,CAGlB,OAAS,qBAAqB,KAAQ,kBAAkB,CACxD,OAAS,YAAY,KAAQ,cAAc,CAC3C,MAAO,YAAW,KAAM,sBAAsB,CAE9C,MAAO,QAAO,KAAM,SAAS,CAE7B,OAAS,KAAK,KAAQ,sBAAsB,CAC5C,OAAS,mBAAmB,CAAE,UAAU,KAAQ,gCAAgC,CAChF,OAAS,cAAc,KAAgC,0BAA0B,CAAC,OAGxD,YAAY,oDAE/B,MAAK,kBAEZ;AACA;AAAA,2CACA,KAAM,CAAE,M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AC9D,IAAI,CAAC,CAAC,CACR,CACF,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA;AACA;AACA;AACA,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAChB,CAAE,MAAO,KAAK,CAAE,CACd,IAAI,CAAC,KAAK,CAAC,CACb,CACF,CAAC,CACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"renderer.js","names":[],"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 { HelmetProvider, type HelmetServerState } 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 private pRedirectTo?: string;\n private pStatus: number = 200;\n\n req: Request;\n\n get redirectTo(): string | undefined {\n return this.pRedirectTo;\n }\n\n get status(): number {\n return this.pStatus;\n }\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 /**\n * Sets status code and `redirectTo` value.\n */\n setStatus(status: number, redirectTo?: string): void {\n this.pRedirectTo = redirectTo;\n this.pStatus = status;\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 if (!webpackConfig.context) throw Error('Missing Webpack context');\n const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context);\n setBuildInfo(buildInfo);\n\n if (!webpackConfig.output) throw Error('Missing Webpack output config');\n // publicPath from webpack.output has a trailing slash at the end.\n const { path: outputPath, publicPath } = webpackConfig.output;\n if (!outputPath) throw Error('Missing output path');\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 if (ops.staticCacheSize === undefined) throw Error('Missing staticCacheSize');\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 if (!ops.staticCacheController) throw Error('Missing staticCacheController');\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 if (!ops.beforeRender) throw Error('Missing beforeRender');\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 helmetState: HelmetServerState | undefined;\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 // TODO: I guess, if we refactor the rendering pass function\n // (promise) using less Promises, but Barrier instead - it might\n // become a better understandable.\n const resolve = (arg: NodeJS.ReadableStream) => {\n // NOTE: The error might be set via the `onError` handler passed\n // into the prerenderToNodeStream() call below (which will reject\n // the rendering pass promise), after which the this resolve()\n // will be called from .then() handler, and we should just ignore\n // it, and do nothing.\n if (!error) 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 // TODO: Perhaps assert \"arg instanceof Error\"?\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 void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider\n onServerState={(state) => {\n helmetState = state;\n }}\n >\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then(\n (result) => {\n resolve(result.prelude);\n },\n reject,\n );\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n if (ops.maxSsrRounds === undefined) throw Error('Missing maxSsrRounds');\n for (; ssrRound < ops.maxSsrRounds; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\n if (ops.ssrTimeout === undefined) throw Error('Missing SSR timeout');\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 if (ops.ssrTimeout === undefined) throw Error('Missing SSR timeout');\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout.toString()} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds.toString()} round(s)`;\n } else logMsg = `SSR completed in ${(ssrRound + 1).toString()} round(s)`;\n\n if (!ops.logger) throw Error('Missing logger');\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 // NOTE: It is not a mistake that the \"/favicon.ico\" path is hard-coded\n // here! Note, that during the server setup the \"favicon\" middleware is\n // configured to serve the given `ops.favicon` from the \"/favicon.ico\"\n // path.\n ? '<link rel=\"icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmetState?.title.toString() ?? ''}\n ${helmetState?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmetState?.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 if (cache === null) throw Error('Missing cache');\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":"kIAAA;AACA;AACA,GAEA,OAAS,MAAM,KAAQ,aAAa,CACpC,OAAwB,cAAc,CAAE,WAAW,KAAQ,aAAa,CACxE,MAAO,GAAE,KAAM,SAAS,CACxB,MAAO,KAAI,KAAM,WAAW,CAC5B,OAAS,QAAQ,KAAQ,aAAa,CACtC,OAAS,cAAc,CAAE,gBAAgB,KAAQ,WAAW,CAE5D,MAAO,OAAM,KAAM,QAAQ,CAG3B,OACE,SAAS,CACT,QAAQ,CACR,GAAG,CACH,SAAS,KACJ,WAAW,CAGlB,OAAS,qBAAqB,KAAQ,kBAAkB,CACxD,OAAS,YAAY,KAAQ,cAAc,CAC3C,MAAO,YAAW,KAAM,sBAAsB,CAE9C,MAAO,QAAO,KAAM,SAAS,CAE7B,OAAS,KAAK,KAAQ,sBAAsB,CAC5C,OAAS,mBAAmB,CAAE,UAAU,KAAQ,gCAA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List":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import _pushInstanceProperty from"core-js-pure/
|
|
1
|
+
import _pushInstanceProperty from"core-js-pure/features/instance/push.js";/**
|
|
2
2
|
* Creation of standard ExpressJS server for ReactJS apps.
|
|
3
3
|
*/import{sep}from"node:path";import{pathToFileURL}from"node:url";import compression from"compression";import cookieParser from"cookie-parser";import express from"express";import helmet from"helmet";import{cloneDeep,mapValues,pick}from"lodash-es";import loggerMiddleware from"morgan";import requestIp from"request-ip";import favicon from"serve-favicon";import csrf from"@dr.pogodin/csurf";import rendererFactory from"./renderer.js";import{CODES,ERRORS,getErrorForCode,newError}from"./utils/errors.js";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
4
4
|
/**
|
|
@@ -27,17 +27,17 @@ delete defaultCspSettings.directives["upgrade-insecure-requests"];/**
|
|
|
27
27
|
* }} A deep copy of default CSP settings object used by `react-utils`,
|
|
28
28
|
* with the exception of `nonce-xxx` clause in `script-src` directive,
|
|
29
29
|
* which is added dynamically for each request.
|
|
30
|
-
*/export function getDefaultCspSettings(){return cloneDeep(defaultCspSettings);}export default async function factory(webpackConfig,options){const rendererOps=pick(options,["Application","beforeRender","favicon","logger","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=rendererFactory(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=express();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server);}if(options.logger)server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;res.redirect(url);return;}next();});}server.use(compression());server.use(helmet({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{var _context;const req2=req;req2.nonce=globalThis.crypto.randomUUID();// TODO: This is deprecated, but it is kept for now for backward
|
|
30
|
+
*/export function getDefaultCspSettings(){return cloneDeep(defaultCspSettings);}export default async function factory(webpackConfig,options){const rendererOps=pick(options,["Application","beforeRender","favicon","logger","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=rendererFactory(webpackConfig,rendererOps);if(!webpackConfig.output)throw Error("Missing output config");const{publicPath}=webpackConfig.output;const server=express();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server);}if(options.logger)server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){if(!req.headers.host)throw Error("Missing host name");let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;res.redirect(url);return;}next();});}server.use(compression());server.use(helmet({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{var _context;const req2=req;req2.nonce=globalThis.crypto.randomUUID();// TODO: This is deprecated, but it is kept for now for backward
|
|
31
31
|
// compatibility. Should be removed sometime later.
|
|
32
32
|
req2.cspNonce=req2.nonce;// The deep clone is necessary here to ensure that default value can't be
|
|
33
33
|
// mutated during request processing.
|
|
34
|
-
let cspSettings=cloneDeep(defaultCspSettings);_pushInstanceProperty(_context=cspSettings.directives?.["script-src"]).call(_context,`'nonce-${req2.nonce}'`);if(options.cspSettingsHook){cspSettings=options.cspSettingsHook(cspSettings,req);}helmet.contentSecurityPolicy(cspSettings)(req,res,next);});}if(options.favicon){server.use(favicon(options.favicon));}server.use("/robots.txt",(req,res)=>{res.send("User-agent: *\nDisallow:");});server.use(express.json({limit:"300kb"}));server.use(express.urlencoded({extended:false}));server.use(cookieParser(options.cookieSignatureSecret));server.use(requestIp.mw());server.use(csrf({cookie:true,ignoreRequest:options.csrfIgnoreRequest}));loggerMiddleware.token("ip",req=>req.clientIp);const FORMAT=":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";server.use(loggerMiddleware(FORMAT,{stream:{// TODO: This implies the logger is always set. Is it on a higher level?
|
|
34
|
+
let cspSettings=cloneDeep(defaultCspSettings);_pushInstanceProperty(_context=cspSettings.directives?.["script-src"]).call(_context,`'nonce-${req2.nonce}'`);if(options.cspSettingsHook){cspSettings=options.cspSettingsHook(cspSettings,req);}helmet.contentSecurityPolicy(cspSettings)(req,res,next);});}if(options.favicon){server.use(favicon(options.favicon));}server.use("/robots.txt",(req,res)=>{res.send("User-agent: *\nDisallow:");});server.use(express.json({limit:"300kb"}));server.use(express.urlencoded({extended:false}));server.use(cookieParser(options.cookieSignatureSecret));server.use(requestIp.mw());server.use(csrf({cookie:true,ignoreRequest:options.csrfIgnoreRequest}));loggerMiddleware.token("ip",req=>req.clientIp);if(!options.logger)throw Error("Missing logger");const FORMAT=":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";server.use(loggerMiddleware(FORMAT,{stream:{// TODO: This implies the logger is always set. Is it on a higher level?
|
|
35
35
|
// then mark it as always present.
|
|
36
36
|
write:options.logger.info.bind(options.logger)}}));// Note: no matter the "public path", we want the service worker, if any,
|
|
37
37
|
// to be served from the root, to have all web app pages in its scope.
|
|
38
38
|
// Thus, this setup to serve it. Probably, need some more configuration
|
|
39
39
|
// for special cases, but this will do for now.
|
|
40
|
-
server.get("/__service-worker.js",express.static(webpackConfig.output
|
|
40
|
+
server.get("/__service-worker.js",express.static(webpackConfig.output.path??"",{setHeaders:res=>res.set("Cache-Control","no-cache")}));/* Setup of Hot Module Reloading for development environment.
|
|
41
41
|
* These dependencies are not used, nor installed for production use,
|
|
42
42
|
* hence we should violate some import-related lint rules. *//* eslint-disable import/no-extraneous-dependencies */if(options.devMode){// This is a workaround for SASS bug:
|
|
43
43
|
// https://github.com/dart-lang/sdk/issues/27979
|
|
@@ -45,7 +45,7 @@ server.get("/__service-worker.js",express.static(webpackConfig.output?.path??"",
|
|
|
45
45
|
// (in dev mode), and app modules are imported in some unfortunate ways.
|
|
46
46
|
// TODO: Double-check, what is going on here.
|
|
47
47
|
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
48
|
-
if(!global.location){global.location={href:`${pathToFileURL(process.cwd()).href}${sep}`};}const{default:webpack}=await import(/* webpackChunkName: "server-side-code" */"webpack");const{default:webpackDevMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-dev-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{hot:true,publicPath,serverSideRender:true}));}/* eslint-enable import/no-extraneous-dependencies */server.use(publicPath,express.static(
|
|
48
|
+
if(!global.location){global.location={href:`${pathToFileURL(process.cwd()).href}${sep}`};}const{default:webpack}=await import(/* webpackChunkName: "server-side-code" */"webpack");const{default:webpackDevMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-dev-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{hot:true,publicPath,serverSideRender:true}));}/* eslint-enable import/no-extraneous-dependencies */const outputPath=webpackConfig.output.path;if(!outputPath)throw Error("Missing output path");server.use(publicPath,express.static(outputPath));if(options.onExpressJsSetup){await options.onExpressJsSetup(server);}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use((req,res,next)=>{next(newError(ERRORS.NOT_FOUND,CODES.NOT_FOUND));});let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server);}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: Do we need this error handler at all? It actually seems to do
|
|
49
49
|
// what the default ExpressJS error handler does anyway, see:
|
|
50
50
|
// https://expressjs.com/en/guide/error-handling.html
|
|
51
51
|
//
|
|
@@ -56,6 +56,6 @@ if(!global.location){global.location={href:`${pathToFileURL(process.cwd()).href}
|
|
|
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
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
|
+
const serverSide=status>=CODES.INTERNAL_SERVER_ERROR;if(!options.logger)throw Error("Missing logger");// Log server-side errors always, client-side at debug level only.
|
|
60
60
|
options.logger.log(serverSide?"error":"debug",error.stack??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;}
|
|
61
61
|
//# sourceMappingURL=server.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":[],"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 compiler = webpack(webpackConfig);\n\n server.use(webpackDevMiddleware(compiler, {\n hot: true,\n publicPath,\n serverSideRender: true,\n }));\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(\n serverSide ? 'error' : 'debug',\n error.stack ?? error.toString(),\n );\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":"wEAAA;AACA;AACA,GAEA,OAAS,GAAG,KAAQ,WAAW,CAC/B,OAAS,aAAa,KAAQ,UAAU,CAExC,MAAO,YAAW,KAAM,aAAa,CACrC,MAAO,aAAY,KAAM,eAAe,CAExC,MAAO,QAAO,KAKP,SAAS,CAEhB,MAAO,OAAM,KAA8B,QAAQ,CACnD,OAAS,SAAS,CAAE,SAAS,CAAE,IAAI,KAAQ,WAAW,CACtD,MAAO,iBAAgB,KAAM,QAAQ,CACrC,MAAO,UAAS,KAAM,YAAY,CAClC,MAAO,QAAO,KAAM,eAAe,CAInC,MAAO,KAAI,KAAM,mBAAmB,CAAC,MAE9B,gBAAe,4BAMpB,KAAK,CACL,MAAM,CACN,eAAe,CACf,QAAQ,yBAKV;AAMA;AACA;AACA;AACA,GACA,KAAM,mBAAkB,CAAG,CACzB,UAAU,CAAE,SAAS,CACn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AAI,OAAO,CAAC,oBAAoB,CAAE,CAChC,6BAA6B,CAAG,KAAM,QAAO,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAC5E,CAEA,oBACA,GAAI,CAAC,6BAA6B,CAAE,CAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,CAAC,GAAG,CAAC,CACT,KAEC,CACD,GAAY,CACZ,GAAa,CACb,IAAkB,GACf,CACH;AACA;AACA,GAAI,GAAG,CAAC,WAAW,CAAE,CACnB,IAAI,CAAC,KAAK,CAAC,CACX,OACF,CAEA,KAAM,OAAM,CAAG,KAAK,CAAC,MAAM,EAAI,KAAK,CAAC,qBAAqB,CAE1D;AACA,KAAM,WAAU,CAAG,MAAM,EAAI,KAAK,CAAC,qBAAqB,CAExD;AACA,OAAO,CAAC,MAAM,CAAE,GAAG,CACjB,UAAU,CAAG,OAAO,CAAG,OAAO,CAC9B,KAAK,CAAC,KAAK,EAAI,KAAK,CAAC,QAAQ,CAAC,CAChC,CAAC,CAED,GAAI,QAAO,CAAG,KAAK,CAAC,OAAO,EAAI,eAAe,CAAC,MAAM,CAAC,CACtD,GAAI,UAAU,EAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAK,YAAY,CAAE,CACvD,OAAO,CAAG,MAAM,CAAC,qBAAqB,CACxC,CAEA,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAClC,CAAC,CAAC,CACJ,CAEA,MAAO,OAAM,CACf","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"server.js","names":[],"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 if (!webpackConfig.output) throw Error('Missing output config');\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 if (!req.headers.host) throw Error('Missing host name');\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 if (!options.logger) throw Error('Missing logger');\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 compiler = webpack(webpackConfig);\n\n server.use(webpackDevMiddleware(compiler, {\n hot: true,\n publicPath,\n serverSideRender: true,\n }));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n const outputPath = webpackConfig.output.path;\n if (!outputPath) throw Error('Missing output path');\n server.use(publicPath as string, express.static(outputPath));\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 if (!options.logger) throw Error('Missing logger');\n // Log server-side errors always, client-side at debug level only.\n options.logger.log(\n serverSide ? 'error' : 'debug',\n error.stack ?? error.toString(),\n );\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":"0EAAA;AACA;AACA,GAEA,OAAS,GAAG,KAAQ,WAAW,CAC/B,OAAS,aAAa,KAAQ,UAAU,CAExC,MAAO,YAAW,KAAM,aAAa,CACrC,MAAO,aAAY,KAAM,eAAe,CAExC,MAAO,QAAO,KAKP,SAAS,CAEhB,MAAO,OAAM,KAA8B,QAAQ,CACnD,OAAS,SAAS,CAAE,SAAS,CAAE,IAAI,KAAQ,WAAW,CACtD,MAAO,iBAAgB,KAAM,QAAQ,CACrC,MAAO,UAAS,KAAM,YAAY,CAClC,MAAO,QAAO,KAAM,eAAe,CAInC,MAAO,KAAI,KAAM,mBAAmB,CAAC,MAE9B,gBAAe,4BAMpB,KAAK,CACL,MAAM,CACN,eAAe,CACf,QAAQ,yBAKV;AAMA;AACA;AACA;AACA,GACA,KAAM,mBAAkB,CAAG,CACzB,UAAU,CAAE,SAAS,CACnB,MAAM,CAAC,qBAAqB,CAAC,oBAAoB,CAAC,CAAC,CAEnD;AACA;AACA;AACA;AACC,KAAK,EAAM,KAAK,CAAc,MAAM,CAAE,IAAY,EAAK,IAAI,GAAK,QAAQ,CAC3E,CACF,CAAC,CACD,kBAAkB,CAAC,UAAU,CAAC,WAAW,CAAC,CAAG,CAC3C,QAAQ,CAER;AACA;AACA,uBAAuB,CACxB,CAED,CACE,KAAM,WAAU,CAAG,kBAAkB,CAAC,UAAU,CAAC,YAAY,CAAC,CAC9D,GAAI,UAAU,CAAE,gCAAU,OAAV,UAAU,CAAM,eAAe,CAAC,CAAC,IAC5C,mBAAkB,CAAC,UAAU,CAAC,YAAY,CAAC,CAAG,CAAC,eAAe,CAAC,CACtE,CAEA;AACA;AACA;AACA,MAAO,mBAAkB,CAAC,UAAU,CAAC,2BAA2B,CAAC,CAEjE;AACA;AACA;AACA;AACA;AAC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AY,CACZ,GAAa,CACb,IAAkB,GACf,CACH;AACA;AACA,GAAI,GAAG,CAAC,WAAW,CAAE,CACnB,IAAI,CAAC,KAAK,CAAC,CACX,OACF,CAEA,KAAM,OAAM,CAAG,KAAK,CAAC,MAAM,EAAI,KAAK,CAAC,qBAAqB,CAE1D;AACA,KAAM,WAAU,CAAG,MAAM,EAAI,KAAK,CAAC,qBAAqB,CAExD,GAAI,CAAC,OAAO,CAAC,MAAM,CAAE,KAAM,MAAK,CAAC,gBAAgB,CAAC,CAClD;AACA,OAAO,CAAC,MAAM,CAAC,GAAG,CAChB,UAAU,CAAG,OAAO,CAAG,OAAO,CAC9B,KAAK,CAAC,KAAK,EAAI,KAAK,CAAC,QAAQ,CAAC,CAChC,CAAC,CAED,GAAI,QAAO,CAAG,KAAK,CAAC,OAAO,EAAI,eAAe,CAAC,MAAM,CAAC,CACtD,GAAI,UAAU,EAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAK,YAAY,CAAE,CACvD,OAAO,CAAG,MAAM,CAAC,qBAAqB,CACxC,CAEA,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAClC,CAAC,CAAC,CACJ,CAEA,MAAO,OAAM,CACf","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../../../../src/server/utils/errors.ts"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n// TODO: It could accept the status code as a constructor argument.\nclass ErrorWithStatus extends Error {\n status: number = CODES.INTERNAL_SERVER_ERROR;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(\n message: string,\n statusCode = CODES.INTERNAL_SERVER_ERROR,\n): ErrorWithStatus {\n const error = new ErrorWithStatus(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * Throws an error with given message and HTTP status code.\n */\nexport function fail(\n message: string,\n statusCode: CODES = CODES.INTERNAL_SERVER_ERROR,\n): Error {\n throw newError(message, statusCode);\n}\n\n/**\n * Validates the `value` against the given \"standard\" validation `schema`.\n * Resolves to the correctly typed `value`, if it has passed the validation;\n * otherwise throws an error.\n * @param value The value to validate.\n * @param schema The \"standard\" validation schema to use.\n * @param [message] Optional error message, to prepend the validation error\n * message.\n * @param [statusCode=400] HTTP status code. Defaults to 400 (Bad Request).\n */\nexport async function assert<T extends StandardSchemaV1>(\n value: unknown,\n schema: T,\n message = '',\n statusCode = CODES.BAD_REQUEST,\n): Promise<StandardSchemaV1.InferOutput<T>> {\n let result = schema['~standard'].validate(value);\n if (result instanceof Promise) result = await result;\n\n if (result.issues) {\n let error = JSON.stringify(result.issues, null, 2);\n if (message) error = `${message}\\n\\n${error}`;\n throw fail(error, statusCode);\n }\n\n return result.value;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../../../../src/server/utils/errors.ts"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n// TODO: It could accept the status code as a constructor argument.\nclass ErrorWithStatus extends Error {\n status: number = CODES.INTERNAL_SERVER_ERROR;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(\n message: string,\n statusCode = CODES.INTERNAL_SERVER_ERROR,\n): ErrorWithStatus {\n const error = new ErrorWithStatus(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * Throws an error with given message and HTTP status code.\n */\nexport function fail(\n message: string,\n statusCode: CODES = CODES.INTERNAL_SERVER_ERROR,\n): Error {\n throw newError(message, statusCode);\n}\n\n/**\n * Validates the `value` against the given \"standard\" validation `schema`.\n * Resolves to the correctly typed `value`, if it has passed the validation;\n * otherwise throws an error.\n * @param value The value to validate.\n * @param schema The \"standard\" validation schema to use.\n * @param [message] Optional error message, to prepend the validation error\n * message.\n * @param [statusCode=400] HTTP status code. Defaults to 400 (Bad Request).\n */\nexport async function assert<T extends StandardSchemaV1>(\n value: unknown,\n schema: T,\n message = '',\n statusCode = CODES.BAD_REQUEST,\n): Promise<StandardSchemaV1.InferOutput<T>> {\n let result = schema['~standard'].validate(value);\n if (result instanceof Promise) result = await result;\n\n if (result.issues) {\n let error = JSON.stringify(result.issues, null, 2);\n if (message) error = `${message}\\n\\n${error}`;\n throw fail(error, statusCode);\n }\n\n return result.value;\n}\n"],"mappings":"qEAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAEA,OACE,WAAW,GAAI,MAAK,CACpB,aAAa,GAAI,OAAM,CACvB,eAAe,GAAI,gBAAe,KAC7B,mBAAmB,CAI1B;AACA;AACA;AACA;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O,OAAM,CAAC,KAAK,CACrB","ignoreList":[]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{c as _c}from"react/compiler-runtime";// The <Button> component implements a standard button / button-like link.
|
|
2
|
-
import{useTheme}from"@dr.pogodin/react-themes";import Link from"../Link.js";const defaultTheme={"context":"_0S7CYa","ad":"YFXz0-","hoc":"BElFuo","button":"hXiBOw","active":"biX-UA","disabled":"_-6CH9q"};import{jsx as _jsx}from"react/jsx-runtime";export const BaseButton=t0=>{const $=_c(32);const{active,children,disabled,enforceA,keepScrollPosition,onClick,onKeyDown:onKeyDownProp,onKeyUp,onMouseDown,onMouseUp,onPointerDown,onPointerUp,openNewTab,replace,testId,theme,to}=t0;let className=theme.button;if(active&&theme.active){className=className+` ${theme.active}`;}if(disabled){if(theme.disabled){className=className+` ${theme.disabled}`;}const t1=process.env.NODE_ENV==="production"?undefined:testId;let t2;if($[0]!==children||$[1]!==className||$[2]!==t1){t2=/*#__PURE__*/_jsx("div",{className:className,"data-testid":t1,children:children});$[0]=children;$[1]=className;$[2]=t1;$[3]=t2;}else{t2=$[3];}return t2;}let onKeyDown=onKeyDownProp;if(!onKeyDown&&onClick){let t1;if($[4]!==onClick){t1=e=>{if(e.key==="Enter"){onClick(e);}};$[4]=onClick;$[5]=t1;}else{t1=$[5];}onKeyDown=t1;}if(to){const t1=process.env.NODE_ENV==="production"?undefined:testId;let t2;if($[6]!==children||$[7]!==className||$[8]!==enforceA||$[9]!==keepScrollPosition||$[10]!==onClick||$[11]!==onKeyUp||$[12]!==onMouseDown||$[13]!==onMouseUp||$[14]!==onPointerDown||$[15]!==onPointerUp||$[16]!==openNewTab||$[17]!==replace||$[18]!==t1||$[19]!==to){t2=/*#__PURE__*/_jsx(Link,{className:className,"data-testid":t1,enforceA:enforceA,keepScrollPosition:keepScrollPosition,onClick:onClick,onKeyUp:onKeyUp,onMouseDown:onMouseDown,onMouseUp:onMouseUp,onPointerDown:onPointerDown,onPointerUp:onPointerUp,openNewTab:openNewTab,replace:replace,to:to,children:children});$[6]=children;$[7]=className;$[8]=enforceA;$[9]=keepScrollPosition;$[10]=onClick;$[11]=onKeyUp;$[12]=onMouseDown;$[13]=onMouseUp;$[14]=onPointerDown;$[15]=onPointerUp;$[16]=openNewTab;$[17]=replace;$[18]=t1;$[19]=to;$[20]=t2;}else{t2=$[20];}return t2;}const t1=process.env.NODE_ENV==="production"?undefined:testId;let t2;if($[21]!==children||$[22]!==className||$[23]!==onClick||$[24]!==onKeyDown||$[25]!==onKeyUp||$[26]!==onMouseDown||$[27]!==onMouseUp||$[28]!==onPointerDown||$[29]!==onPointerUp||$[30]!==t1){t2=/*#__PURE__*/_jsx("div",{className:className,"data-testid":t1,onClick:onClick,onKeyDown:onKeyDown,onKeyUp:onKeyUp,onMouseDown:onMouseDown,onMouseUp:onMouseUp,onPointerDown:onPointerDown,onPointerUp:onPointerUp,role:"button",tabIndex:0,children:children});$[21]=children;$[22]=className;$[23]=onClick;$[24]=onKeyDown;$[25]=onKeyUp;$[26]=onMouseDown;$[27]=onMouseUp;$[28]=onPointerDown;$[29]=onPointerUp;$[30]=t1;$[31]=t2;}else{t2=$[31];}return t2;};const Button=t0=>{const $=_c(6);let rest;let theme;if($[0]!==t0){({theme,...rest}=t0);$[0]=t0;$[1]=rest;$[2]=theme;}else{rest=$[1];theme=$[2];}const composed=useTheme("Button",defaultTheme,theme);let t1;if($[3]!==composed||$[4]!==rest){t1=/*#__PURE__*/_jsx(BaseButton,{...rest,theme:composed});$[3]=composed;$[4]=rest;$[5]=t1;}else{t1=$[5];}return t1;};export default Button;
|
|
2
|
+
import{useTheme}from"@dr.pogodin/react-themes";import Link from"../Link.js";const defaultTheme={"context":"_0S7CYa","ad":"YFXz0-","hoc":"BElFuo","button":"hXiBOw","active":"biX-UA","disabled":"_-6CH9q"};import{jsx as _jsx}from"react/jsx-runtime";export const BaseButton=t0=>{const $=_c(32);const{active,children,disabled,enforceA,keepScrollPosition,onClick,onKeyDown:onKeyDownProp,onKeyUp,onMouseDown,onMouseUp,onPointerDown,onPointerUp,openNewTab,replace,testId,theme,to}=t0;let className=theme.button??"";if(active&&theme.active){className=className+` ${theme.active}`;}if(disabled){if(theme.disabled){className=className+` ${theme.disabled}`;}const t1=process.env.NODE_ENV==="production"?undefined:testId;let t2;if($[0]!==children||$[1]!==className||$[2]!==t1){t2=/*#__PURE__*/_jsx("div",{className:className,"data-testid":t1,children:children});$[0]=children;$[1]=className;$[2]=t1;$[3]=t2;}else{t2=$[3];}return t2;}let onKeyDown=onKeyDownProp;if(!onKeyDown&&onClick){let t1;if($[4]!==onClick){t1=e=>{if(e.key==="Enter"){onClick(e);}};$[4]=onClick;$[5]=t1;}else{t1=$[5];}onKeyDown=t1;}if(to){const t1=process.env.NODE_ENV==="production"?undefined:testId;let t2;if($[6]!==children||$[7]!==className||$[8]!==enforceA||$[9]!==keepScrollPosition||$[10]!==onClick||$[11]!==onKeyUp||$[12]!==onMouseDown||$[13]!==onMouseUp||$[14]!==onPointerDown||$[15]!==onPointerUp||$[16]!==openNewTab||$[17]!==replace||$[18]!==t1||$[19]!==to){t2=/*#__PURE__*/_jsx(Link,{className:className,"data-testid":t1,enforceA:enforceA,keepScrollPosition:keepScrollPosition,onClick:onClick,onKeyUp:onKeyUp,onMouseDown:onMouseDown,onMouseUp:onMouseUp,onPointerDown:onPointerDown,onPointerUp:onPointerUp,openNewTab:openNewTab,replace:replace,to:to,children:children});$[6]=children;$[7]=className;$[8]=enforceA;$[9]=keepScrollPosition;$[10]=onClick;$[11]=onKeyUp;$[12]=onMouseDown;$[13]=onMouseUp;$[14]=onPointerDown;$[15]=onPointerUp;$[16]=openNewTab;$[17]=replace;$[18]=t1;$[19]=to;$[20]=t2;}else{t2=$[20];}return t2;}const t1=process.env.NODE_ENV==="production"?undefined:testId;let t2;if($[21]!==children||$[22]!==className||$[23]!==onClick||$[24]!==onKeyDown||$[25]!==onKeyUp||$[26]!==onMouseDown||$[27]!==onMouseUp||$[28]!==onPointerDown||$[29]!==onPointerUp||$[30]!==t1){t2=/*#__PURE__*/_jsx("div",{className:className,"data-testid":t1,onClick:onClick,onKeyDown:onKeyDown,onKeyUp:onKeyUp,onMouseDown:onMouseDown,onMouseUp:onMouseUp,onPointerDown:onPointerDown,onPointerUp:onPointerUp,role:"button",tabIndex:0,children:children});$[21]=children;$[22]=className;$[23]=onClick;$[24]=onKeyDown;$[25]=onKeyUp;$[26]=onMouseDown;$[27]=onMouseUp;$[28]=onPointerDown;$[29]=onPointerUp;$[30]=t1;$[31]=t2;}else{t2=$[31];}return t2;};const Button=t0=>{const $=_c(6);let rest;let theme;if($[0]!==t0){({theme,...rest}=t0);$[0]=t0;$[1]=rest;$[2]=theme;}else{rest=$[1];theme=$[2];}const composed=useTheme("Button",defaultTheme,theme);let t1;if($[3]!==composed||$[4]!==rest){t1=/*#__PURE__*/_jsx(BaseButton,{...rest,theme:composed});$[3]=composed;$[4]=rest;$[5]=t1;}else{t1=$[5];}return t1;};export default Button;
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/components/Button/index.tsx"],"sourcesContent":["// The <Button> component implements a standard button / button-like link.\n\nimport type {\n FunctionComponent,\n KeyboardEventHandler,\n MouseEventHandler,\n PointerEventHandler,\n ReactNode,\n} from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport Link from 'components/Link';\n\nimport defaultTheme from './style.scss';\n\ntype ThemeT = Theme<'active' | 'button' | 'disabled'>;\n\ntype PropsT = {\n active?: boolean;\n children?: ReactNode;\n disabled?: boolean;\n enforceA?: boolean;\n keepScrollPosition?: boolean;\n onClick?: KeyboardEventHandler & MouseEventHandler;\n onKeyDown?: KeyboardEventHandler;\n onKeyUp?: KeyboardEventHandler;\n onMouseDown?: MouseEventHandler;\n onMouseUp?: MouseEventHandler;\n onPointerDown?: PointerEventHandler;\n onPointerUp?: PointerEventHandler;\n openNewTab?: boolean;\n replace?: boolean;\n testId?: string;\n theme: ThemeT;\n\n // TODO: It needs a more precise typing of the object option.\n to?: object | string;\n};\n\nexport const BaseButton: FunctionComponent<PropsT> = ({\n active,\n children,\n disabled,\n enforceA,\n keepScrollPosition,\n onClick,\n onKeyDown: onKeyDownProp,\n onKeyUp,\n onMouseDown,\n onMouseUp,\n onPointerDown,\n onPointerUp,\n openNewTab,\n replace,\n testId,\n theme,\n to,\n}) => {\n let className = theme.button;\n if (active && theme.active) className += ` ${theme.active}`;\n if (disabled) {\n if (theme.disabled) className += ` ${theme.disabled}`;\n return (\n <div\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n >\n {children}\n </div>\n );\n }\n\n let onKeyDown = onKeyDownProp;\n if (!onKeyDown && onClick) {\n onKeyDown = (e) => {\n if (e.key === 'Enter') onClick(e);\n };\n }\n\n if (to) {\n return (\n <Link\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n enforceA={enforceA}\n\n // TODO: This was exposed as a hotifx... however, I guess we better want\n // to check if the `to` URL contains an anchor (#), and if it does we should\n // automatically opt to keep the position here; and enforce <a> (as\n // react-router link does not seem to respect the hash tag either,\n // at least not without some additional settings).\n keepScrollPosition={keepScrollPosition}\n\n onClick={onClick}\n\n // TODO: For now, the `onKeyDown` handler is not passed to the <Link>,\n // as <Link> component does not call it anyway, presumably due to\n // the inner implementation details. We should look into supporting it:\n // https://github.com/birdofpreyru/react-utils/issues/444\n // onKeyDown={onKeyDown}\n\n onKeyUp={onKeyUp}\n onMouseDown={onMouseDown}\n onMouseUp={onMouseUp}\n onPointerDown={onPointerDown}\n onPointerUp={onPointerUp}\n openNewTab={openNewTab}\n replace={replace}\n to={to}\n >\n {children}\n </Link>\n );\n }\n\n return (\n <div\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onClick={onClick}\n onKeyDown={onKeyDown}\n onKeyUp={onKeyUp}\n onMouseDown={onMouseDown}\n onMouseUp={onMouseUp}\n onPointerDown={onPointerDown}\n onPointerUp={onPointerUp}\n role=\"button\"\n tabIndex={0}\n >\n {children}\n </div>\n );\n};\n\nconst Button: FunctionComponent<\n Omit<PropsT, 'theme'> & { theme?: ThemeT }\n> = ({ theme, ...rest }) => {\n const composed = useTheme('Button', defaultTheme, theme);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return <BaseButton {...rest} theme={composed} />;\n};\n\nexport default Button;\n"],"mappings":"4CAAA;AAUA,OAAqB,QAAQ,KAAQ,0BAA0B,CAAC,MAEzD,KAAI,kBAEX,+HAAwC,2CA0BxC,MAAO,MAAM,WAAqC,CAAG,oBAAC,yLAkBrD,CACC,cAAgB,KAAK,
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/components/Button/index.tsx"],"sourcesContent":["// The <Button> component implements a standard button / button-like link.\n\nimport type {\n FunctionComponent,\n KeyboardEventHandler,\n MouseEventHandler,\n PointerEventHandler,\n ReactNode,\n} from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport Link from 'components/Link';\n\nimport defaultTheme from './style.scss';\n\ntype ThemeT = Theme<'active' | 'button' | 'disabled'>;\n\ntype PropsT = {\n active?: boolean;\n children?: ReactNode;\n disabled?: boolean;\n enforceA?: boolean;\n keepScrollPosition?: boolean;\n onClick?: KeyboardEventHandler & MouseEventHandler;\n onKeyDown?: KeyboardEventHandler;\n onKeyUp?: KeyboardEventHandler;\n onMouseDown?: MouseEventHandler;\n onMouseUp?: MouseEventHandler;\n onPointerDown?: PointerEventHandler;\n onPointerUp?: PointerEventHandler;\n openNewTab?: boolean;\n replace?: boolean;\n testId?: string;\n theme: ThemeT;\n\n // TODO: It needs a more precise typing of the object option.\n to?: object | string;\n};\n\nexport const BaseButton: FunctionComponent<PropsT> = ({\n active,\n children,\n disabled,\n enforceA,\n keepScrollPosition,\n onClick,\n onKeyDown: onKeyDownProp,\n onKeyUp,\n onMouseDown,\n onMouseUp,\n onPointerDown,\n onPointerUp,\n openNewTab,\n replace,\n testId,\n theme,\n to,\n}) => {\n let className = theme.button ?? '';\n if (active && theme.active) className += ` ${theme.active}`;\n if (disabled) {\n if (theme.disabled) className += ` ${theme.disabled}`;\n return (\n <div\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n >\n {children}\n </div>\n );\n }\n\n let onKeyDown = onKeyDownProp;\n if (!onKeyDown && onClick) {\n onKeyDown = (e) => {\n if (e.key === 'Enter') onClick(e);\n };\n }\n\n if (to) {\n return (\n <Link\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n enforceA={enforceA}\n\n // TODO: This was exposed as a hotifx... however, I guess we better want\n // to check if the `to` URL contains an anchor (#), and if it does we should\n // automatically opt to keep the position here; and enforce <a> (as\n // react-router link does not seem to respect the hash tag either,\n // at least not without some additional settings).\n keepScrollPosition={keepScrollPosition}\n\n onClick={onClick}\n\n // TODO: For now, the `onKeyDown` handler is not passed to the <Link>,\n // as <Link> component does not call it anyway, presumably due to\n // the inner implementation details. We should look into supporting it:\n // https://github.com/birdofpreyru/react-utils/issues/444\n // onKeyDown={onKeyDown}\n\n onKeyUp={onKeyUp}\n onMouseDown={onMouseDown}\n onMouseUp={onMouseUp}\n onPointerDown={onPointerDown}\n onPointerUp={onPointerUp}\n openNewTab={openNewTab}\n replace={replace}\n to={to}\n >\n {children}\n </Link>\n );\n }\n\n return (\n <div\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onClick={onClick}\n onKeyDown={onKeyDown}\n onKeyUp={onKeyUp}\n onMouseDown={onMouseDown}\n onMouseUp={onMouseUp}\n onPointerDown={onPointerDown}\n onPointerUp={onPointerUp}\n role=\"button\"\n tabIndex={0}\n >\n {children}\n </div>\n );\n};\n\nconst Button: FunctionComponent<\n Omit<PropsT, 'theme'> & { theme?: ThemeT }\n> = ({ theme, ...rest }) => {\n const composed = useTheme('Button', defaultTheme, theme);\n\n // eslint-disable-next-line react/js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1D,MAA0D,qMAFzE,4BACa,SAAS,CAAT,SAAS,CACP,gBAA0D,CAC9D,OAAO,CAAP,OAAO,CACL,SAAS,CAAT,SAAS,CACX,OAAO,CAAP,OAAO,CACH,WAAW,CAAX,WAAW,CACb,SAAS,CAAT,SAAS,CACL,aAAa,CAAb,aAAa,CACf,WAAW,CAAX,WAAW,CACnB,IAAQ,CAAR,QAAQ,CACH,QAAC,CAAD,CAAC,UAEV,QAAQ,CACN,CAAC,4LAdN,GAcM,EAET,CAED,KAAM,OAEL,CAAG,oDAAC,mBAAkB,2DACrB,eAAiB,QAAQ,CAAC,QAAQ,CAAE,YAAY,CAAE,KAAK,CAAC,CAAC,wCAGlD,qBAAC,UAAU,KAAK,IAAI,CAAS,KAAQ,CAAR,QAAQ,CAAG,CAAC,sDAAzC,GAAyC,EACjD,CAED,cAAe,OAAM","ignoreList":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as _c}from"react/compiler-runtime";import{useTheme}from"@dr.pogodin/react-themes";const defaultTheme={"context":"_08mmmo","ad":"Hc06MV","hoc":"toOtOd","checkbox":"v4DmWM","indeterminate":"ckSC8W","container":"g7wee9","label":"XQ57WS","error":"foaF-C","errorMessage":"WC9mi1","disabled":"baVvQA"};import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const Checkbox=t0=>{const $=_c(17);const{checked,disabled,error,label,onChange,testId,theme}=t0;const composed=useTheme("Checkbox",defaultTheme,theme);let containerClassName=composed.container;if(disabled){containerClassName=containerClassName+` ${composed.disabled}`;}let checkboxClassName=composed.checkbox;if(checked==="indeterminate"){checkboxClassName=checkboxClassName+` ${composed.indeterminate}`;}if(error){containerClassName=containerClassName+` ${composed.error}`;}let t1;if($[0]!==composed.label||$[1]!==label){t1=label===undefined?null:/*#__PURE__*/_jsx("div",{className:composed.label,children:label});$[0]=composed.label;$[1]=label;$[2]=t1;}else{t1=$[2];}const t2=checked===undefined?undefined:checked===true;const t3=process.env.NODE_ENV==="production"?undefined:testId;let t4;if($[3]!==checkboxClassName||$[4]!==disabled||$[5]!==onChange||$[6]!==t2||$[7]!==t3){t4=/*#__PURE__*/_jsx("input",{checked:t2,className:checkboxClassName,"data-testid":t3,disabled:disabled,onChange:onChange,onClick:_temp,type:"checkbox"});$[3]=checkboxClassName;$[4]=disabled;$[5]=onChange;$[6]=t2;$[7]=t3;$[8]=t4;}else{t4=$[8];}let t5;if($[9]!==composed.errorMessage||$[10]!==error){t5=error&&error!==true?/*#__PURE__*/_jsx("div",{className:composed.errorMessage,children:error}):null;$[9]=composed.errorMessage;$[10]=error;$[11]=t5;}else{t5=$[11];}let t6;if($[12]!==containerClassName||$[13]!==t1||$[14]!==t4||$[15]!==t5){t6=/*#__PURE__*/_jsxs("div",{className:containerClassName,children:[t1,t4,t5]});$[12]=containerClassName;$[13]=t1;$[14]=t4;$[15]=t5;$[16]=t6;}else{t6=$[16];}return t6;};export default Checkbox;function _temp(e){e.stopPropagation();}
|
|
1
|
+
import{c as _c}from"react/compiler-runtime";import{useTheme}from"@dr.pogodin/react-themes";const defaultTheme={"context":"_08mmmo","ad":"Hc06MV","hoc":"toOtOd","checkbox":"v4DmWM","indeterminate":"ckSC8W","container":"g7wee9","label":"XQ57WS","error":"foaF-C","errorMessage":"WC9mi1","disabled":"baVvQA"};import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const Checkbox=t0=>{const $=_c(17);const{checked,disabled,error,label,onChange,testId,theme}=t0;const composed=useTheme("Checkbox",defaultTheme,theme);let containerClassName=composed.container??"";if(disabled){containerClassName=containerClassName+` ${composed.disabled??""}`;}let checkboxClassName=composed.checkbox??"";if(checked==="indeterminate"){checkboxClassName=checkboxClassName+` ${composed.indeterminate??""}`;}if(error){containerClassName=containerClassName+` ${composed.error??""}`;}let t1;if($[0]!==composed.label||$[1]!==label){t1=label===undefined?null:/*#__PURE__*/_jsx("div",{className:composed.label,children:label});$[0]=composed.label;$[1]=label;$[2]=t1;}else{t1=$[2];}const t2=checked===undefined?undefined:checked===true;const t3=process.env.NODE_ENV==="production"?undefined:testId;let t4;if($[3]!==checkboxClassName||$[4]!==disabled||$[5]!==onChange||$[6]!==t2||$[7]!==t3){t4=/*#__PURE__*/_jsx("input",{checked:t2,className:checkboxClassName,"data-testid":t3,disabled:disabled,onChange:onChange,onClick:_temp,type:"checkbox"});$[3]=checkboxClassName;$[4]=disabled;$[5]=onChange;$[6]=t2;$[7]=t3;$[8]=t4;}else{t4=$[8];}let t5;if($[9]!==composed.errorMessage||$[10]!==error){t5=error&&error!==true?/*#__PURE__*/_jsx("div",{className:composed.errorMessage,children:error}):null;$[9]=composed.errorMessage;$[10]=error;$[11]=t5;}else{t5=$[11];}let t6;if($[12]!==containerClassName||$[13]!==t1||$[14]!==t4||$[15]!==t5){t6=/*#__PURE__*/_jsxs("div",{className:containerClassName,children:[t1,t4,t5]});$[12]=containerClassName;$[13]=t1;$[14]=t4;$[15]=t5;$[16]=t6;}else{t6=$[16];}return t6;};export default Checkbox;function _temp(e){e.stopPropagation();}
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/components/Checkbox/index.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './theme.scss';\n\ntype PropT<ValueT> = {\n checked?: ValueT;\n disabled?: boolean;\n error?: ReactNode;\n label?: React.ReactNode;\n onChange?: React.ChangeEventHandler<HTMLInputElement>;\n testId?: string;\n theme?: Theme<\n | 'checkbox'\n | 'container'\n | 'disabled'\n | 'error'\n | 'errorMessage'\n | 'indeterminate'\n | 'label'\n >;\n};\n\nconst Checkbox = <ValueT extends 'indeterminate' | boolean = boolean>({\n checked,\n disabled,\n error,\n label,\n onChange,\n testId,\n theme,\n}: PropT<ValueT>): ReactNode => {\n const composed = useTheme('Checkbox', defaultTheme, theme);\n\n let containerClassName = composed.container;\n if (disabled) containerClassName += ` ${composed.disabled}`;\n\n let checkboxClassName = composed.checkbox;\n if (checked === 'indeterminate') checkboxClassName += ` ${composed.indeterminate}`;\n\n if (error) containerClassName += ` ${composed.error}`;\n\n return (\n <div className={containerClassName}>\n { label === undefined\n ? null : <div className={composed.label}>{label}</div> }\n <input\n checked={checked === undefined ? undefined : checked === true}\n className={checkboxClassName}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n disabled={disabled}\n onChange={onChange}\n onClick={(e) => {\n e.stopPropagation();\n }}\n type=\"checkbox\"\n />\n {error && error !== true\n ? <div className={composed.errorMessage}>{error}</div>\n : null}\n </div>\n );\n};\n\nexport default Checkbox;\n"],"mappings":"4CAEA,OAAqB,QAAQ,KAAQ,0BAA0B,CAE/D,sNAAwC,yDAoBxC,KAAM,SAAQ,CAAG,oBAAqD,4DAQtD,CACd,eAAiB,QAAQ,CAAC,UAAU,CAAE,YAAY,CAAE,KAAK,CAAC,CAE1D,uBAAyB,QAAQ,
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/components/Checkbox/index.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './theme.scss';\n\ntype PropT<ValueT> = {\n checked?: ValueT;\n disabled?: boolean;\n error?: ReactNode;\n label?: React.ReactNode;\n onChange?: React.ChangeEventHandler<HTMLInputElement>;\n testId?: string;\n theme?: Theme<\n | 'checkbox'\n | 'container'\n | 'disabled'\n | 'error'\n | 'errorMessage'\n | 'indeterminate'\n | 'label'\n >;\n};\n\nconst Checkbox = <ValueT extends 'indeterminate' | boolean = boolean>({\n checked,\n disabled,\n error,\n label,\n onChange,\n testId,\n theme,\n}: PropT<ValueT>): ReactNode => {\n const composed = useTheme('Checkbox', defaultTheme, theme);\n\n let containerClassName = composed.container ?? '';\n if (disabled) containerClassName += ` ${composed.disabled ?? ''}`;\n\n let checkboxClassName = composed.checkbox ?? '';\n if (checked === 'indeterminate') checkboxClassName += ` ${composed.indeterminate ?? ''}`;\n\n if (error) containerClassName += ` ${composed.error ?? ''}`;\n\n return (\n <div className={containerClassName}>\n { label === undefined\n ? null : <div className={composed.label}>{label}</div> }\n <input\n checked={checked === undefined ? undefined : checked === true}\n className={checkboxClassName}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n disabled={disabled}\n onChange={onChange}\n onClick={(e) => {\n e.stopPropagation();\n }}\n type=\"checkbox\"\n />\n {error && error !== true\n ? <div className={composed.errorMessage}>{error}</div>\n : null}\n </div>\n );\n};\n\nexport default Checkbox;\n"],"mappings":"4CAEA,OAAqB,QAAQ,KAAQ,0BAA0B,CAE/D,sNAAwC,yDAoBxC,KAAM,SAAQ,CAAG,oBAAqD,4DAQtD,CACd,eAAiB,QAAQ,CAAC,UAAU,CAAE,YAAY,CAAE,KAAK,CAAC,CAE1D,uBAAyB,QAAQ,UAAgB,EAAxB,EAAwB,CACjD,GAAI,QAAQ,EAAE,qCAAkB,CAAI,IAAI,QAAQ,SAAe,EAAvB,EAAuB,EAAE,EAEjE,sBAAwB,QAAQ,SAAe,EAAvB,EAAuB,CAC/C,GAAI,OAAO,GAAK,eAAe,EAAE,mCAAiB,CAAI,IAAI,QAAQ,cAAoB,EAA5B,EAA4B,EAAE,EAExF,GAAI,KAAK,EAAE,qCAAkB,CAAI,IAAI,QAAQ,MAAY,EAApB,EAAoB,EAAE,EAAC,+CAItD,QAAK,GAAK,SAC4C,CADtD,IACsD,cADtD,YACyB,SAAc,CAAd,QAAQ,MAAM,UAAG,KAAK,CAAM,CAAC,uDAE7C,gBAAO,GAAK,SAAwC,CAApD,SAAoD,CAAhB,OAAO,GAAK,IAAI,CAEhD,gBAAO,IAAI,SAAS,GAAK,YAAiC,CAA1D,SAA0D,CAA1D,MAA0D,6FAHzE,8BACW,OAAoD,CAApD,EAAoD,CAClD,SAAiB,CAAjB,iBAAiB,CACf,gBAA0D,CAC7D,QAAQ,CAAR,QAAQ,CACR,QAAQ,CAAR,QAAQ,CACT,OAER,CAFQ,KAER,CACI,IAAU,CAAV,UAAU,CAChB,CAAC,kJACD,QAAuB,EAAd,KAAK,GAAK,IAEZ,cAFP,YACmB,SAAqB,CAArB,QAAQ,aAAa,UAAG,KAAK,CAC1C,CAAC,CAFP,IAEO,2IAhBV,6BAAgB,SAAkB,CAAlB,kBAAkB,WAC9B,EACsD,CACxD,EAUE,CACD,EAEO,EACL,CAAC,oFAjBN,GAiBM,EAET,CAED,cAAe,SAAQ,CAzCN,kBA8BP,CAAC,gBAAgB,CAAC,CAAC","ignoreList":[]}
|
|
@@ -5,5 +5,5 @@ import{c as _c}from"react/compiler-runtime";import{useRef,useState}from"react";i
|
|
|
5
5
|
* @param [props...] [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)
|
|
6
6
|
* @param [props...] Any other properties are passed to the underlying
|
|
7
7
|
* `<input>` element.
|
|
8
|
-
*/const Input=t0=>{const $=_c(42);let children;let composeAdhocTheme;let error;let label;let ref;let rest;let testId;let theme;if($[0]!==t0){({children,composeAdhocTheme,error,label,ref,testId,theme,...rest}=t0);$[0]=t0;$[1]=children;$[2]=composeAdhocTheme;$[3]=error;$[4]=label;$[5]=ref;$[6]=rest;$[7]=testId;$[8]=theme;}else{children=$[1];composeAdhocTheme=$[2];error=$[3];label=$[4];ref=$[5];rest=$[6];testId=$[7];theme=$[8];}let t1;if($[9]!==composeAdhocTheme){t1={composeAdhocTheme};$[9]=composeAdhocTheme;$[10]=t1;}else{t1=$[10];}const composed=useTheme("Input",defaultTheme,theme,t1);const[focused,setFocused]=useState(false);const localRef=useRef(null);let containerClassName=composed.container;if(focused){containerClassName=containerClassName+` ${composed.focused}`;}if(!rest.value&&composed.empty){containerClassName=containerClassName+` ${composed.empty}`;}if(error){containerClassName=containerClassName+` ${composed.error}`;}let t2;if($[11]!==ref){t2=()=>{if(typeof ref==="object"){ref?.current?.focus();}else{localRef.current?.focus();}};$[11]=ref;$[12]=t2;}else{t2=$[12];}let t3;if($[13]!==composed.label||$[14]!==label){t3=label===undefined?null:/*#__PURE__*/_jsx("div",{className:composed.label,children:label});$[13]=composed.label;$[14]=label;$[15]=t3;}else{t3=$[15];}const t4=process.env.NODE_ENV==="production"?undefined:testId;const t5=ref??localRef;let t6;if($[16]!==composed.focused||$[17]!==rest){t6=composed.focused?e=>{setFocused(false);rest.onBlur?.(e);}:rest.onBlur;$[16]=composed.focused;$[17]=rest;$[18]=t6;}else{t6=$[18];}let t7;if($[19]!==composed.focused||$[20]!==rest){t7=composed.focused?e_0=>{setFocused(true);rest.onFocus?.(e_0);}:rest.onFocus;$[19]=composed.focused;$[20]=rest;$[21]=t7;}else{t7=$[21];}let t8;if($[22]!==composed.input||$[23]!==rest||$[24]!==t4||$[25]!==t5||$[26]!==t6||$[27]!==t7){t8=/*#__PURE__*/_jsx("input",{className:composed.input,"data-testid":t4,ref:t5,...rest,onBlur:t6,onFocus:t7});$[22]=composed.input;$[23]=rest;$[24]=t4;$[25]=t5;$[26]=t6;$[27]=t7;$[28]=t8;}else{t8=$[28];}let t9;if($[29]!==composed.errorMessage||$[30]!==error){t9=error&&error!==true?/*#__PURE__*/_jsx("div",{className:composed.errorMessage,children:error}):null;$[29]=composed.errorMessage;$[30]=error;$[31]=t9;}else{t9=$[31];}let t10;if($[32]!==children||$[33]!==composed.children){t10=children?/*#__PURE__*/_jsx("div",{className:composed.children,children:children}):null;$[32]=children;$[33]=composed.children;$[34]=t10;}else{t10=$[34];}let t11;if($[35]!==containerClassName||$[36]!==t10||$[37]!==t2||$[38]!==t3||$[39]!==t8||$[40]!==t9){t11=/*#__PURE__*/_jsxs("div",{className:containerClassName,onFocus:t2,children:[t3,t8,t9,t10]});$[35]=containerClassName;$[36]=t10;$[37]=t2;$[38]=t3;$[39]=t8;$[40]=t9;$[41]=t11;}else{t11=$[41];}return t11;};export default Input;
|
|
8
|
+
*/const Input=t0=>{const $=_c(42);let children;let composeAdhocTheme;let error;let label;let ref;let rest;let testId;let theme;if($[0]!==t0){({children,composeAdhocTheme,error,label,ref,testId,theme,...rest}=t0);$[0]=t0;$[1]=children;$[2]=composeAdhocTheme;$[3]=error;$[4]=label;$[5]=ref;$[6]=rest;$[7]=testId;$[8]=theme;}else{children=$[1];composeAdhocTheme=$[2];error=$[3];label=$[4];ref=$[5];rest=$[6];testId=$[7];theme=$[8];}let t1;if($[9]!==composeAdhocTheme){t1={composeAdhocTheme};$[9]=composeAdhocTheme;$[10]=t1;}else{t1=$[10];}const composed=useTheme("Input",defaultTheme,theme,t1);const[focused,setFocused]=useState(false);const localRef=useRef(null);let containerClassName=composed.container??"";if(focused){containerClassName=containerClassName+` ${composed.focused??""}`;}if(!rest.value&&composed.empty){containerClassName=containerClassName+` ${composed.empty}`;}if(error){containerClassName=containerClassName+` ${composed.error??""}`;}let t2;if($[11]!==ref){t2=()=>{if(typeof ref==="object"){ref?.current?.focus();}else{localRef.current?.focus();}};$[11]=ref;$[12]=t2;}else{t2=$[12];}let t3;if($[13]!==composed.label||$[14]!==label){t3=label===undefined?null:/*#__PURE__*/_jsx("div",{className:composed.label,children:label});$[13]=composed.label;$[14]=label;$[15]=t3;}else{t3=$[15];}const t4=process.env.NODE_ENV==="production"?undefined:testId;const t5=ref??localRef;let t6;if($[16]!==composed.focused||$[17]!==rest){t6=composed.focused?e=>{setFocused(false);rest.onBlur?.(e);}:rest.onBlur;$[16]=composed.focused;$[17]=rest;$[18]=t6;}else{t6=$[18];}let t7;if($[19]!==composed.focused||$[20]!==rest){t7=composed.focused?e_0=>{setFocused(true);rest.onFocus?.(e_0);}:rest.onFocus;$[19]=composed.focused;$[20]=rest;$[21]=t7;}else{t7=$[21];}let t8;if($[22]!==composed.input||$[23]!==rest||$[24]!==t4||$[25]!==t5||$[26]!==t6||$[27]!==t7){t8=/*#__PURE__*/_jsx("input",{className:composed.input,"data-testid":t4,ref:t5,...rest,onBlur:t6,onFocus:t7});$[22]=composed.input;$[23]=rest;$[24]=t4;$[25]=t5;$[26]=t6;$[27]=t7;$[28]=t8;}else{t8=$[28];}let t9;if($[29]!==composed.errorMessage||$[30]!==error){t9=error&&error!==true?/*#__PURE__*/_jsx("div",{className:composed.errorMessage,children:error}):null;$[29]=composed.errorMessage;$[30]=error;$[31]=t9;}else{t9=$[31];}let t10;if($[32]!==children||$[33]!==composed.children){t10=children?/*#__PURE__*/_jsx("div",{className:composed.children,children:children}):null;$[32]=children;$[33]=composed.children;$[34]=t10;}else{t10=$[34];}let t11;if($[35]!==containerClassName||$[36]!==t10||$[37]!==t2||$[38]!==t3||$[39]!==t8||$[40]!==t9){t11=/*#__PURE__*/_jsxs("div",{className:containerClassName,onFocus:t2,children:[t3,t8,t9,t10]});$[35]=containerClassName;$[36]=t10;$[37]=t2;$[38]=t3;$[39]=t8;$[40]=t9;$[41]=t11;}else{t11=$[41];}return t11;};export default Input;
|
|
9
9
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/components/Input/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n type Ref,\n useRef,\n useState,\n} from 'react';\n\nimport { type COMPOSE, type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeKeyT = 'children' | 'container' | 'empty' | 'error' | 'errorMessage'\n | 'focused' | 'input' | 'label';\n\ntype PropsT = React.InputHTMLAttributes<HTMLInputElement> & {\n children?: ReactNode;\n composeAdhocTheme?: COMPOSE;\n error?: ReactNode;\n label?: React.ReactNode;\n ref?: Ref<HTMLInputElement>;\n testId?: string;\n theme?: Theme<ThemeKeyT>;\n};\n\n/**\n * Themeable input field, based on the standard HTML `<input>` element.\n * @param [props.label] Input label.\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props...] [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n * @param [props...] Any other properties are passed to the underlying\n * `<input>` element.\n */\nconst Input: FunctionComponent<PropsT> = ({\n children,\n composeAdhocTheme,\n error,\n label,\n ref,\n testId,\n theme,\n ...rest\n}) => {\n const composed = useTheme('Input', defaultTheme, theme, {\n composeAdhocTheme,\n });\n\n // NOTE: As of now, it is only updated when \"theme.focused\" is defined,\n // as otherwise its value is not used.\n const [focused, setFocused] = useState(false);\n\n const localRef = useRef<HTMLInputElement>(null);\n\n let containerClassName = composed.container;\n\n // NOTE: As of now, \"focused\" can be true only when \"theme.focused\"\n // is provided.\n if (focused /* && theme.focused */) containerClassName += ` ${composed.focused}`;\n\n if (!rest.value && composed.empty) containerClassName += ` ${composed.empty}`;\n\n if (error) containerClassName += ` ${composed.error}`;\n\n return (\n <div\n className={containerClassName}\n onFocus={() => {\n // TODO: It does not really work if a callback-style `ref` is passed in,\n // we need a more complex logic to cover that case, but for now this serves\n // the case we need it for.\n if (typeof ref === 'object') ref?.current?.focus();\n else localRef.current?.focus();\n }}\n >\n {label === undefined\n ? null : <div className={composed.label}>{label}</div>}\n <input\n className={composed.input}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n ref={ref ?? localRef}\n\n // TODO: Avoid the spreading later.\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest}\n\n onBlur={composed.focused ? (e) => {\n setFocused(false);\n rest.onBlur?.(e);\n } : rest.onBlur}\n onFocus={composed.focused ? (e) => {\n setFocused(true);\n rest.onFocus?.(e);\n } : rest.onFocus}\n />\n {error && error !== true\n ? <div className={composed.errorMessage}>{error}</div>\n : null}\n {children ? <div className={composed.children}>{children}</div> : null}\n </div>\n );\n};\n\nexport default Input;\n"],"mappings":"4CAAA,OAIE,MAAM,CACN,QAAQ,KACH,OAAO,CAEd,OAAmC,QAAQ,KAAQ,0BAA0B,CAE7E,0LAAwC,yDAexC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,MAAgC,CAAG,+HAAC,qEASzC,+PACyD,qBAExD,CAAC,iDAFD,eAAiB,QAAQ,CAAC,OAAO,CAAE,YAAY,CAAE,KAAK,CAAE,EAEvD,CAAC,CAIF,0BAA8B,QAAQ,CAAC,KAAK,CAAC,CAE7C,eAAiB,MAAM,CAAmB,IAAI,CAAC,CAE/C,uBAAyB,QAAQ,
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/components/Input/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n type Ref,\n useRef,\n useState,\n} from 'react';\n\nimport { type COMPOSE, type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeKeyT = 'children' | 'container' | 'empty' | 'error' | 'errorMessage'\n | 'focused' | 'input' | 'label';\n\ntype PropsT = React.InputHTMLAttributes<HTMLInputElement> & {\n children?: ReactNode;\n composeAdhocTheme?: COMPOSE;\n error?: ReactNode;\n label?: React.ReactNode;\n ref?: Ref<HTMLInputElement>;\n testId?: string;\n theme?: Theme<ThemeKeyT>;\n};\n\n/**\n * Themeable input field, based on the standard HTML `<input>` element.\n * @param [props.label] Input label.\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props...] [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n * @param [props...] Any other properties are passed to the underlying\n * `<input>` element.\n */\nconst Input: FunctionComponent<PropsT> = ({\n children,\n composeAdhocTheme,\n error,\n label,\n ref,\n testId,\n theme,\n ...rest\n}) => {\n const composed = useTheme('Input', defaultTheme, theme, {\n composeAdhocTheme,\n });\n\n // NOTE: As of now, it is only updated when \"theme.focused\" is defined,\n // as otherwise its value is not used.\n const [focused, setFocused] = useState(false);\n\n const localRef = useRef<HTMLInputElement>(null);\n\n let containerClassName = composed.container ?? '';\n\n // NOTE: As of now, \"focused\" can be true only when \"theme.focused\"\n // is provided.\n if (focused /* && theme.focused */) containerClassName += ` ${composed.focused ?? ''}`;\n\n if (!rest.value && composed.empty) containerClassName += ` ${composed.empty}`;\n\n if (error) containerClassName += ` ${composed.error ?? ''}`;\n\n return (\n <div\n className={containerClassName}\n onFocus={() => {\n // TODO: It does not really work if a callback-style `ref` is passed in,\n // we need a more complex logic to cover that case, but for now this serves\n // the case we need it for.\n if (typeof ref === 'object') ref?.current?.focus();\n else localRef.current?.focus();\n }}\n >\n {label === undefined\n ? null : <div className={composed.label}>{label}</div>}\n <input\n className={composed.input}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n ref={ref ?? localRef}\n\n // TODO: Avoid the spreading later.\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest}\n\n onBlur={composed.focused ? (e) => {\n setFocused(false);\n rest.onBlur?.(e);\n } : rest.onBlur}\n onFocus={composed.focused ? (e) => {\n setFocused(true);\n rest.onFocus?.(e);\n } : rest.onFocus}\n />\n {error && error !== true\n ? <div className={composed.errorMessage}>{error}</div>\n : null}\n {children ? <div className={composed.children}>{children}</div> : null}\n </div>\n );\n};\n\nexport default Input;\n"],"mappings":"4CAAA,OAIE,MAAM,CACN,QAAQ,KACH,OAAO,CAEd,OAAmC,QAAQ,KAAQ,0BAA0B,CAE7E,0LAAwC,yDAexC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,MAAgC,CAAG,+HAAC,qEASzC,+PACyD,qBAExD,CAAC,iDAFD,eAAiB,QAAQ,CAAC,OAAO,CAAE,YAAY,CAAE,KAAK,CAAE,EAEvD,CAAC,CAIF,0BAA8B,QAAQ,CAAC,KAAK,CAAC,CAE7C,eAAiB,MAAM,CAAmB,IAAI,CAAC,CAE/C,uBAAyB,QAAQ,UAAgB,EAAxB,EAAwB,CAIjD,GAAI,OAAO,EAAyB,qCAAkB,CAAI,IAAI,QAAQ,QAAc,EAAtB,EAAsB,EAAE,EAEtF,GAAI,CAAC,IAAI,MAAwB,EAAd,QAAQ,MAAM,EAAE,qCAAkB,CAAI,IAAI,QAAQ,MAAM,EAAE,EAE7E,GAAI,KAAK,EAAE,qCAAkB,CAAI,IAAI,QAAQ,MAAY,EAApB,EAAo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