catalyst-core 0.0.1-beta.2

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 (106) hide show
  1. package/.prettierignore +2 -0
  2. package/.prettierrc.json +7 -0
  3. package/LICENSE +9 -0
  4. package/README.md +132 -0
  5. package/babel.config.json +24 -0
  6. package/bin/catalyst.js +41 -0
  7. package/caching.js +16 -0
  8. package/checkVersion.js +3 -0
  9. package/config/config.js +24 -0
  10. package/config.json +8 -0
  11. package/index.js +16 -0
  12. package/logger/index.js +96 -0
  13. package/package.json +87 -0
  14. package/packages/create-framework-app/node_modules/.package-lock.json +249 -0
  15. package/packages/create-framework-app/templates/redux-js/node_modules/@babel/core/lib/config/caching.js +261 -0
  16. package/packages/create-framework-app/templates/redux-js/node_modules/@remix-run/router/dist/router.js +4327 -0
  17. package/packages/create-framework-app/templates/redux-js/node_modules/catalyst/router.js +15 -0
  18. package/packages/create-framework-app/templates/redux-js/node_modules/http-proxy-middleware/dist/router.js +46 -0
  19. package/reducer/index.js +88 -0
  20. package/reducer/loadableConfigReducer.js +19 -0
  21. package/router/ClientRouter.js +15 -0
  22. package/router/ServerRouter.js +28 -0
  23. package/router/index.js +32 -0
  24. package/router.js +16 -0
  25. package/scripts/build.js +27 -0
  26. package/scripts/loadEnvironmentVariables.js +37 -0
  27. package/scripts/loadScriptsBeforeServerStarts.js +55 -0
  28. package/scripts/prepare.js +19 -0
  29. package/scripts/registerAliases.js +30 -0
  30. package/scripts/serve.js +27 -0
  31. package/scripts/start.js +28 -0
  32. package/scripts/validator.js +99 -0
  33. package/server/mainIndex.js +65 -0
  34. package/server/mainServer.js +70 -0
  35. package/server/renderer/document/Body.js +37 -0
  36. package/server/renderer/document/Head.js +44 -0
  37. package/server/renderer/document/index.js +25 -0
  38. package/server/renderer/extract.js +86 -0
  39. package/server/renderer/handler.js +228 -0
  40. package/server/renderer/index.js +13 -0
  41. package/server/renderer/render.js +71 -0
  42. package/server/renderer/userAgentUtil.js +55 -0
  43. package/server/utils/validator.js +98 -0
  44. package/store/index.dev.js +73 -0
  45. package/store/index.js +25 -0
  46. package/store/index.prod.js +66 -0
  47. package/tsconfig.json +110 -0
  48. package/types/caching.d.ts +1 -0
  49. package/types/config/config.d.ts +19 -0
  50. package/types/index.d.ts +1 -0
  51. package/types/logger/index.d.ts +14 -0
  52. package/types/reducer/index.d.ts +22 -0
  53. package/types/reducer/loadableConfigReducer.d.ts +9 -0
  54. package/types/router/ClientRouter.d.ts +5 -0
  55. package/types/router/ServerRouter.d.ts +7 -0
  56. package/types/router/index.d.ts +8 -0
  57. package/types/router.d.ts +1 -0
  58. package/types/scripts/build.d.ts +1 -0
  59. package/types/scripts/loadEnvironmentVariables.d.ts +5 -0
  60. package/types/scripts/loadScriptsBeforeServerStarts.d.ts +1 -0
  61. package/types/scripts/prepare.d.ts +1 -0
  62. package/types/scripts/registerAliases.d.ts +1 -0
  63. package/types/scripts/serve.d.ts +1 -0
  64. package/types/scripts/start.d.ts +1 -0
  65. package/types/scripts/validator.d.ts +9 -0
  66. package/types/scripts/verifyConfig.d.ts +1 -0
  67. package/types/server/mainIndex.d.ts +1 -0
  68. package/types/server/mainServer.d.ts +2 -0
  69. package/types/server/renderer/document/Body.d.ts +11 -0
  70. package/types/server/renderer/document/Head.d.ts +11 -0
  71. package/types/server/renderer/document/index.d.ts +2 -0
  72. package/types/server/renderer/extract.d.ts +18 -0
  73. package/types/server/renderer/handler.d.ts +6 -0
  74. package/types/server/renderer/index.d.ts +2 -0
  75. package/types/server/renderer/render.d.ts +38 -0
  76. package/types/server/renderer/userAgentUtil.d.ts +1 -0
  77. package/types/store/index.d.ts +11 -0
  78. package/types/store/index.dev.d.ts +8 -0
  79. package/types/store/index.prod.d.ts +8 -0
  80. package/types/webpack/babel-plugins/remove-client.plugin.d.ts +10 -0
  81. package/types/webpack/babel-plugins/remove-ssr.plugin.d.ts +10 -0
  82. package/types/webpack/babel.config.client.d.ts +21 -0
  83. package/types/webpack/babel.config.d.ts +16 -0
  84. package/types/webpack/babel.config.ssr.d.ts +21 -0
  85. package/types/webpack/base.babel.d.ts +184 -0
  86. package/types/webpack/development.client.babel.d.ts +1 -0
  87. package/types/webpack/plugins/mime-types.d.ts +78 -0
  88. package/types/webpack/plugins/route-manifest-plugin.d.ts +1 -0
  89. package/types/webpack/plugins/upload-assets-plugin.d.ts +1 -0
  90. package/types/webpack/production.client.babel.d.ts +174 -0
  91. package/types/webpack/production.ssr.babel.d.ts +2 -0
  92. package/types/webpack/scssParams.d.ts +2 -0
  93. package/webpack/babel-plugins/remove-client.plugin.js +31 -0
  94. package/webpack/babel-plugins/remove-ssr.plugin.js +21 -0
  95. package/webpack/babel.config.client.js +24 -0
  96. package/webpack/babel.config.js +20 -0
  97. package/webpack/babel.config.ssr.js +24 -0
  98. package/webpack/base.babel.js +174 -0
  99. package/webpack/development.client.babel.js +82 -0
  100. package/webpack/plugins/mime-types.js +82 -0
  101. package/webpack/plugins/route-manifest-copy.js +122 -0
  102. package/webpack/plugins/route-manifest-plugin.js +122 -0
  103. package/webpack/plugins/upload-assets-plugin.js +181 -0
  104. package/webpack/production.client.babel.js +79 -0
  105. package/webpack/production.ssr.babel.js +61 -0
  106. package/webpack/scssParams.js +31 -0
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _default = exports.default = {
8
+ babelrc: false,
9
+ presets: [["@babel/preset-env", {
10
+ targets: {
11
+ node: "current"
12
+ }
13
+ }], "@babel/preset-react"],
14
+ plugins: ["@babel/plugin-proposal-object-rest-spread", "@babel/plugin-transform-react-jsx", "transform-class-properties", "transform-export-extensions", "syntax-dynamic-import", "@loadable/babel-plugin"],
15
+ env: {
16
+ development: {
17
+ plugins: ["react-refresh/babel"]
18
+ },
19
+ production: {
20
+ plugins: [require("./babel-plugins/remove-client.plugin").default, "transform-react-remove-prop-types"]
21
+ }
22
+ },
23
+ ignore: ["__TEST__"]
24
+ };
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = exports.basePlugins = void 0;
7
+ var _path = _interopRequireDefault(require("path"));
8
+ var _webpack = _interopRequireDefault(require("webpack"));
9
+ var _miniCssExtractPlugin = _interopRequireDefault(require("mini-css-extract-plugin"));
10
+ var _webpackBundleAnalyzer = require("webpack-bundle-analyzer");
11
+ var _webpackPlugin = _interopRequireDefault(require("@loadable/webpack-plugin"));
12
+ var _scssParams = require("./scssParams");
13
+ var _babelConfig = _interopRequireDefault(require("./babel.config.client"));
14
+ var _babelConfig2 = _interopRequireDefault(require("./babel.config.ssr"));
15
+ var _loadEnvironmentVariables = _interopRequireDefault(require("../scripts/loadEnvironmentVariables"));
16
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
+ const catalystConfig = require(_path.default.resolve(__dirname, "..", "config.json"));
18
+ const {
19
+ enableDynamicImports,
20
+ clientEnv
21
+ } = require(`${process.env.src_path}/config`);
22
+ const {
23
+ _moduleAliases
24
+ } = require(`${process.env.src_path}/package.json`);
25
+ (0, _loadEnvironmentVariables.default)();
26
+ const isDev = process.env.NODE_ENV !== "production";
27
+ const isSSR = !!process.env.SSR || false;
28
+ const basePlugins = exports.basePlugins = [new _webpackPlugin.default({
29
+ filename: "loadable-stats.json",
30
+ writeToDisk: {
31
+ filename: _path.default.join(__dirname, "..")
32
+ }
33
+ }),
34
+ // **This loads process.env variable during webpack build process
35
+ new _webpack.default.DefinePlugin({
36
+ "process.env": ([...clientEnv, ...Object.keys(process.env)] || []).reduce((clientEnvMap, env) => {
37
+ clientEnvMap[env] = JSON.stringify(process.env[env]);
38
+ return clientEnvMap;
39
+ }, {}),
40
+ // Loadable dynamic rendring config
41
+ "process.loadableConfig": {
42
+ CLIENT_ONLY_RENDER: process.env["CLIENT_ONLY_RENDER"] === "true",
43
+ SERVER_SIDE_RENDER: process.env["SERVER_SIDE_RENDER"] === "true"
44
+ }
45
+ }),
46
+ // ** This is used to analyze bundle size.
47
+ catalystConfig.analyzeBundle && new _webpackBundleAnalyzer.BundleAnalyzerPlugin({
48
+ generateStatsFile: true
49
+ }), new _webpack.default.IgnorePlugin({
50
+ resourceRegExp: /^\.\/locale$/,
51
+ contextRegExp: /moment$/
52
+ })];
53
+ let publicPath = process.env.PUBLIC_ASSET_PATH || "/";
54
+ var _default = exports.default = {
55
+ context: _path.default.resolve(process.env.src_path),
56
+ mode: isDev ? "development" : "production",
57
+ entry: {
58
+ app: [_path.default.resolve(process.env.src_path, "./client/index.js")]
59
+ },
60
+ // TODO this will be moved each config
61
+
62
+ output: {
63
+ path: _path.default.join(process.env.src_path, process.env.PUBLIC_OUTPUT_PATH),
64
+ filename: catalystConfig.chunkFileNameDev,
65
+ publicPath: publicPath,
66
+ chunkFilename: enableDynamicImports ? catalystConfig.chunkFileNameDev : undefined
67
+ },
68
+ resolve: {
69
+ extensions: [".js", ".jsx", ".scss"],
70
+ alias: Object.keys(_moduleAliases || {}).reduce((moduleEnvMap, alias) => {
71
+ moduleEnvMap[alias] = _path.default.join(process.env.src_path, ..._moduleAliases[alias].split("/"));
72
+ return moduleEnvMap;
73
+ }, {})
74
+ },
75
+ // TODO common plugins here. Rest will be moved to each file
76
+ plugins: basePlugins,
77
+ // TODO module rules will be here. and should be common for all
78
+ module: {
79
+ rules: [{
80
+ test: /\.jsx$|\.js$/,
81
+ exclude: _path.default.resolve(process.env.src_path, "./node_modules"),
82
+ use: {
83
+ loader: "babel-loader",
84
+ options: isSSR ? _babelConfig2.default : _babelConfig.default
85
+ }
86
+ }, {
87
+ // For all .scss files that should be modularized. This should exclude
88
+ // anything inside node_modules and everything inside src/css/base
89
+ // since they should be globally scoped.
90
+ test: /\.scss$/,
91
+ exclude: [_path.default.resolve(process.env.src_path, "./node_modules"), _path.default.resolve(process.env.src_path, "./src/static/css/base")],
92
+ use: [isDev && "css-hot-loader", !isSSR && _miniCssExtractPlugin.default.loader, {
93
+ loader: "css-loader",
94
+ options: {
95
+ modules: {
96
+ mode: "local",
97
+ exportOnlyLocals: !isDev && isSSR,
98
+ localIdentName: isDev ? catalystConfig.cssModulesIdentifierDev : catalystConfig.cssModulesIdentifierProd
99
+ },
100
+ importLoaders: 0
101
+ }
102
+ }, {
103
+ loader: "postcss-loader"
104
+ }, {
105
+ loader: "sass-loader",
106
+ options: {
107
+ additionalData: "$font_url: " + (0, _scssParams.fontUrl)() + ";" + "$url_for: " + (0, _scssParams.urlFor)() + ";"
108
+ }
109
+ }, {
110
+ loader: "sass-resources-loader",
111
+ options: {
112
+ resources: [_path.default.resolve(process.env.src_path, "./src/static/css/resources/*.scss")]
113
+ }
114
+ }]
115
+ }, {
116
+ // in local dev, client request app.css whoever in prod this css is injected in the doc sent from the server
117
+ // for .scss modules that need to be available globally, we don't pass
118
+ // the files through css-loader to be modularized.
119
+ test: /\.scss$/,
120
+ include: [_path.default.resolve(process.env.src_path, "./node_modules"), _path.default.resolve(process.env.src_path, "./src/static/css/base")],
121
+ use: ["css-hot-loader", !isSSR && _miniCssExtractPlugin.default.loader, {
122
+ loader: "css-loader"
123
+ }, {
124
+ loader: "postcss-loader"
125
+ }, {
126
+ loader: "sass-loader",
127
+ options: {
128
+ additionalData: "$font_url: " + (0, _scssParams.fontUrl)() + ";" + "$url_for: " + (0, _scssParams.urlFor)() + ";"
129
+ }
130
+ }, {
131
+ loader: "sass-resources-loader",
132
+ options: {
133
+ resources: [_path.default.resolve(process.env.src_path, "./src/static/css/resources/*.scss")]
134
+ }
135
+ }]
136
+ }, {
137
+ test: /\.css$/,
138
+ use: [!isSSR && _miniCssExtractPlugin.default.loader, "css-loader", "postcss-loader"]
139
+ },
140
+ // TODO replace them with asset/module
141
+ {
142
+ test: /\.(png|jpg|gif|jpeg|ico?)$/,
143
+ use: ["url-loader?limit=10240", "img-loader"]
144
+ }, {
145
+ test: /\.svg$/i,
146
+ issuer: /\.[jt]sx?$/,
147
+ use: ["@svgr/webpack", "url-loader?limit=10240", "img-loader"]
148
+ }, {
149
+ // Load fonts using file-loader
150
+ test: /\.(ttf|eot|woff2|json?)$/,
151
+ use: [{
152
+ loader: "url-loader",
153
+ options: {
154
+ limit: 10240,
155
+ outputPath: [_path.default.resolve(process.env.src_path, "./src/static/fonts/")]
156
+ }
157
+ }, "file-loader"]
158
+ }, {
159
+ // Load html files
160
+ test: /\.html$/,
161
+ use: [{
162
+ loader: "html-loader",
163
+ options: {
164
+ minimize: {
165
+ minifyJS: true,
166
+ minifyCSS: true,
167
+ removeComments: false,
168
+ collapseWhitespace: true
169
+ }
170
+ }
171
+ }]
172
+ }]
173
+ }
174
+ };
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+
3
+ var _path = _interopRequireDefault(require("path"));
4
+ var _webpackDevServer = _interopRequireDefault(require("webpack-dev-server"));
5
+ var _webpack = _interopRequireDefault(require("webpack"));
6
+ var _webpackMerge = _interopRequireDefault(require("webpack-merge"));
7
+ var _baseBabel = _interopRequireDefault(require("./base.babel.js"));
8
+ var _reactRefreshWebpackPlugin = _interopRequireDefault(require("@pmmmwh/react-refresh-webpack-plugin"));
9
+ var _miniCssExtractPlugin = _interopRequireDefault(require("mini-css-extract-plugin"));
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
+ /* eslint-disable no-console */
12
+
13
+ const {
14
+ DEV_SERVER_HOST_URL
15
+ } = process.env;
16
+ const catalystConfig = require(_path.default.resolve(__dirname, "..", "config.json"));
17
+ const plugins = require(_path.default.join(process.env.src_path, "webpackConfig.js"));
18
+ const webpackConfig = (0, _webpackMerge.default)(_baseBabel.default, {
19
+ devtool: "inline-source-map",
20
+ plugins: [new _reactRefreshWebpackPlugin.default({
21
+ overlay: {
22
+ entry: false
23
+ }
24
+ }),
25
+ // TODO added in client and dev build
26
+ new _miniCssExtractPlugin.default({
27
+ filename: catalystConfig.cssChunkFileName,
28
+ ignoreOrder: true
29
+ }), ...plugins.developmentPlugins].filter(Boolean),
30
+ optimization: {
31
+ runtimeChunk: "single",
32
+ moduleIds: "deterministic",
33
+ splitChunks: {
34
+ cacheGroups: {
35
+ commonVendor: {
36
+ test: /[\\/]node_modules[\\/](react|react-dom|react-redux|react-router|react-router-dom|redux|redux-thunk|axios|react-loadable-visibility|react-helmet-async|react-google-recaptcha|normalize.css|react-detect-offline|react-side-effect|react-fast-compare|react-async-script|babel|history)[\\/]/,
37
+ name: "commonVendor",
38
+ minSize: 30000
39
+ },
40
+ utilityVendor: {
41
+ maxInitialRequests: Infinity,
42
+ chunks: "all",
43
+ // minSize: 0, // Enable to replicate stand alone chunking for all packages
44
+ reuseExistingChunk: true,
45
+ // Disable to replicate stand alone chunking for all packages
46
+ minRemainingSize: 1000,
47
+ // Disable to replicate stand alone chunking for all packages
48
+ test: /[\\/]node_modules[\\/]/,
49
+ name(module) {
50
+ const moduleFileName = module.identifier().split("/").reduceRight(item => item);
51
+ return `npm.${moduleFileName}`;
52
+ }
53
+ }
54
+ }
55
+ }
56
+ }
57
+ });
58
+ console.info("Firing up catalyst dev server...\n");
59
+ let devServer = new _webpackDevServer.default({
60
+ port: process.env.DEV_SERVER_PORT,
61
+ static: {
62
+ publicPath: webpackConfig.output.publicPath
63
+ },
64
+ hot: true,
65
+ historyApiFallback: true,
66
+ headers: {
67
+ "Access-Control-Allow-Origin": "*"
68
+ },
69
+ client: {
70
+ logging: "error",
71
+ overlay: {
72
+ errors: false,
73
+ warnings: false,
74
+ runtimeErrors: false
75
+ },
76
+ progress: true,
77
+ reconnect: true
78
+ }
79
+ }, (0, _webpack.default)(webpackConfig));
80
+ devServer.startCallback(() => {
81
+ console.info(`Webpack dev server mounted at ${DEV_SERVER_HOST_URL}.`);
82
+ });
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+
3
+ module.exports = {
4
+ m4a: "audio/mp4",
5
+ f4a: "audio/mp4",
6
+ f4b: "audio/mp4",
7
+ oga: "audio/ogg",
8
+ ogg: "audio/ogg",
9
+ mid: "audio/&",
10
+ midi: "audio/&",
11
+ mp3: "audio/&",
12
+ wav: "audio/&",
13
+ js: "application/javascript",
14
+ jsonp: "application/javascript",
15
+ json: "application/json",
16
+ doc: "application/msword",
17
+ dot: "application/msword",
18
+ bin: "application/octet-stream",
19
+ ai: "application/postscript",
20
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
21
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
22
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
23
+ xla: "application/vnd.ms-excel",
24
+ xls: "application/vnd.ms-excel",
25
+ xlt: "application/vnd.ms-excel",
26
+ eot: "application/vnd.ms-fontobject",
27
+ pot: "application/vnd.ms-powerpoint",
28
+ ppa: "application/vnd.ms-powerpoint",
29
+ pps: "application/vnd.ms-powerpoint",
30
+ ppt: "application/vnd.ms-powerpoint",
31
+ swf: "application/x-shockwave-flash",
32
+ atom: "application/xml",
33
+ rdf: "application/xml",
34
+ rss: "application/xml",
35
+ xml: "application/xml",
36
+ pdf: "application/&",
37
+ rtf: "application/&",
38
+ zip: "application/&",
39
+ otf: "font/opentype",
40
+ ttf: "font/&",
41
+ ttc: "font/&",
42
+ woff: "font/&",
43
+ jpe: "image/jpeg",
44
+ jpeg: "image/jpeg",
45
+ jpg: "image/jpeg",
46
+ svg: "image/svg+xml",
47
+ svgz: "image/svg+xml",
48
+ psd: "image/vnd.adobe.photoshop",
49
+ ico: "image/vnd.microsoft.icon",
50
+ bmp: "image/&",
51
+ ief: "image/&",
52
+ gif: "image/&",
53
+ png: "image/&",
54
+ tif: "image/&",
55
+ tiff: "image/&",
56
+ webp: "image/&",
57
+ appcache: "text/cache-manifest",
58
+ manifest: "text/cache-manifest",
59
+ txt: "text/plain",
60
+ htc: "text/x-component",
61
+ vcf: "text/x-vcard",
62
+ css: "text/&",
63
+ html: "text/&",
64
+ php: "text/&",
65
+ vtt: "text/&",
66
+ markdown: "text/x-&",
67
+ md: "text/x-&",
68
+ mp4: "video/mp4",
69
+ m4v: "video/mp4",
70
+ f4v: "video/mp4",
71
+ f4p: "video/mp4",
72
+ ogv: "video/ogg",
73
+ mov: "video/quicktime",
74
+ qt: "video/quicktime",
75
+ avi: "video/&",
76
+ mpg: "video/&",
77
+ vdo: "video/&",
78
+ viv: "video/&",
79
+ vivo: "video/&",
80
+ webm: "video/&",
81
+ flv: "video/x-&"
82
+ };
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+
3
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
5
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
7
+ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
8
+ const NAME = "route-manifest-plugin";
9
+ const fs = require("fs");
10
+ const path = require("path");
11
+ const acornLoose = require("acorn-loose");
12
+ const zlib = require("zlib");
13
+ const generateMappingToOrigin = (pathToRoutesFile, routesVariableName) => {
14
+ const fileContent = fs.readFileSync(path.resolve(pathToRoutesFile), "utf-8");
15
+ const ast = acornLoose.parse(fileContent, {
16
+ ecmaVersion: 2020
17
+ });
18
+ const routes = [];
19
+ const componentMapping = {};
20
+ const getValue = valueObj => {
21
+ switch (valueObj.type) {
22
+ case "Literal":
23
+ return valueObj.value;
24
+ case "Identifier":
25
+ return valueObj.name;
26
+ default:
27
+ return "";
28
+ }
29
+ };
30
+ ast.body.forEach(declarationBlock => {
31
+ declarationBlock?.declarations?.forEach(variableDeclaration => {
32
+ if (variableDeclaration?.id?.name === routesVariableName) {
33
+ const objectExpression = variableDeclaration?.init?.elements;
34
+ objectExpression.forEach(obj => {
35
+ const route = {};
36
+ obj?.properties.forEach(property => {
37
+ if (property) route[property.key.name] = getValue(property.value);
38
+ });
39
+ routes.push(route);
40
+ });
41
+ }
42
+ if (variableDeclaration?.init?.type === "CallExpression" && variableDeclaration?.init?.callee?.name === "loadable") {
43
+ const componentName = variableDeclaration?.id?.name;
44
+ const importArgument = variableDeclaration?.init?.arguments?.[0]; // import is first argument in loadable;
45
+ componentMapping[componentName] = importArgument?.body?.source?.value;
46
+ }
47
+ });
48
+ });
49
+ const mappedRoutes = routes.map(route => _objectSpread(_objectSpread({}, route), {}, {
50
+ origin: componentMapping[route.component] || ""
51
+ }));
52
+ return mappedRoutes;
53
+ };
54
+ const RoutesManifestPlugin = function (options) {
55
+ this.options = options;
56
+ };
57
+ RoutesManifestPlugin.prototype.run = function (bundle, options) {
58
+ const {
59
+ pathToRoutesFile,
60
+ routesVariableName
61
+ } = options;
62
+ const mappedRoutes = generateMappingToOrigin(pathToRoutesFile, routesVariableName);
63
+ const {
64
+ publicPath,
65
+ chunks
66
+ } = bundle.getStats().toJson();
67
+ const originToChunksMapping = {};
68
+ const originToChildrenMapping = {};
69
+ chunks.forEach(chunk => {
70
+ chunk.origins.forEach(origin => {
71
+ originToChunksMapping[origin.request] = [...(originToChunksMapping[origin.request] || []), ...chunk.files.map(file => `${publicPath}${file}`)];
72
+ chunk.children.forEach(childId => {
73
+ const chunk = chunks.find(chunk => chunk.id === childId);
74
+ originToChildrenMapping[origin.request] = [...(originToChildrenMapping[origin.request] || []), ...chunk.files.map(file => `${publicPath}${file}`)];
75
+ });
76
+ });
77
+ });
78
+ mappedRoutes.forEach(mappedRoute => {
79
+ mappedRoute.chunks = [...new Set(originToChunksMapping[mappedRoute.origin])];
80
+ mappedRoute.children = [...new Set(originToChildrenMapping[mappedRoute.origin])];
81
+ });
82
+ return mappedRoutes;
83
+ };
84
+ RoutesManifestPlugin.prototype.apply = function (compiler) {
85
+ if (compiler.hooks !== void 0) {
86
+ compiler.hooks.emit.tap(NAME, compilation => {
87
+ const assetsMappingJson = this.run(compilation, this.options);
88
+ const stringifiedAssetsMappingJson = JSON.stringify(assetsMappingJson);
89
+ const compressedGzip = zlib.gzipSync(stringifiedAssetsMappingJson);
90
+ const compressedBrotli = zlib.brotliCompressSync(stringifiedAssetsMappingJson);
91
+ compilation.assets["route-manifest.json.gz"] = {
92
+ source: function () {
93
+ return compressedGzip;
94
+ },
95
+ size: function () {
96
+ return compressedGzip.length;
97
+ }
98
+ };
99
+ compilation.assets["route-manifest.json.br"] = {
100
+ source: function () {
101
+ return compressedBrotli;
102
+ },
103
+ size: function () {
104
+ return compressedBrotli.length;
105
+ }
106
+ };
107
+ compilation.assets["route-manifest.json"] = {
108
+ source: function () {
109
+ return stringifiedAssetsMappingJson;
110
+ },
111
+ size: function () {
112
+ return stringifiedAssetsMappingJson.length;
113
+ }
114
+ };
115
+ });
116
+ } else {
117
+ compiler.plugin("emit", bundle => {
118
+ this.run(bundle, this.options);
119
+ });
120
+ }
121
+ };
122
+ module.exports = RoutesManifestPlugin;
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+
3
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
5
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
7
+ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
8
+ const NAME = "route-manifest-plugin";
9
+ const fs = require("fs");
10
+ const path = require("path");
11
+ const acornLoose = require("acorn-loose");
12
+ const zlib = require("zlib");
13
+ const generateMappingToOrigin = (pathToRoutesFile, routesVariableName) => {
14
+ const fileContent = fs.readFileSync(path.resolve(pathToRoutesFile), "utf-8");
15
+ const ast = acornLoose.parse(fileContent, {
16
+ ecmaVersion: 2020
17
+ });
18
+ const routes = [];
19
+ const componentMapping = {};
20
+ const getValue = valueObj => {
21
+ switch (valueObj.type) {
22
+ case "Literal":
23
+ return valueObj.value;
24
+ case "Identifier":
25
+ return valueObj.name;
26
+ default:
27
+ return "";
28
+ }
29
+ };
30
+ ast.body.forEach(declarationBlock => {
31
+ declarationBlock?.declarations?.forEach(variableDeclaration => {
32
+ if (variableDeclaration?.id?.name === routesVariableName) {
33
+ const objectExpression = variableDeclaration?.init?.elements;
34
+ objectExpression.forEach(obj => {
35
+ const route = {};
36
+ obj?.properties.forEach(property => {
37
+ if (property) route[property.key.name] = getValue(property.value);
38
+ });
39
+ routes.push(route);
40
+ });
41
+ }
42
+ if (variableDeclaration?.init?.type === "CallExpression" && variableDeclaration?.init?.callee?.name === "loadable") {
43
+ const componentName = variableDeclaration?.id?.name;
44
+ const importArgument = variableDeclaration?.init?.arguments?.[0]; // import is first argument in loadable;
45
+ componentMapping[componentName] = importArgument?.body?.source?.value;
46
+ }
47
+ });
48
+ });
49
+ const mappedRoutes = routes.map(route => _objectSpread(_objectSpread({}, route), {}, {
50
+ origin: componentMapping[route.component] || ""
51
+ }));
52
+ return mappedRoutes;
53
+ };
54
+ const RoutesManifestPlugin = function (options) {
55
+ this.options = options;
56
+ };
57
+ RoutesManifestPlugin.prototype.run = function (bundle, options) {
58
+ const {
59
+ pathToRoutesFile,
60
+ routesVariableName
61
+ } = options;
62
+ const mappedRoutes = generateMappingToOrigin(pathToRoutesFile, routesVariableName);
63
+ const {
64
+ publicPath,
65
+ chunks
66
+ } = bundle.getStats().toJson();
67
+ const originToChunksMapping = {};
68
+ const originToChildrenMapping = {};
69
+ chunks.forEach(chunk => {
70
+ chunk.origins.forEach(origin => {
71
+ originToChunksMapping[origin.request] = [...(originToChunksMapping[origin.request] || []), ...chunk.files.map(file => `${publicPath}${file}`)];
72
+ chunk.children.forEach(childId => {
73
+ const chunk = chunks.find(chunk => chunk.id === childId);
74
+ originToChildrenMapping[origin.request] = [...(originToChildrenMapping[origin.request] || []), ...chunk.files.map(file => `${publicPath}${file}`)];
75
+ });
76
+ });
77
+ });
78
+ mappedRoutes.forEach(mappedRoute => {
79
+ mappedRoute.chunks = [...new Set(originToChunksMapping[mappedRoute.origin])];
80
+ mappedRoute.children = [...new Set(originToChildrenMapping[mappedRoute.origin])];
81
+ });
82
+ return mappedRoutes;
83
+ };
84
+ RoutesManifestPlugin.prototype.apply = function (compiler) {
85
+ if (compiler.hooks !== void 0) {
86
+ compiler.hooks.emit.tap(NAME, compilation => {
87
+ const assetsMappingJson = this.run(compilation, this.options);
88
+ const stringifiedAssetsMappingJson = JSON.stringify(assetsMappingJson);
89
+ const compressedGzip = zlib.gzipSync(stringifiedAssetsMappingJson);
90
+ const compressedBrotli = zlib.brotliCompressSync(stringifiedAssetsMappingJson);
91
+ compilation.assets["route-manifest.json.gz"] = {
92
+ source: function () {
93
+ return compressedGzip;
94
+ },
95
+ size: function () {
96
+ return compressedGzip.length;
97
+ }
98
+ };
99
+ compilation.assets["route-manifest.json.br"] = {
100
+ source: function () {
101
+ return compressedBrotli;
102
+ },
103
+ size: function () {
104
+ return compressedBrotli.length;
105
+ }
106
+ };
107
+ compilation.assets["route-manifest.json"] = {
108
+ source: function () {
109
+ return stringifiedAssetsMappingJson;
110
+ },
111
+ size: function () {
112
+ return stringifiedAssetsMappingJson.length;
113
+ }
114
+ };
115
+ });
116
+ } else {
117
+ compiler.plugin("emit", bundle => {
118
+ this.run(bundle, this.options);
119
+ });
120
+ }
121
+ };
122
+ module.exports = RoutesManifestPlugin;