@modern-js/plugin-ssg 2.69.4 → 3.0.0-alpha.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 (52) hide show
  1. package/dist/cjs/index.js +130 -156
  2. package/dist/cjs/libs/make.js +69 -62
  3. package/dist/cjs/libs/output.js +50 -44
  4. package/dist/cjs/libs/replace.js +68 -64
  5. package/dist/cjs/libs/util.js +200 -182
  6. package/dist/cjs/server/consts.js +33 -25
  7. package/dist/cjs/server/index.js +137 -92
  8. package/dist/cjs/server/prerender.js +72 -68
  9. package/dist/cjs/types.js +17 -15
  10. package/dist/esm/index.mjs +89 -0
  11. package/dist/esm/libs/make.mjs +31 -0
  12. package/dist/esm/libs/output.mjs +11 -0
  13. package/dist/esm/libs/replace.mjs +28 -0
  14. package/dist/esm/libs/util.mjs +147 -0
  15. package/dist/esm/server/consts.mjs +2 -0
  16. package/dist/esm/server/index.mjs +97 -0
  17. package/dist/esm/server/prerender.mjs +30 -0
  18. package/dist/esm-node/index.mjs +89 -0
  19. package/dist/esm-node/libs/make.mjs +31 -0
  20. package/dist/esm-node/libs/output.mjs +11 -0
  21. package/dist/esm-node/libs/replace.mjs +28 -0
  22. package/dist/esm-node/libs/util.mjs +147 -0
  23. package/dist/esm-node/server/consts.mjs +2 -0
  24. package/dist/esm-node/server/index.mjs +97 -0
  25. package/dist/esm-node/server/prerender.mjs +30 -0
  26. package/dist/types/libs/util.d.ts +1 -1
  27. package/dist/types/server/index.d.ts +2 -2
  28. package/package.json +27 -29
  29. package/rslib.config.mts +4 -0
  30. package/rstest.config.ts +7 -0
  31. package/dist/cjs/server/process.js +0 -108
  32. package/dist/esm/index.js +0 -163
  33. package/dist/esm/libs/make.js +0 -36
  34. package/dist/esm/libs/output.js +0 -15
  35. package/dist/esm/libs/replace.js +0 -41
  36. package/dist/esm/libs/util.js +0 -210
  37. package/dist/esm/server/consts.js +0 -4
  38. package/dist/esm/server/index.js +0 -66
  39. package/dist/esm/server/prerender.js +0 -46
  40. package/dist/esm/server/process.js +0 -263
  41. package/dist/esm-node/index.js +0 -128
  42. package/dist/esm-node/libs/make.js +0 -37
  43. package/dist/esm-node/libs/output.js +0 -15
  44. package/dist/esm-node/libs/replace.js +0 -36
  45. package/dist/esm-node/libs/util.js +0 -161
  46. package/dist/esm-node/server/consts.js +0 -4
  47. package/dist/esm-node/server/index.js +0 -62
  48. package/dist/esm-node/server/prerender.js +0 -37
  49. package/dist/esm-node/server/process.js +0 -85
  50. package/dist/types/server/process.d.ts +0 -1
  51. /package/dist/esm/{types.js → types.mjs} +0 -0
  52. /package/dist/esm-node/{types.js → types.mjs} +0 -0
@@ -1,96 +1,141 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var server_exports = {};
30
- __export(server_exports, {
31
- createServer: () => createServer
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.n = (module)=>{
5
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
6
+ __webpack_require__.d(getter, {
7
+ a: getter
8
+ });
9
+ return getter;
10
+ };
11
+ })();
12
+ (()=>{
13
+ __webpack_require__.d = (exports1, definition)=>{
14
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
15
+ enumerable: true,
16
+ get: definition[key]
17
+ });
18
+ };
19
+ })();
20
+ (()=>{
21
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
22
+ })();
23
+ (()=>{
24
+ __webpack_require__.r = (exports1)=>{
25
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
26
+ value: 'Module'
27
+ });
28
+ Object.defineProperty(exports1, '__esModule', {
29
+ value: true
30
+ });
31
+ };
32
+ })();
33
+ var __webpack_exports__ = {};
34
+ __webpack_require__.r(__webpack_exports__);
35
+ __webpack_require__.d(__webpack_exports__, {
36
+ createServer: ()=>createServer
32
37
  });
33
- module.exports = __toCommonJS(server_exports);
34
- var import_child_process = __toESM(require("child_process"));
35
- var import_path = __toESM(require("path"));
36
- var import_utils = require("@modern-js/utils");
37
- var import_util = require("../libs/util");
38
- var import_consts = require("./consts");
39
- const createServer = (api, ssgRoutes, pageRoutes, apiRoutes, options, appDirectory) => new Promise((resolve, reject) => {
40
- var _cp_stderr, _cp_stdout;
41
- const entries = ssgRoutes.map((route) => route.entryName);
42
- const backup = (0, import_util.openRouteSSR)(pageRoutes, entries);
43
- const total = backup.concat(apiRoutes);
44
- const cp = import_child_process.default.fork(import_path.default.join(__dirname, "process"), {
45
- cwd: appDirectory,
46
- silent: true
47
- });
48
- const appContext = api.useAppContext();
49
- const plugins = appContext.serverPlugins;
50
- cp.send(JSON.stringify({
51
- options,
52
- renderRoutes: ssgRoutes,
53
- routes: total,
54
- appContext: {
55
- // Make sure that bff runs the product of the dist directory, because we dont register ts-node in the child process
56
- apiDirectory: import_path.default.join(appContext.distDirectory, import_path.default.relative(appContext.appDirectory, appContext.apiDirectory)),
57
- lambdaDirectory: import_path.default.join(appContext.distDirectory, import_path.default.relative(appContext.appDirectory, appContext.lambdaDirectory)),
58
- appDirectory: appContext.appDirectory
59
- },
60
- plugins,
61
- distDirectory: appContext.distDirectory
62
- }));
63
- const htmlChunks = [];
64
- const htmlAry = [];
65
- cp.on("message", (chunk) => {
66
- if (chunk !== null) {
67
- htmlChunks.push(chunk);
68
- } else {
69
- const html = htmlChunks.join("");
70
- htmlAry.push(html);
71
- htmlChunks.length = 0;
72
- }
73
- if (htmlAry.length === ssgRoutes.length) {
74
- cp.send(import_consts.CLOSE_SIGN);
75
- resolve(htmlAry);
38
+ const external_node_http_namespaceObject = require("node:http");
39
+ const external_path_namespaceObject = require("path");
40
+ var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
41
+ const prod_server_namespaceObject = require("@modern-js/prod-server");
42
+ const utils_namespaceObject = require("@modern-js/utils");
43
+ const util_js_namespaceObject = require("../libs/util.js");
44
+ function getLogger() {
45
+ const l = (0, utils_namespaceObject.createLogger)({
46
+ level: 'verbose'
47
+ });
48
+ return {
49
+ ...l,
50
+ error: (...args)=>{
51
+ console.error(...args);
52
+ }
53
+ };
54
+ }
55
+ const MAX_CONCURRENT_REQUESTS = 10;
56
+ function createMockIncomingMessage(url, headers = {}) {
57
+ const urlObj = new URL(url);
58
+ const mockReq = new external_node_http_namespaceObject.IncomingMessage({});
59
+ mockReq.url = urlObj.pathname + urlObj.search;
60
+ mockReq.method = 'GET';
61
+ mockReq.headers = {
62
+ host: urlObj.host,
63
+ 'user-agent': 'SSG-Renderer/1.0',
64
+ accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
65
+ 'accept-language': 'en-US,en;q=0.5',
66
+ 'accept-encoding': 'gzip, deflate',
67
+ connection: 'keep-alive',
68
+ ...headers
69
+ };
70
+ mockReq.httpVersion = '1.1';
71
+ mockReq.httpVersionMajor = 1;
72
+ mockReq.httpVersionMinor = 1;
73
+ mockReq.complete = true;
74
+ mockReq.rawHeaders = [];
75
+ mockReq.socket = {};
76
+ mockReq.connection = mockReq.socket;
77
+ return mockReq;
78
+ }
79
+ function createMockServerResponse() {
80
+ const mockRes = new external_node_http_namespaceObject.ServerResponse({});
81
+ return mockRes;
82
+ }
83
+ const createServer = async (appContext, ssgRoutes, pageRoutes, apiRoutes, options)=>{
84
+ const entries = ssgRoutes.map((route)=>route.entryName);
85
+ const backup = (0, util_js_namespaceObject.openRouteSSR)(pageRoutes, entries);
86
+ const total = backup.concat(apiRoutes);
87
+ try {
88
+ const meta = (0, utils_namespaceObject.getMeta)(appContext.metaName);
89
+ const distDirectory = appContext.distDirectory;
90
+ const serverConfigPath = external_path_default().resolve(distDirectory, utils_namespaceObject.SERVER_DIR, `${meta}.server`);
91
+ const plugins = appContext.serverPlugins;
92
+ const serverOptions = {
93
+ pwd: distDirectory,
94
+ config: options,
95
+ appContext,
96
+ serverConfigPath,
97
+ routes: total,
98
+ plugins: await (0, prod_server_namespaceObject.loadServerPlugins)(plugins, appContext.appDirectory || distDirectory),
99
+ staticGenerate: true,
100
+ logger: getLogger()
101
+ };
102
+ const nodeServer = await (0, prod_server_namespaceObject.createProdServer)(serverOptions);
103
+ const requestHandler = nodeServer.getRequestHandler();
104
+ const chunkedRoutes = (0, util_js_namespaceObject.chunkArray)(ssgRoutes, MAX_CONCURRENT_REQUESTS);
105
+ const results = [];
106
+ for (const routes of chunkedRoutes){
107
+ const promises = routes.map(async (route)=>{
108
+ const url = `http://localhost${route.urlPath}`;
109
+ const request = new Request(url, {
110
+ method: 'GET',
111
+ headers: {
112
+ host: 'localhost',
113
+ 'x-modern-ssg-render': 'true'
114
+ }
115
+ });
116
+ const mockReq = createMockIncomingMessage(url);
117
+ const mockRes = createMockServerResponse();
118
+ const response = await requestHandler(request, {
119
+ node: {
120
+ req: mockReq,
121
+ res: mockRes
122
+ }
123
+ });
124
+ return await response.text();
125
+ });
126
+ const batch = await Promise.all(promises);
127
+ results.push(...batch);
128
+ }
129
+ return results;
130
+ } catch (e) {
131
+ utils_namespaceObject.logger.error(e instanceof Error ? e.stack : e.toString());
132
+ throw new Error('ssg render failed');
76
133
  }
77
- });
78
- (_cp_stderr = cp.stderr) === null || _cp_stderr === void 0 ? void 0 : _cp_stderr.on("data", (chunk) => {
79
- const str = chunk.toString();
80
- if (str.includes("Error")) {
81
- import_utils.logger.error(str);
82
- reject(new Error("ssg render failed"));
83
- cp.kill("SIGKILL");
84
- } else {
85
- import_utils.logger.info(str.replace(/[^\S\n]+/g, " "));
86
- }
87
- });
88
- (_cp_stdout = cp.stdout) === null || _cp_stdout === void 0 ? void 0 : _cp_stdout.on("data", (chunk) => {
89
- const str = chunk.toString();
90
- import_utils.logger.info(str.replace(/[^\S\n]+/g, " "));
91
- });
92
- });
93
- // Annotate the CommonJS export names for ESM import in node:
94
- 0 && (module.exports = {
95
- createServer
134
+ };
135
+ exports.createServer = __webpack_exports__.createServer;
136
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
137
+ "createServer"
138
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
139
+ Object.defineProperty(exports, '__esModule', {
140
+ value: true
96
141
  });
@@ -1,71 +1,75 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var prerender_exports = {};
30
- __export(prerender_exports, {
31
- compile: () => compile
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.n = (module)=>{
5
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
6
+ __webpack_require__.d(getter, {
7
+ a: getter
8
+ });
9
+ return getter;
10
+ };
11
+ })();
12
+ (()=>{
13
+ __webpack_require__.d = (exports1, definition)=>{
14
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
15
+ enumerable: true,
16
+ get: definition[key]
17
+ });
18
+ };
19
+ })();
20
+ (()=>{
21
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
22
+ })();
23
+ (()=>{
24
+ __webpack_require__.r = (exports1)=>{
25
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
26
+ value: 'Module'
27
+ });
28
+ Object.defineProperty(exports1, '__esModule', {
29
+ value: true
30
+ });
31
+ };
32
+ })();
33
+ var __webpack_exports__ = {};
34
+ __webpack_require__.r(__webpack_exports__);
35
+ __webpack_require__.d(__webpack_exports__, {
36
+ compile: ()=>compile
32
37
  });
33
- module.exports = __toCommonJS(prerender_exports);
34
- var import_events = __toESM(require("events"));
35
- var import_stream = require("stream");
36
- var import_node_mocks_http = __toESM(require("node-mocks-http"));
37
- const compile = (requestHandler) => (options, extend = {}) => new Promise((resolve, reject) => {
38
- const req = import_node_mocks_http.default.createRequest({
39
- ...options,
40
- eventEmitter: import_stream.Readable
41
- });
42
- const res = import_node_mocks_http.default.createResponse({
43
- eventEmitter: import_events.default
44
- });
45
- Object.assign(req, extend);
46
- const proxyRes = new Proxy(res, {
47
- get(obj, prop) {
48
- if (typeof prop === "symbol" && !obj[prop]) {
49
- return null;
50
- }
51
- return obj[prop];
52
- }
53
- });
54
- res.on("finish", () => {
55
- if (res.statusCode !== 200) {
56
- reject(new Error(res.statusMessage));
57
- } else {
58
- resolve(res._getData());
59
- }
60
- });
61
- res.on("error", (e) => reject(e));
62
- try {
63
- requestHandler(req, proxyRes);
64
- } catch (e) {
65
- reject(e);
66
- }
67
- });
68
- // Annotate the CommonJS export names for ESM import in node:
69
- 0 && (module.exports = {
70
- compile
38
+ const external_events_namespaceObject = require("events");
39
+ var external_events_default = /*#__PURE__*/ __webpack_require__.n(external_events_namespaceObject);
40
+ const external_stream_namespaceObject = require("stream");
41
+ const external_node_mocks_http_namespaceObject = require("node-mocks-http");
42
+ var external_node_mocks_http_default = /*#__PURE__*/ __webpack_require__.n(external_node_mocks_http_namespaceObject);
43
+ const compile = (requestHandler)=>(options, extend = {})=>new Promise((resolve, reject)=>{
44
+ const req = external_node_mocks_http_default().createRequest({
45
+ ...options,
46
+ eventEmitter: external_stream_namespaceObject.Readable
47
+ });
48
+ const res = external_node_mocks_http_default().createResponse({
49
+ eventEmitter: external_events_default()
50
+ });
51
+ Object.assign(req, extend);
52
+ const proxyRes = new Proxy(res, {
53
+ get (obj, prop) {
54
+ if ('symbol' == typeof prop && !obj[prop]) return null;
55
+ return obj[prop];
56
+ }
57
+ });
58
+ res.on('finish', ()=>{
59
+ if (200 !== res.statusCode) reject(new Error(res.statusMessage));
60
+ else resolve(res._getData());
61
+ });
62
+ res.on('error', (e)=>reject(e));
63
+ try {
64
+ requestHandler(req, proxyRes);
65
+ } catch (e) {
66
+ reject(e);
67
+ }
68
+ });
69
+ exports.compile = __webpack_exports__.compile;
70
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
71
+ "compile"
72
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
73
+ Object.defineProperty(exports, '__esModule', {
74
+ value: true
71
75
  });
package/dist/cjs/types.js CHANGED
@@ -1,16 +1,18 @@
1
1
  "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __copyProps = (to, from, except, desc) => {
7
- if (from && typeof from === "object" || typeof from === "function") {
8
- for (let key of __getOwnPropNames(from))
9
- if (!__hasOwnProp.call(to, key) && key !== except)
10
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
- }
12
- return to;
13
- };
14
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
- var types_exports = {};
16
- module.exports = __toCommonJS(types_exports);
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.r = (exports1)=>{
5
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
6
+ value: 'Module'
7
+ });
8
+ Object.defineProperty(exports1, '__esModule', {
9
+ value: true
10
+ });
11
+ };
12
+ })();
13
+ var __webpack_exports__ = {};
14
+ __webpack_require__.r(__webpack_exports__);
15
+ for(var __rspack_i in __webpack_exports__)exports[__rspack_i] = __webpack_exports__[__rspack_i];
16
+ Object.defineProperty(exports, '__esModule', {
17
+ value: true
18
+ });
@@ -0,0 +1,89 @@
1
+ import path from "path";
2
+ import { filterRoutesForServer, logger } from "@modern-js/utils";
3
+ import { makeRoute } from "./libs/make";
4
+ import { writeHtmlFile } from "./libs/output";
5
+ import { replaceRoute } from "./libs/replace";
6
+ import { flattenRoutes, formatOutput, isDynamicUrl, readJSONSpec, standardOptions, writeJSONSpec } from "./libs/util";
7
+ import { createServer } from "./server";
8
+ const ssgPlugin = ()=>({
9
+ name: '@modern-js/plugin-ssg',
10
+ pre: [
11
+ '@modern-js/plugin-bff'
12
+ ],
13
+ setup: (api)=>{
14
+ const agreedRouteMap = {};
15
+ api.modifyFileSystemRoutes(async ({ entrypoint, routes })=>{
16
+ const { entryName } = entrypoint;
17
+ const flattedRoutes = flattenRoutes(filterRoutesForServer(routes));
18
+ agreedRouteMap[entryName] = flattedRoutes;
19
+ return {
20
+ entrypoint,
21
+ routes
22
+ };
23
+ });
24
+ api.onAfterBuild(async ()=>{
25
+ const resolvedConfig = api.getNormalizedConfig();
26
+ const appContext = api.getAppContext();
27
+ const { appDirectory, entrypoints } = appContext;
28
+ const { output, server } = resolvedConfig;
29
+ const { ssg, ssgByEntries, distPath: { root: outputPath } = {} } = output;
30
+ const ssgOptions = (Array.isArray(ssg) ? ssg.pop() : ssg) ?? true;
31
+ const buildDir = path.join(appDirectory, outputPath);
32
+ const routes = readJSONSpec(buildDir);
33
+ const pageRoutes = routes.filter((route)=>route.isSPA);
34
+ const apiRoutes = routes.filter((route)=>!route.isSPA);
35
+ if (0 === pageRoutes.length) return;
36
+ const intermediateOptions = standardOptions(ssgOptions, entrypoints, pageRoutes, server, ssgByEntries);
37
+ if (!intermediateOptions) return;
38
+ const ssgRoutes = [];
39
+ pageRoutes.forEach((pageRoute)=>{
40
+ const { entryName, entryPath } = pageRoute;
41
+ const agreedRoutes = agreedRouteMap[entryName];
42
+ let entryOptions = intermediateOptions[entryName] || intermediateOptions[pageRoute.urlPath];
43
+ if (agreedRoutes) {
44
+ if (!entryOptions) return;
45
+ if (true === entryOptions) entryOptions = {
46
+ routes: [],
47
+ headers: {}
48
+ };
49
+ const { routes: userRoutes = [], headers } = entryOptions || {};
50
+ if (userRoutes.length > 0) userRoutes.forEach((route)=>{
51
+ ssgRoutes.push(makeRoute(pageRoute, route, headers));
52
+ });
53
+ else agreedRoutes.forEach((route)=>{
54
+ if (!isDynamicUrl(route.path)) ssgRoutes.push(makeRoute(pageRoute, route.path, headers));
55
+ });
56
+ } else {
57
+ if (!entryOptions) return;
58
+ if (true === entryOptions) ssgRoutes.push({
59
+ ...pageRoute,
60
+ output: entryPath
61
+ });
62
+ else if (entryOptions.routes && entryOptions.routes.length > 0) {
63
+ const { routes: enrtyRoutes, headers } = entryOptions;
64
+ enrtyRoutes.forEach((route)=>{
65
+ ssgRoutes.push(makeRoute(pageRoute, route, headers));
66
+ });
67
+ }
68
+ }
69
+ });
70
+ if (0 === ssgRoutes.length) return;
71
+ ssgRoutes.forEach((ssgRoute)=>{
72
+ if (ssgRoute.isSSR) {
73
+ const isOriginRoute = pageRoutes.some((pageRoute)=>pageRoute.urlPath === ssgRoute.urlPath && pageRoute.entryName === ssgRoute.entryName);
74
+ if (isOriginRoute) throw new Error(`ssg can not using with ssr,url - ${ssgRoute.urlPath}, entry - ${ssgRoute.entryName} `);
75
+ logger.warn(`new ssg route ${ssgRoute.urlPath} is using ssr now,maybe from parent route ${ssgRoute.entryName},close ssr`);
76
+ }
77
+ ssgRoute.isSSR = false;
78
+ ssgRoute.output = formatOutput(ssgRoute.output);
79
+ });
80
+ const htmlAry = await createServer(appContext, ssgRoutes, pageRoutes, apiRoutes, resolvedConfig);
81
+ writeHtmlFile(htmlAry, ssgRoutes, buildDir);
82
+ replaceRoute(ssgRoutes, pageRoutes);
83
+ writeJSONSpec(buildDir, pageRoutes.concat(apiRoutes));
84
+ logger.info('ssg Compiled successfully');
85
+ });
86
+ }
87
+ });
88
+ const src = ssgPlugin;
89
+ export { src as default, ssgPlugin };
@@ -0,0 +1,31 @@
1
+ import path from "path";
2
+ import normalize_path from "normalize-path";
3
+ function makeRender(ssgRoutes, render, port) {
4
+ return ssgRoutes.map((ssgRoute)=>render({
5
+ url: ssgRoute.urlPath,
6
+ headers: {
7
+ host: `localhost:${port}`,
8
+ ...ssgRoute.headers
9
+ },
10
+ connection: {}
11
+ }));
12
+ }
13
+ function makeRoute(baseRoute, route, headers = {}) {
14
+ const { urlPath, entryPath } = baseRoute;
15
+ if ('string' == typeof route) return {
16
+ ...baseRoute,
17
+ urlPath: normalize_path(`${urlPath}${route}`) || '/',
18
+ headers,
19
+ output: path.join(entryPath, `..${'/' === route ? '' : route}`)
20
+ };
21
+ return {
22
+ ...baseRoute,
23
+ urlPath: normalize_path(`${urlPath}${route.url}`) || '/',
24
+ headers: {
25
+ ...headers,
26
+ ...route.headers
27
+ },
28
+ output: route.output ? path.normalize(route.output) : path.join(entryPath, `..${'/' === route.url ? '' : route.url}`)
29
+ };
30
+ }
31
+ export { makeRender, makeRoute };
@@ -0,0 +1,11 @@
1
+ import path from "path";
2
+ import { fs } from "@modern-js/utils";
3
+ function writeHtmlFile(htmlAry, ssgRoutes, baseDir) {
4
+ htmlAry.forEach((html, index)=>{
5
+ const ssgRoute = ssgRoutes[index];
6
+ const filepath = path.join(baseDir, ssgRoute.output);
7
+ if (!fs.existsSync(path.dirname(filepath))) fs.ensureDirSync(path.dirname(filepath));
8
+ fs.writeFileSync(filepath, html);
9
+ });
10
+ }
11
+ export { writeHtmlFile };
@@ -0,0 +1,28 @@
1
+ import normalize_path from "normalize-path";
2
+ function exist(route, pageRoutes) {
3
+ return pageRoutes.slice().findIndex((pageRoute)=>{
4
+ const urlEqual = normalize_path(pageRoute.urlPath) === normalize_path(route.urlPath);
5
+ const entryEqual = pageRoute.entryName === route.entryName;
6
+ if (urlEqual && entryEqual) return true;
7
+ return false;
8
+ });
9
+ }
10
+ function replaceRoute(ssgRoutes, pageRoutes) {
11
+ const cleanSsgRoutes = ssgRoutes.map((ssgRoute)=>{
12
+ const { output, headers, ...cleanSsgRoute } = ssgRoute;
13
+ return Object.assign(cleanSsgRoute, output ? {
14
+ entryPath: output
15
+ } : {});
16
+ });
17
+ const freshRoutes = [];
18
+ cleanSsgRoutes.forEach((ssgRoute)=>{
19
+ const index = exist(ssgRoute, pageRoutes);
20
+ if (index < 0) freshRoutes.push({
21
+ ...ssgRoute
22
+ });
23
+ else pageRoutes[index].entryPath = ssgRoute.entryPath;
24
+ });
25
+ pageRoutes.push(...freshRoutes);
26
+ return pageRoutes;
27
+ }
28
+ export { exist, replaceRoute };