@xfe-repo/web-app 1.6.3 → 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 (48) hide show
  1. package/README.md +60 -1
  2. package/client.d.ts +1 -0
  3. package/deploy/.drone.yml +11 -4
  4. package/deploy/Dockerfile +14 -6
  5. package/deploy/helm/templates/deployment.yaml +5 -18
  6. package/deploy/helm/templates/svc.yaml +1 -1
  7. package/dist/cli.js +275 -413
  8. package/dist/cli.mjs +273 -267
  9. package/dist/config.d.mts +20 -6
  10. package/dist/config.d.ts +20 -6
  11. package/dist/config.js +83 -297
  12. package/dist/config.mjs +69 -2
  13. package/dist/framework.d.mts +10 -0
  14. package/dist/framework.d.ts +10 -0
  15. package/dist/framework.js +174 -0
  16. package/dist/framework.mjs +137 -0
  17. package/dist/react-router-config.d.mts +11 -0
  18. package/dist/react-router-config.d.ts +11 -0
  19. package/dist/react-router-config.js +66 -0
  20. package/dist/react-router-config.mjs +35 -0
  21. package/dist/root.d.mts +17 -0
  22. package/dist/root.d.ts +17 -0
  23. package/dist/root.js +61 -0
  24. package/dist/root.mjs +34 -0
  25. package/dist/serve.d.mts +10 -0
  26. package/dist/serve.d.ts +10 -0
  27. package/dist/serve.js +71 -0
  28. package/dist/serve.mjs +36 -0
  29. package/dist/vite.d.mts +9 -0
  30. package/dist/vite.d.ts +9 -0
  31. package/dist/vite.js +135 -0
  32. package/dist/vite.mjs +100 -0
  33. package/package.json +22 -71
  34. package/tsconfig.json +4 -1
  35. package/config/env.js +0 -104
  36. package/config/getHttpsConfig.js +0 -66
  37. package/config/jest/babelTransform.js +0 -29
  38. package/config/jest/cssTransform.js +0 -14
  39. package/config/jest/fileTransform.js +0 -40
  40. package/config/modules.js +0 -133
  41. package/config/paths.js +0 -65
  42. package/config/webpack/persistentCache/createEnvironmentHash.js +0 -9
  43. package/config/webpack/webpack.config.js +0 -737
  44. package/config/webpack/webpackDevServer.config.js +0 -122
  45. package/deploy/nginx.conf +0 -62
  46. package/dist/chunk-75BJNL7E.mjs +0 -239
  47. package/scripts/build.js +0 -217
  48. package/scripts/dev.js +0 -162
package/dist/cli.mjs CHANGED
@@ -1,271 +1,277 @@
1
- function _array_like_to_array(arr, len) {
2
- if (len == null || len > arr.length) len = arr.length;
3
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
4
- return arr2;
5
- }
6
- function _array_with_holes(arr) {
7
- if (Array.isArray(arr)) return arr;
8
- }
9
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
10
- try {
11
- var info = gen[key](arg);
12
- var value = info.value;
13
- } catch (error) {
14
- reject(error);
15
- return;
16
- }
17
- if (info.done) {
18
- resolve(value);
19
- } else {
20
- Promise.resolve(value).then(_next, _throw);
21
- }
22
- }
23
- function _async_to_generator(fn) {
24
- return function() {
25
- var self = this, args = arguments;
26
- return new Promise(function(resolve, reject) {
27
- var gen = fn.apply(self, args);
28
- function _next(value) {
29
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
30
- }
31
- function _throw(err) {
32
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
33
- }
34
- _next(undefined);
35
- });
36
- };
37
- }
38
- function _define_property(obj, key, value) {
39
- if (key in obj) {
40
- Object.defineProperty(obj, key, {
41
- value: value,
42
- enumerable: true,
43
- configurable: true,
44
- writable: true
45
- });
46
- } else {
47
- obj[key] = value;
48
- }
49
- return obj;
50
- }
51
- function _iterable_to_array_limit(arr, i) {
52
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
53
- if (_i == null) return;
54
- var _arr = [];
55
- var _n = true;
56
- var _d = false;
57
- var _s, _e;
58
- try {
59
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
60
- _arr.push(_s.value);
61
- if (i && _arr.length === i) break;
62
- }
63
- } catch (err) {
64
- _d = true;
65
- _e = err;
66
- } finally{
67
- try {
68
- if (!_n && _i["return"] != null) _i["return"]();
69
- } finally{
70
- if (_d) throw _e;
71
- }
72
- }
73
- return _arr;
74
- }
75
- function _non_iterable_rest() {
76
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
77
- }
78
- function _object_spread(target) {
79
- for(var i = 1; i < arguments.length; i++){
80
- var source = arguments[i] != null ? arguments[i] : {};
81
- var ownKeys = Object.keys(source);
82
- if (typeof Object.getOwnPropertySymbols === "function") {
83
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
84
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
85
- }));
86
- }
87
- ownKeys.forEach(function(key) {
88
- _define_property(target, key, source[key]);
89
- });
90
- }
91
- return target;
92
- }
93
- function _sliced_to_array(arr, i) {
94
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
95
- }
96
- function _unsupported_iterable_to_array(o, minLen) {
97
- if (!o) return;
98
- if (typeof o === "string") return _array_like_to_array(o, minLen);
99
- var n = Object.prototype.toString.call(o).slice(8, -1);
100
- if (n === "Object" && o.constructor) n = o.constructor.name;
101
- if (n === "Map" || n === "Set") return Array.from(n);
102
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
103
- }
104
- function _ts_generator(thisArg, body) {
105
- var f, y, t, _ = {
106
- label: 0,
107
- sent: function() {
108
- if (t[0] & 1) throw t[1];
109
- return t[1];
110
- },
111
- trys: [],
112
- ops: []
113
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
114
- return d(g, "next", {
115
- value: verb(0)
116
- }), d(g, "throw", {
117
- value: verb(1)
118
- }), d(g, "return", {
119
- value: verb(2)
120
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
121
- value: function() {
122
- return this;
123
- }
124
- }), g;
125
- function verb(n) {
126
- return function(v) {
127
- return step([
128
- n,
129
- v
130
- ]);
131
- };
132
- }
133
- function step(op) {
134
- if (f) throw new TypeError("Generator is already executing.");
135
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
136
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
137
- if (y = 0, t) op = [
138
- op[0] & 2,
139
- t.value
140
- ];
141
- switch(op[0]){
142
- case 0:
143
- case 1:
144
- t = op;
145
- break;
146
- case 4:
147
- _.label++;
148
- return {
149
- value: op[1],
150
- done: false
151
- };
152
- case 5:
153
- _.label++;
154
- y = op[1];
155
- op = [
156
- 0
157
- ];
158
- continue;
159
- case 7:
160
- op = _.ops.pop();
161
- _.trys.pop();
162
- continue;
163
- default:
164
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
165
- _ = 0;
166
- continue;
167
- }
168
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
169
- _.label = op[1];
170
- break;
171
- }
172
- if (op[0] === 6 && _.label < t[1]) {
173
- _.label = t[1];
174
- t = op;
175
- break;
176
- }
177
- if (t && _.label < t[2]) {
178
- _.label = t[2];
179
- _.ops.push(op);
180
- break;
181
- }
182
- if (t[2]) _.ops.pop();
183
- _.trys.pop();
184
- continue;
185
- }
186
- op = body.call(thisArg, _);
187
- } catch (e) {
188
- op = [
189
- 6,
190
- e
191
- ];
192
- y = 0;
193
- } finally{
194
- f = t = 0;
195
- }
196
- if (op[0] & 5) throw op[1];
197
- return {
198
- value: op[0] ? op[1] : void 0,
199
- done: true
200
- };
201
- }
202
- }
203
- import { configDeploy, getJwtEnv } from "./chunk-75BJNL7E.mjs";
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
204
8
  // src/cli.ts
205
- import minimist from "minimist";
206
- import { execSync } from "child_process";
9
+ import { spawnSync } from "child_process";
10
+ import { mkdirSync } from "fs";
11
+ import path4 from "path";
12
+
13
+ // src/config.ts
207
14
  import path from "path";
208
- var argv = minimist(process.argv.slice(2));
209
- var commands = argv._;
210
- var _commands = _sliced_to_array(commands, 1), command = _commands[0];
211
- var appPackageRoot = path.resolve(__dirname, "../");
212
- function main() {
213
- return _async_to_generator(function() {
214
- var jwtEnv, jwtEnv1;
215
- return _ts_generator(this, function(_state) {
216
- switch(_state.label){
217
- case 0:
218
- if (!(command === "dev")) return [
219
- 3,
220
- 2
221
- ];
222
- return [
223
- 4,
224
- getJwtEnv()
225
- ];
226
- case 1:
227
- jwtEnv = _state.sent();
228
- execSync("node ".concat(path.join(appPackageRoot, "scripts/dev.js")), {
229
- stdio: "inherit",
230
- env: _object_spread({}, process.env, jwtEnv)
231
- });
232
- return [
233
- 3,
234
- 5
235
- ];
236
- case 2:
237
- if (!(command === "build")) return [
238
- 3,
239
- 4
240
- ];
241
- return [
242
- 4,
243
- getJwtEnv()
244
- ];
245
- case 3:
246
- jwtEnv1 = _state.sent();
247
- execSync("node ".concat(path.join(appPackageRoot, "scripts/build.js")), {
248
- stdio: "inherit",
249
- env: _object_spread({}, process.env, jwtEnv1)
250
- });
251
- return [
252
- 3,
253
- 5
254
- ];
255
- case 4:
256
- if (command === "config") {
257
- configDeploy();
258
- }
259
- _state.label = 5;
260
- case 5:
261
- return [
262
- 2
263
- ];
264
- }
265
- });
266
- })();
15
+ import fs from "fs";
16
+ import yaml from "yaml";
17
+ var loadXfeConfig = (root = process.cwd()) => {
18
+ const xfeConfigPath = path.join(root, "xfe.json");
19
+ if (!fs.existsSync(xfeConfigPath)) {
20
+ throw new Error("xfe.json \u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u9879\u76EE\u6839\u76EE\u5F55\u4E0B\u521B\u5EFA\u8BE5\u6587\u4EF6\u3002");
21
+ }
22
+ const xfeConfigContent = fs.readFileSync(xfeConfigPath, "utf8");
23
+ const config = JSON.parse(xfeConfigContent);
24
+ const renderMode = config.webapp?.renderMode;
25
+ if (renderMode !== void 0 && renderMode !== "client" && renderMode !== "server") {
26
+ throw new Error("xfe.json.webapp.renderMode \u53EA\u80FD\u4E3A client \u6216 server");
27
+ }
28
+ return config;
29
+ };
30
+ var configDeploy = () => {
31
+ const xfeConfig = loadXfeConfig();
32
+ if (!xfeConfig?.deploy) return;
33
+ const droneConfigFilePath = path.resolve(__dirname, "../deploy/.drone.yml");
34
+ fs.cpSync(droneConfigFilePath, xfeConfig.deploy.droneConfigPath || "./.drone.yml");
35
+ const valuesYamlFilePath = path.resolve(__dirname, "../deploy/helm/values.yaml");
36
+ const valuesYamlFile = fs.readFileSync(valuesYamlFilePath, "utf8");
37
+ const valuesYaml = yaml.parse(valuesYamlFile);
38
+ if (!valuesYaml.virtualService) valuesYaml.virtualService = {};
39
+ if (!valuesYaml.virtualService.hosts) valuesYaml.virtualService.hosts = { test: [], stage: [], prod: [] };
40
+ const {
41
+ virtualServiceEnabled = true,
42
+ hostsProd = [],
43
+ hostsStage = [],
44
+ hostsTest = [],
45
+ gateways = ["common-gateway-eshetang"]
46
+ } = xfeConfig.deploy;
47
+ const { targetK8s = "saas", targetNamespace = "" } = xfeConfig.deploy;
48
+ valuesYaml.virtualService.enabled = virtualServiceEnabled;
49
+ valuesYaml.virtualService.gateways = gateways;
50
+ valuesYaml.virtualService.hosts.prod = hostsProd;
51
+ valuesYaml.virtualService.hosts.stage = hostsStage;
52
+ valuesYaml.virtualService.hosts.test = hostsTest;
53
+ valuesYaml.targetK8s = targetK8s;
54
+ valuesYaml.namespace = targetNamespace;
55
+ const valuesYamlStr = yaml.stringify(valuesYaml, { defaultStringType: "QUOTE_SINGLE", defaultKeyType: "PLAIN" });
56
+ fs.writeFileSync(valuesYamlFilePath, valuesYamlStr, "utf8");
57
+ };
58
+ var getJwtEnv = async () => {
59
+ const xfeConfig = loadXfeConfig();
60
+ if (!xfeConfig?.jwt) return {};
61
+ const { aud = "" } = xfeConfig.jwt;
62
+ if (!aud) throw new Error("xfe.json \u4E2D\u7684 jwt \u914D\u7F6E\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u786E\u4FDD\u5305\u542B aud \u5B57\u6BB5\u3002");
63
+ const jwkRes = await fetch(`https://app.eshetang.com/jwk?appId=${aud}`);
64
+ if (!jwkRes.ok) {
65
+ throw new Error(`\u8FDC\u7A0B\u83B7\u53D6\u5BC6\u94A5\u5931\u8D25: ${jwkRes.status} ${jwkRes.statusText}`);
66
+ }
67
+ let JwkResponseJson;
68
+ try {
69
+ JwkResponseJson = await jwkRes.json();
70
+ } catch (err) {
71
+ throw new Error(`\u8FDC\u7A0B\u83B7\u53D6\u5BC6\u94A5\u5931\u8D25\uFF0C\u54CD\u5E94\u89E3\u6790\u9519\u8BEF: ${err.message}, response text: ${await jwkRes.text()}`);
72
+ }
73
+ const { keyId, privateKeyPkcs8 } = JwkResponseJson?.data || {};
74
+ if (!keyId || !privateKeyPkcs8) throw new Error(`\u672A\u83B7\u53D6\u5230\u9879\u76EE\u7B7E\u540D\u5BC6\u94A5, \u8BF7\u68C0\u67E5aud\u662F\u5426\u6B63\u786E: ${aud}`);
75
+ return { XFE_JWT_AUD: aud, XFE_JWT_KEY_ID: keyId, XFE_JWT_PRIVATE_KEY: privateKeyPkcs8 };
76
+ };
77
+
78
+ // src/framework.ts
79
+ import fs2 from "fs";
80
+ import { createRequire } from "module";
81
+ import path2 from "path";
82
+ import { fileURLToPath } from "url";
83
+ var frameworkDirectory = typeof __dirname === "string" ? __dirname : path2.dirname(fileURLToPath(import.meta.url));
84
+ var requireFromFramework = createRequire(path2.join(frameworkDirectory, "framework.js"));
85
+ var extensions = [".tsx", ".ts", ".jsx", ".js"];
86
+ var findSource = (directory, name) => extensions.map((extension) => path2.join(directory, `${name}${extension}`)).find(fs2.existsSync);
87
+ var findValueExports = (file) => [...fs2.readFileSync(file, "utf8").matchAll(/^\s*export\s+(?:async\s+)?(?:const|let|var|function|class)\s+([A-Za-z_$][\w$]*)/gm)].map(
88
+ ([, name]) => name
89
+ );
90
+ var importPath = (from, target) => {
91
+ const relative = path2.relative(from, target).replace(path2.extname(target), "").replaceAll(path2.sep, "/");
92
+ return relative.startsWith(".") ? relative : `./${relative}`;
93
+ };
94
+ var writeGenerated = (file, content) => {
95
+ if (fs2.existsSync(file) && fs2.readFileSync(file, "utf8") === content) return;
96
+ fs2.writeFileSync(file, content);
97
+ };
98
+ var defaultRootSource = (projectRoot, appDirectory) => {
99
+ const { webapp = {} } = loadXfeConfig(projectRoot);
100
+ const layoutSource = findSource(path2.join(projectRoot, "src"), "layout");
101
+ const layoutExports = layoutSource ? findValueExports(layoutSource) : [];
102
+ const hasErrorView = layoutExports.includes("ErrorView");
103
+ const layoutImport = layoutSource ? `import AppLayout${hasErrorView ? ", { ErrorView }" : ""} from ${JSON.stringify(importPath(appDirectory, layoutSource))}
104
+ ` : "";
105
+ return `import { createElement, type ReactNode } from 'react'
106
+ import { Outlet } from 'react-router'
107
+ import { Document, PageError, PageLoading } from '@xfe-repo/web-app/dist/root.mjs'
108
+ ${layoutImport}
109
+ export const meta = () => [{ title: ${JSON.stringify(webapp.title || "XFE App")} }]
110
+ export const Layout = ({ children }: { children: ReactNode }) => createElement(Document, { children, lang: ${JSON.stringify(webapp.lang || "zh-CN")}, themeColor: ${JSON.stringify(webapp.themeColor)} })
111
+ export default function Root() { return ${layoutSource ? "createElement(AppLayout, { children: createElement(Outlet) })" : "createElement(Outlet)"} }
112
+ export function ErrorBoundary() { return createElement(PageError, { ${hasErrorView ? "view: ErrorView" : ""} }) }
113
+ export function HydrateFallback() { return createElement(PageLoading) }
114
+ `;
115
+ };
116
+ var getFrameworkRoot = (projectRoot) => path2.join(projectRoot, "node_modules/.cache/xfe-web/react-router");
117
+ var prepareFramework = (projectRoot = process.cwd()) => {
118
+ const sourceDirectory = path2.join(projectRoot, "src");
119
+ const rootSource = findSource(sourceDirectory, "root");
120
+ const appServerSource = findSource(sourceDirectory, "app.server");
121
+ const pagesSource = path2.join(sourceDirectory, "pages");
122
+ if (!fs2.existsSync(pagesSource)) throw new Error("\u672A\u627E\u5230 src/pages");
123
+ const rootDirectory = getFrameworkRoot(projectRoot);
124
+ const appDirectory = path2.join(rootDirectory, "app");
125
+ fs2.mkdirSync(appDirectory, { recursive: true });
126
+ const routerDirectory = path2.dirname(requireFromFramework.resolve("react-router/package.json"));
127
+ const routerLink = path2.join(rootDirectory, "node_modules/react-router");
128
+ fs2.mkdirSync(path2.dirname(routerLink), { recursive: true });
129
+ if (!fs2.lstatSync(routerLink, { throwIfNoEntry: false })?.isSymbolicLink() || fs2.readlinkSync(routerLink) !== routerDirectory) {
130
+ fs2.rmSync(routerLink, { force: true });
131
+ fs2.symlinkSync(routerDirectory, routerLink, "junction");
132
+ }
133
+ const rootTarget = path2.join(appDirectory, "root.tsx");
134
+ const rootImport = rootSource ? importPath(appDirectory, rootSource) : "";
135
+ const rootExports = rootSource ? findValueExports(rootSource).filter((name) => name !== "middleware" || !appServerSource) : [];
136
+ const namedExports = rootExports.length ? `export { ${rootExports.join(", ")} } from ${JSON.stringify(rootImport)}
137
+ ` : "";
138
+ const errorBoundaryExport = rootExports.includes("ErrorBoundary") ? "" : "export { DefaultErrorBoundary as ErrorBoundary } from '@xfe-repo/web-router/errors'\n";
139
+ const middlewareExport = appServerSource ? `export { middleware } from ${JSON.stringify(importPath(appDirectory, appServerSource))}
140
+ ` : "";
141
+ writeGenerated(
142
+ rootTarget,
143
+ rootSource ? `export * from ${JSON.stringify(rootImport)}
144
+ export { default } from ${JSON.stringify(rootImport)}
145
+ ${namedExports}${errorBoundaryExport}${middlewareExport}` : `${defaultRootSource(projectRoot, appDirectory)}${middlewareExport}`
146
+ );
147
+ const pagesLink = path2.join(appDirectory, "pages");
148
+ if (!fs2.existsSync(pagesLink)) fs2.symlinkSync(path2.relative(appDirectory, pagesSource), pagesLink, "dir");
149
+ writeGenerated(
150
+ path2.join(rootDirectory, "react-router.config.js"),
151
+ "export { default } from '@xfe-repo/web-app/dist/react-router-config.mjs'\n"
152
+ );
153
+ writeGenerated(
154
+ path2.join(appDirectory, "routes.js"),
155
+ `import { collectPageRoutes } from '@xfe-repo/web-router/routes'
156
+ export default collectPageRoutes(${JSON.stringify(appDirectory)})
157
+ `
158
+ );
159
+ const defaultsDirectory = path2.join(path2.dirname(requireFromFramework.resolve("@react-router/dev/package.json")), "dist/config/defaults");
160
+ writeGenerated(
161
+ path2.join(appDirectory, "entry.server.tsx"),
162
+ `export { default, streamTimeout } from ${JSON.stringify(importPath(appDirectory, path2.join(defaultsDirectory, "entry.server.web.tsx")))}
163
+ `
164
+ );
165
+ const typeScriptConfig = path2.join(rootDirectory, "tsconfig.json");
166
+ writeGenerated(
167
+ typeScriptConfig,
168
+ JSON.stringify(
169
+ {
170
+ extends: path2.join(projectRoot, "tsconfig.json"),
171
+ compilerOptions: { rootDirs: [projectRoot, rootDirectory, path2.join(rootDirectory, ".react-router/types")] },
172
+ include: [
173
+ path2.join(sourceDirectory, "**/*"),
174
+ path2.join(projectRoot, "types/**/*"),
175
+ path2.join(appDirectory, "*.tsx"),
176
+ path2.join(rootDirectory, ".react-router/types/**/*")
177
+ ],
178
+ exclude: []
179
+ },
180
+ null,
181
+ 2
182
+ )
183
+ );
184
+ return {
185
+ appDirectory,
186
+ rootDirectory,
187
+ viteConfig: path2.resolve(frameworkDirectory, "vite.mjs"),
188
+ typeScriptConfig
189
+ };
190
+ };
191
+
192
+ // src/serve.ts
193
+ import { existsSync } from "fs";
194
+ import path3 from "path";
195
+ import express from "express";
196
+ var serveClient = ({
197
+ directory,
198
+ host,
199
+ port,
200
+ basename = "/"
201
+ }) => {
202
+ const indexFile = path3.join(directory, "index.html");
203
+ if (!existsSync(indexFile)) throw new Error(`\u672A\u627E\u5230 SPA \u5165\u53E3 ${indexFile}\uFF0C\u8BF7\u5148\u6267\u884C xfe-web build`);
204
+ const app = express().disable("x-powered-by");
205
+ const router = express.Router();
206
+ app.use((_request, response, next) => {
207
+ response.setHeader("Access-Control-Allow-Origin", "*");
208
+ next();
209
+ });
210
+ app.use(
211
+ "/assets",
212
+ express.static(path3.join(directory, "assets"), { immutable: true, maxAge: "1y" }),
213
+ (_request, response) => response.status(404).end()
214
+ );
215
+ app.use(express.static(directory));
216
+ router.get("/{*path}", (_request, response) => response.sendFile(indexFile));
217
+ app.use(basename, router);
218
+ const server = app.listen(port, host);
219
+ server.once("listening", () => {
220
+ const address = server.address();
221
+ console.log(`[xfe-web] SPA http://${host}:${typeof address === "object" && address ? address.port : port}${basename}`);
222
+ });
223
+ return server;
224
+ };
225
+
226
+ // src/cli.ts
227
+ var [command, ...args] = process.argv.slice(2);
228
+ var resolveBin = (packageName) => path4.join(path4.dirname(__require.resolve(`${packageName}/package.json`)), packageName === "typescript" ? "lib/tsc.js" : "bin.cjs");
229
+ var run = (packageName, commandArgs, options = {}) => {
230
+ const result = spawnSync(process.execPath, [resolveBin(packageName), ...commandArgs], {
231
+ stdio: "inherit",
232
+ env: options.env,
233
+ cwd: options.cwd
234
+ });
235
+ if (result.error) throw result.error;
236
+ if (result.status !== 0) process.exit(result.status ?? 1);
237
+ };
238
+ async function main() {
239
+ const projectRoot = process.cwd();
240
+ if (command === "config") return configDeploy();
241
+ if (command === "start") {
242
+ const { webapp = {} } = loadXfeConfig(projectRoot);
243
+ if (webapp.renderMode === "client") {
244
+ serveClient({
245
+ directory: path4.join(projectRoot, "build/client"),
246
+ host: process.env.HOST || webapp.host || "0.0.0.0",
247
+ port: Number(process.env.PORT ?? webapp.port ?? 3e3),
248
+ basename: webapp.basename
249
+ });
250
+ return;
251
+ }
252
+ const rootDirectory = getFrameworkRoot(projectRoot);
253
+ mkdirSync(rootDirectory, { recursive: true });
254
+ return run("@react-router/serve", [path4.join(projectRoot, "build/server/index.js"), ...args], {
255
+ cwd: rootDirectory,
256
+ env: { ...process.env, ...await getJwtEnv() }
257
+ });
258
+ }
259
+ if (!command || !["dev", "build", "typegen", "typecheck"].includes(command)) {
260
+ throw new Error(`\u4E0D\u652F\u6301\u7684\u547D\u4EE4: ${command || "undefined"}\uFF0C\u53EF\u7528\u547D\u4EE4: dev\u3001build\u3001typegen\u3001typecheck\u3001start\u3001config`);
261
+ }
262
+ const framework = prepareFramework(projectRoot);
263
+ const env = { ...process.env, XFE_WEB_ROOT: projectRoot };
264
+ const options = { cwd: framework.rootDirectory, env };
265
+ if (command === "typegen" || command === "typecheck") {
266
+ run("@react-router/dev", ["typegen", ...command === "typegen" ? args : []], options);
267
+ if (command === "typecheck") run("typescript", ["--noEmit", "--project", framework.typeScriptConfig, ...args]);
268
+ return;
269
+ }
270
+ Object.assign(env, await getJwtEnv());
271
+ if (command === "build") delete env.XFE_JWT_PRIVATE_KEY;
272
+ run("@react-router/dev", [command, framework.rootDirectory, "--config", framework.viteConfig, ...args], options);
267
273
  }
268
- main().catch(function(err) {
269
- console.error("XFE Web CLI \u6267\u884C\u51FA\u9519:", err);
270
- process.exit(1);
274
+ main().catch((err) => {
275
+ console.error("XFE Web CLI \u6267\u884C\u51FA\u9519:", err);
276
+ process.exit(1);
271
277
  });
package/dist/config.d.mts CHANGED
@@ -1,9 +1,23 @@
1
- declare const loadXfeConfig: () => Record<string, any>;
2
- declare const configDeploy: () => void;
3
- declare const getJwtEnv: () => Promise<{
4
- XFE_JWT_AUD: any;
1
+ type WebAppConfig = {
2
+ basename?: string;
3
+ host?: string;
4
+ port?: number;
5
+ /** 渲染方式由 XFE 转换为底层框架配置;省略时兼容已有服务端应用。 */
6
+ renderMode?: 'client' | 'server';
7
+ title?: string;
8
+ lang?: string;
9
+ themeColor?: string;
10
+ };
11
+ type XfeConfig = Record<string, any> & {
12
+ webapp?: WebAppConfig;
13
+ };
14
+ type JwtEnv = {
15
+ XFE_JWT_AUD: string;
5
16
  XFE_JWT_KEY_ID: string;
6
17
  XFE_JWT_PRIVATE_KEY: string;
7
- }>;
18
+ };
19
+ declare const loadXfeConfig: (root?: string) => XfeConfig;
20
+ declare const configDeploy: () => void;
21
+ declare const getJwtEnv: () => Promise<Partial<JwtEnv>>;
8
22
 
9
- export { configDeploy, getJwtEnv, loadXfeConfig };
23
+ export { type JwtEnv, type WebAppConfig, type XfeConfig, configDeploy, getJwtEnv, loadXfeConfig };
package/dist/config.d.ts CHANGED
@@ -1,9 +1,23 @@
1
- declare const loadXfeConfig: () => Record<string, any>;
2
- declare const configDeploy: () => void;
3
- declare const getJwtEnv: () => Promise<{
4
- XFE_JWT_AUD: any;
1
+ type WebAppConfig = {
2
+ basename?: string;
3
+ host?: string;
4
+ port?: number;
5
+ /** 渲染方式由 XFE 转换为底层框架配置;省略时兼容已有服务端应用。 */
6
+ renderMode?: 'client' | 'server';
7
+ title?: string;
8
+ lang?: string;
9
+ themeColor?: string;
10
+ };
11
+ type XfeConfig = Record<string, any> & {
12
+ webapp?: WebAppConfig;
13
+ };
14
+ type JwtEnv = {
15
+ XFE_JWT_AUD: string;
5
16
  XFE_JWT_KEY_ID: string;
6
17
  XFE_JWT_PRIVATE_KEY: string;
7
- }>;
18
+ };
19
+ declare const loadXfeConfig: (root?: string) => XfeConfig;
20
+ declare const configDeploy: () => void;
21
+ declare const getJwtEnv: () => Promise<Partial<JwtEnv>>;
8
22
 
9
- export { configDeploy, getJwtEnv, loadXfeConfig };
23
+ export { type JwtEnv, type WebAppConfig, type XfeConfig, configDeploy, getJwtEnv, loadXfeConfig };