catalyst-core-internal 0.0.1-beta.6 → 0.0.1-beta.60

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.
Files changed (139) hide show
  1. package/README.md +21 -125
  2. package/babel.config.js +32 -0
  3. package/bin/catalyst.js +33 -35
  4. package/changelog.md +34 -0
  5. package/config.json +1 -1
  6. package/dist/caching.js +1 -0
  7. package/dist/index.js +1 -0
  8. package/dist/logger.js +10 -0
  9. package/dist/router/ClientRouter.js +3 -0
  10. package/dist/router/ServerRouter.js +1 -0
  11. package/dist/router.js +1 -0
  12. package/dist/scripts/build.js +3 -0
  13. package/dist/scripts/checkVersion.js +1 -0
  14. package/dist/scripts/devBuild.js +3 -0
  15. package/dist/scripts/devServe.js +3 -0
  16. package/dist/scripts/loadEnvironmentVariables.js +5 -0
  17. package/dist/scripts/loadScriptsBeforeServerStarts.js +4 -0
  18. package/dist/scripts/registerAliases.js +2 -0
  19. package/dist/scripts/scriptUtils.js +2 -0
  20. package/dist/scripts/serve.js +3 -0
  21. package/dist/scripts/start.js +6 -0
  22. package/dist/scripts/validator.js +1 -0
  23. package/dist/server/expressServer.js +9 -0
  24. package/dist/server/renderer/document/Body.js +11 -0
  25. package/dist/server/renderer/document/Head.js +9 -0
  26. package/dist/server/renderer/document/index.js +1 -0
  27. package/dist/server/renderer/extract.js +27 -0
  28. package/dist/server/renderer/handler.js +22 -0
  29. package/dist/server/renderer/index.js +1 -0
  30. package/dist/server/startServer.js +7 -0
  31. package/dist/server/utils/userAgentUtil.js +9 -0
  32. package/dist/server/utils/validator.js +1 -0
  33. package/dist/webpack/babel-plugins/remove-client.plugin.js +5 -0
  34. package/dist/webpack/babel-plugins/remove-ssr.plugin.js +5 -0
  35. package/dist/webpack/babel.config.client.js +1 -0
  36. package/dist/webpack/babel.config.ssr.js +1 -0
  37. package/dist/webpack/base.babel.js +8 -0
  38. package/dist/webpack/development.client.babel.js +19 -0
  39. package/dist/webpack/production.client.babel.js +4 -0
  40. package/dist/webpack/production.ssr.babel.js +4 -0
  41. package/dist/webpack/scssParams.js +9 -0
  42. package/license +10 -0
  43. package/package.json +119 -83
  44. package/babel.config.json +0 -24
  45. package/caching.js +0 -16
  46. package/index.js +0 -16
  47. package/logger.js +0 -96
  48. package/packages/create-framework-app/templates/redux-js/node_modules/@babel/core/lib/config/caching.js +0 -261
  49. package/packages/create-framework-app/templates/redux-js/node_modules/@remix-run/router/dist/router.js +0 -4327
  50. package/packages/create-framework-app/templates/redux-js/node_modules/catalyst/router.js +0 -15
  51. package/packages/create-framework-app/templates/redux-js/node_modules/catalyst/src/router.js +0 -1
  52. package/packages/create-framework-app/templates/redux-js/node_modules/http-proxy-middleware/dist/router.js +0 -46
  53. package/router/ClientRouter.js +0 -19
  54. package/router/ServerRouter.js +0 -19
  55. package/router/index.js +0 -32
  56. package/router.js +0 -16
  57. package/scripts/build.js +0 -29
  58. package/scripts/checkVersion.js +0 -5
  59. package/scripts/loadEnvironmentVariables.js +0 -24
  60. package/scripts/loadScriptsBeforeServerStarts.js +0 -47
  61. package/scripts/prepare.js +0 -19
  62. package/scripts/registerAliases.js +0 -30
  63. package/scripts/serve.js +0 -30
  64. package/scripts/start.js +0 -26
  65. package/scripts/validator.js +0 -128
  66. package/server/expressServer.js +0 -50
  67. package/server/mainIndex.js +0 -65
  68. package/server/mainServer.js +0 -70
  69. package/server/renderer/document/Body.js +0 -36
  70. package/server/renderer/document/Head.js +0 -43
  71. package/server/renderer/document/index.js +0 -27
  72. package/server/renderer/extract.js +0 -87
  73. package/server/renderer/handler.js +0 -252
  74. package/server/renderer/index.js +0 -12
  75. package/server/renderer/render.js +0 -73
  76. package/server/renderer/userAgentUtil.js +0 -55
  77. package/server/startServer.js +0 -65
  78. package/server/utils/userAgentUtil.js +0 -55
  79. package/server/utils/validator.js +0 -128
  80. package/tsconfig.json +0 -110
  81. package/types/caching.d.ts +0 -1
  82. package/types/config/config.d.ts +0 -19
  83. package/types/index.d.ts +0 -1
  84. package/types/logger/index.d.ts +0 -14
  85. package/types/reducer/index.d.ts +0 -22
  86. package/types/reducer/loadableConfigReducer.d.ts +0 -9
  87. package/types/router/ClientRouter.d.ts +0 -5
  88. package/types/router/ServerRouter.d.ts +0 -7
  89. package/types/router/index.d.ts +0 -8
  90. package/types/router.d.ts +0 -1
  91. package/types/scripts/build.d.ts +0 -1
  92. package/types/scripts/loadEnvironmentVariables.d.ts +0 -5
  93. package/types/scripts/loadScriptsBeforeServerStarts.d.ts +0 -1
  94. package/types/scripts/prepare.d.ts +0 -1
  95. package/types/scripts/registerAliases.d.ts +0 -1
  96. package/types/scripts/serve.d.ts +0 -1
  97. package/types/scripts/start.d.ts +0 -1
  98. package/types/scripts/validator.d.ts +0 -9
  99. package/types/scripts/verifyConfig.d.ts +0 -1
  100. package/types/server/mainIndex.d.ts +0 -1
  101. package/types/server/mainServer.d.ts +0 -2
  102. package/types/server/renderer/document/Body.d.ts +0 -11
  103. package/types/server/renderer/document/Head.d.ts +0 -11
  104. package/types/server/renderer/document/index.d.ts +0 -2
  105. package/types/server/renderer/extract.d.ts +0 -18
  106. package/types/server/renderer/handler.d.ts +0 -6
  107. package/types/server/renderer/index.d.ts +0 -2
  108. package/types/server/renderer/render.d.ts +0 -38
  109. package/types/server/renderer/userAgentUtil.d.ts +0 -1
  110. package/types/store/index.d.ts +0 -11
  111. package/types/store/index.dev.d.ts +0 -8
  112. package/types/store/index.prod.d.ts +0 -8
  113. package/types/webpack/babel-plugins/remove-client.plugin.d.ts +0 -10
  114. package/types/webpack/babel-plugins/remove-ssr.plugin.d.ts +0 -10
  115. package/types/webpack/babel.config.client.d.ts +0 -21
  116. package/types/webpack/babel.config.d.ts +0 -16
  117. package/types/webpack/babel.config.ssr.d.ts +0 -21
  118. package/types/webpack/base.babel.d.ts +0 -184
  119. package/types/webpack/development.client.babel.d.ts +0 -1
  120. package/types/webpack/plugins/mime-types.d.ts +0 -78
  121. package/types/webpack/plugins/route-manifest-plugin.d.ts +0 -1
  122. package/types/webpack/plugins/upload-assets-plugin.d.ts +0 -1
  123. package/types/webpack/production.client.babel.d.ts +0 -174
  124. package/types/webpack/production.ssr.babel.d.ts +0 -2
  125. package/types/webpack/scssParams.d.ts +0 -2
  126. package/webpack/babel-plugins/remove-client.plugin.js +0 -31
  127. package/webpack/babel-plugins/remove-ssr.plugin.js +0 -21
  128. package/webpack/babel.config.client.js +0 -24
  129. package/webpack/babel.config.js +0 -20
  130. package/webpack/babel.config.ssr.js +0 -24
  131. package/webpack/base.babel.js +0 -167
  132. package/webpack/development.client.babel.js +0 -82
  133. package/webpack/plugins/mime-types.js +0 -82
  134. package/webpack/plugins/route-manifest-copy.js +0 -122
  135. package/webpack/plugins/route-manifest-plugin.js +0 -122
  136. package/webpack/plugins/upload-assets-plugin.js +0 -181
  137. package/webpack/production.client.babel.js +0 -78
  138. package/webpack/production.ssr.babel.js +0 -61
  139. package/webpack/scssParams.js +0 -35
package/README.md CHANGED
@@ -1,145 +1,41 @@
1
- # Catalyst
1
+ <div align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://onemg.gumlet.io/staging/7ee66dfb-b5fb-4fbe-8dea-789685e45f7a.svg">
4
+ <img alt="Catalyst logo" src="https://onemg.gumlet.io/staging/2fdb0975-8f51-4fd1-bd7d-6375d793f581.svg" height="128">
5
+ </picture>
6
+ </div>
2
7
 
3
- Frontend framework with server rendering support for web applications.
4
-
5
- ## Table of Contents
6
-
7
- - Overview
8
- - Installation
9
- - Data Fetching with Catalyst
10
- - serverFetcher
11
- - clientFetcher
12
- - refetch (for data revalidation)
13
- - State Management
14
-
15
- ## Overview
16
-
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.
8
+ ## Table of Contents
18
9
 
10
+ - Overview
11
+ - Installation
12
+
13
+ ## Overview
19
14
 
15
+ Catalyst offers a comprehensive suite of features designed for modern web development. It includes isomorphic rendering for optimal performance, an extendable server with full-stack capabilities, and configurable state management. The framework employs smart prefetching of data and chunks, allows easy configuration of global styles and layouts, and provides SEO optimization at both global and page levels.
20
16
  ## Installation
21
17
 
22
18
  **System Requirements**
23
19
 
24
- - Node version 20.4.0 or later
25
- - macOS and Linux are supported
26
-
20
+ - Node version 20.4.0 or later
21
+ - Compatible with **macOS** and **Linux**
27
22
 
28
23
  **Automatic Installation**
29
24
 
30
- - Run the following commands in the directory where you want to set up the Catalyst app.
25
+ Run the following commands in the directory where you want to set up the Catalyst app:
31
26
 
32
- ```js
27
+ ```bash
33
28
  npx create-catalyst-app@latest
34
29
  ```
35
30
 
36
- If successful, you will see the following prompts in your terminal.
37
-
38
- - Enter the name of your Catalyst application.
39
- - Choose state management.
40
- - Once packages are installed, start the development server by running the following command.
41
-
42
- ```js
43
- npm run start
44
- ```
45
-
46
- - Navigate to http://localhost:3005
47
-
48
- The dev server should be running now.
31
+ You will see some prompts to configure your application.
49
32
 
50
- Visit our official documentation:
51
- https://catalyst.1mg.com/public_docs/content/installation
52
-
53
-
54
-
55
- ## Data Fetching with Catalyst
56
-
57
- we have serverFetcher function for fetching with SSR and clientFetcher function for fetching during client side rendering and navigations.
58
-
59
- **serverFetcher**
60
-
61
- 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
-
63
- if server fetcher is called for a route then client fetcher will not be called for that route, unless called with refetch.
64
- ```js
65
- Home.serverFetcher = async ({ req,params,searchParams }, { store }) => {
66
- store.dispatch(someAction())
67
- const res = await fetch("some_url");
68
- const json = await res.json();
69
- return json;
70
- };
71
- ```
72
- data returned from fetcher function will be accessible through useCurrentRouteData() hook provided by router.
73
- ```js
74
- const [data,error,isFetched] = useCurrentRouteData()
33
+ ```bash
34
+ cd <name-of-your-project> && npm run start
75
35
  ```
76
- error and loading state would be handled by router.
77
36
 
78
- **clientFetcher**
79
-
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
-
82
- ```js
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
- ```
90
- data returned from client fetcher function will be accessible through useCurrentRouteData() hook provided by router (hook for data access through client is same).
91
- ```js
92
- const [data,error,isFetched] = useCurrentRouteData()
93
- ```
94
-
95
-
96
- **refetch (for data revalidation)**
97
-
98
- 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
- We can pass arguments in refetch function which would
101
-
102
- ```js
103
- const [data,error,isFetched,refetch] = useCurrentRouteData()
104
-
105
- useEffect(()=>{
106
- refetch({refetchArgument:some_value})
107
- },[arg])
108
-
109
- clientFetcher = ({},{refetchArgument}) => {
110
-
111
- const res = await api_call // refetchArg can be used as a param in api call
112
- return res
113
- }
114
-
115
- ```
116
-
117
-
118
- ## State Management
119
- state management wrappers are defined in stateProvider.js file
120
-
121
- store can be configured by manipulating store/index.js as per user requirements (custom middlewares etc can be added in this way.
122
-
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
-
125
- ```js
126
- const configureStore = (initialState, cookies, requestObj, customHeaders) => {
127
- const api = fetchInstance
128
- const store = createStore({
129
- reducer: rootReducer,
130
- middleware: (getDefaultMiddleware) =>
131
- getDefaultMiddleware({
132
- thunk: {
133
- extraArgument: { api },
134
- },
135
- }),
136
- preloadedState: initialState,
137
- })
138
- return store
139
- }
140
-
141
- export default configureStore
142
- ```
37
+ The development server will start at ```http://localhost:3005```
143
38
 
144
39
  ## Documentation
40
+
145
41
  Visit https://catalyst.1mg.com to view the full documentation.
@@ -0,0 +1,32 @@
1
+ module.exports = (api) => {
2
+ api.cache(true)
3
+
4
+ return {
5
+ presets: [
6
+ [
7
+ "@babel/preset-typescript",
8
+ {
9
+ isTSX: true,
10
+ allExtensions: true,
11
+ },
12
+ ],
13
+ [
14
+ "@babel/preset-env",
15
+ {
16
+ targets: {
17
+ node: "current",
18
+ },
19
+ },
20
+ ],
21
+ ["@babel/preset-react", { runtime: "automatic" }],
22
+ ],
23
+ compact: true,
24
+ plugins: ["@loadable/babel-plugin"],
25
+ env: {
26
+ test: {
27
+ presets: ["@babel/preset-react"],
28
+ },
29
+ },
30
+ ignore: ["__TEST__"],
31
+ }
32
+ }
package/bin/catalyst.js CHANGED
@@ -1,40 +1,38 @@
1
1
  #!/usr/bin/env node
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);
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
- x => x === 'build' || x === 'start' || x=== 'serve'
10
- );
11
- const script = scriptIndex === -1 ? args[0] : args[scriptIndex];
12
- const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : [];
13
- if (['build', 'start', 'serve'].includes(script)) {
14
- const result = spawnSync(
15
- process.execPath,
16
- nodeArgs
17
- .concat(require.resolve('../scripts/' + script))
18
- .concat(args.slice(scriptIndex + 1)),
19
- { stdio: 'inherit' }
20
- );
21
- if (result.signal) {
22
- if (result.signal === 'SIGKILL') {
23
- console.log(
24
- 'The build failed because the process exited too early. ' +
25
- 'This probably means the system ran out of memory or someone called ' +
26
- '`kill -9` on the process.'
27
- );
28
- } else if (result.signal === 'SIGTERM') {
29
- console.log(
30
- 'The build failed because the process exited too early. ' +
31
- 'Someone might have called `kill` or `killall`, or the system could ' +
32
- 'be shutting down.'
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(1);
36
- }
37
- process.exit(result.status);
35
+ process.exit(result.status)
38
36
  } else {
39
- console.log('Unknown script "' + script + '".');
37
+ console.log('Unknown script "' + script + '".')
40
38
  }
package/changelog.md ADDED
@@ -0,0 +1,34 @@
1
+ # Changelog
2
+
3
+ ## [0.0.1-beta.12] - 06-03-2025
4
+
5
+ - Add support for ESM only packages
6
+
7
+ ## [0.0.1-beta.11] - 21-02-2025
8
+
9
+ - Add support for custom react compiler config
10
+ - Add support for typescript
11
+ - Fix json import issue
12
+ - Fix common name module conflict issue
13
+
14
+ ## [0.0.1-beta.10] - 06-02-2024
15
+
16
+ ### Changes
17
+
18
+ - New lifecycle methods
19
+ - Support for windows - Adds native support for powershell
20
+ - Add support for react compiler
21
+ - Add document CSS in response for bot agents
22
+
23
+ ## [0.0.1-beta.9] - 13-12-2024
24
+
25
+ ### Changes
26
+
27
+ - Update @tata1mg/router's version to 0.0.1-beta.6.
28
+
29
+ ## [0.0.1-beta.8] - 09-12-2024
30
+
31
+ ### Changes
32
+
33
+ - Filter out host machine's environment variable from client environment variables
34
+ - Update @tata1mg/router's version to 0.0.1-beta.5.
package/config.json CHANGED
@@ -4,4 +4,4 @@
4
4
  "chunkFileNameDev": "[name].bundle.js",
5
5
  "chunkFileNameProd": "[name].[contenthash].js",
6
6
  "cssChunkFileName": "[name].[contenthash].css"
7
- }
7
+ }
@@ -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,3 @@
1
+ "use strict";const path=require("path");const{spawnSync}=require("child_process");const{green,cyan,yellow}=require("picocolors");const{name}=require(`${process.cwd()}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.cwd()}/config/config.json`);const{arrayToObject,printBundleInformation}=require("./scriptUtils.js");/**
2
+ * @description - creates a production build of the application.
3
+ */function build(){const isWindows=process.platform==="win32";const commandLineArguments=process.argv.slice(2);const argumentsObject=arrayToObject(commandLineArguments);const dirname=path.resolve(__dirname,"../../");const commands=["node ./dist/scripts/checkVersion",`${isWindows?"rd -r -fo":"rm -rf"} ${process.cwd()}/${BUILD_OUTPUT_PATH} & node ./dist/scripts/loadScriptsBeforeServerStarts.js`,`cross-env APPLICATION=${name||"catalyst_app"} webpack --config ./dist/webpack/production.client.babel.js --progress`,`cross-env APPLICATION=${name||"catalyst_app"} SSR=true webpack --config ./dist/webpack/production.ssr.babel.js`,`cross-env APPLICATION=${name||"catalyst_app"} npx babel ./dist/server --out-dir ${process.cwd()}/${BUILD_OUTPUT_PATH} --ignore '**/*.test.js,./dist/server/renderer/handler.js' --quiet`,`cross-env APPLICATION=${name||"catalyst_app"} npx babel ${process.cwd()}/server --out-dir ${process.cwd()}/${BUILD_OUTPUT_PATH} --quiet`];const command=commands.join(isWindows?" && ":" ; ");console.log("Creating an optimized production build...");const result=spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.cwd(),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%20and%20Production/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,3 @@
1
+ "use strict";const path=require("path");const{spawnSync}=require("child_process");const{green,cyan,yellow}=require("picocolors");const{name}=require(`${process.cwd()}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.cwd()}/config/config.json`);const{arrayToObject,printBundleInformation}=require("./scriptUtils.js");/**
2
+ * @description - creates a production build of the application.
3
+ */function devBuild(){const isWindows=process.platform==="win32";const commandLineArguments=process.argv.slice(2);const argumentsObject=arrayToObject(commandLineArguments);const dirname=path.resolve(__dirname,"../../");const commands=["node ./dist/scripts/checkVersion",`${isWindows?"rd -r -fo":"rm -rf"} ${process.cwd()}/${BUILD_OUTPUT_PATH} & node ./dist/scripts/loadScriptsBeforeServerStarts.js`,`cross-env APPLICATION=${name||"catalyst_app"} webpack --config ./dist/webpack/production.client.babel.js --progress`,` cross-env APPLICATION=${name||"catalyst_app"} SSR=true webpack --config ./dist/webpack/production.ssr.babel.js`,`cross-env APPLICATION=${name||"catalyst_app"} npx babel ./dist/server --out-dir ${process.cwd()}/${BUILD_OUTPUT_PATH} --ignore '**/*.test.js,./dist/server/renderer/handler.js' --quiet`,`cross-env APPLICATION=${name||"catalyst_app"} npx babel ${process.cwd()}/server --out-dir ${process.cwd()}/${BUILD_OUTPUT_PATH} --quiet`];const command=commands.join(isWindows?" && ":" ; ");console.log("Creating an optimized local build...");const result=spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.cwd(),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%20and%20Production/deployment\n"));}}devBuild();
@@ -0,0 +1,3 @@
1
+ "use strict";const path=require("path");const{spawnSync}=require("child_process");const{arrayToObject}=require("./scriptUtils");const{name}=require(`${process.cwd()}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.cwd()}/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=`cross-env APPLICATION=${name||"catalyst_app"} node -r ./dist/scripts/loadScriptsBeforeServerStarts.js ${process.cwd()}/${BUILD_OUTPUT_PATH}/startServer.js`;spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.cwd(),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";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(e){return e&&e.__esModule?e:{default:e};}/* 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.posix.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(e){return e&&e.__esModule?e:{default:e};}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.cwd()}/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.cwd(),`${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,3 @@
1
+ "use strict";const path=require("path");const{spawnSync}=require("child_process");const{arrayToObject}=require("./scriptUtils");const{name}=require(`${process.cwd()}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.cwd()}/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=`cross-env APPLICATION=${name||"catalyst_app"} node -r ./dist/scripts/loadScriptsBeforeServerStarts.js ${process.cwd()}/${BUILD_OUTPUT_PATH}/startServer.js`;spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.cwd(),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,spawn}=require("child_process");const{arrayToObject}=require("./scriptUtils");const{name}=require(`${process.cwd()}/package.json`);const{BUILD_OUTPUT_PATH}=require(`${process.cwd()}/config/config.json`);/**
2
+ * @description - starts webpack dev server and node server.
3
+ */function start(){const isWindows=process.platform==="win32";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 --extensions .js,.ts,.jsx,.tsx --watch-path=${process.env.PWD}/server --watch-path=${process.env.PWD}/src --ignore='__IGNORE__' --no-warnings=ExperimentalWarning --no-warnings=BABEL
6
+ `;if(isWindows){spawn(`node ./dist/scripts/checkVersion && start /b npx babel-node -r ./dist/scripts/loadScriptsBeforeServerStarts.js ./dist/webpack/development.client.babel --no-warnings=ExperimentalWarning --no-warnings=BABEL`,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.cwd(),NODE_ENV:"development",IS_DEV_COMMAND:false,APPLICATION:name||"catalyst_app",BUILD_OUTPUT_PATH:BUILD_OUTPUT_PATH,...argumentsObject}});spawn(`node ./dist/scripts/checkVersion && npx babel-node -r ./dist/scripts/loadScriptsBeforeServerStarts.js ./dist/server/startServer.js --watch-path=${process.cwd()}/server --watch-path=${process.cwd()}/src --ignore='__IGNORE__' --no-warnings=ExperimentalWarning --no-warnings=BABEL`,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.cwd(),NODE_ENV:"development",IS_DEV_COMMAND:false,APPLICATION:name||"catalyst_app",BUILD_OUTPUT_PATH:BUILD_OUTPUT_PATH,...argumentsObject}});}else{spawnSync(command,[],{cwd:dirname,stdio:"inherit",shell:true,env:{...process.env,src_path:process.cwd(),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(e){return e&&e.__esModule?e:{default:e};}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,11 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Body=Body;var _react=_interopRequireDefault(require("react"));var _propTypes=_interopRequireDefault(require("prop-types"));var _jsxRuntime=require("react/jsx-runtime");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}/**
2
+ * Body component which will be used in page component
3
+ * @param {object} jsx - page jsx code
4
+ * @param {object} initialState - initial state object for redux store
5
+ * @param {object} firstFoldCss - style elements extracted for initial page load
6
+ * @param {object} fetcherData - contains data from executing serverFetcher function
7
+ * @param {object} children - contains any child elements defined within the component
8
+ */function Body(props){const{jsx="",initialState={},fetcherData={},children}=props;return/*#__PURE__*/(0,_jsxRuntime.jsxs)("body",{children:[jsx,/*#__PURE__*/(0,_jsxRuntime.jsx)("script",{/* eslint-disable */dangerouslySetInnerHTML:{__html:`
9
+ window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}
10
+ window.__ROUTER_INITIAL_DATA__ = ${JSON.stringify(fetcherData)}
11
+ `}}),children]});}Body.propTypes={initialState:_propTypes.default.object,jsx:_propTypes.default.any,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"));var _jsxRuntime=require("react/jsx-runtime");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}/**
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;if(children){return/*#__PURE__*/(0,_jsxRuntime.jsxs)("head",{children:[children,metaTags&&metaTags,pageCss&&/*#__PURE__*/(0,_jsxRuntime.jsx)("style",{dangerouslySetInnerHTML:{__html:pageCss}}),!isBot&&preloadJSLinks]});}return/*#__PURE__*/(0,_jsxRuntime.jsxs)("head",{children:[/*#__PURE__*/(0,_jsxRuntime.jsx)("meta",{charSet:"utf-8"}),/*#__PURE__*/(0,_jsxRuntime.jsx)("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),publicAssetPath&&/*#__PURE__*/(0,_jsxRuntime.jsx)("link",{rel:"preconnect",href:publicAssetPath}),publicAssetPath&&/*#__PURE__*/(0,_jsxRuntime.jsx)("link",{rel:"dns-prefetch",href:publicAssetPath}),metaTags&&metaTags,pageCss&&/*#__PURE__*/(0,_jsxRuntime.jsx)("style",{dangerouslySetInnerHTML:{__html:pageCss}}),!isBot&&preloadJSLinks]});}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,27 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.cacheAndFetchAssets=void 0;exports.cacheCSS=cacheCSS;exports.cachePreloadJSLinks=cachePreloadJSLinks;exports.default=_default;var _path=_interopRequireDefault(require("path"));var _fs=_interopRequireDefault(require("fs"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function cachePreloadJSLinks(key,data){if(!process.preloadJSLinkCache){process.preloadJSLinkCache={};}let preloadJSLinks=[];if(Array.isArray(data)){try{preloadJSLinks=data.filter(asset=>asset?.props?.as==="script");}catch(error){}}process.preloadJSLinkCache[key]=preloadJSLinks;}/**
2
+ * Stores css chunks styles into cache in string format
3
+ * @param {string} key - router path
4
+ * @param {object} data - css elements array extracted through loadable chunk extracter
5
+ */function cacheCSS(key,data){if(!process.cssCache){process.cssCache={};}let pageCss="";let listOfCachedAssets={};if(Array.isArray(data)){try{if(process.env.NODE_ENV==="production"){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
6
+ 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 css cache exists for a route and there are some uncached css, add that css to the cache
7
+ // this will run on subsequent hits and will add css of uncached widgets to the cache
8
+ if(process.cssCache[key]){if(pageCss!==""){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.
9
+ process.cssCache[key]={pageCss,listOfCachedAssets};}return pageCss;}/**
10
+ * returns cached css
11
+ * @param {string} key - router path
12
+ * @return {string} - cached css
13
+ */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;}/**
14
+ * stores css and js in cache
15
+ * @param {object} res - response object
16
+ * @param {string} route - route path
17
+ */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){}}const cacheAndFetchAssets=({webExtractor,res,isBot})=>{// 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){if(isProd){firstFoldCss=cacheCSS(routePath,linkElements);if(firstFoldCss?.length)firstFoldCss=`<style>${firstFoldCss}</style>`;}else{cacheCSS(routePath,linkElements);firstFoldCss=webExtractor.getStyleTags();}// firstFoldJS = webExtractor.getScriptTags({ nonce: cspNonce })
22
+ firstFoldJS=webExtractor.getScriptTags();}// 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
+ !isBot&&cachePreloadJSLinks(routePath,linkElements);}return{firstFoldCss,firstFoldJS};};exports.cacheAndFetchAssets=cacheAndFetchAssets;
@@ -0,0 +1,22 @@
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 _extract=_interopRequireWildcard(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");var _index2=require("@catalyst/template/server/index.js");var _jsxRuntime=require("react/jsx-runtime");function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var r=new WeakMap(),t=new WeakMap();return(_getRequireWildcardCache=function(e){return e?t:r;})(e);}function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache(r);if(t&&t.has(e))return t.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&{}.hasOwnProperty.call(e,u)){var i=a?Object.getOwnPropertyDescriptor(e,u):null;i&&(i.get||i.set)?Object.defineProperty(n,u,i):n[u]=e[u];}return n.default=e,t&&t.set(e,n),n;}function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}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(!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){//moving routing logic outside of the App and using ServerRoutes for creating routes on server instead
3
+ (0,_server3.renderToString)(/*#__PURE__*/(0,_jsxRuntime.jsx)(_server2.ChunkExtractorManager,{extractor:webExtractor,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactRedux.Provider,{store:store,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_server.StaticRouter,{context:context,location:req.originalUrl,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_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__*/(0,_jsxRuntime.jsx)("div",{id:"app",children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactRedux.Provider,{store:store,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_server.StaticRouter,{context:context,location:req.originalUrl,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_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;let state=store.getState();const jsx=webExtractor.collectChunks(getComponent(store,context,req,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
7
+ if(IS_DEV_COMMAND==="true"){publicAssetPath=`http://${WEBPACK_DEV_SERVER_HOSTNAME}:${WEBPACK_DEV_SERVER_PORT}/assets/`;}const finalProps={req,res,lang:"en",pageCss:res.locals.pageCss,preloadJSLinks:res.locals.preloadJSLinks,metaTags,isBot,publicAssetPath,jsx,initialState:state,fetcherData};let CompleteDocument=()=>{if((0,_validator.validateCustomDocument)(_document2.default)){return(0,_document2.default)(finalProps);}else{return/*#__PURE__*/(0,_jsxRuntime.jsxs)("html",{lang:finalProps.lang,children:[/*#__PURE__*/(0,_jsxRuntime.jsx)(_document.Head,{isBot:finalProps.isBot,pageCss:finalProps.pageCss,metaTags:finalProps.metaTags,preloadJSLinks:finalProps.preloadJSLinks,publicAssetPath:finalProps.publicAssetPath}),/*#__PURE__*/(0,_jsxRuntime.jsx)(_document.Body,{jsx:finalProps.jsx,fetcherData:finalProps.fetcherData,initialState:finalProps.initialState})]});}};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__*/(0,_jsxRuntime.jsx)(CompleteDocument,{}),{onShellReady(){res.setHeader("content-type","text/html");pipe(res);},onAllReady(){const{firstFoldCss,firstFoldJS}=(0,_extract.cacheAndFetchAssets)({webExtractor,res,isBot});res.write(firstFoldCss);res.write(firstFoldJS);res.end();},onError(error){logger.error({message:`\n Error while renderToPipeableStream : ${error.toString()}`});// function defined by user which needs to run if rendering fails
8
+ (0,_validator.safeCall)(_index2.onRenderError);}});}catch(error){logger.error("Error in rendering document on server:"+error);// function defined by user which needs to run if rendering fails
9
+ (0,_validator.safeCall)(_index2.onRenderError);}};/**
10
+ * middleware for document handling
11
+ * @param {object} req - request object
12
+ * @param {object} res - response object
13
+ */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
14
+ const store=(0,_validator.validateConfigureStore)(createStore)?createStore({},req,res):null;// user defined routes
15
+ const routes=(0,_validator.validateGetRoutes)(_utils.getRoutes)?(0,_utils.getRoutes)():[];// Matches req url with routes
16
+ const matches=getMatchRoutes(routes,req,res,store,context,fetcherData,undefined,webExtractor);const allMatches=(0,_router.matchRoutes)((0,_utils.getRoutes)(),req.baseUrl);let allTags=[];// function defined by user which needs to run after route is matched
17
+ (0,_validator.safeCall)(_index2.onRouteMatch,{req,res,matches});// Executing app server side function
18
+ _index.default.serverSideFunction({store,req,res})// Executing serverFetcher functions with serverDataFetcher provided by router and returning document
19
+ .then(()=>{(0,_router.serverDataFetcher)({routes:routes,req,res,url:req.originalUrl},{store}).then(response=>{fetcherData=response;allTags=(0,_router.getMetaData)(allMatches,fetcherData);// function defined by user which needs to run after SSR functions are executed
20
+ (0,_validator.safeCall)(_index2.onFetcherSuccess,{req,res,fetcherData});}).then(async()=>await renderMarkUp(null,req,res,allTags,fetcherData,store,matches,context,webExtractor))// TODO: this is never called, serverDataFetcher never throws any error
21
+ .catch(async error=>{logger.error("Error in executing serverFetcher functions: "+error);(0,_validator.safeCall)(_index2.onFetcherError,{req,res,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());// function defined by user which needs to run when an error occurs in the handler
22
+ (0,_validator.safeCall)(_index2.onRequestError,{req,res,error});}}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _express=_interopRequireDefault(require("express"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}const router=_express.default.Router();if(process.env.NODE_ENV==="production"){const handler=require("./handler").default;router.use(handler);}else{const developmentHandler=require("../../../.catalyst-dev/server/renderer/handler.development.js").default;router.use(developmentHandler);}var _default=exports.default=router;
@@ -0,0 +1,7 @@
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(e){return e&&e.__esModule?e:{default:e};}const env=process.env.NODE_ENV||"development";// function defined by user which needs to run before server starts
2
+ (0,_validator.safeCall)(_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,`../../`,".catalyst-dev","/server","/renderer","handler.development.js");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;const{APPLICATION,NODE_SERVER_HOSTNAME,NODE_SERVER_PORT}=process.env;serverInstance=server.listen({port,host});console.log("Server Restarted!");console.log(`You can now view ${APPLICATION} in the browser.`);console.log(_nodeUtil.default.format("Local:",(0,_picocolors.cyan)(`http://${NODE_SERVER_HOSTNAME}:${NODE_SERVER_PORT}`)));};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);// function defined by user which needs to run if server fails
4
+ (0,_validator.safeCall)(_index.onServerError);return;}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%20and%20Production/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.
5
+ 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.
6
+ 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.
7
+ 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(e){return e&&e.__esModule?e:{default:e};}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;
@@ -0,0 +1 @@
1
+ "use strict";const pc=require("picocolors");const handleError=e=>{console.log(pc.red("Failed to start server: "),e);};const safeCall=(fn,...args)=>{try{if(!fn)return;if(typeof fn!=="function"){console.log(pc.red("Invalid lifecycle method defined in server/index.js"));return;}fn(...args);}catch(e){console.log(pc.red(`Failed to execute ${fn.name}: `),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={safeCall,validateConfigFile,validateConfigureStore,validateCustomDocument,validateGetRoutes,validatePackageJson,validateReducerFunction,validateModuleAlias,validatePreInitServer,validateMiddleware};