@modern-js/app-tools 1.21.5 → 2.0.0-beta.1

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 (170) hide show
  1. package/CHANGELOG.md +319 -51
  2. package/dist/js/modern/analyze/constants.js +1 -0
  3. package/dist/js/modern/analyze/generateCode.js +126 -32
  4. package/dist/js/modern/analyze/getBundleEntry.js +7 -14
  5. package/dist/js/modern/analyze/getClientRoutes/getRoutes.js +173 -0
  6. package/dist/js/modern/analyze/{getClientRoutes.js → getClientRoutes/getRoutesLegacy.js} +13 -58
  7. package/dist/js/modern/analyze/getClientRoutes/index.js +2 -0
  8. package/dist/js/modern/analyze/getClientRoutes/utils.js +18 -0
  9. package/dist/js/modern/analyze/getFileSystemEntry.js +27 -21
  10. package/dist/js/modern/analyze/getHtmlTemplate.js +2 -9
  11. package/dist/js/modern/analyze/getServerRoutes.js +15 -32
  12. package/dist/js/modern/analyze/index.js +81 -23
  13. package/dist/js/modern/analyze/isDefaultExportFunction.js +0 -4
  14. package/dist/js/modern/analyze/makeLegalIdentifier.js +0 -2
  15. package/dist/js/modern/analyze/nestedRoutes.js +102 -0
  16. package/dist/js/modern/analyze/templates.js +151 -12
  17. package/dist/js/modern/analyze/utils.js +2 -8
  18. package/dist/js/modern/builder/builderPlugins/compatModern.js +208 -0
  19. package/dist/js/modern/builder/createHtmlConfig.js +58 -0
  20. package/dist/js/modern/builder/createOutputConfig.js +70 -0
  21. package/dist/js/modern/builder/createSourceConfig.js +74 -0
  22. package/dist/js/modern/builder/createToolsConfig.js +87 -0
  23. package/dist/js/modern/builder/index.js +108 -0
  24. package/dist/js/modern/builder/share.js +44 -0
  25. package/dist/js/modern/builder/webpackPlugins/htmlAsyncChunkPlugin.js +29 -0
  26. package/dist/js/modern/builder/webpackPlugins/htmlBottomTemplate.js +33 -0
  27. package/dist/js/modern/builder/webpackPlugins/routerPlugin.js +97 -0
  28. package/dist/js/modern/commands/build.js +16 -110
  29. package/dist/js/modern/commands/dev.js +12 -28
  30. package/dist/js/modern/commands/inspect.js +8 -66
  31. package/dist/js/modern/commands/start.js +2 -3
  32. package/dist/js/modern/index.js +17 -16
  33. package/dist/js/modern/locale/en.js +0 -1
  34. package/dist/js/modern/locale/zh.js +0 -1
  35. package/dist/js/modern/utils/commands.js +5 -0
  36. package/dist/js/modern/utils/config.js +1 -12
  37. package/dist/js/modern/utils/createServer.js +12 -1
  38. package/dist/js/modern/utils/getSpecifiedEntries.js +0 -6
  39. package/dist/js/modern/utils/printInstructions.js +3 -2
  40. package/dist/js/modern/utils/routes.js +0 -2
  41. package/dist/js/node/analyze/constants.js +3 -1
  42. package/dist/js/node/analyze/generateCode.js +123 -47
  43. package/dist/js/node/analyze/getBundleEntry.js +7 -20
  44. package/dist/js/node/analyze/getClientRoutes/getRoutes.js +181 -0
  45. package/dist/js/node/analyze/{getClientRoutes.js → getClientRoutes/getRoutesLegacy.js} +19 -78
  46. package/dist/js/node/analyze/getClientRoutes/index.js +19 -0
  47. package/dist/js/node/analyze/getClientRoutes/utils.js +28 -0
  48. package/dist/js/node/analyze/getFileSystemEntry.js +26 -28
  49. package/dist/js/node/analyze/getHtmlTemplate.js +2 -23
  50. package/dist/js/node/analyze/getServerRoutes.js +14 -40
  51. package/dist/js/node/analyze/index.js +81 -33
  52. package/dist/js/node/analyze/isDefaultExportFunction.js +0 -12
  53. package/dist/js/node/analyze/makeLegalIdentifier.js +0 -4
  54. package/dist/js/node/analyze/nestedRoutes.js +111 -0
  55. package/dist/js/node/analyze/templates.js +153 -21
  56. package/dist/js/node/analyze/utils.js +4 -20
  57. package/dist/js/node/builder/builderPlugins/compatModern.js +216 -0
  58. package/dist/js/node/builder/createHtmlConfig.js +68 -0
  59. package/dist/js/node/builder/createOutputConfig.js +76 -0
  60. package/dist/js/node/builder/createSourceConfig.js +82 -0
  61. package/dist/js/node/builder/createToolsConfig.js +94 -0
  62. package/dist/js/node/builder/index.js +117 -0
  63. package/dist/js/node/builder/share.js +51 -0
  64. package/dist/js/node/builder/webpackPlugins/htmlAsyncChunkPlugin.js +36 -0
  65. package/dist/js/node/builder/webpackPlugins/htmlBottomTemplate.js +40 -0
  66. package/dist/js/node/builder/webpackPlugins/routerPlugin.js +105 -0
  67. package/dist/js/node/commands/build.js +14 -121
  68. package/dist/js/node/commands/deploy.js +0 -2
  69. package/dist/js/node/commands/dev.js +10 -44
  70. package/dist/js/node/commands/index.js +0 -6
  71. package/dist/js/node/commands/inspect.js +10 -90
  72. package/dist/js/node/commands/start.js +2 -11
  73. package/dist/js/node/exports/server.js +0 -1
  74. package/dist/js/node/hooks.js +0 -2
  75. package/dist/js/node/index.js +22 -32
  76. package/dist/js/node/locale/en.js +0 -1
  77. package/dist/js/node/locale/index.js +0 -4
  78. package/dist/js/node/locale/zh.js +0 -1
  79. package/dist/js/node/utils/commands.js +12 -0
  80. package/dist/js/node/utils/config.js +1 -25
  81. package/dist/js/node/utils/createServer.js +15 -11
  82. package/dist/js/node/utils/getSpecifiedEntries.js +0 -9
  83. package/dist/js/node/utils/language.js +0 -2
  84. package/dist/js/node/utils/printInstructions.js +3 -6
  85. package/dist/js/node/utils/routes.js +0 -5
  86. package/dist/js/treeshaking/analyze/constants.js +16 -0
  87. package/dist/js/treeshaking/analyze/generateCode.js +369 -0
  88. package/dist/js/treeshaking/analyze/getBundleEntry.js +69 -0
  89. package/dist/js/treeshaking/analyze/getClientRoutes/getRoutes.js +184 -0
  90. package/dist/js/treeshaking/analyze/getClientRoutes/getRoutesLegacy.js +185 -0
  91. package/dist/js/treeshaking/analyze/getClientRoutes/index.js +2 -0
  92. package/dist/js/treeshaking/analyze/getClientRoutes/utils.js +24 -0
  93. package/dist/js/treeshaking/analyze/getFileSystemEntry.js +96 -0
  94. package/dist/js/treeshaking/analyze/getHtmlTemplate.js +129 -0
  95. package/dist/js/treeshaking/analyze/getServerRoutes.js +157 -0
  96. package/dist/js/treeshaking/analyze/index.js +334 -0
  97. package/dist/js/treeshaking/analyze/isDefaultExportFunction.js +28 -0
  98. package/dist/js/treeshaking/analyze/makeLegalIdentifier.js +16 -0
  99. package/dist/js/treeshaking/analyze/nestedRoutes.js +165 -0
  100. package/dist/js/treeshaking/analyze/templates.js +170 -0
  101. package/dist/js/treeshaking/analyze/utils.js +88 -0
  102. package/dist/js/treeshaking/builder/builderPlugins/compatModern.js +212 -0
  103. package/dist/js/treeshaking/builder/createHtmlConfig.js +59 -0
  104. package/dist/js/treeshaking/builder/createOutputConfig.js +70 -0
  105. package/dist/js/treeshaking/builder/createSourceConfig.js +88 -0
  106. package/dist/js/treeshaking/builder/createToolsConfig.js +85 -0
  107. package/dist/js/treeshaking/builder/index.js +161 -0
  108. package/dist/js/treeshaking/builder/share.js +46 -0
  109. package/dist/js/treeshaking/builder/webpackPlugins/htmlAsyncChunkPlugin.js +46 -0
  110. package/dist/js/treeshaking/builder/webpackPlugins/htmlBottomTemplate.js +41 -0
  111. package/dist/js/treeshaking/builder/webpackPlugins/routerPlugin.js +121 -0
  112. package/dist/js/treeshaking/commands/build.js +83 -0
  113. package/dist/js/treeshaking/commands/deploy.js +26 -0
  114. package/dist/js/treeshaking/commands/dev.js +124 -0
  115. package/dist/js/treeshaking/commands/index.js +3 -0
  116. package/dist/js/treeshaking/commands/inspect.js +29 -0
  117. package/dist/js/treeshaking/commands/start.js +69 -0
  118. package/dist/js/treeshaking/exports/server.js +1 -0
  119. package/dist/js/treeshaking/hooks.js +21 -0
  120. package/dist/js/treeshaking/index.js +267 -0
  121. package/dist/js/treeshaking/locale/en.js +34 -0
  122. package/dist/js/treeshaking/locale/index.js +9 -0
  123. package/dist/js/treeshaking/locale/zh.js +34 -0
  124. package/dist/js/treeshaking/utils/commands.js +5 -0
  125. package/dist/js/treeshaking/utils/config.js +124 -0
  126. package/dist/js/treeshaking/utils/createServer.js +73 -0
  127. package/dist/js/treeshaking/utils/getSpecifiedEntries.js +58 -0
  128. package/dist/js/treeshaking/utils/language.js +5 -0
  129. package/dist/js/treeshaking/utils/printInstructions.js +30 -0
  130. package/dist/js/treeshaking/utils/routes.js +29 -0
  131. package/dist/js/treeshaking/utils/types.js +0 -0
  132. package/dist/types/analyze/constants.d.ts +1 -0
  133. package/dist/types/analyze/generateCode.d.ts +1 -1
  134. package/dist/types/analyze/{getClientRoutes.d.ts → getClientRoutes/getRoutes.d.ts} +2 -7
  135. package/dist/types/analyze/getClientRoutes/getRoutesLegacy.d.ts +15 -0
  136. package/dist/types/analyze/getClientRoutes/index.d.ts +2 -0
  137. package/dist/types/analyze/getClientRoutes/utils.d.ts +5 -0
  138. package/dist/types/analyze/index.d.ts +4 -5
  139. package/dist/types/analyze/nestedRoutes.d.ts +5 -0
  140. package/dist/types/analyze/templates.d.ts +19 -3
  141. package/dist/types/analyze/utils.d.ts +2 -1
  142. package/dist/types/builder/builderPlugins/compatModern.d.ts +13 -0
  143. package/dist/types/builder/createHtmlConfig.d.ts +6 -0
  144. package/dist/types/builder/createOutputConfig.d.ts +3 -0
  145. package/dist/types/builder/createSourceConfig.d.ts +5 -0
  146. package/dist/types/builder/createToolsConfig.d.ts +13 -0
  147. package/dist/types/builder/index.d.ts +15 -0
  148. package/dist/types/builder/share.d.ts +26 -0
  149. package/dist/types/builder/webpackPlugins/htmlAsyncChunkPlugin.d.ts +8 -0
  150. package/dist/types/builder/webpackPlugins/htmlBottomTemplate.d.ts +10 -0
  151. package/dist/types/builder/webpackPlugins/routerPlugin.d.ts +10 -0
  152. package/dist/types/commands/build.d.ts +2 -1
  153. package/dist/types/commands/deploy.d.ts +2 -1
  154. package/dist/types/commands/dev.d.ts +2 -1
  155. package/dist/types/commands/inspect.d.ts +2 -6
  156. package/dist/types/commands/start.d.ts +2 -1
  157. package/dist/types/hooks.d.ts +15 -10
  158. package/dist/types/index.d.ts +4 -4
  159. package/dist/types/locale/en.d.ts +0 -1
  160. package/dist/types/locale/index.d.ts +0 -2
  161. package/dist/types/locale/zh.d.ts +0 -1
  162. package/dist/types/utils/commands.d.ts +1 -0
  163. package/dist/types/utils/config.d.ts +0 -1
  164. package/dist/types/utils/createServer.d.ts +8 -1
  165. package/dist/types/utils/printInstructions.d.ts +3 -2
  166. package/dist/types/utils/types.d.ts +2 -3
  167. package/package.json +25 -42
  168. package/dist/js/modern/utils/createCompiler.js +0 -61
  169. package/dist/js/node/utils/createCompiler.js +0 -81
  170. package/dist/types/utils/createCompiler.d.ts +0 -13
@@ -1,27 +1,21 @@
1
1
  const _excluded = ["path"],
2
- _excluded2 = ["path"];
3
-
2
+ _excluded2 = ["path"];
4
3
  function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
5
-
6
4
  function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
7
-
8
5
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
9
-
10
6
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
11
-
12
7
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
13
-
14
8
  import path from 'path';
15
9
  import fs from 'fs';
16
10
  import { urlJoin, isPlainObject, removeLeadingSlash, getEntryOptions, SERVER_BUNDLE_DIRECTORY, MAIN_ENTRY_NAME, removeTailSlash } from '@modern-js/utils';
17
11
  import { walkDirectory } from "./utils";
12
+
18
13
  /**
19
14
  * Add base url for each server route.
20
15
  * @param baseUrl - Base url from server.baseUrl
21
16
  * @param routes - Server routes.
22
17
  * @returns Server routes with baseUrl prefixed.
23
18
  */
24
-
25
19
  const applyBaseUrl = (baseUrl, routes) => {
26
20
  if (baseUrl) {
27
21
  if (Array.isArray(baseUrl)) {
@@ -35,37 +29,34 @@ const applyBaseUrl = (baseUrl, routes) => {
35
29
  });
36
30
  }
37
31
  }
38
-
39
32
  return routes;
40
33
  };
34
+
41
35
  /**
42
36
  *
43
37
  * @param original - Original entrypoint route info.
44
38
  * @param routeOptions - Custom entrypoint route config from server.routes.
45
39
  * @returns
46
40
  */
47
-
48
-
49
41
  const applyRouteOptions = (original, routeOptions) => {
50
42
  const {
51
43
  route,
52
44
  disableSpa
53
45
  } = routeOptions;
54
- original.isSPA = !disableSpa; // set entryPath as dir
46
+ original.isSPA = !disableSpa;
55
47
 
48
+ // set entryPath as dir
56
49
  !original.isSPA && (original.entryPath = path.dirname(original.entryPath));
57
50
  let routes;
58
-
59
51
  if (route) {
60
52
  if (Array.isArray(route)) {
61
53
  routes = route.map(url => {
62
54
  if (isPlainObject(url)) {
63
55
  const _ref = url,
64
- {
65
- path: urlPath
66
- } = _ref,
67
- other = _objectWithoutProperties(_ref, _excluded);
68
-
56
+ {
57
+ path: urlPath
58
+ } = _ref,
59
+ other = _objectWithoutProperties(_ref, _excluded);
69
60
  return _objectSpread(_objectSpread(_objectSpread({}, original), other), {}, {
70
61
  urlPath
71
62
  });
@@ -77,11 +68,10 @@ const applyRouteOptions = (original, routeOptions) => {
77
68
  });
78
69
  } else if (isPlainObject(route)) {
79
70
  const _ref2 = route,
80
- {
81
- path: urlPath
82
- } = _ref2,
83
- other = _objectWithoutProperties(_ref2, _excluded2);
84
-
71
+ {
72
+ path: urlPath
73
+ } = _ref2,
74
+ other = _objectWithoutProperties(_ref2, _excluded2);
85
75
  routes = [_objectSpread(_objectSpread(_objectSpread({}, original), other), {}, {
86
76
  urlPath
87
77
  })];
@@ -93,17 +83,15 @@ const applyRouteOptions = (original, routeOptions) => {
93
83
  } else {
94
84
  routes = [original];
95
85
  }
96
-
97
86
  return routes;
98
87
  };
88
+
99
89
  /**
100
90
  * Collect routes from entrypoints.
101
91
  * @param entrypoints - Bundle entrypoints.
102
92
  * @param config - Normalized user config.
103
93
  * @returns entrypoint Routes
104
94
  */
105
-
106
-
107
95
  const collectHtmlRoutes = (entrypoints, appContext, config) => {
108
96
  const {
109
97
  output: {
@@ -139,27 +127,24 @@ const collectHtmlRoutes = (entrypoints, appContext, config) => {
139
127
  enableModernMode: Boolean(enableModernMode),
140
128
  bundle: isSSR ? `${SERVER_BUNDLE_DIRECTORY}/${entryName}.js` : undefined
141
129
  };
142
-
143
130
  if (routes !== null && routes !== void 0 && routes.hasOwnProperty(entryName)) {
144
131
  const routeOptions = isPlainObject(routes[entryName]) ? routes[entryName] : {
145
132
  route: routes[entryName]
146
133
  };
147
134
  route = applyRouteOptions(route, routeOptions);
148
135
  }
149
-
150
136
  return Array.isArray(route) ? [...previous, ...route] : [...previous, route];
151
137
  }, []);
152
138
  htmlRoutes = applyBaseUrl(baseUrl, htmlRoutes);
153
139
  return htmlRoutes;
154
140
  };
141
+
155
142
  /**
156
143
  * Collect static public file routes from config/public folder.
157
144
  * @param appContext - App context info.
158
145
  * @param config - normalized user config.
159
146
  * @returns Static public file routes.
160
147
  */
161
-
162
-
163
148
  const collectStaticRoutes = (appContext, config) => {
164
149
  const {
165
150
  appDirectory
@@ -183,10 +168,8 @@ const collectStaticRoutes = (appContext, config) => {
183
168
  };
184
169
  }) : [];
185
170
  };
186
-
187
171
  export const getServerRoutes = (entrypoints, {
188
172
  appContext,
189
173
  config
190
174
  }) => [...collectHtmlRoutes(entrypoints, appContext, config), ...collectStaticRoutes(appContext, config)];
191
-
192
175
  const toPosix = pathStr => pathStr.split(path.sep).join(path.posix.sep);
@@ -1,13 +1,15 @@
1
1
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
-
3
2
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
-
5
3
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
-
7
4
  import * as path from 'path';
8
5
  import { createAsyncWaterfall } from '@modern-js/plugin';
9
6
  import { createDebugger, fs, isApiOnly } from '@modern-js/utils';
10
7
  import { cloneDeep } from '@modern-js/utils/lodash';
8
+ import { createBuilderForEdenX } from "../builder";
9
+ import { printInstructions } from "../utils/printInstructions";
10
+ import { generateRoutes } from "../utils/routes";
11
+ import { emitResolvedConfig } from "../utils/config";
12
+ import { getCommand } from "../utils/commands";
11
13
  import { isRouteComponentFile } from "./utils";
12
14
  const debug = createDebugger('plugin-analyze');
13
15
  export const modifyEntryImports = createAsyncWaterfall();
@@ -42,19 +44,16 @@ export default (() => ({
42
44
  return {
43
45
  async prepare() {
44
46
  var _resolvedConfig$sourc;
45
-
46
- const appContext = api.useAppContext();
47
+ let appContext = api.useAppContext();
47
48
  const resolvedConfig = api.useResolvedConfigContext();
48
49
  const hookRunners = api.useHookRunners();
49
-
50
50
  try {
51
51
  fs.emptydirSync(appContext.internalDirectory);
52
- } catch (_unused) {// FIXME:
52
+ } catch (_unused) {
53
+ // FIXME:
53
54
  }
54
-
55
55
  const apiOnly = await isApiOnly(appContext.appDirectory, resolvedConfig === null || resolvedConfig === void 0 ? void 0 : (_resolvedConfig$sourc = resolvedConfig.source) === null || _resolvedConfig$sourc === void 0 ? void 0 : _resolvedConfig$sourc.entriesDir);
56
56
  await hookRunners.addRuntimeExports();
57
-
58
57
  if (apiOnly) {
59
58
  const {
60
59
  routes
@@ -62,13 +61,13 @@ export default (() => ({
62
61
  routes: []
63
62
  });
64
63
  debug(`server routes: %o`, routes);
65
- api.setAppContext(_objectSpread(_objectSpread({}, appContext), {}, {
64
+ appContext = _objectSpread(_objectSpread({}, appContext), {}, {
66
65
  apiOnly,
67
66
  serverRoutes: routes
68
- }));
67
+ });
68
+ api.setAppContext(appContext);
69
69
  return;
70
70
  }
71
-
72
71
  const [{
73
72
  getBundleEntry
74
73
  }, {
@@ -91,11 +90,13 @@ export default (() => ({
91
90
  routes: initialRoutes
92
91
  });
93
92
  debug(`server routes: %o`, routes);
94
- api.setAppContext(_objectSpread(_objectSpread({}, appContext), {}, {
93
+ appContext = _objectSpread(_objectSpread({}, appContext), {}, {
95
94
  entrypoints,
96
95
  serverRoutes: routes
97
- }));
98
- pagesDir = entrypoints.map(point => point.entry);
96
+ });
97
+ api.setAppContext(appContext);
98
+ const nestedRouteEntries = entrypoints.map(point => point.nestedRoutesEntry).filter(Boolean);
99
+ pagesDir = entrypoints.map(point => point.entry).filter(Boolean).concat(nestedRouteEntries);
99
100
  originEntrypoints = cloneDeep(entrypoints);
100
101
  await generateCode(appContext, resolvedConfig, entrypoints, api);
101
102
  const htmlTemplates = await getHtmlTemplate(entrypoints, api, {
@@ -105,19 +106,80 @@ export default (() => ({
105
106
  debug(`html templates: %o`, htmlTemplates);
106
107
  await hookRunners.addDefineTypes();
107
108
  debug(`add Define Types`);
108
- api.setAppContext(_objectSpread(_objectSpread({}, appContext), {}, {
109
+ appContext = _objectSpread(_objectSpread({}, appContext), {}, {
109
110
  entrypoints,
110
111
  checkedEntries: defaultChecked,
111
112
  apiOnly,
112
113
  serverRoutes: routes,
113
114
  htmlTemplates
114
- }));
115
+ });
116
+ api.setAppContext(appContext);
117
+ const command = getCommand();
118
+ const buildCommands = ['dev', 'build', 'inspect', 'deploy'];
119
+ if (buildCommands.includes(command)) {
120
+ const normalizedConfig = api.useResolvedConfigContext();
121
+ const builder = await createBuilderForEdenX({
122
+ normalizedConfig,
123
+ appContext,
124
+ compatPluginConfig: {
125
+ async onBeforeBuild({
126
+ bundlerConfigs
127
+ }) {
128
+ const hookRunners = api.useHookRunners();
129
+ await generateRoutes(appContext);
130
+ await hookRunners.beforeBuild({
131
+ bundlerConfigs
132
+ });
133
+ },
134
+ async onAfterBuild({
135
+ stats
136
+ }) {
137
+ const hookRunners = api.useHookRunners();
138
+ await hookRunners.afterBuild({
139
+ stats
140
+ });
141
+ await emitResolvedConfig(appContext.appDirectory, normalizedConfig);
142
+ },
143
+ async onDevCompileDone({
144
+ isFirstCompile
145
+ }) {
146
+ const hookRunners = api.useHookRunners();
147
+ if (process.stdout.isTTY || isFirstCompile) {
148
+ hookRunners.afterDev();
149
+ if (isFirstCompile) {
150
+ printInstructions(hookRunners, appContext, normalizedConfig);
151
+ }
152
+ }
153
+ },
154
+ async onBeforeCreateCompiler({
155
+ bundlerConfigs
156
+ }) {
157
+ const hookRunners = api.useHookRunners();
158
+ // run modernjs framework `beforeCreateCompiler` hook
159
+ await hookRunners.beforeCreateCompiler({
160
+ bundlerConfigs
161
+ });
162
+ },
163
+ async onAfterCreateCompiler({
164
+ compiler
165
+ }) {
166
+ const hookRunners = api.useHookRunners();
167
+ // run modernjs framework afterCreateCompiler hooks
168
+ await hookRunners.afterCreateCompiler({
169
+ compiler
170
+ });
171
+ }
172
+ }
173
+ });
174
+ appContext = _objectSpread(_objectSpread({}, appContext), {}, {
175
+ builder
176
+ });
177
+ api.setAppContext(appContext);
178
+ }
115
179
  },
116
-
117
180
  watchFiles() {
118
181
  return pagesDir;
119
182
  },
120
-
121
183
  async fileChange(e) {
122
184
  const appContext = api.useAppContext();
123
185
  const {
@@ -127,12 +189,9 @@ export default (() => ({
127
189
  filename,
128
190
  eventType
129
191
  } = e;
130
-
131
192
  const isPageFile = name => pagesDir.some(pageDir => name.includes(pageDir));
132
-
133
193
  const absoluteFilePath = path.resolve(appDirectory, filename);
134
194
  const isRouteComponent = isPageFile(absoluteFilePath) && isRouteComponentFile(absoluteFilePath);
135
-
136
195
  if (isRouteComponent && (eventType === 'add' || eventType === 'unlink')) {
137
196
  const resolvedConfig = api.useResolvedConfigContext();
138
197
  const {
@@ -142,7 +201,6 @@ export default (() => ({
142
201
  generateCode(appContext, resolvedConfig, entrypoints, api);
143
202
  }
144
203
  }
145
-
146
204
  };
147
205
  }
148
206
  }));
@@ -2,14 +2,11 @@ import fs from 'fs';
2
2
  import { parse } from '@babel/parser';
3
3
  import traverse from '@babel/traverse';
4
4
  import * as t from '@babel/types';
5
-
6
5
  const isFunction = node => t.isFunctionDeclaration(node) || t.isFunctionExpression(node) || t.isArrowFunctionExpression(node);
7
-
8
6
  export const isDefaultExportFunction = file => {
9
7
  if (!file || !fs.existsSync(file)) {
10
8
  return false;
11
9
  }
12
-
13
10
  const ast = parse(fs.readFileSync(file, 'utf8'), {
14
11
  sourceType: 'unambiguous',
15
12
  plugins: ['jsx', 'typescript', 'classProperties', 'dynamicImport', 'exportDefaultFrom', 'exportNamespaceFrom', 'decorators-legacy', 'functionBind', 'classPrivateMethods', ['pipelineOperator', {
@@ -22,7 +19,6 @@ export const isDefaultExportFunction = file => {
22
19
  const {
23
20
  declaration
24
21
  } = path.node;
25
-
26
22
  if (isFunction(declaration)) {
27
23
  isExportFunction = true;
28
24
  }
@@ -7,10 +7,8 @@ const builtins = 'arguments Infinity NaN undefined null true false eval uneval i
7
7
  const forbidList = new Set(`${reservedWords} ${builtins}`.split(' '));
8
8
  export function makeLegalIdentifier(str) {
9
9
  const identifier = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g, '_');
10
-
11
10
  if (/\d/.test(identifier[0]) || forbidList.has(identifier)) {
12
11
  return `_${identifier}`;
13
12
  }
14
-
15
13
  return identifier || '_';
16
14
  }
@@ -0,0 +1,102 @@
1
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
3
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
4
+ import * as path from 'path';
5
+ import { fs, getRouteId } from '@modern-js/utils';
6
+ import { JS_EXTENSIONS } from "./constants";
7
+ import { replaceWithAlias } from "./utils";
8
+ const LAYOUT_FILE = 'layout';
9
+ const PAGE_FILE = 'page';
10
+ const LOADING_FILE = 'loading';
11
+ const ERROR_FILE = 'error';
12
+ const LOADER_FILE = 'loader';
13
+ const conventionNames = [LAYOUT_FILE, PAGE_FILE, LOADING_FILE, ERROR_FILE, LOADER_FILE];
14
+ const replaceDynamicPath = routePath => {
15
+ return routePath.replace(/\[(.*?)\]/g, ':$1');
16
+ };
17
+ const createIndexRoute = (routeInfo, rootDir, filename, entryName) => {
18
+ return createRoute(_objectSpread(_objectSpread({}, routeInfo), {}, {
19
+ index: true,
20
+ children: undefined
21
+ }), rootDir, filename, entryName);
22
+ };
23
+ const createRoute = (routeInfo, rootDir, filename, entryName) => {
24
+ const id = getRouteId(filename, rootDir, entryName);
25
+ return _objectSpread(_objectSpread({}, routeInfo), {}, {
26
+ id,
27
+ type: 'nested'
28
+ });
29
+ };
30
+ export const walk = async (dirname, rootDir, alias, entryName) => {
31
+ if (!(await fs.pathExists(dirname))) {
32
+ return null;
33
+ }
34
+ const isDirectory = (await fs.stat(dirname)).isDirectory();
35
+ if (!isDirectory) {
36
+ return null;
37
+ }
38
+ const relativeDir = path.relative(rootDir, dirname);
39
+ const pathSegments = relativeDir.split(path.sep);
40
+ const lastSegment = pathSegments[pathSegments.length - 1];
41
+ const isRoot = lastSegment === '';
42
+ const isPathlessLayout = lastSegment.startsWith('__');
43
+ const isWithoutLayoutPath = lastSegment.includes('.');
44
+ let routePath = isRoot || isPathlessLayout ? '/' : `${lastSegment}`;
45
+ if (isWithoutLayoutPath) {
46
+ routePath = lastSegment.split('.').join('/');
47
+ }
48
+ routePath = replaceDynamicPath(routePath);
49
+ const route = {
50
+ path: routePath,
51
+ children: []
52
+ };
53
+ const items = await fs.readdir(dirname);
54
+ for (const item of items) {
55
+ const itemPath = path.join(dirname, item);
56
+ const extname = path.extname(item);
57
+ const itemWithoutExt = item.slice(0, -extname.length);
58
+ const isDirectory = (await fs.stat(itemPath)).isDirectory();
59
+ if (isDirectory) {
60
+ const childRoute = await walk(itemPath, rootDir, alias, entryName);
61
+ if (childRoute) {
62
+ var _route$children;
63
+ (_route$children = route.children) === null || _route$children === void 0 ? void 0 : _route$children.push(childRoute);
64
+ }
65
+ }
66
+ if (extname && (!JS_EXTENSIONS.includes(extname) || !conventionNames.includes(itemWithoutExt))) {
67
+ continue;
68
+ }
69
+ if (itemWithoutExt === LAYOUT_FILE) {
70
+ route._component = replaceWithAlias(alias.basename, itemPath, alias.name);
71
+ }
72
+ if (itemWithoutExt === PAGE_FILE) {
73
+ var _route$children2;
74
+ const childRoute = createIndexRoute({
75
+ _component: replaceWithAlias(alias.basename, itemPath, alias.name)
76
+ }, rootDir, itemPath, entryName);
77
+ (_route$children2 = route.children) === null || _route$children2 === void 0 ? void 0 : _route$children2.push(childRoute);
78
+ }
79
+ if (itemWithoutExt === LOADER_FILE) {
80
+ route.loader = replaceWithAlias(alias.basename, itemPath, alias.name);
81
+ }
82
+ if (itemWithoutExt === LOADING_FILE) {
83
+ route.loading = replaceWithAlias(alias.basename, itemPath, alias.name);
84
+ }
85
+ if (itemWithoutExt === ERROR_FILE) {
86
+ route.error = replaceWithAlias(alias.basename, itemPath, alias.name);
87
+ }
88
+ }
89
+ const finalRoute = createRoute(route, rootDir, path.join(dirname, `${LAYOUT_FILE}.ts`), entryName);
90
+
91
+ /**
92
+ * when the url is /, the __auth/layout.tsx component should not be rendered
93
+ * - routes
94
+ * - __auth
95
+ * - layout.tsx
96
+ * - layout.tsx
97
+ */
98
+ if (isPathlessLayout) {
99
+ delete finalRoute.path;
100
+ }
101
+ return finalRoute;
102
+ };
@@ -1,3 +1,6 @@
1
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
3
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
1
4
  export const index = ({
2
5
  mountId,
3
6
  imports,
@@ -73,16 +76,152 @@ export const html = partials => `
73
76
 
74
77
  </html>
75
78
  `;
79
+ export const routesForServer = ({
80
+ routes,
81
+ alias
82
+ }) => {
83
+ const {
84
+ name,
85
+ basename
86
+ } = alias;
87
+ const loaders = [];
88
+ const traverseRouteTree = route => {
89
+ let children;
90
+ if ('children' in route && route.children) {
91
+ var _route$children;
92
+ children = route === null || route === void 0 ? void 0 : (_route$children = route.children) === null || _route$children === void 0 ? void 0 : _route$children.map(traverseRouteTree);
93
+ }
94
+ let loader;
95
+ if (route.type === 'nested') {
96
+ if (route.loader) {
97
+ loaders.push(route.loader);
98
+ loader = `loader_${loaders.length - 1}`;
99
+ }
100
+ }
101
+ const finalRoute = _objectSpread(_objectSpread({}, route), {}, {
102
+ loader,
103
+ children
104
+ });
105
+ return finalRoute;
106
+ };
107
+ let routesCode = `
108
+ export const routes = [
109
+ `;
110
+ for (const route of routes) {
111
+ if ('type' in route) {
112
+ const newRoute = traverseRouteTree(route);
113
+ routesCode += `${JSON.stringify(newRoute, null, 2).replace(/"(loader_[^"])"/g, '$1')},`;
114
+ } else {
115
+ routesCode += `${JSON.stringify(route, null, 2)}`;
116
+ }
117
+ }
118
+ routesCode += `\n];`;
119
+ const importLoadersCode = loaders.map((loader, index) => {
120
+ const realLoaderPath = loader.replace(name, basename);
121
+ return `import loader_${index} from '${realLoaderPath}';\n`;
122
+ }).join('');
123
+ return `
124
+ ${importLoadersCode}
125
+ ${routesCode}
126
+ `;
127
+ };
76
128
  export const fileSystemRoutes = ({
77
- routes
78
- }) => `
79
- import loadable from '@modern-js/runtime/loadable';
80
-
81
- ${routes.map(({
82
- component,
83
- _component
84
- }) => `const ${component} = loadable(() => import('${_component}'));`).join('\n\n')}
85
-
86
-
87
- export const routes = ${JSON.stringify(routes, null, 2).replace(/"component"\s*:\s*"(\S+)"/g, '"component": $1')}
88
- `;
129
+ routes,
130
+ ssrMode,
131
+ nestedRoutesEntry,
132
+ entryName
133
+ }) => {
134
+ // The legacy mode and pages dir routes should use loadable
135
+ // nested routes + renderTostring should use loadable.lazy
136
+ // nested routes + renderToStream should use react.lazy
137
+ const importLazyCode = `
138
+ import { lazy } from "react";
139
+ import loadable, { lazy as loadableLazy } from "@modern-js/runtime/loadable"
140
+ `;
141
+ let dataLoaderPath = '';
142
+ if (ssrMode) {
143
+ dataLoaderPath = require.resolve(`@modern-js/plugin-data-loader/loader`);
144
+ if (nestedRoutesEntry) {
145
+ dataLoaderPath = `${dataLoaderPath}?routesDir=${nestedRoutesEntry}&entryName=${entryName}!`;
146
+ }
147
+ }
148
+ const loadings = [];
149
+ const errors = [];
150
+ const loaders = [];
151
+ const traverseRouteTree = route => {
152
+ let children;
153
+ if ('children' in route && route.children) {
154
+ var _route$children2;
155
+ children = route === null || route === void 0 ? void 0 : (_route$children2 = route.children) === null || _route$children2 === void 0 ? void 0 : _route$children2.map(traverseRouteTree);
156
+ }
157
+ let loading;
158
+ let error;
159
+ let loader;
160
+ let component = '';
161
+ if (route.type === 'nested') {
162
+ if (route.loading) {
163
+ loadings.push(route.loading);
164
+ loading = `loading_${loadings.length - 1}`;
165
+ }
166
+ if (route.error) {
167
+ errors.push(route.error);
168
+ error = `error_${errors.length - 1}`;
169
+ }
170
+ if (route.loader) {
171
+ loaders.push(route.loader);
172
+ loader = `loader_${loaders.length - 1}`;
173
+ }
174
+ if (route._component) {
175
+ if (ssrMode === 'stream') {
176
+ component = `lazy(() => import(/* webpackChunkName: "${route.id}" */ /* webpackMode: "lazy-once" */ '${route._component}'))`;
177
+ } else {
178
+ component = `loadable(() => import(/* webpackChunkName: "${route.id}" */ /* webpackMode: "lazy-once" */ '${route._component}'))`;
179
+ }
180
+ }
181
+ } else if (route._component) {
182
+ component = `loadable(() => import('${route._component}'))`;
183
+ }
184
+ const finalRoute = _objectSpread(_objectSpread({}, route), {}, {
185
+ loading,
186
+ loader,
187
+ error,
188
+ children
189
+ });
190
+ if (route._component) {
191
+ finalRoute.component = component;
192
+ }
193
+ return finalRoute;
194
+ };
195
+ let routeComponentsCode = `
196
+ export const routes = [
197
+ `;
198
+ for (const route of routes) {
199
+ if ('type' in route) {
200
+ const newRoute = traverseRouteTree(route);
201
+ routeComponentsCode += `${JSON.stringify(newRoute, null, 2).replace(/"(loadable.*\))"/g, '$1').replace(/"(loadableLazy.*\))"/g, '$1').replace(/"(lazy.*\))"/g, '$1').replace(/"(loading_[^"])"/g, '$1').replace(/"(loader_[^"])"/g, '$1').replace(/"(error_[^"])"/g, '$1').replace(/\\"/g, '"')},`;
202
+ } else {
203
+ const component = `loadable(() => import('${route._component}'))`;
204
+ const finalRoute = _objectSpread(_objectSpread({}, route), {}, {
205
+ component
206
+ });
207
+ routeComponentsCode += `${JSON.stringify(finalRoute, null, 2).replace(/"(loadable[^"]*)"/g, '$1').replace(/"(lazy[^"]*)"/g, '$1')},`;
208
+ }
209
+ }
210
+ routeComponentsCode += `\n];`;
211
+ const importLoadingCode = loadings.map((loading, index) => {
212
+ return `import loading_${index} from '${loading}';\n`;
213
+ }).join('');
214
+ const importErrorComponentsCode = errors.map((error, index) => {
215
+ return `import error_${index} from '${error}';\n`;
216
+ }).join('');
217
+ const importLoaderComponentsCode = loaders.map((loader, index) => {
218
+ return `import loader_${index} from '${dataLoaderPath}${loader}';\n`;
219
+ }).join('');
220
+ return `
221
+ ${importLazyCode}
222
+ ${importLoadingCode}
223
+ ${importErrorComponentsCode}
224
+ ${importLoaderComponentsCode}
225
+ ${routeComponentsCode}
226
+ `;
227
+ };