@dd-code/uni-tools 1.0.9 → 1.0.11

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.
@@ -0,0 +1,357 @@
1
+ #!/usr/bin/env node
2
+ import { program } from '@dd-code/shared';
3
+ import path from 'path';
4
+ import fs from 'fs';
5
+ import 'crypto';
6
+ import 'chokidar';
7
+ import { execSync } from 'child_process';
8
+ import inquirer from 'inquirer';
9
+
10
+ /******************************************************************************
11
+ Copyright (c) Microsoft Corporation.
12
+
13
+ Permission to use, copy, modify, and/or distribute this software for any
14
+ purpose with or without fee is hereby granted.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
17
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
18
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
19
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
20
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
21
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
22
+ PERFORMANCE OF THIS SOFTWARE.
23
+ ***************************************************************************** */
24
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
25
+
26
+
27
+ function __awaiter(thisArg, _arguments, P, generator) {
28
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
29
+ return new (P || (P = Promise))(function (resolve, reject) {
30
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
31
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
32
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
33
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
34
+ });
35
+ }
36
+
37
+ function __generator(thisArg, body) {
38
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
39
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
40
+ function verb(n) { return function (v) { return step([n, v]); }; }
41
+ function step(op) {
42
+ if (f) throw new TypeError("Generator is already executing.");
43
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
44
+ 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;
45
+ if (y = 0, t) op = [op[0] & 2, t.value];
46
+ switch (op[0]) {
47
+ case 0: case 1: t = op; break;
48
+ case 4: _.label++; return { value: op[1], done: false };
49
+ case 5: _.label++; y = op[1]; op = [0]; continue;
50
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
51
+ default:
52
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
53
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
54
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
55
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
56
+ if (t[2]) _.ops.pop();
57
+ _.trys.pop(); continue;
58
+ }
59
+ op = body.call(thisArg, _);
60
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
61
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
62
+ }
63
+ }
64
+
65
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
66
+ var e = new Error(message);
67
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
68
+ };
69
+
70
+ var MFE_NAME = "mfe.json";
71
+
72
+ /**
73
+ * 读取文件内容
74
+ * 支持JSON文件的自动解析
75
+ * @param {string} filaPath - 文件路径
76
+ * @returns {string|Object} 返回文件内容,JSON文件返回对象,其他返回字符串
77
+ */
78
+ function uniReadFile(filaPath) {
79
+ try {
80
+ if (filaPath.endsWith(".json")) {
81
+ return require(filaPath);
82
+ }
83
+ var res = fs.readFileSync(filaPath, "utf-8");
84
+ return res;
85
+ }
86
+ catch (e) {
87
+ // console.error(`${filaPath} notfound`);
88
+ // console.log(e);
89
+ }
90
+ return "";
91
+ }
92
+ /**
93
+ * 写入文件内容
94
+ * 自动创建目录结构,支持对象和字符串内容
95
+ * @param {string} filaPath - 文件路径
96
+ * @param {string|Object} content - 文件内容
97
+ * @returns {void}
98
+ */
99
+ function writeFiles(filaPath, content) {
100
+ // 检查文件路径是否存在
101
+ var dir = path.dirname(filaPath);
102
+ if (!fs.existsSync(dir)) {
103
+ // 如果路径不存在,创建路径
104
+ fs.mkdirSync(dir, { recursive: true });
105
+ }
106
+ return fs.writeFileSync(filaPath, content, "utf-8");
107
+ }
108
+ var checkAndgenreDir = function (dir) {
109
+ if (!fs.existsSync(dir)) {
110
+ // 如果路径不存在,创建路径
111
+ fs.mkdirSync(dir, { recursive: true });
112
+ }
113
+ };
114
+ var loadViteConfig = function (mode) {
115
+ var loadEnv = require("vite").loadEnv;
116
+ var ROOT = process.cwd();
117
+ return loadEnv(mode, ROOT, "MFE_");
118
+ };
119
+
120
+ // 项目 Git 子模块路径
121
+ var PROJECT_GIT_PATH = "src/subtree";
122
+ // CDN 文件保存路径
123
+ path.join(process.cwd(), "node_modules/@dd-code/uni-files");
124
+ path.join(process.cwd(), "node_modules/@dd-code/__main-pwd.txt");
125
+ path.join(process.cwd(), "node_modules/@dd-code/manifest-list.json");
126
+ path.join(process.cwd(), "node_modules/@dd-code/current-files");
127
+ // 发布目录路径
128
+ path.join(process.cwd(), "dist/publish");
129
+ var ROOT_APP_CODE = "__MFE_APP_ROOT__";
130
+ var EBuildMode;
131
+ (function (EBuildMode) {
132
+ EBuildMode["BUILD"] = "build";
133
+ EBuildMode["SERVE"] = "serve";
134
+ })(EBuildMode || (EBuildMode = {}));
135
+ /**
136
+ * 获取微前端配置 JSON
137
+ * @description 读取并解析 mfe.json 配置文件,同时从环境变量中获取相关配置
138
+ * @returns {Object} 包含微前端配置的对象
139
+ * @returns {boolean} returns.isRoot - 是否为根应用
140
+ * @returns {string} returns.code - 项目代码
141
+ * @returns {string} returns.appCode - 应用代码
142
+ * @example
143
+ * // 返回: { isRoot: true, code: 'myapp', appCode: 'main', ... }
144
+ */
145
+ var getMfeJson = function () {
146
+ // 读取 mfe.json 配置文件
147
+ var jsonPath = path.resolve(process.cwd(), MFE_NAME);
148
+ var json = uniReadFile(jsonPath) || {};
149
+ // const root = process.cwd();
150
+ // const { loadEnv } = require("vite");
151
+ // const viteEnv = loadEnv(mode || "dev", root, "");
152
+ // const envObj = {
153
+ // ...viteEnv,
154
+ // platform: process.env.UNI_PLATFORM || "h5",
155
+ // };
156
+ // console.log("-----", process.env, mode, "viteEnv");
157
+ // // 从环境变量中获取配置
158
+ // json.isRoot = envObj.UNI_IS_ROOT;
159
+ // json.code = envObj.UNI_CODE;
160
+ // json.appCode = envObj.MFE_APP_CODE;
161
+ json.platform = process.env.UNI_PLATFORM || "h5";
162
+ // json.mode = envObj.MODE || "dev";
163
+ return json;
164
+ };
165
+ var formatCliCommandConfig = function (mode) {
166
+ var viteEnv = loadViteConfig(mode || "dev");
167
+ var isRoot = viteEnv.MFE_UNI_IS_ROOT;
168
+ // MFE_CDN_HOST
169
+ return {
170
+ isRoot: isRoot,
171
+ appCode: isRoot ? ROOT_APP_CODE : viteEnv.MFE_APP_CODE,
172
+ code: viteEnv.MFE_UNI_CODE,
173
+ mode: mode,
174
+ cdn: viteEnv.MFE_CDN_HOST,
175
+ serve: viteEnv.MFE_UNI_SERVE, // 是否开启 serve 功能
176
+ };
177
+ };
178
+ var E_WS_TYPE;
179
+ (function (E_WS_TYPE) {
180
+ E_WS_TYPE["INIT"] = "init_files";
181
+ E_WS_TYPE["CHANGE"] = "change_files";
182
+ })(E_WS_TYPE || (E_WS_TYPE = {}));
183
+
184
+ var excuteUniCommand = function (command, opt) { return __awaiter(void 0, void 0, void 0, function () {
185
+ var _a, isRoot, appCode, cmd;
186
+ return __generator(this, function (_b) {
187
+ process.env.MFE_TARGET_DIR = (opt === null || opt === void 0 ? void 0 : opt.buildDir) || "";
188
+ _a = opt || {}, isRoot = _a.isRoot, appCode = _a.appCode;
189
+ cmd = "".concat(command, " ").concat(!isRoot ? "--subpackage=".concat(appCode) : "");
190
+ // if (isRoot) {
191
+ // const mfeJson = getMfeJson();
192
+ // const apps = mfeJson.apps?.map((i) => i.appCode) || [];
193
+ // apps.forEach((appCode) => {
194
+ // const appCodeDir = appCode.replace(/\//g, "_");
195
+ // // console.log(appCodeDir, 'appCodeDir');
196
+ // const childPath = path.join(process.cwd(), PROJECT_GIT_PATH, appCodeDir);
197
+ // console.log(existsSync(appCodeDir), childPath, "childPath");
198
+ // // if (existsSync(appCodeDir)) {
199
+ // // excuteUniCommand(`cd ${childPath} && ${command}`, {
200
+ // // appCode,
201
+ // // target: appCodeDir,
202
+ // // });
203
+ // // 开一个子线程启动
204
+ // // execSync(cmd, {
205
+ // // stdio: "inherit",
206
+ // // });
207
+ // // }
208
+ // });
209
+ // // setTimeout(() => {
210
+ // // console.log(process.env.UNI_OUTPUT_DIR, "process.env.UNI_OUTPUT_DIR");
211
+ // // });
212
+ // }
213
+ // console.log(cmd, "-------");
214
+ execSync(cmd, {
215
+ stdio: "inherit",
216
+ });
217
+ return [2 /*return*/];
218
+ });
219
+ }); };
220
+
221
+ //@ts-ignore
222
+ var inquirerPrompt = ((inquirer === null || inquirer === void 0 ? void 0 : inquirer.default) ||
223
+ inquirer);
224
+
225
+ var fetchAppsRepo = function () { return __awaiter(void 0, void 0, void 0, function () {
226
+ var mfeJson, apps, answers, selectedApps, selectedGitApps;
227
+ return __generator(this, function (_a) {
228
+ switch (_a.label) {
229
+ case 0:
230
+ mfeJson = getMfeJson();
231
+ apps = (mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) || [];
232
+ return [4 /*yield*/, inquirerPrompt.prompt([
233
+ {
234
+ type: "checkbox",
235
+ name: "selectedApps",
236
+ message: "请选择要拉取的应用仓库:",
237
+ choices: apps.map(function (app) { return ({
238
+ name: app.appCode,
239
+ value: app.appCode,
240
+ }); }),
241
+ },
242
+ ])];
243
+ case 1:
244
+ answers = _a.sent();
245
+ selectedApps = answers.selectedApps;
246
+ selectedGitApps = apps.filter(function (app) { return selectedApps.includes(app.appCode) && app.repoUrl; });
247
+ console.log("选择的应用仓库:", selectedGitApps);
248
+ // 执行拉取操作
249
+ selectedGitApps.forEach(function (_a) {
250
+ var appCode = _a.appCode, repoUrl = _a.repoUrl;
251
+ if (repoUrl) {
252
+ var fileName = appCode.replace(/\//g, "_");
253
+ var dir = PROJECT_GIT_PATH;
254
+ checkAndgenreDir(dir);
255
+ execSync("cd ".concat(dir, " && git clone ").concat(repoUrl, " ").concat(fileName), {
256
+ stdio: "inherit",
257
+ });
258
+ }
259
+ });
260
+ return [2 /*return*/];
261
+ }
262
+ });
263
+ }); };
264
+
265
+ var runParallelAllUni = function (cmd) { return __awaiter(void 0, void 0, void 0, function () {
266
+ var configPath;
267
+ return __generator(this, function (_a) {
268
+ configPath = path.join(process.cwd(), "pnpm-workspace.yaml");
269
+ writeFiles(configPath, "packages:\n - '*'\n - 'src/subtree/*'");
270
+ // pnpm -r --parallel --workspace-root --filter=* run dev:mp-weixin --b root
271
+ execSync("pnpm -r --parallel --workspace-root --filter=* run ".concat(cmd, " --b root"), {
272
+ stdio: "inherit",
273
+ });
274
+ // 删除文件
275
+ fs.unlinkSync(configPath);
276
+ return [2 /*return*/];
277
+ });
278
+ }); };
279
+
280
+ var addUniOptions = function (program) {
281
+ return program
282
+ .option("-p <platform>", "平台", "h5")
283
+ .option("--mode <mode>", "模式", "development")
284
+ .option("--b <buildDir>", "目标路径", "");
285
+ };
286
+ var dev = program
287
+ .name("uni-tools")
288
+ .command("serve")
289
+ .description("uni 工具方法");
290
+ var build = program.command("build").description("构建 uni 项目");
291
+ // const pushCdn = program.command("push-cdn").description("推送 uni 项目到 cdn");
292
+ var fetchGit = program.command("fetch").description("拉取 uni 项目到本地");
293
+ var runAll = program.command("runAll").description("运行所有 uni 项目");
294
+ fetchGit.action(function () { return __awaiter(void 0, void 0, void 0, function () {
295
+ return __generator(this, function (_a) {
296
+ switch (_a.label) {
297
+ case 0: return [4 /*yield*/, fetchAppsRepo()];
298
+ case 1:
299
+ _a.sent();
300
+ return [2 /*return*/];
301
+ }
302
+ });
303
+ }); });
304
+ // pushCdn.option("--mode <mode>", "模式", "dev").action(({ mode }) => {
305
+ // pushDistToCdn(mode);
306
+ // });
307
+ addUniOptions(runAll).action(function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
308
+ _b.mode; var platform = _b.p; _b.b;
309
+ return __generator(this, function (_c) {
310
+ if (platform === 'mp-weixin') {
311
+ runParallelAllUni("dev:mp-weixin");
312
+ }
313
+ return [2 /*return*/];
314
+ });
315
+ }); });
316
+ addUniOptions(dev).action(function (_a) {
317
+ var mode = _a.mode, platform = _a.p, b = _a.b;
318
+ process.env.MFE_BUILD_MODE = EBuildMode.SERVE;
319
+ var _b = formatCliCommandConfig(mode), isRoot = _b.isRoot, appCode = _b.appCode;
320
+ switch (platform) {
321
+ case "h5":
322
+ excuteUniCommand("uni -p ".concat(platform, " --mode ").concat(mode));
323
+ break;
324
+ case "mp-weixin":
325
+ excuteUniCommand("uni -p ".concat(platform, " --mode ").concat(mode), {
326
+ isRoot: isRoot,
327
+ appCode: appCode,
328
+ buildDir: b,
329
+ });
330
+ break;
331
+ default:
332
+ excuteUniCommand("uni -p ".concat(platform, " --mode ").concat(mode));
333
+ break;
334
+ }
335
+ // debugger;
336
+ // console.log(JSON.stringify({ mode, platform, mfeJson }), "-111-------------");
337
+ });
338
+ addUniOptions(build).action(function (_a) {
339
+ var mode = _a.mode, platform = _a.p;
340
+ process.env.MFE_BUILD_MODE = EBuildMode.BUILD;
341
+ var _b = formatCliCommandConfig(mode), isRoot = _b.isRoot, appCode = _b.appCode;
342
+ switch (platform) {
343
+ case "h5":
344
+ excuteUniCommand("uni build -p ".concat(platform, " --mode ").concat(mode));
345
+ break;
346
+ case "mp-weixin":
347
+ excuteUniCommand("uni build -p ".concat(platform, " --mode ").concat(mode), {
348
+ isRoot: isRoot,
349
+ appCode: appCode,
350
+ });
351
+ break;
352
+ default:
353
+ excuteUniCommand("uni build -p ".concat(platform, " --mode ").concat(mode));
354
+ break;
355
+ }
356
+ });
357
+ program.parseAsync(process.argv);