catalyst-core-internal 0.0.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +145 -0
  2. package/babel.config.json +24 -0
  3. package/bin/catalyst.js +40 -0
  4. package/caching.js +16 -0
  5. package/config.json +7 -0
  6. package/index.js +16 -0
  7. package/logger.js +96 -0
  8. package/package.json +84 -0
  9. package/packages/create-framework-app/templates/redux-js/node_modules/@babel/core/lib/config/caching.js +261 -0
  10. package/packages/create-framework-app/templates/redux-js/node_modules/@remix-run/router/dist/router.js +4327 -0
  11. package/packages/create-framework-app/templates/redux-js/node_modules/catalyst/router.js +15 -0
  12. package/packages/create-framework-app/templates/redux-js/node_modules/catalyst/src/router.js +1 -0
  13. package/packages/create-framework-app/templates/redux-js/node_modules/http-proxy-middleware/dist/router.js +46 -0
  14. package/router/ClientRouter.js +19 -0
  15. package/router/ServerRouter.js +19 -0
  16. package/router/index.js +32 -0
  17. package/router.js +16 -0
  18. package/scripts/build.js +29 -0
  19. package/scripts/checkVersion.js +5 -0
  20. package/scripts/loadEnvironmentVariables.js +24 -0
  21. package/scripts/loadScriptsBeforeServerStarts.js +47 -0
  22. package/scripts/prepare.js +19 -0
  23. package/scripts/registerAliases.js +30 -0
  24. package/scripts/serve.js +30 -0
  25. package/scripts/start.js +26 -0
  26. package/scripts/validator.js +130 -0
  27. package/server/expressServer.js +50 -0
  28. package/server/mainIndex.js +65 -0
  29. package/server/mainServer.js +70 -0
  30. package/server/renderer/document/Body.js +36 -0
  31. package/server/renderer/document/Head.js +43 -0
  32. package/server/renderer/document/index.js +27 -0
  33. package/server/renderer/extract.js +87 -0
  34. package/server/renderer/handler.js +244 -0
  35. package/server/renderer/index.js +12 -0
  36. package/server/renderer/render.js +73 -0
  37. package/server/renderer/userAgentUtil.js +55 -0
  38. package/server/startServer.js +65 -0
  39. package/server/utils/userAgentUtil.js +55 -0
  40. package/server/utils/validator.js +130 -0
  41. package/tsconfig.json +110 -0
  42. package/types/caching.d.ts +1 -0
  43. package/types/config/config.d.ts +19 -0
  44. package/types/index.d.ts +1 -0
  45. package/types/logger/index.d.ts +14 -0
  46. package/types/reducer/index.d.ts +22 -0
  47. package/types/reducer/loadableConfigReducer.d.ts +9 -0
  48. package/types/router/ClientRouter.d.ts +5 -0
  49. package/types/router/ServerRouter.d.ts +7 -0
  50. package/types/router/index.d.ts +8 -0
  51. package/types/router.d.ts +1 -0
  52. package/types/scripts/build.d.ts +1 -0
  53. package/types/scripts/loadEnvironmentVariables.d.ts +5 -0
  54. package/types/scripts/loadScriptsBeforeServerStarts.d.ts +1 -0
  55. package/types/scripts/prepare.d.ts +1 -0
  56. package/types/scripts/registerAliases.d.ts +1 -0
  57. package/types/scripts/serve.d.ts +1 -0
  58. package/types/scripts/start.d.ts +1 -0
  59. package/types/scripts/validator.d.ts +9 -0
  60. package/types/scripts/verifyConfig.d.ts +1 -0
  61. package/types/server/mainIndex.d.ts +1 -0
  62. package/types/server/mainServer.d.ts +2 -0
  63. package/types/server/renderer/document/Body.d.ts +11 -0
  64. package/types/server/renderer/document/Head.d.ts +11 -0
  65. package/types/server/renderer/document/index.d.ts +2 -0
  66. package/types/server/renderer/extract.d.ts +18 -0
  67. package/types/server/renderer/handler.d.ts +6 -0
  68. package/types/server/renderer/index.d.ts +2 -0
  69. package/types/server/renderer/render.d.ts +38 -0
  70. package/types/server/renderer/userAgentUtil.d.ts +1 -0
  71. package/types/store/index.d.ts +11 -0
  72. package/types/store/index.dev.d.ts +8 -0
  73. package/types/store/index.prod.d.ts +8 -0
  74. package/types/webpack/babel-plugins/remove-client.plugin.d.ts +10 -0
  75. package/types/webpack/babel-plugins/remove-ssr.plugin.d.ts +10 -0
  76. package/types/webpack/babel.config.client.d.ts +21 -0
  77. package/types/webpack/babel.config.d.ts +16 -0
  78. package/types/webpack/babel.config.ssr.d.ts +21 -0
  79. package/types/webpack/base.babel.d.ts +184 -0
  80. package/types/webpack/development.client.babel.d.ts +1 -0
  81. package/types/webpack/plugins/mime-types.d.ts +78 -0
  82. package/types/webpack/plugins/route-manifest-plugin.d.ts +1 -0
  83. package/types/webpack/plugins/upload-assets-plugin.d.ts +1 -0
  84. package/types/webpack/production.client.babel.d.ts +174 -0
  85. package/types/webpack/production.ssr.babel.d.ts +2 -0
  86. package/types/webpack/scssParams.d.ts +2 -0
  87. package/webpack/babel-plugins/remove-client.plugin.js +31 -0
  88. package/webpack/babel-plugins/remove-ssr.plugin.js +21 -0
  89. package/webpack/babel.config.client.js +24 -0
  90. package/webpack/babel.config.js +20 -0
  91. package/webpack/babel.config.ssr.js +24 -0
  92. package/webpack/base.babel.js +165 -0
  93. package/webpack/development.client.babel.js +82 -0
  94. package/webpack/plugins/mime-types.js +82 -0
  95. package/webpack/plugins/route-manifest-copy.js +122 -0
  96. package/webpack/plugins/route-manifest-plugin.js +122 -0
  97. package/webpack/plugins/upload-assets-plugin.js +181 -0
  98. package/webpack/production.client.babel.js +78 -0
  99. package/webpack/production.ssr.babel.js +61 -0
  100. package/webpack/scssParams.js +35 -0
package/README.md ADDED
@@ -0,0 +1,145 @@
1
+ # Catalyst
2
+
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.
18
+
19
+
20
+ ## Installation
21
+
22
+ **System Requirements**
23
+
24
+ - Node version 20.4.0 or later
25
+ - macOS and Linux are supported
26
+
27
+
28
+ **Automatic Installation**
29
+
30
+ - Run the following commands in the directory where you want to set up the Catalyst app.
31
+
32
+ ```js
33
+ npx create-catalyst-app@latest
34
+ ```
35
+
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.
49
+
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()
75
+ ```
76
+ error and loading state would be handled by router.
77
+
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
+ ```
143
+
144
+ ## Documentation
145
+ Visit https://catalyst.1mg.com to view the full documentation.
@@ -0,0 +1,24 @@
1
+ {
2
+ "presets": [
3
+ [
4
+ "@babel/preset-env",
5
+ {
6
+ "targets": {
7
+ "node": "current"
8
+ }
9
+ }
10
+ ],
11
+ "@babel/preset-react"
12
+ ],
13
+ "plugins": [
14
+ "@babel/plugin-proposal-object-rest-spread",
15
+ "transform-class-properties",
16
+ "@loadable/babel-plugin"
17
+ ],
18
+ "env": {
19
+ "test": {
20
+ "presets": ["@babel/preset-react"]
21
+ }
22
+ },
23
+ "ignore": ["__TEST__"]
24
+ }
@@ -0,0 +1,40 @@
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);
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
+ );
34
+ }
35
+ process.exit(1);
36
+ }
37
+ process.exit(result.status);
38
+ } else {
39
+ console.log('Unknown script "' + script + '".');
40
+ }
package/caching.js ADDED
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ var _apiCaching = require("@tata1mg/api-caching");
7
+ Object.keys(_apiCaching).forEach(function (key) {
8
+ if (key === "default" || key === "__esModule") return;
9
+ if (key in exports && exports[key] === _apiCaching[key]) return;
10
+ Object.defineProperty(exports, key, {
11
+ enumerable: true,
12
+ get: function () {
13
+ return _apiCaching[key];
14
+ }
15
+ });
16
+ });
package/config.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "cssModulesIdentifierDev": "[name]__[local]",
3
+ "cssModulesIdentifierProd": "[name]__[local]__[hash:base64:5]",
4
+ "chunkFileNameDev": "[name].bundle.js",
5
+ "chunkFileNameProd": "[name].[contenthash].js",
6
+ "cssChunkFileName": "[name].[contenthash].css"
7
+ }
package/index.js ADDED
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ var _index = require("./server/renderer/document/index");
7
+ Object.keys(_index).forEach(function (key) {
8
+ if (key === "default" || key === "__esModule") return;
9
+ if (key in exports && exports[key] === _index[key]) return;
10
+ Object.defineProperty(exports, key, {
11
+ enumerable: true,
12
+ get: function () {
13
+ return _index[key];
14
+ }
15
+ });
16
+ });
package/logger.js ADDED
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+
3
+ const winston = require("winston");
4
+ const DailyRotateFile = require("winston-daily-rotate-file");
5
+ const pc = require("picocolors");
6
+ const {
7
+ createLogger,
8
+ format,
9
+ transports
10
+ } = winston;
11
+
12
+ /**
13
+ * @description Logger library with rotational strategy. Creates a logs folder in root.
14
+ * With debug, error and info log directories with their respective log files.
15
+ *
16
+ * @format Logstash with timestamp
17
+ * @param config { @enableDebugLogs: Bool // default: true }
18
+ * @returns loggerInstance
19
+ *
20
+ */
21
+ const configureLogger = (config = {}) => {
22
+ const {
23
+ enableDebugLogs = true,
24
+ enableFileLogging = true,
25
+ enableConsoleLogging = true
26
+ } = config;
27
+ const consoleTransport = new transports.Console({
28
+ level: "debug"
29
+ });
30
+ const fileTransport = (type = "info") => {
31
+ return new DailyRotateFile({
32
+ filename: `./logs/${type}/%DATE%.${type}.log`,
33
+ datePattern: "YYYY-MM-DD",
34
+ maxFiles: "3d",
35
+ // Logs will be removed after 2days,
36
+ loglevel: type,
37
+ level: type
38
+ });
39
+ };
40
+ const infoLogger = createLogger({
41
+ format: format.combine(format.timestamp({
42
+ format: "YYYY-MM-DD HH:mm:ss"
43
+ }), format.json()),
44
+ defaultMeta: {
45
+ loglevel: "info"
46
+ }
47
+ });
48
+ const debugLogger = createLogger({
49
+ format: format.combine(format.timestamp({
50
+ format: "YYYY-MM-DD HH:mm:ss"
51
+ }), format.json()),
52
+ defaultMeta: {
53
+ loglevel: "debug"
54
+ }
55
+ });
56
+ const errorLogger = createLogger({
57
+ format: format.combine(format.timestamp({
58
+ format: "YYYY-MM-DD HH:mm:ss"
59
+ }), format.json()),
60
+ defaultMeta: {
61
+ loglevel: "error"
62
+ }
63
+ });
64
+ if (enableConsoleLogging && JSON.parse(enableConsoleLogging)) {
65
+ infoLogger.add(consoleTransport);
66
+ debugLogger.add(consoleTransport);
67
+ errorLogger.add(consoleTransport);
68
+ }
69
+ if (enableFileLogging && JSON.parse(enableFileLogging)) {
70
+ infoLogger.add(fileTransport("info"));
71
+ debugLogger.add(fileTransport("debug"));
72
+ errorLogger.add(fileTransport("error"));
73
+ }
74
+ const Logger = {
75
+ debug: () => {},
76
+ error: msg => {
77
+ console.log(pc.red(pc.bold("ERROR: " + JSON.stringify(msg))));
78
+ errorLogger.error(msg);
79
+ },
80
+ info: msg => {
81
+ console.log(pc.green(pc.bold("INFO: " + JSON.stringify(msg))));
82
+ infoLogger.info(msg);
83
+ }
84
+ };
85
+ if (enableDebugLogs && JSON.parse(enableDebugLogs)) {
86
+ Logger.debug = msg => {
87
+ console.log(pc.yellow(pc.bold("DEBUG: " + JSON.stringify(msg))));
88
+ debugLogger.debug(msg);
89
+ };
90
+ }
91
+ if (global) global.logger = Logger;
92
+ return Logger;
93
+ };
94
+ module.exports = {
95
+ configureLogger
96
+ };
package/package.json ADDED
@@ -0,0 +1,84 @@
1
+ {
2
+ "name": "catalyst-core-internal",
3
+ "version": "0.0.1-beta.0",
4
+ "main": "index.js",
5
+ "description": "Web framework that provides great performance out of the box",
6
+ "bin": {
7
+ "catalyst": "./bin/catalyst.js"
8
+ },
9
+ "scripts": {
10
+ "prepare": "babel src --out-dir . ",
11
+ "start": "node ./scripts/checkVersion && npm run start:client & npm run start:server --disable-warning=ExperimentalWarning",
12
+ "start:client": "npx babel-node -r ./scripts/loadScriptsBeforeServerStarts.js webpack/development.client.babel --disable-warning=ExperimentalWarning",
13
+ "start:server": "npx babel-node -r ./scripts/loadScriptsBeforeServerStarts.js ./server/startServer.js --watch-path=${npm_config_src_path}/server --watch-path=${npm_config_src_path}/src --ignore='__IGNORE__' --disable-warning=ExperimentalWarning",
14
+ "build": "node ./scripts/checkVersion && npm run build:prepare && npm run build:client && npm run build:ssr && npm run build:server --disable-warning=ExperimentalWarning",
15
+ "build:prepare": "rm -rf ${npm_config_src_path}/build & node ./scripts/loadScriptsBeforeServerStarts.js",
16
+ "build:client": "APPLICATION=${npm_config_app_name} NODE_ENV=production webpack --config ./webpack/production.client.babel.js --progress",
17
+ "build:ssr": "APPLICATION=${npm_config_app_name} NODE_ENV=production SSR=true webpack --config ./webpack/production.ssr.babel.js --progress",
18
+ "build:server": "APPLICATION=${npm_config_app_name} NODE_ENV=production npx babel ./server --out-dir ${npm_config_src_path}/build --ignore '**/*.test.js,./server/renderer/handler.js' && APPLICATION=${npm_config_app_name} npx babel ${npm_config_src_path}/server --out-dir ${npm_config_src_path}/build ",
19
+ "serve": "APPLICATION=${npm_config_app_name} NODE_ENV=production node -r ./scripts/loadScriptsBeforeServerStarts.js ${npm_config_src_path}/build/startServer.js --disable-warning=ExperimentalWarning"
20
+ },
21
+ "license": "ISC",
22
+ "dependencies": {
23
+ "@babel/cli": "^7.23.0",
24
+ "@babel/core": "^7.23.2",
25
+ "@babel/node": "^7.22.19",
26
+ "@babel/plugin-proposal-object-rest-spread": "^7.20.7",
27
+ "@babel/plugin-transform-react-jsx": "^7.22.15",
28
+ "@babel/preset-env": "^7.23.2",
29
+ "@babel/preset-react": "^7.22.15",
30
+ "@babel/register": "^7.22.15",
31
+ "@loadable/babel-plugin": "^5.16.1",
32
+ "@loadable/component": "^5.15.3",
33
+ "@loadable/server": "^5.16.1",
34
+ "@loadable/webpack-plugin": "^5.15.2",
35
+ "@pmmmwh/react-refresh-webpack-plugin": "^0.5.11",
36
+ "@svgr/webpack": "^8.1.0",
37
+ "@tata1mg/router": "^0.0.1-alpha.13",
38
+ "app-root-path": "^3.1.0",
39
+ "babel-loader": "^9.1.3",
40
+ "babel-plugin-dynamic-import-node": "^2.3.3",
41
+ "babel-plugin-syntax-dynamic-import": "^6.18.0",
42
+ "babel-plugin-transform-class-properties": "^6.24.1",
43
+ "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
44
+ "babel-plugin-transform-export-extensions": "^6.22.0",
45
+ "babel-plugin-transform-react-remove-prop-types": "^0.4.24",
46
+ "body-parser": "^1.20.2",
47
+ "chokidar": "^3.6.0",
48
+ "compression": "^1.7.4",
49
+ "cookie-parser": "^1.4.6",
50
+ "css-hot-loader": "^1.4.4",
51
+ "css-loader": "^6.8.1",
52
+ "css-modules-require-hook": "^4.2.3",
53
+ "express": "^4.18.2",
54
+ "express-static-gzip": "^2.1.7",
55
+ "file-loader": "^6.2.0",
56
+ "html-loader": "^4.2.0",
57
+ "img-loader": "^4.0.0",
58
+ "isomorphic-dompurify": "^1.13.0",
59
+ "mini-css-extract-plugin": "^2.7.6",
60
+ "module-alias": "^2.2.3",
61
+ "picocolors": "^1.0.0",
62
+ "postcss-loader": "^7.3.3",
63
+ "react": "^18.2.0",
64
+ "react-dom": "^18.2.0",
65
+ "react-redux": "^8.1.3",
66
+ "react-refresh": "^0.14.0",
67
+ "react-router-dom": "^6.16.0",
68
+ "redux": "^4.2.1",
69
+ "sass": "^1.69.5",
70
+ "sass-loader": "^13.3.2",
71
+ "sass-resources-loader": "^2.2.5",
72
+ "ua-parser-js": "^1.0.37",
73
+ "url": "^0.11.3",
74
+ "url-loader": "^4.1.1",
75
+ "webpack": "^5.88.2",
76
+ "webpack-bundle-analyzer": "^4.9.1",
77
+ "webpack-cli": "^5.1.4",
78
+ "webpack-dev-server": "^4.15.1",
79
+ "webpack-merge": "^5.9.0",
80
+ "webpack-node-externals": "^3.0.0",
81
+ "winston": "^3.11.0",
82
+ "winston-daily-rotate-file": "^5.0.0"
83
+ }
84
+ }
@@ -0,0 +1,261 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.assertSimpleType = assertSimpleType;
7
+ exports.makeStrongCache = makeStrongCache;
8
+ exports.makeStrongCacheSync = makeStrongCacheSync;
9
+ exports.makeWeakCache = makeWeakCache;
10
+ exports.makeWeakCacheSync = makeWeakCacheSync;
11
+ function _gensync() {
12
+ const data = require("gensync");
13
+ _gensync = function () {
14
+ return data;
15
+ };
16
+ return data;
17
+ }
18
+ var _async = require("../gensync-utils/async.js");
19
+ var _util = require("./util.js");
20
+ const synchronize = gen => {
21
+ return _gensync()(gen).sync;
22
+ };
23
+ function* genTrue() {
24
+ return true;
25
+ }
26
+ function makeWeakCache(handler) {
27
+ return makeCachedFunction(WeakMap, handler);
28
+ }
29
+ function makeWeakCacheSync(handler) {
30
+ return synchronize(makeWeakCache(handler));
31
+ }
32
+ function makeStrongCache(handler) {
33
+ return makeCachedFunction(Map, handler);
34
+ }
35
+ function makeStrongCacheSync(handler) {
36
+ return synchronize(makeStrongCache(handler));
37
+ }
38
+ function makeCachedFunction(CallCache, handler) {
39
+ const callCacheSync = new CallCache();
40
+ const callCacheAsync = new CallCache();
41
+ const futureCache = new CallCache();
42
+ return function* cachedFunction(arg, data) {
43
+ const asyncContext = yield* (0, _async.isAsync)();
44
+ const callCache = asyncContext ? callCacheAsync : callCacheSync;
45
+ const cached = yield* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data);
46
+ if (cached.valid) return cached.value;
47
+ const cache = new CacheConfigurator(data);
48
+ const handlerResult = handler(arg, cache);
49
+ let finishLock;
50
+ let value;
51
+ if ((0, _util.isIterableIterator)(handlerResult)) {
52
+ value = yield* (0, _async.onFirstPause)(handlerResult, () => {
53
+ finishLock = setupAsyncLocks(cache, futureCache, arg);
54
+ });
55
+ } else {
56
+ value = handlerResult;
57
+ }
58
+ updateFunctionCache(callCache, cache, arg, value);
59
+ if (finishLock) {
60
+ futureCache.delete(arg);
61
+ finishLock.release(value);
62
+ }
63
+ return value;
64
+ };
65
+ }
66
+ function* getCachedValue(cache, arg, data) {
67
+ const cachedValue = cache.get(arg);
68
+ if (cachedValue) {
69
+ for (const {
70
+ value,
71
+ valid
72
+ } of cachedValue) {
73
+ if (yield* valid(data)) return {
74
+ valid: true,
75
+ value
76
+ };
77
+ }
78
+ }
79
+ return {
80
+ valid: false,
81
+ value: null
82
+ };
83
+ }
84
+ function* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data) {
85
+ const cached = yield* getCachedValue(callCache, arg, data);
86
+ if (cached.valid) {
87
+ return cached;
88
+ }
89
+ if (asyncContext) {
90
+ const cached = yield* getCachedValue(futureCache, arg, data);
91
+ if (cached.valid) {
92
+ const value = yield* (0, _async.waitFor)(cached.value.promise);
93
+ return {
94
+ valid: true,
95
+ value
96
+ };
97
+ }
98
+ }
99
+ return {
100
+ valid: false,
101
+ value: null
102
+ };
103
+ }
104
+ function setupAsyncLocks(config, futureCache, arg) {
105
+ const finishLock = new Lock();
106
+ updateFunctionCache(futureCache, config, arg, finishLock);
107
+ return finishLock;
108
+ }
109
+ function updateFunctionCache(cache, config, arg, value) {
110
+ if (!config.configured()) config.forever();
111
+ let cachedValue = cache.get(arg);
112
+ config.deactivate();
113
+ switch (config.mode()) {
114
+ case "forever":
115
+ cachedValue = [{
116
+ value,
117
+ valid: genTrue
118
+ }];
119
+ cache.set(arg, cachedValue);
120
+ break;
121
+ case "invalidate":
122
+ cachedValue = [{
123
+ value,
124
+ valid: config.validator()
125
+ }];
126
+ cache.set(arg, cachedValue);
127
+ break;
128
+ case "valid":
129
+ if (cachedValue) {
130
+ cachedValue.push({
131
+ value,
132
+ valid: config.validator()
133
+ });
134
+ } else {
135
+ cachedValue = [{
136
+ value,
137
+ valid: config.validator()
138
+ }];
139
+ cache.set(arg, cachedValue);
140
+ }
141
+ }
142
+ }
143
+ class CacheConfigurator {
144
+ constructor(data) {
145
+ this._active = true;
146
+ this._never = false;
147
+ this._forever = false;
148
+ this._invalidate = false;
149
+ this._configured = false;
150
+ this._pairs = [];
151
+ this._data = void 0;
152
+ this._data = data;
153
+ }
154
+ simple() {
155
+ return makeSimpleConfigurator(this);
156
+ }
157
+ mode() {
158
+ if (this._never) return "never";
159
+ if (this._forever) return "forever";
160
+ if (this._invalidate) return "invalidate";
161
+ return "valid";
162
+ }
163
+ forever() {
164
+ if (!this._active) {
165
+ throw new Error("Cannot change caching after evaluation has completed.");
166
+ }
167
+ if (this._never) {
168
+ throw new Error("Caching has already been configured with .never()");
169
+ }
170
+ this._forever = true;
171
+ this._configured = true;
172
+ }
173
+ never() {
174
+ if (!this._active) {
175
+ throw new Error("Cannot change caching after evaluation has completed.");
176
+ }
177
+ if (this._forever) {
178
+ throw new Error("Caching has already been configured with .forever()");
179
+ }
180
+ this._never = true;
181
+ this._configured = true;
182
+ }
183
+ using(handler) {
184
+ if (!this._active) {
185
+ throw new Error("Cannot change caching after evaluation has completed.");
186
+ }
187
+ if (this._never || this._forever) {
188
+ throw new Error("Caching has already been configured with .never or .forever()");
189
+ }
190
+ this._configured = true;
191
+ const key = handler(this._data);
192
+ const fn = (0, _async.maybeAsync)(handler, `You appear to be using an async cache handler, but Babel has been called synchronously`);
193
+ if ((0, _async.isThenable)(key)) {
194
+ return key.then(key => {
195
+ this._pairs.push([key, fn]);
196
+ return key;
197
+ });
198
+ }
199
+ this._pairs.push([key, fn]);
200
+ return key;
201
+ }
202
+ invalidate(handler) {
203
+ this._invalidate = true;
204
+ return this.using(handler);
205
+ }
206
+ validator() {
207
+ const pairs = this._pairs;
208
+ return function* (data) {
209
+ for (const [key, fn] of pairs) {
210
+ if (key !== (yield* fn(data))) return false;
211
+ }
212
+ return true;
213
+ };
214
+ }
215
+ deactivate() {
216
+ this._active = false;
217
+ }
218
+ configured() {
219
+ return this._configured;
220
+ }
221
+ }
222
+ function makeSimpleConfigurator(cache) {
223
+ function cacheFn(val) {
224
+ if (typeof val === "boolean") {
225
+ if (val) cache.forever();else cache.never();
226
+ return;
227
+ }
228
+ return cache.using(() => assertSimpleType(val()));
229
+ }
230
+ cacheFn.forever = () => cache.forever();
231
+ cacheFn.never = () => cache.never();
232
+ cacheFn.using = cb => cache.using(() => assertSimpleType(cb()));
233
+ cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb()));
234
+ return cacheFn;
235
+ }
236
+ function assertSimpleType(value) {
237
+ if ((0, _async.isThenable)(value)) {
238
+ throw new Error(`You appear to be using an async cache handler, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously handle your caching logic.`);
239
+ }
240
+ if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") {
241
+ throw new Error("Cache keys must be either string, boolean, number, null, or undefined.");
242
+ }
243
+ return value;
244
+ }
245
+ class Lock {
246
+ constructor() {
247
+ this.released = false;
248
+ this.promise = void 0;
249
+ this._resolve = void 0;
250
+ this.promise = new Promise(resolve => {
251
+ this._resolve = resolve;
252
+ });
253
+ }
254
+ release(value) {
255
+ this.released = true;
256
+ this._resolve(value);
257
+ }
258
+ }
259
+ 0 && 0;
260
+
261
+ //# sourceMappingURL=caching.js.map