catalyst-core-internal 0.0.1-beta.3 → 0.0.1-beta.31
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/README.md +45 -43
- package/babel.config.json +2 -5
- package/bin/catalyst.js +33 -35
- package/changelog.md +18 -0
- package/config.json +1 -1
- package/dist/caching.js +1 -0
- package/dist/index.js +1 -0
- package/dist/logger.js +10 -0
- package/dist/router/ClientRouter.js +3 -0
- package/dist/router/ServerRouter.js +1 -0
- package/dist/router.js +1 -0
- package/dist/scripts/build.js +10 -0
- package/dist/scripts/checkVersion.js +1 -0
- package/dist/scripts/devBuild.js +10 -0
- package/dist/scripts/devServe.js +5 -0
- package/dist/scripts/loadEnvironmentVariables.js +5 -0
- package/dist/scripts/loadScriptsBeforeServerStarts.js +4 -0
- package/dist/scripts/registerAliases.js +2 -0
- package/dist/scripts/scriptUtils.js +2 -0
- package/dist/scripts/serve.js +5 -0
- package/dist/scripts/start.js +6 -0
- package/dist/scripts/validator.js +1 -0
- package/dist/server/expressServer.js +9 -0
- package/dist/server/renderer/document/Body.js +14 -0
- package/dist/server/renderer/document/Head.js +9 -0
- package/dist/server/renderer/document/index.js +1 -0
- package/dist/server/renderer/extract.js +23 -0
- package/dist/server/renderer/handler.js +17 -0
- package/dist/server/renderer/index.js +1 -0
- package/dist/server/renderer/render.js +27 -0
- package/dist/server/startServer.js +6 -0
- package/dist/server/utils/userAgentUtil.js +9 -0
- package/dist/server/utils/validator.js +1 -0
- package/dist/webpack/babel-plugins/remove-client.plugin.js +5 -0
- package/dist/webpack/babel-plugins/remove-ssr.plugin.js +5 -0
- package/dist/webpack/babel.config.client.js +1 -0
- package/dist/webpack/babel.config.ssr.js +1 -0
- package/dist/webpack/base.babel.js +8 -0
- package/dist/webpack/development.client.babel.js +4 -0
- package/dist/webpack/production.client.babel.js +4 -0
- package/dist/webpack/production.ssr.babel.js +4 -0
- package/dist/webpack/scssParams.js +9 -0
- package/license +10 -0
- package/package.json +110 -83
- package/run.sh +4 -0
- package/caching.js +0 -16
- package/index.js +0 -16
- package/logger.js +0 -96
- package/packages/create-framework-app/templates/redux-js/node_modules/@babel/core/lib/config/caching.js +0 -261
- package/packages/create-framework-app/templates/redux-js/node_modules/@remix-run/router/dist/router.js +0 -4327
- package/packages/create-framework-app/templates/redux-js/node_modules/catalyst/router.js +0 -15
- package/packages/create-framework-app/templates/redux-js/node_modules/catalyst/src/router.js +0 -1
- package/packages/create-framework-app/templates/redux-js/node_modules/http-proxy-middleware/dist/router.js +0 -46
- package/router/ClientRouter.js +0 -19
- package/router/ServerRouter.js +0 -19
- package/router/index.js +0 -32
- package/router.js +0 -16
- package/scripts/build.js +0 -29
- package/scripts/checkVersion.js +0 -5
- package/scripts/loadEnvironmentVariables.js +0 -24
- package/scripts/loadScriptsBeforeServerStarts.js +0 -47
- package/scripts/prepare.js +0 -19
- package/scripts/registerAliases.js +0 -30
- package/scripts/serve.js +0 -30
- package/scripts/start.js +0 -26
- package/scripts/validator.js +0 -130
- package/server/expressServer.js +0 -50
- package/server/mainIndex.js +0 -65
- package/server/mainServer.js +0 -70
- package/server/renderer/document/Body.js +0 -36
- package/server/renderer/document/Head.js +0 -43
- package/server/renderer/document/index.js +0 -27
- package/server/renderer/extract.js +0 -87
- package/server/renderer/handler.js +0 -244
- package/server/renderer/index.js +0 -12
- package/server/renderer/render.js +0 -73
- package/server/renderer/userAgentUtil.js +0 -55
- package/server/startServer.js +0 -65
- package/server/utils/userAgentUtil.js +0 -55
- package/server/utils/validator.js +0 -130
- package/tsconfig.json +0 -110
- package/types/caching.d.ts +0 -1
- package/types/config/config.d.ts +0 -19
- package/types/index.d.ts +0 -1
- package/types/logger/index.d.ts +0 -14
- package/types/reducer/index.d.ts +0 -22
- package/types/reducer/loadableConfigReducer.d.ts +0 -9
- package/types/router/ClientRouter.d.ts +0 -5
- package/types/router/ServerRouter.d.ts +0 -7
- package/types/router/index.d.ts +0 -8
- package/types/router.d.ts +0 -1
- package/types/scripts/build.d.ts +0 -1
- package/types/scripts/loadEnvironmentVariables.d.ts +0 -5
- package/types/scripts/loadScriptsBeforeServerStarts.d.ts +0 -1
- package/types/scripts/prepare.d.ts +0 -1
- package/types/scripts/registerAliases.d.ts +0 -1
- package/types/scripts/serve.d.ts +0 -1
- package/types/scripts/start.d.ts +0 -1
- package/types/scripts/validator.d.ts +0 -9
- package/types/scripts/verifyConfig.d.ts +0 -1
- package/types/server/mainIndex.d.ts +0 -1
- package/types/server/mainServer.d.ts +0 -2
- package/types/server/renderer/document/Body.d.ts +0 -11
- package/types/server/renderer/document/Head.d.ts +0 -11
- package/types/server/renderer/document/index.d.ts +0 -2
- package/types/server/renderer/extract.d.ts +0 -18
- package/types/server/renderer/handler.d.ts +0 -6
- package/types/server/renderer/index.d.ts +0 -2
- package/types/server/renderer/render.d.ts +0 -38
- package/types/server/renderer/userAgentUtil.d.ts +0 -1
- package/types/store/index.d.ts +0 -11
- package/types/store/index.dev.d.ts +0 -8
- package/types/store/index.prod.d.ts +0 -8
- package/types/webpack/babel-plugins/remove-client.plugin.d.ts +0 -10
- package/types/webpack/babel-plugins/remove-ssr.plugin.d.ts +0 -10
- package/types/webpack/babel.config.client.d.ts +0 -21
- package/types/webpack/babel.config.d.ts +0 -16
- package/types/webpack/babel.config.ssr.d.ts +0 -21
- package/types/webpack/base.babel.d.ts +0 -184
- package/types/webpack/development.client.babel.d.ts +0 -1
- package/types/webpack/plugins/mime-types.d.ts +0 -78
- package/types/webpack/plugins/route-manifest-plugin.d.ts +0 -1
- package/types/webpack/plugins/upload-assets-plugin.d.ts +0 -1
- package/types/webpack/production.client.babel.d.ts +0 -174
- package/types/webpack/production.ssr.babel.d.ts +0 -2
- package/types/webpack/scssParams.d.ts +0 -2
- package/webpack/babel-plugins/remove-client.plugin.js +0 -31
- package/webpack/babel-plugins/remove-ssr.plugin.js +0 -21
- package/webpack/babel.config.client.js +0 -24
- package/webpack/babel.config.js +0 -20
- package/webpack/babel.config.ssr.js +0 -24
- package/webpack/base.babel.js +0 -167
- package/webpack/development.client.babel.js +0 -82
- package/webpack/plugins/mime-types.js +0 -82
- package/webpack/plugins/route-manifest-copy.js +0 -122
- package/webpack/plugins/route-manifest-plugin.js +0 -122
- package/webpack/plugins/upload-assets-plugin.js +0 -181
- package/webpack/production.client.babel.js +0 -78
- package/webpack/production.ssr.babel.js +0 -61
- package/webpack/scssParams.js +0 -35
package/README.md
CHANGED
|
@@ -2,32 +2,30 @@
|
|
|
2
2
|
|
|
3
3
|
Frontend framework with server rendering support for web applications.
|
|
4
4
|
|
|
5
|
-
## Table of Contents
|
|
5
|
+
## Table of Contents
|
|
6
6
|
|
|
7
|
-
-
|
|
8
|
-
-
|
|
9
|
-
-
|
|
10
|
-
-
|
|
11
|
-
-
|
|
12
|
-
-
|
|
13
|
-
-
|
|
7
|
+
- Overview
|
|
8
|
+
- Installation
|
|
9
|
+
- Data Fetching with Catalyst
|
|
10
|
+
- serverFetcher
|
|
11
|
+
- clientFetcher
|
|
12
|
+
- refetch (for data revalidation)
|
|
13
|
+
- State Management
|
|
14
14
|
|
|
15
|
-
## Overview
|
|
15
|
+
## Overview
|
|
16
16
|
|
|
17
17
|
This package provides a way to proxy your request through your server. It allows you to cache your incoming request to improve your server response time.
|
|
18
18
|
|
|
19
|
-
|
|
20
19
|
## Installation
|
|
21
20
|
|
|
22
21
|
**System Requirements**
|
|
23
22
|
|
|
24
|
-
-
|
|
25
|
-
-
|
|
26
|
-
|
|
23
|
+
- Node version 20.4.0 or later
|
|
24
|
+
- macOS and Linux are supported
|
|
27
25
|
|
|
28
26
|
**Automatic Installation**
|
|
29
27
|
|
|
30
|
-
-
|
|
28
|
+
- Run the following commands in the directory where you want to set up the Catalyst app.
|
|
31
29
|
|
|
32
30
|
```js
|
|
33
31
|
npx create-catalyst-app@latest
|
|
@@ -35,24 +33,22 @@ npx create-catalyst-app@latest
|
|
|
35
33
|
|
|
36
34
|
If successful, you will see the following prompts in your terminal.
|
|
37
35
|
|
|
38
|
-
-
|
|
39
|
-
-
|
|
40
|
-
-
|
|
36
|
+
- Enter the name of your Catalyst application.
|
|
37
|
+
- Choose state management.
|
|
38
|
+
- Once packages are installed,start the development server by running the following command.
|
|
41
39
|
|
|
42
40
|
```js
|
|
43
|
-
npm run start
|
|
41
|
+
cd project-name && npm run start
|
|
44
42
|
```
|
|
45
43
|
|
|
46
|
-
-
|
|
44
|
+
- Navigate to http://localhost:3005
|
|
47
45
|
|
|
48
46
|
The dev server should be running now.
|
|
49
47
|
|
|
50
|
-
Visit our official documentation:
|
|
48
|
+
Visit our official documentation:
|
|
51
49
|
https://catalyst.1mg.com/public_docs/content/installation
|
|
52
50
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
## Data Fetching with Catalyst
|
|
51
|
+
## Data Fetching with Catalyst
|
|
56
52
|
|
|
57
53
|
we have serverFetcher function for fetching with SSR and clientFetcher function for fetching during client side rendering and navigations.
|
|
58
54
|
|
|
@@ -61,18 +57,22 @@ we have serverFetcher function for fetching with SSR and clientFetcher function
|
|
|
61
57
|
server fetcher will get request, request params, search params and store (if project is setup with redux or rtk) as arguments. We can declare it as an async function and use await for fetching or use then chaining for data fetching.
|
|
62
58
|
|
|
63
59
|
if server fetcher is called for a route then client fetcher will not be called for that route, unless called with refetch.
|
|
60
|
+
|
|
64
61
|
```js
|
|
65
|
-
Home.serverFetcher = async ({ req,params,searchParams }, { store }) => {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
}
|
|
62
|
+
Home.serverFetcher = async ({ req, params, searchParams }, { store }) => {
|
|
63
|
+
store.dispatch(someAction())
|
|
64
|
+
const res = await fetch("some_url")
|
|
65
|
+
const json = await res.json()
|
|
66
|
+
return json
|
|
67
|
+
}
|
|
71
68
|
```
|
|
69
|
+
|
|
72
70
|
data returned from fetcher function will be accessible through useCurrentRouteData() hook provided by router.
|
|
71
|
+
|
|
73
72
|
```js
|
|
74
|
-
const [data,error,isFetched] = useCurrentRouteData()
|
|
73
|
+
const [data, error, isFetched] = useCurrentRouteData()
|
|
75
74
|
```
|
|
75
|
+
|
|
76
76
|
error and loading state would be handled by router.
|
|
77
77
|
|
|
78
78
|
**clientFetcher**
|
|
@@ -80,24 +80,25 @@ error and loading state would be handled by router.
|
|
|
80
80
|
client fetcher would be called on client side rendering and client side navigations. `store` would be available as a param in client side for dispatching redux/rtk actions.
|
|
81
81
|
|
|
82
82
|
```js
|
|
83
|
-
Home.clientFetcher = async ({route,location,params,searchParams,navigate},{store}) => {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
}
|
|
83
|
+
Home.clientFetcher = async ({ route, location, params, searchParams, navigate }, { store }) => {
|
|
84
|
+
store.dispatch(someAction())
|
|
85
|
+
const res = await fetch("some_url")
|
|
86
|
+
const json = await res.json()
|
|
87
|
+
return json
|
|
88
|
+
}
|
|
89
89
|
```
|
|
90
|
-
|
|
90
|
+
|
|
91
|
+
data returned from client fetcher function will be accessible through useCurrentRouteData() hook provided by router (hook for data access through client is same).
|
|
92
|
+
|
|
91
93
|
```js
|
|
92
|
-
const [data,error,isFetched] = useCurrentRouteData()
|
|
94
|
+
const [data, error, isFetched] = useCurrentRouteData()
|
|
93
95
|
```
|
|
94
96
|
|
|
95
|
-
|
|
96
97
|
**refetch (for data revalidation)**
|
|
97
98
|
|
|
98
99
|
refetch function can be used were we need to execute clientFetcher based on some condition(such as for infinite scroll or some state change inside container or onClick.)
|
|
99
100
|
|
|
100
|
-
We can pass arguments in refetch function which would
|
|
101
|
+
We can pass arguments in refetch function which would
|
|
101
102
|
|
|
102
103
|
```js
|
|
103
104
|
const [data,error,isFetched,refetch] = useCurrentRouteData()
|
|
@@ -107,20 +108,20 @@ useEffect(()=>{
|
|
|
107
108
|
},[arg])
|
|
108
109
|
|
|
109
110
|
clientFetcher = ({},{refetchArgument}) => {
|
|
110
|
-
|
|
111
|
+
|
|
111
112
|
const res = await api_call // refetchArg can be used as a param in api call
|
|
112
113
|
return res
|
|
113
114
|
}
|
|
114
115
|
|
|
115
116
|
```
|
|
116
117
|
|
|
117
|
-
|
|
118
118
|
## State Management
|
|
119
|
+
|
|
119
120
|
state management wrappers are defined in stateProvider.js file
|
|
120
121
|
|
|
121
122
|
store can be configured by manipulating store/index.js as per user requirements (custom middlewares etc can be added in this way.
|
|
122
123
|
|
|
123
|
-
initial state and request object would be provided in createStore function which will be called on server and client, we use the params to add additional arguments and middlewares in redux store.
|
|
124
|
+
initial state and request object would be provided in createStore function which will be called on server and client, we use the params to add additional arguments and middlewares in redux store.
|
|
124
125
|
|
|
125
126
|
```js
|
|
126
127
|
const configureStore = (initialState, cookies, requestObj, customHeaders) => {
|
|
@@ -142,4 +143,5 @@ export default configureStore
|
|
|
142
143
|
```
|
|
143
144
|
|
|
144
145
|
## Documentation
|
|
146
|
+
|
|
145
147
|
Visit https://catalyst.1mg.com to view the full documentation.
|
package/babel.config.json
CHANGED
|
@@ -10,11 +10,8 @@
|
|
|
10
10
|
],
|
|
11
11
|
"@babel/preset-react"
|
|
12
12
|
],
|
|
13
|
-
"
|
|
14
|
-
|
|
15
|
-
"transform-class-properties",
|
|
16
|
-
"@loadable/babel-plugin"
|
|
17
|
-
],
|
|
13
|
+
"compact": true,
|
|
14
|
+
"plugins": ["@loadable/babel-plugin"],
|
|
18
15
|
"env": {
|
|
19
16
|
"test": {
|
|
20
17
|
"presets": ["@babel/preset-react"]
|
package/bin/catalyst.js
CHANGED
|
@@ -1,40 +1,38 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
process.on(
|
|
4
|
-
throw err
|
|
5
|
-
})
|
|
6
|
-
const { spawnSync } = require(
|
|
7
|
-
const args = process.argv.slice(2)
|
|
2
|
+
"use strict"
|
|
3
|
+
process.on("unhandledRejection", (err) => {
|
|
4
|
+
throw err
|
|
5
|
+
})
|
|
6
|
+
const { spawnSync } = require("node:child_process")
|
|
7
|
+
const args = process.argv.slice(2)
|
|
8
8
|
const scriptIndex = args.findIndex(
|
|
9
|
-
|
|
10
|
-
)
|
|
11
|
-
const script = scriptIndex === -1 ? args[0] : args[scriptIndex]
|
|
12
|
-
const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : []
|
|
13
|
-
if ([
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
9
|
+
(x) => x === "build" || x === "start" || x === "serve" || x === "devBuild" || x === "devServe"
|
|
10
|
+
)
|
|
11
|
+
const script = scriptIndex === -1 ? args[0] : args[scriptIndex]
|
|
12
|
+
const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : []
|
|
13
|
+
if (["build", "start", "serve", "devBuild", "devServe"].includes(script)) {
|
|
14
|
+
const result = spawnSync(
|
|
15
|
+
process.execPath,
|
|
16
|
+
nodeArgs.concat(require.resolve("../dist/scripts/" + script)).concat(args.slice(scriptIndex + 1)),
|
|
17
|
+
{ stdio: "inherit" }
|
|
18
|
+
)
|
|
19
|
+
if (result.signal) {
|
|
20
|
+
if (result.signal === "SIGKILL") {
|
|
21
|
+
console.log(
|
|
22
|
+
"The build failed because the process exited too early. " +
|
|
23
|
+
"This probably means the system ran out of memory or someone called " +
|
|
24
|
+
"`kill -9` on the process."
|
|
25
|
+
)
|
|
26
|
+
} else if (result.signal === "SIGTERM") {
|
|
27
|
+
console.log(
|
|
28
|
+
"The build failed because the process exited too early. " +
|
|
29
|
+
"Someone might have called `kill` or `killall`, or the system could " +
|
|
30
|
+
"be shutting down."
|
|
31
|
+
)
|
|
32
|
+
}
|
|
33
|
+
process.exit(1)
|
|
34
34
|
}
|
|
35
|
-
process.exit(
|
|
36
|
-
}
|
|
37
|
-
process.exit(result.status);
|
|
35
|
+
process.exit(result.status)
|
|
38
36
|
} else {
|
|
39
|
-
|
|
37
|
+
console.log('Unknown script "' + script + '".')
|
|
40
38
|
}
|
package/changelog.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [0.0.1-beta.6] - 28-06-2024
|
|
4
|
+
|
|
5
|
+
### Changes
|
|
6
|
+
|
|
7
|
+
- Moved router, scripts, server and webpack directories present in root directoy to dist folder
|
|
8
|
+
- Removed dependency from user defined module aliases (user can change any module alias without breaking catalyst)
|
|
9
|
+
- Module aliases defined for catalyst
|
|
10
|
+
- Added exports inside package.json for tree shakeable support for logger, caching and ClientRouter.js
|
|
11
|
+
- Hidden unnecessary files from published package:
|
|
12
|
+
.prettierrc.json
|
|
13
|
+
.eslintrc
|
|
14
|
+
.eslintignore
|
|
15
|
+
/.husky
|
|
16
|
+
/.github
|
|
17
|
+
commitlint.config.js
|
|
18
|
+
tsconfig.json
|
package/config.json
CHANGED
package/dist/caching.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _apiCaching=require("@tata1mg/api-caching");Object.keys(_apiCaching).forEach(function(key){if(key==="default"||key==="__esModule")return;if(key in exports&&exports[key]===_apiCaching[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _apiCaching[key];}});});
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _index=require("./server/renderer/document/index");Object.keys(_index).forEach(function(key){if(key==="default"||key==="__esModule")return;if(key in exports&&exports[key]===_index[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _index[key];}});});
|
package/dist/logger.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";const pc=require("picocolors");const winston=require("winston");const DailyRotateFile=require("winston-daily-rotate-file");const{createLogger,format,transports}=winston;/**
|
|
2
|
+
* @description Logger library with rotational strategy. Creates a logs folder in root.
|
|
3
|
+
* With debug, error and info log directories with their respective log files.
|
|
4
|
+
*
|
|
5
|
+
* @format Logstash with timestamp
|
|
6
|
+
* @param config { @enableDebugLogs: Bool // default: true }
|
|
7
|
+
* @returns loggerInstance
|
|
8
|
+
*
|
|
9
|
+
*/const configureLogger=(config={})=>{const{enableDebugLogs=true,enableFileLogging=true,enableConsoleLogging=true}=config;const consoleTransport=new transports.Console({level:"debug"});const fileTransport=(type="info")=>{return new DailyRotateFile({filename:`${process.env.src_path}/logs/${type}/%DATE%.${type}.log`,datePattern:"YYYY-MM-DD",maxFiles:"3d",// Logs will be removed after 2days,
|
|
10
|
+
loglevel:type,level:type});};const infoLogger=createLogger({format:format.combine(format.timestamp({format:"YYYY-MM-DD HH:mm:ss"}),format.json()),defaultMeta:{loglevel:"info"}});const debugLogger=createLogger({format:format.combine(format.timestamp({format:"YYYY-MM-DD HH:mm:ss"}),format.json()),defaultMeta:{loglevel:"debug"}});const errorLogger=createLogger({format:format.combine(format.timestamp({format:"YYYY-MM-DD HH:mm:ss"}),format.json()),defaultMeta:{loglevel:"error"}});if(enableConsoleLogging&&JSON.parse(enableConsoleLogging)){infoLogger.add(consoleTransport);debugLogger.add(consoleTransport);errorLogger.add(consoleTransport);}if(enableFileLogging&&JSON.parse(enableFileLogging)){infoLogger.add(fileTransport("info"));debugLogger.add(fileTransport("debug"));errorLogger.add(fileTransport("error"));}const Logger={debug:()=>{},error:msg=>{console.log(pc.red(pc.bold("ERROR: "+JSON.stringify(msg))));errorLogger.error(msg);},info:msg=>{console.log(pc.green(pc.bold("INFO: "+JSON.stringify(msg))));infoLogger.info(msg);}};if(enableDebugLogs&&JSON.parse(enableDebugLogs)){Logger.debug=msg=>{console.log(pc.yellow(pc.bold("DEBUG: "+JSON.stringify(msg))));debugLogger.debug(msg);};}if(global)global.logger=Logger;return Logger;};module.exports={configureLogger};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _router=require("@tata1mg/router");const{preparedRoutes}=require(`${process.env.src_path}/src/js/routes/utils.js`);/**
|
|
2
|
+
* @returns returns browsers routers (client routes)
|
|
3
|
+
*/const clientRouter=({store,routerInitialState})=>(0,_router.createBrowserRouter)(preparedRoutes({store,routerInitialState}));var _default=exports.default=clientRouter;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _router=require("@tata1mg/router");const{preparedRoutes}=require(`${process.env.src_path}/src/js/routes/utils.js`);const ServerRouter=reduxData=>{const{store,intialData}=reduxData;return(0,_router.useRoutes)(preparedRoutes({store,routerInitialState:intialData}));};var _default=exports.default=ServerRouter;
|
package/dist/router.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _router=require("@tata1mg/router");Object.keys(_router).forEach(function(key){if(key==="default"||key==="__esModule")return;if(key in exports&&exports[key]===_router[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _router[key];}});});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";const path=require("path");const{spawnSync}=require("child_process");const{green,cyan,yellow}=require("picocolors");const{name}=require(`${process.env.PWD}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.env.PWD}/config/config.json`);const{arrayToObject,printBundleInformation}=require("./scriptUtils.js");/**
|
|
2
|
+
* @description - creates a production build of the application.
|
|
3
|
+
*/function build(){const commandLineArguments=process.argv.slice(2);const argumentsObject=arrayToObject(commandLineArguments);const dirname=path.resolve(__dirname,"../../");const command=`
|
|
4
|
+
node ./dist/scripts/checkVersion
|
|
5
|
+
rm -rf ${process.env.PWD}/${BUILD_OUTPUT_PATH} & node ./dist/scripts/loadScriptsBeforeServerStarts.js
|
|
6
|
+
APPLICATION=${name||"catalyst_app"} webpack --config ./dist/webpack/production.client.babel.js --progress
|
|
7
|
+
APPLICATION=${name||"catalyst_app"} SSR=true webpack --config ./dist/webpack/production.ssr.babel.js
|
|
8
|
+
APPLICATION=${name||"catalyst_app"} npx babel ./dist/server --out-dir ${process.env.PWD}/${BUILD_OUTPUT_PATH} --ignore '**/*.test.js,./dist/server/renderer/handler.js' --quiet
|
|
9
|
+
APPLICATION=${name||"catalyst_app"} npx babel ${process.env.PWD}/server --out-dir ${process.env.PWD}/${BUILD_OUTPUT_PATH} --quiet
|
|
10
|
+
`;console.log("Creating an optimized production build...");const result=spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.env.PWD,BUILD_OUTPUT_PATH:BUILD_OUTPUT_PATH,NODE_ENV:"production",IS_DEV_COMMAND:false,...argumentsObject}});if(result.error){console.error("Error occurred:",result.error);}else{console.log(green("Compiled successfully."));console.log("\nFile sizes after gzip:\n");printBundleInformation();console.log(`\nThe ${cyan(BUILD_OUTPUT_PATH)} folder is ready to be deployed.`);console.log("You may serve it with a serve command:");console.log(cyan("\n npm run serve"));console.log("\nFind out more about deployment here:");console.log(yellow("\n https://catalyst.1mg.com/public_docs/content/deployment\n"));}}build();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";if(process.versions.node.split(".")[0]<20){console.error("\x1b[31m%s\x1b[0m","use node version >=20");}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";const path=require("path");const{spawnSync}=require("child_process");const{green,cyan,yellow}=require("picocolors");const{name}=require(`${process.env.PWD}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.env.PWD}/config/config.json`);const{arrayToObject,printBundleInformation}=require("./scriptUtils.js");/**
|
|
2
|
+
* @description - creates a production build of the application.
|
|
3
|
+
*/function devBuild(){const commandLineArguments=process.argv.slice(2);const argumentsObject=arrayToObject(commandLineArguments);const dirname=path.resolve(__dirname,"../../");const command=`
|
|
4
|
+
node ./dist/scripts/checkVersion
|
|
5
|
+
rm -rf ${process.env.PWD}/${BUILD_OUTPUT_PATH} & node ./dist/scripts/loadScriptsBeforeServerStarts.js
|
|
6
|
+
APPLICATION=${name||"catalyst_app"} webpack --config ./dist/webpack/production.client.babel.js --progress
|
|
7
|
+
APPLICATION=${name||"catalyst_app"} SSR=true webpack --config ./dist/webpack/production.ssr.babel.js
|
|
8
|
+
APPLICATION=${name||"catalyst_app"} npx babel ./dist/server --out-dir ${process.env.PWD}/${BUILD_OUTPUT_PATH} --ignore '**/*.test.js,./dist/server/renderer/handler.js' --quiet
|
|
9
|
+
APPLICATION=${name||"catalyst_app"} npx babel ${process.env.PWD}/server --out-dir ${process.env.PWD}/${BUILD_OUTPUT_PATH} --quiet
|
|
10
|
+
`;console.log("Creating an optimized local build...");const result=spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.env.PWD,BUILD_OUTPUT_PATH:BUILD_OUTPUT_PATH,NODE_ENV:"production",IS_DEV_COMMAND:true,...argumentsObject}});if(result.error){console.error("Error occurred:",result.error);}else{console.log(green("Compiled successfully."));console.log("\nFile sizes after gzip:\n");printBundleInformation();console.log(`\nThe ${cyan(BUILD_OUTPUT_PATH)} folder is ready to be deployed.`);console.log("You may serve it with a serve command:");console.log(cyan("\n npm run devServe"));console.log("\nFind out more about deployment here:");console.log(yellow("\n https://catalyst.1mg.com/public_docs/content/deployment\n"));}}devBuild();
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";const path=require("path");const{spawnSync}=require("child_process");const{arrayToObject}=require("./scriptUtils");const{name}=require(`${process.env.PWD}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.env.PWD}/config/config.json`);/**
|
|
2
|
+
* @description - Serves production build of the application.
|
|
3
|
+
*/function devServe(){const commandLineArguments=process.argv.slice(2);const argumentsObject=arrayToObject(commandLineArguments);const dirname=path.resolve(__dirname,"../../");const command=`
|
|
4
|
+
APPLICATION=${name||"catalyst_app"} node -r ./dist/scripts/loadScriptsBeforeServerStarts.js ${process.env.PWD}/${BUILD_OUTPUT_PATH}/startServer.js
|
|
5
|
+
`;spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.env.PWD,BUILD_OUTPUT_PATH:BUILD_OUTPUT_PATH,NODE_ENV:"production",IS_DEV_COMMAND:true,...argumentsObject}});}devServe();
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;const appConfig=require("@catalyst/template/config/config.json");const{validateConfigFile}=require("@catalyst/scripts/validator.js");/**
|
|
2
|
+
* @description stores all config.json key value into process.env before server starts.
|
|
3
|
+
*/const loadEnvironmentVariables=()=>{if(validateConfigFile(appConfig)){for(let k in appConfig){// below code provides support for object handling present in config.
|
|
4
|
+
// However, for usage on client the client logic in define plugin needs to be checked and updated
|
|
5
|
+
process.env[k]=typeof appConfig[k]==="object"?JSON.stringify(appConfig[k]):appConfig[k];}}};var _default=exports.default=loadEnvironmentVariables;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"use strict";var _registerAliases2=_interopRequireDefault(require("./registerAliases.js"));var _cssModulesRequireHook=_interopRequireDefault(require("@dr.pogodin/css-modules-require-hook"));var _path=_interopRequireDefault(require("path"));var _loadEnvironmentVariables=_interopRequireDefault(require("./loadEnvironmentVariables"));var _postcssScss=_interopRequireDefault(require("postcss-scss"));var _logger=require("@catalyst/logger.js");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/* eslint-disable */const{cssModulesIdentifierDev}=require("@catalyst/root/config.json");// stores your config keys in enviorments variables
|
|
2
|
+
(0,_loadEnvironmentVariables.default)();// creates logger instance with provided config and stores them at global level.
|
|
3
|
+
(0,_logger.configureLogger)({enableDebugLogs:process.env.ENABLE_DEBUG_LOGS,enableFileLogging:process.env.ENABLE_FILE_LOGGING,enableConsoleLogging:process.env.ENABLE_CONSOLE_LOGGING});// compile css-variables in realtime in dev mode.
|
|
4
|
+
if(process.env.NODE_ENV==="development")(0,_cssModulesRequireHook.default)({extensions:[".scss",".css"],processorOpts:{parser:_postcssScss.default.parse},generateScopedName:cssModulesIdentifierDev,devMode:true,ignore:_path.default.join(process.env.src_path,"/src/static/css/base/(?!.*.scss$).*")});
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.catalystResultMap=void 0;var _path=_interopRequireDefault(require("path"));var _moduleAlias=_interopRequireDefault(require("module-alias"));var _package=require("../../package.json");var _validator=require("./validator.js");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const{_moduleAliases:templateModuleAliases}=require(`${process.env.src_path}/package.json`);const catalystResultMap=exports.catalystResultMap=Object.keys(_package._moduleAliases||[]).reduce((resultMap,aliasName)=>{const aliasPath=_package._moduleAliases[aliasName];if(aliasName?.includes("@catalyst/template")){if(aliasName?.includes("server")&&process.env.NODE_ENV==="production"){resultMap[aliasName]=_path.default.join(process.env.src_path,process.env.BUILD_OUTPUT_PATH);}else{resultMap[aliasName]=_path.default.join(process.env.src_path,aliasPath);}return resultMap;}if(aliasName?.includes("@catalyst")&&!aliasName?.includes("@catalyst/template")){if(aliasName?.includes("server")&&process.env.NODE_ENV==="production"){resultMap[aliasName]=_path.default.join(process.env.src_path,process.env.BUILD_OUTPUT_PATH);}else{resultMap[aliasName]=_path.default.join(__dirname,"../",aliasPath);}return resultMap;}return resultMap;},{});_moduleAlias.default.addAliases(catalystResultMap);// resolves module alias imports
|
|
2
|
+
if((0,_validator.validateModuleAlias)(templateModuleAliases)){_moduleAlias.default.addAliases(Object.keys(templateModuleAliases||[]).reduce((resultMap,aliasName)=>{const aliasPath=templateModuleAliases[aliasName];if(aliasPath.includes("server")){if(process.env.NODE_ENV!=="production"){resultMap[aliasName]=_path.default.join(process.env.src_path,aliasPath);}else{resultMap[aliasName]=_path.default.join(process.env.src_path,process.env.BUILD_OUTPUT_PATH);}}else resultMap[aliasName]=_path.default.join(process.env.src_path,aliasPath);return resultMap;},{}));}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.arrayToObject=arrayToObject;exports.printBundleInformation=void 0;const fs=require("fs");const path=require("path");const util=require("node:util");const{gray,cyan}=require("picocolors");const{BUILD_OUTPUT_PATH}=require(`${process.env.PWD}/config/config.json`);// Function to get file size synchronously
|
|
2
|
+
function getFileSizeSync(filePath){try{const stats=fs.statSync(filePath);return stats.size;}catch(err){console.error(`Error getting bundle information for file ${filePath}: ${err}`);return null;}}const printBundleInformation=()=>{let bundleList=[];const directoryPath=path.join(process.env.PWD,`${BUILD_OUTPUT_PATH}/public`);try{const files=fs.readdirSync(directoryPath);files.forEach(file=>{if(!file.includes("txt")&&!file.includes("json")){const filePath=path.join(directoryPath,file);const fileSize=getFileSizeSync(filePath);if(fileSize!==null){bundleList.push({file,fileSize});}}});}catch(err){console.error("Unable to scan build folder: "+err);}bundleList.sort((a,b)=>b.fileSize-a.fileSize);bundleList.forEach(({file,fileSize})=>{const fileName=`${gray(`${BUILD_OUTPUT_PATH}/public/`)}${cyan(file)}`;const fileSizeInKb=(fileSize/1024).toFixed(2);const size=`\t${fileSizeInKb} kB`.padEnd(16);console.log(util.format(size,fileName));});};exports.printBundleInformation=printBundleInformation;function arrayToObject(array){const obj={};array.forEach(item=>{const[key,value]=item.split("=");if(value)obj[key]=value;});return obj;}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";const path=require("path");const{spawnSync}=require("child_process");const{arrayToObject}=require("./scriptUtils");const{name}=require(`${process.env.PWD}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.env.PWD}/config/config.json`);/**
|
|
2
|
+
* @description - Serves production build of the application.
|
|
3
|
+
*/function serve(){const commandLineArguments=process.argv.slice(2);const argumentsObject=arrayToObject(commandLineArguments);const dirname=path.resolve(__dirname,"../../");const command=`
|
|
4
|
+
APPLICATION=${name||"catalyst_app"} node -r ./dist/scripts/loadScriptsBeforeServerStarts.js ${process.env.PWD}/${BUILD_OUTPUT_PATH}/startServer.js
|
|
5
|
+
`;spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.env.PWD,BUILD_OUTPUT_PATH:BUILD_OUTPUT_PATH,NODE_ENV:"production",IS_DEV_COMMAND:false,...argumentsObject}});}serve();
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";const path=require("path");const{spawnSync}=require("child_process");const{arrayToObject}=require("./scriptUtils");const{name}=require(`${process.env.PWD}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.env.PWD}/config/config.json`);/**
|
|
2
|
+
* @description - starts webpack dev server and node server.
|
|
3
|
+
*/function start(){const commandLineArguments=process.argv.slice(2);const argumentsObject=arrayToObject(commandLineArguments);const dirname=path.resolve(__dirname,"../../");const command=`
|
|
4
|
+
node ./dist/scripts/checkVersion
|
|
5
|
+
npx babel-node -r ./dist/scripts/loadScriptsBeforeServerStarts.js ./dist/webpack/development.client.babel --no-warnings=ExperimentalWarning --no-warnings=BABEL & npx babel-node -r ./dist/scripts/loadScriptsBeforeServerStarts.js ./dist/server/startServer.js --watch-path=${process.env.PWD}/server --watch-path=${process.env.PWD}/src --ignore='__IGNORE__' --no-warnings=ExperimentalWarning --no-warnings=BABEL
|
|
6
|
+
`;spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.env.PWD,NODE_ENV:"development",IS_DEV_COMMAND:false,APPLICATION:name||"catalyst_app",BUILD_OUTPUT_PATH:BUILD_OUTPUT_PATH,...argumentsObject}});}start();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const pc=require("picocolors");const handleError=e=>{console.log(pc.red("Failed to start server: "),e);};const validatePreInitServer=fn=>{try{if(!fn)throw new Error("preServerInit named function should be defined in server/index.js");if(typeof fn!=="function")throw new Error("preServerInit should be function present in server/index.js");return true;}catch(e){handleError(e);}};const validateMiddleware=fn=>{try{if(!fn)throw new Error("addMiddlewares named function not found in server/server.js");if(typeof fn!=="function")throw new Error("addMiddlewares should be function present in server/server.js");return true;}catch(e){handleError(e);}};const validateReducerFunction=fn=>{try{if(!fn)throw new Error("reducer not found in src/js/containers/App/reducer");if(typeof fn!=="function")throw new Error("reducer should present in src/js/containers/App/reducer");return true;}catch(e){handleError(e);}};const validateConfigFile=obj=>{try{if(!obj)throw new Error("config not found in config folder");if(typeof obj!=="object")throw new Error("config object should be exported from config folder inside your project root directory");if(typeof obj==="object"){const requiredConfigKeys={NODE_SERVER_HOSTNAME:"",NODE_SERVER_PORT:"",WEBPACK_DEV_SERVER_HOSTNAME:"",WEBPACK_DEV_SERVER_PORT:"",BUILD_OUTPUT_PATH:"",PUBLIC_STATIC_ASSET_PATH:"",PUBLIC_STATIC_ASSET_URL:"",CLIENT_ENV_VARIABLES:[],ANALYZE_BUNDLE:""};for(let key in requiredConfigKeys){if(!(key in obj))throw new Error(`${key} key not found inside config.json`);}}return true;}catch(e){handleError(e);}};const validatePackageJson=obj=>{try{if(!obj)throw new Error("package.json not found in the project");if(typeof obj!=="object")throw new Error("package.json should be defined in project root directory");return true;}catch(e){handleError(e);}};const validateModuleAlias=obj=>{try{if(!obj)throw new Error("moduleAliases not found in package.json file present in root directory.");if(typeof obj!=="object")throw new Error("moduleAliases named object should be exported from package.json");if(typeof obj==="object"){const requiredModuleAliases={"@api":"api.js","@containers":"src/js/containers","@server":"server","@config":"config","@css":"src/static/css","@routes":"src/js/routes/"};for(let key in requiredModuleAliases){if(key.includes("catalyst"))throw new Error(`Catalyst keyword is restricted for defining aliases`);if(!(key in obj))throw new Error(`${key} module alias not defined inside package.json`);}}return true;}catch(e){handleError(e);}};const validateConfigureStore=fn=>{try{if(!fn)throw new Error("configureStore not found in file src/js/store/index.js");if(typeof fn!=="function")throw new Error("configureStore should be function exported from src/js/store/index.js");return true;}catch(e){handleError(e);}};const validateGetRoutes=fn=>{try{if(!fn)throw new Error("getRoutes not found in file src/js/routes/utils.js");if(typeof fn!=="function")throw new Error("getRoutes should be function exported from src/js/routers/index.js");return true;}catch(e){handleError(e);}};const validateCustomDocument=fn=>{try{if(!fn)throw new Error("document not found in file server/document.js");if(typeof fn!=="function")throw new Error("document should be a react component exported from server/document.js");return true;}catch(e){handleError(e);}};module.exports={validateConfigFile,validateConfigureStore,validateCustomDocument,validateGetRoutes,validatePackageJson,validateReducerFunction,validateModuleAlias,validatePreInitServer,validateMiddleware};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _path=_interopRequireDefault(require("path"));var _express=_interopRequireDefault(require("express"));var _bodyParser=_interopRequireDefault(require("body-parser"));var _compression=_interopRequireDefault(require("compression"));var _cookieParser=_interopRequireDefault(require("cookie-parser"));var _expressStaticGzip=_interopRequireDefault(require("express-static-gzip"));var _renderer=_interopRequireDefault(require("@catalyst/server/renderer"));var _server=require("@catalyst/template/server/server.js");var _validator=require("@catalyst/server/utils/validator");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const env=process.env.NODE_ENV||"development";const app=(0,_express.default)();// This middleware is being used to extract the body of the request
|
|
2
|
+
app.use(_bodyParser.default.json());// This middleware has been added to accommodate “byetstream array”
|
|
3
|
+
app.use(_bodyParser.default.raw({type:"application/*"}));// This middleware is being used to parse cookies!
|
|
4
|
+
app.use((0,_cookieParser.default)());// All the middlewares defined by the user will run here.
|
|
5
|
+
if((0,_validator.validateMiddleware)(_server.addMiddlewares))(0,_server.addMiddlewares)(app);// The middleware will attempt to compress response bodies for all request that traverse through the middleware
|
|
6
|
+
app.use((0,_compression.default)());// This endpoint will serve the built assets from the node server. The requests will be made to PUBLIC_STATIC_ASSET_PATH which has been defined in the application config.
|
|
7
|
+
// expressStaticGzip will compress the assets.
|
|
8
|
+
if(env==="production"){app.use(process.env.PUBLIC_STATIC_ASSET_PATH,(0,_expressStaticGzip.default)(_path.default.join(process.env.src_path,`./${process.env.BUILD_OUTPUT_PATH}/public`),{enableBrotli:true,orderPreference:["br","gzip","deflate"]}));}else{app.use(process.env.PUBLIC_STATIC_ASSET_PATH,_express.default.static(_path.default.join(process.env.src_path,`./${process.env.BUILD_OUTPUT_PATH}/public`)));}// This middleware handles document requests.
|
|
9
|
+
app.use("*",_renderer.default);var _default=exports.default=app;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Body=Body;var _react=_interopRequireDefault(require("react"));var _propTypes=_interopRequireDefault(require("prop-types"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
|
|
2
|
+
* Body component which will be used in page component
|
|
3
|
+
* @param {object} jsx - page jsx code
|
|
4
|
+
* @param {object} statusCode - document request status code
|
|
5
|
+
* @param {object} initialState - initial state object for redux store
|
|
6
|
+
* @param {object} firstFoldCss - style elements extracted for initial page load
|
|
7
|
+
* @param {object} firstFoldJS - javascript elements extracted for initial page load
|
|
8
|
+
* @param {object} fetcherData - contains data from executing serverFetcher function
|
|
9
|
+
* @param {object} children - contains any child elements defined within the component
|
|
10
|
+
*/function Body(props){const{jsx="",statusCode="",initialState={},firstFoldCss="",firstFoldJS="",fetcherData={},children}=props;return/*#__PURE__*/_react.default.createElement("body",null,firstFoldCss,firstFoldJS,jsx,/*#__PURE__*/_react.default.createElement("script",{/* eslint-disable */dangerouslySetInnerHTML:{__html:`
|
|
11
|
+
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}
|
|
12
|
+
window.__STATUS_CODE__ = ${statusCode}
|
|
13
|
+
window.__ROUTER_INITIAL_DATA__ = ${JSON.stringify(fetcherData)}
|
|
14
|
+
`}}),children);}Body.propTypes={initialState:_propTypes.default.object,firstFoldCss:_propTypes.default.any,firstFoldJS:_propTypes.default.any,jsx:_propTypes.default.any,statusCode:_propTypes.default.string,fetcherData:_propTypes.default.object,children:_propTypes.default.node};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Head=Head;var _react=_interopRequireDefault(require("react"));var _propTypes=_interopRequireDefault(require("prop-types"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
|
|
2
|
+
* Head component which will be used in page rendering
|
|
3
|
+
* @param {boolean} isBot - checks if request is made by bot
|
|
4
|
+
* @param {string} pageCss - includes all styles for page css
|
|
5
|
+
* @param {object} preloadJSLinks - async scripts for loading chunks
|
|
6
|
+
* @param {array} metaTags - user defined function which returns meta tags in array
|
|
7
|
+
* @param {string} publicAssetPath - public asset path for assets
|
|
8
|
+
* @param {object} children - contains any child elements defined within the component
|
|
9
|
+
*/function Head(props){const{pageCss,preloadJSLinks,metaTags,isBot,publicAssetPath,children}=props;return/*#__PURE__*/_react.default.createElement("head",null,/*#__PURE__*/_react.default.createElement("meta",{charSet:"utf-8"}),/*#__PURE__*/_react.default.createElement("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),publicAssetPath&&/*#__PURE__*/_react.default.createElement("link",{rel:"preconnect",href:publicAssetPath}),publicAssetPath&&/*#__PURE__*/_react.default.createElement("link",{rel:"dns-prefetch",href:publicAssetPath}),metaTags&&metaTags,!isBot&&preloadJSLinks,!isBot&&pageCss&&/*#__PURE__*/_react.default.createElement("style",{dangerouslySetInnerHTML:{__html:pageCss}}),children);}Head.propTypes={isBot:_propTypes.default.bool,preloadJSLinks:_propTypes.default.object,pageCss:_propTypes.default.string,metaTags:_propTypes.default.array,publicAssetPath:_propTypes.default.string,children:_propTypes.default.node};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _Head=require("./Head");Object.keys(_Head).forEach(function(key){if(key==="default"||key==="__esModule")return;if(key in exports&&exports[key]===_Head[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _Head[key];}});});var _Body=require("./Body");Object.keys(_Body).forEach(function(key){if(key==="default"||key==="__esModule")return;if(key in exports&&exports[key]===_Body[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _Body[key];}});});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.cacheCSS=cacheCSS;exports.cachePreloadJSLinks=cachePreloadJSLinks;exports.default=_default;var _path=_interopRequireDefault(require("path"));var _fs=_interopRequireDefault(require("fs"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function handleProps(asset,props){return typeof props==="function"?"":props;}function propsToString(asset,props){return Object.entries(handleProps(asset,props)).reduce((acc,[key,value])=>`${acc} ${key}="${value}"`,"");}function cachePreloadJSLinks(key,data){if(!process.preloadJSLinkCache){process.preloadJSLinkCache={};}let preloadJSLinks=[];if(Array.isArray(data)){try{preloadJSLinks=data.filter(asset=>asset?.props?.as==="script");// data.map((asset) => {
|
|
2
|
+
// if (asset?.props?.as === "script") {
|
|
3
|
+
// preloadJSLinks.push(`<link ${propsToString(asset, asset.props)}>`)
|
|
4
|
+
// }
|
|
5
|
+
// })
|
|
6
|
+
}catch(error){console.dir({service_name:`pwa-${process.env.APPLICATION}-node-server`,loglevel:"error",version:"v2",message:"\n \n =====> Error While Extracting The Chunk: \n ",traceback:error});}}console.dir({service_name:"pwa-node-server",loglevel:"info",version:"v2",message:`\n========= Cached For preloadJSLinkCache: ${key} ============\n`});// process.preloadJSLinkCache[key] = preloadJSLinks.join("\n")
|
|
7
|
+
process.preloadJSLinkCache[key]=preloadJSLinks;}/**
|
|
8
|
+
* Stores css chunks styles into cache in string format
|
|
9
|
+
* @param {string} key - router path
|
|
10
|
+
* @param {object} data - css elements array extracted through loadable chunk extracter
|
|
11
|
+
*/function cacheCSS(key,data){if(!process.cssCache){process.cssCache={};}let pageCss="";let listOfCachedAssets={};if(Array.isArray(data)){try{data.map(assetChunk=>{const assetPathArr=assetChunk.key.split("/");const assetName=assetPathArr[assetPathArr.length-1];const ext=_path.default.extname(assetName);if(ext===".css"){// if css file has not already been cached, add the content of this CSS file in pageCSS
|
|
12
|
+
if(!listOfCachedAssets[assetName]&&!process.cssCache?.[key]?.listOfCachedAssets?.[assetName]){pageCss+=_fs.default.readFileSync(_path.default.resolve(process.env.src_path,`${process.env.BUILD_OUTPUT_PATH}/public`,assetName));listOfCachedAssets[assetName]=true;}}});}catch(error){if(process.env.NODE_ENV=="development"){console.log("Error While Extracting The Chunk: ",_path.default.resolve(process.env.src_path,`${process.env.BUILD_OUTPUT_PATH}/public`));}}}// if css cache exists for a route and there are some uncached css, add that css to the cache
|
|
13
|
+
// this will run on subsequent hits and will add css of uncached widgets to the cache
|
|
14
|
+
if(process.cssCache[key]){if(pageCss!==""){pageCss="<style>"+pageCss+"</style>";let existingListOfCachedAssets=process.cssCache[key].listOfCachedAssets;const newPageCSS=process.cssCache[key].pageCss+pageCss;let newListOfCachedAssets={...existingListOfCachedAssets,...listOfCachedAssets};process.cssCache[key]={pageCss:newPageCSS,listOfCachedAssets:newListOfCachedAssets};}}else{// create css cache for a page. This will run on the first hit.
|
|
15
|
+
pageCss="<style>"+pageCss+"</style>";process.cssCache[key]={pageCss,listOfCachedAssets};}}/**
|
|
16
|
+
* returns cached css
|
|
17
|
+
* @param {string} key - router path
|
|
18
|
+
* @return {string} - cached css
|
|
19
|
+
*/function fetchCachedCSS(key){return process.cssCache&&process.cssCache[key]?process.cssCache[key].pageCss:"";}function fetchPreloadJSLinkCache(key){return process.preloadJSLinkCache&&process.preloadJSLinkCache[key]?process.preloadJSLinkCache[key]:null;}/**
|
|
20
|
+
* stores css and js in cache
|
|
21
|
+
* @param {object} res - response object
|
|
22
|
+
* @param {string} route - route path
|
|
23
|
+
*/function _default(res,route){try{const requestPath=route.path;const cachedCss=fetchCachedCSS(requestPath);const cachedPreloadJSLinks=fetchPreloadJSLinkCache(requestPath);if(cachedCss||cachedPreloadJSLinks){res.locals.pageCss=cachedCss;res.locals.preloadJSLinks=cachedPreloadJSLinks;return;}}catch(error){console.log("Error while caching your assets.");}}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=_default;var _fs=_interopRequireDefault(require("fs"));var _path=_interopRequireDefault(require("path"));var _react=_interopRequireDefault(require("react"));var _render=_interopRequireDefault(require("./render"));var _extract=_interopRequireDefault(require("./extract"));var _reactRedux=require("react-redux");var _document=require("./document");var _server=require("react-router-dom/server");var _ServerRouter=_interopRequireDefault(require("@catalyst/router/ServerRouter.js"));var _index=_interopRequireDefault(require("@catalyst/template/src/js/containers/App/index.js"));var _server2=require("@loadable/server");var _server3=require("react-dom/server");var _userAgentUtil=require("@catalyst/server/utils/userAgentUtil");var _router=require("@tata1mg/router");var _validator=require("@catalyst/server/utils/validator");var _document2=_interopRequireDefault(require("@catalyst/template/server/document.js"));var _utils=require("@catalyst/template/src/js/routes/utils.js");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const storePath=_path.default.resolve(`${process.env.src_path}/src/js/store/index.js`);let createStore;if(_fs.default.existsSync(storePath)){try{const{default:configureStore}=require(`${process.env.src_path}/src/js/store/index.js`);createStore=configureStore;}catch(error){createStore=()=>{return{getState:()=>{}};};}}else{createStore=()=>{return{getState:()=>{}};};}const isProduction=process.env.NODE_ENV==="production";// matches request route with routes defined in the application.
|
|
2
|
+
const getMatchRoutes=(routes,req,res,store,context,fetcherData,basePath="",webExtractor)=>{return routes.reduce((matches,route)=>{const{path}=route;const match=(0,_router.matchPath)({path:`${basePath}/${path}`,caseSensitive:false,end:true},req.baseUrl||"/");if(match){if(isProduction&&!res.locals.pageCss&&!res.locals.preloadJSLinks&&!res.locals.routePath){res.locals.routePath=path;(0,_extract.default)(res,route);}if(!res.locals.pageCss&&!res.locals.preloadJSLinks){if(!isProduction&&!res.locals.routePath){res.locals.routePath=path;}//moving routing logic outside of the App and using ServerRoutes for creating routes on server instead
|
|
3
|
+
(0,_server3.renderToString)(/*#__PURE__*/_react.default.createElement(_server2.ChunkExtractorManager,{extractor:webExtractor},/*#__PURE__*/_react.default.createElement(_reactRedux.Provider,{store:store},/*#__PURE__*/_react.default.createElement(_server.StaticRouter,{context:context,location:req.originalUrl},/*#__PURE__*/_react.default.createElement(_ServerRouter.default,{store:store,intialData:fetcherData})))));}const wc=route.component;matches.push({route,match,serverSideFunction:wc&&wc.serverSideFunction||(()=>Promise.resolve())});}if(!match&&route.children){// recursively try to match nested routes
|
|
4
|
+
const nested=getMatchRoutes(route.children,req,res,store,context,fetcherData,`${basePath}/${path}`,webExtractor);if(nested.length){matches=matches.concat(nested);}}return matches;},[]);};// Preloads chunks required for rendering document
|
|
5
|
+
const getComponent=(store,context,req,fetcherData)=>{return/*#__PURE__*/_react.default.createElement("div",{id:"app"},/*#__PURE__*/_react.default.createElement(_reactRedux.Provider,{store:store},/*#__PURE__*/_react.default.createElement(_server.StaticRouter,{context:context,location:req.originalUrl},/*#__PURE__*/_react.default.createElement(_ServerRouter.default,{store:store,intialData:fetcherData}))));};// sends document after rendering
|
|
6
|
+
const renderMarkUp=async(errorCode,req,res,metaTags,fetcherData,store,matches,context,webExtractor)=>{const deviceDetails=(0,_userAgentUtil.getUserAgentDetails)(req.headers["user-agent"]||"");const isBot=deviceDetails.googleBot?true:false;// Transforms Head Props
|
|
7
|
+
const shellStart=await _render.default.renderStart(res.locals.pageCss,res.locals.preloadJSLinks,metaTags,isBot,fetcherData);let state=store.getState();const jsx=webExtractor.collectChunks(getComponent(store,context,req,fetcherData));// Transforms Body Props
|
|
8
|
+
const shellEnd=_render.default.renderEnd(webExtractor,state,res,jsx,errorCode,fetcherData,isBot,res.locals.cspNonce);const finalProps={...shellStart,...shellEnd,jsx:jsx,req,res};let CompleteDocument=()=>{if((0,_validator.validateCustomDocument)(_document2.default)){return(0,_document2.default)(finalProps);}else{return/*#__PURE__*/_react.default.createElement("html",{lang:finalProps.lang},/*#__PURE__*/_react.default.createElement(_document.Head,{isBot:finalProps.isBot,preloadJSLinks:finalProps.preloadJSLinks,pageCss:finalProps.pageCss,fetcherData:finalProps.fetcherData,metaTags:finalProps.metaTags,publicAssetPath:finalProps.publicAssetPath}),/*#__PURE__*/_react.default.createElement(_document.Body,{initialState:finalProps.initialState,firstFoldCss:finalProps.firstFoldCss,firstFoldJS:finalProps.firstFoldJS,jsx:finalProps.jsx,statusCode:finalProps.statusCode,fetcherData:finalProps.fetcherData}));}};try{let status=matches.length&&matches[0].match.path==="*"?404:200;res.set({"content-type":"text/html; charset=utf-8"});res.status(status);const{pipe}=(0,_server3.renderToPipeableStream)(/*#__PURE__*/_react.default.createElement(CompleteDocument,null),{onShellReady(){res.setHeader("content-type","text/html");pipe(res);res.end();},onAllReady(){_render.default.renderEnd(webExtractor,state,res,jsx,errorCode,fetcherData,isBot,res.locals.cspNonce);},onError(error){logger.error({message:`\n Error while renderToPipeableStream : ${error.toString()}`});}});}catch(error){logger.error("Error in rendering document on server:"+error);}};/**
|
|
9
|
+
* middleware for document handling
|
|
10
|
+
* @param {object} req - request object
|
|
11
|
+
* @param {object} res - response object
|
|
12
|
+
*/async function _default(req,res){try{let context={};let fetcherData={};let webStats=_path.default.join(__dirname,"../../..",`loadable-stats.json`);if(isProduction){webStats=_path.default.join(process.env.src_path,`${process.env.BUILD_OUTPUT_PATH}/public/loadable-stats.json`);}const webExtractor=new _server2.ChunkExtractor({statsFile:webStats,entrypoints:["app"]});// creates store
|
|
13
|
+
const store=(0,_validator.validateConfigureStore)(createStore)?createStore({},req,res):null;// user defined routes
|
|
14
|
+
const routes=(0,_validator.validateGetRoutes)(_utils.getRoutes)?(0,_utils.getRoutes)():[];// Matches req url with routes
|
|
15
|
+
const matches=getMatchRoutes(routes,req,res,store,context,fetcherData,undefined,webExtractor);const allMatches=(0,_router.matchRoutes)((0,_utils.getRoutes)(),req.baseUrl);let allTags=[];// Executing app server side function
|
|
16
|
+
_index.default.serverSideFunction({store,req,res})// Executing serverFetcher functions with serverDataFetcher provided by router and returning document
|
|
17
|
+
.then(()=>{(0,_router.serverDataFetcher)({routes:routes,req,res,url:req.originalUrl},{store}).then(res=>{fetcherData=res;allTags=(0,_router.getMetaData)(allMatches,fetcherData);}).then(async()=>await renderMarkUp(null,req,res,allTags,fetcherData,store,matches,context,webExtractor)).catch(async error=>{logger.error("Error in executing serverFetcher functions: "+error);await renderMarkUp(404,req,res,allTags,fetcherData,store,matches,context,webExtractor);});}).catch(error=>{logger.error("Error in executing serverSideFunction inside App: "+error);renderMarkUp(error.status_code,req,res,allTags,fetcherData,store,matches,context,webExtractor);});}catch(error){logger.error("Error in handling document request: "+error.toString());}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _express=_interopRequireDefault(require("express"));var _handler=_interopRequireDefault(require("./handler"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const router=_express.default.Router();router.use(_handler.default);var _default=exports.default=router;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _fs=_interopRequireDefault(require("fs"));var _path=_interopRequireDefault(require("path"));var _extract=require("./extract");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/**
|
|
2
|
+
* returns data which will be used in Head component for page rendering
|
|
3
|
+
* @param {string} pageCss - cached styles for page
|
|
4
|
+
* @param {string} preloadJSLinks - cached javscript elements for page
|
|
5
|
+
* @param {function} metaTagFunction - user defined function which returns meta tags in array
|
|
6
|
+
* @param {boolean} isBot - checks if request is made by bot
|
|
7
|
+
* @param {object} fetcherData - router fetched data
|
|
8
|
+
*/const renderStart=(pageCss,preloadJSLinks,metaTags,isBot,fetcherData)=>{const{IS_DEV_COMMAND,WEBPACK_DEV_SERVER_HOSTNAME,WEBPACK_DEV_SERVER_PORT}=process.env;let publicAssetPath=`${process.env.PUBLIC_STATIC_ASSET_URL}${process.env.PUBLIC_STATIC_ASSET_PATH}`;// serves assets from localhost on running devBuild and devServe command
|
|
9
|
+
if(JSON.parse(IS_DEV_COMMAND)){publicAssetPath=`http://${WEBPACK_DEV_SERVER_HOSTNAME}:${WEBPACK_DEV_SERVER_PORT}/assets/`;}return{pageCss,preloadJSLinks,metaTags,isBot,publicAssetPath,fetcherData};};const extractCss=data=>{let pageCss="<style>";if(Array.isArray(data)){try{data.map(assetChunk=>{const assetPathArr=assetChunk.key.split("/");const assetName=assetPathArr[assetPathArr.length-1];const ext=_path.default.extname(assetName);if(ext===".css")pageCss+=_fs.default.readFileSync(_path.default.resolve(`${process.env.OUTPUT_PATH}/public/`+assetName));});}catch(error){console.dir({service_name:`pwa-${process.env.APPLICATION}-node-server`,loglevel:"error",version:"v2",message:"\n \n =====> Error While Extracting The Chunk: \n ",traceback:error});}}pageCss+="</style>";return pageCss;};/**
|
|
10
|
+
* returns data which will be used in body component for page rendering
|
|
11
|
+
* @param {object} webExtractor - loadable object which holds chunking function
|
|
12
|
+
* @param {string} initialState - reducer initial state
|
|
13
|
+
* @param {function} res - response object
|
|
14
|
+
* @param {boolean} jsx - jsx which needs to be render on server side
|
|
15
|
+
* @param {string|number|null} errorCode - error code
|
|
16
|
+
* @param {object} fetcherData - router fetched data
|
|
17
|
+
*/const renderEnd=(webExtractor,initialState={},res,jsx,errorCode,fetcherData,isBot,cspNonce)=>{// For bot first fold css and js would become complete page css and js
|
|
18
|
+
let firstFoldCss="";let firstFoldJS="";const isProd=process.env.NODE_ENV==="production";const{routePath,preloadJSLinks}=res.locals;const linkElements=webExtractor.getLinkElements();// We want to cache/or check for update css on every call
|
|
19
|
+
// We want to extract script tags for every call that will get added to body.
|
|
20
|
+
// Their corresponding preloaded link script tags are already present in head.
|
|
21
|
+
if(routePath){!isBot&&(0,_extract.cacheCSS)(routePath,linkElements);// firstFoldJS = webExtractor.getScriptTags({ nonce: cspNonce })
|
|
22
|
+
firstFoldJS=webExtractor.getScriptElements();}// This block will run for the first time and cache preloaded JS Links for second render
|
|
23
|
+
// firstFoldJS ->scripts gets inject in body
|
|
24
|
+
// firstFoldCss -> Inline css gets injected in body only for the first render
|
|
25
|
+
if(!isProd||isBot||routePath&&!preloadJSLinks){// For production, we inject link tags with preload/prefetch using getLinkElements and inlining them via file reads
|
|
26
|
+
// For local, given we have assets in memory we dont read from file rather directly inject via link elements returned without preload/prefetch
|
|
27
|
+
firstFoldCss=isProd?extractCss(linkElements):webExtractor.getStyleElements();!isBot&&(0,_extract.cachePreloadJSLinks)(routePath,linkElements);}return{initialState,firstFoldCss,firstFoldJS,jsx,errorCode,fetcherData};};var _default=exports.default={renderStart,renderEnd};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";var _fs=_interopRequireDefault(require("fs"));var _path=_interopRequireDefault(require("path"));var _nodeUtil=_interopRequireDefault(require("node:util"));var _chokidar=_interopRequireDefault(require("chokidar"));var _picocolors=require("picocolors");var _index=require("@catalyst/template/server/index.js");var _validator=require("@catalyst/server/utils/validator.js");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const env=process.env.NODE_ENV||"development";// function defined by user which needs to run before server starts
|
|
2
|
+
if((0,_validator.validatePreInitServer)(_index.preServerInit))(0,_index.preServerInit)();process.on("uncaughtException",(err,origin)=>{console.log(process.stderr.fd);console.log(`Caught exception: ${err}\n`+`Exception origin: ${origin}`);});process.on("SIGINT",function(data){console.log("SIGINT");console.log(data);process.exit(0);});process.on("uncaughtExceptionMonitor",(err,origin)=>{console.log(err,origin);});process.on("message",function(msg){if(msg=="shutdown"){console.log("Closing all connections...");setTimeout(function(){console.log("Finished closing connections");process.exit(0);},1500);}});if(env==="development"){// Add better stack tracing for promises in dev mode
|
|
3
|
+
process.on("unhandledRejection",r=>console.debug(r));}const port=process.env.NODE_SERVER_PORT??3005;const host=process.env.NODE_SERVER_HOSTNAME??"localhost";let statsPath=_path.default.join(__dirname,`../../`,"loadable-stats.json");if(env==="production"){statsPath=_path.default.join(process.env.src_path,`${process.env.BUILD_OUTPUT_PATH}/public/loadable-stats.json`);}const watcher=_chokidar.default.watch(statsPath,{persistent:true});let serverInstance=null;const restartServer=()=>{const server=require("./expressServer.js").default;serverInstance=server.listen({port,host});};const startServer=()=>{const server=require("./expressServer.js").default;serverInstance=server.listen({port,host},error=>{const{APPLICATION,NODE_SERVER_HOSTNAME,NODE_SERVER_PORT}=process.env;if(error)console.log("An error occured while starting the Application server : ",error);if(env==="development")console.log((0,_picocolors.green)("Compiled successfully!"));console.log(`\nYou can now view ${APPLICATION} in the browser.\n`);console.log(_nodeUtil.default.format("\tLocal:".padEnd(8),(0,_picocolors.cyan)(`http://${NODE_SERVER_HOSTNAME}:${NODE_SERVER_PORT}`)));if(env==="development"){console.log("\nNote that the development build is not optimized.");console.log("To create a production build, use "+(0,_picocolors.cyan)("npm run build"));}console.log("\nFind out more about deployment here:");console.log((0,_picocolors.yellow)("\n https://catalyst.1mg.com/public_docs/content/deployment\n"));});};if(_fs.default.existsSync(statsPath)){// if loadable-stats.json exist this block will start the server in development environment. This happens in dev environment when loadable stats already exists and developer is making changes to the files. lodable-stats.json will be updated after every change.
|
|
4
|
+
watcher.on("change",()=>{watcher.close();if(serverInstance){serverInstance.close(()=>startServer());}else{startServer();}});// this block will start the server when your files have been compiled for production and lodable-stats.json exists.
|
|
5
|
+
watcher.on("add",()=>{if(env==="production"){watcher.close();startServer();}});}else{// this block will start the server in development environment for the first time when loadable-stats.json does not exists.
|
|
6
|
+
watcher.on("add",()=>{watcher.close();if(serverInstance){serverInstance.close(()=>startServer());}else{startServer();}});}if(_fs.default.existsSync(statsPath)){if(env==="development"){restartServer();}}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getUserAgentDetails=void 0;var _uaParserJs=_interopRequireDefault(require("ua-parser-js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}const googleBots={"APIs-Google":"APIs-Google",AdSense:"Mediapartners-Google","AdsBot Mobile Web Android":"AdsBot-Google-Mobile","AdsBot Mobile Web":"AdsBot-Google-Mobile",AdsBot:"AdsBot-Google","Mobile AdSense":"Mediapartners-Google","Mobile Apps Android":"AdsBot-Google-Mobile-Apps",Feedfetcher:"FeedFetcher-Google","Google Read Aloud":"Google-Read-Aloud","Duplex on the Web":"DuplexWeb-Google","Google Favicon":"Google Favicon","Web Light":"googleweblight","Amp crawler":"Google-AMPHTM",Googlebot:"Googlebot"};/**
|
|
2
|
+
* check if user agent contains bot data
|
|
3
|
+
* @param {string} ua - user agent
|
|
4
|
+
* @return {string|null}
|
|
5
|
+
*/const getGoogleBot=ua=>{for(let key in googleBots){if(ua.includes(googleBots[key]))return key;}return null;};/**
|
|
6
|
+
* returns object which contains google bot and user-agent info
|
|
7
|
+
* @param {string} ua - user agent
|
|
8
|
+
* @return {object} - returns user agent
|
|
9
|
+
*/const getUserAgentDetails=ua=>{const agentDetails=(0,_uaParserJs.default)(ua);const googleBot=getGoogleBot(ua);return{...agentDetails,googleBot};};exports.getUserAgentDetails=getUserAgentDetails;
|