@dimina/compiler 1.0.12 → 1.0.14-beta.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.
package/dist/index.js CHANGED
@@ -1,476 +1,431 @@
1
+ import { c as getPages, l as getTargetPath, n as getAppId, p as storeInfo, r as getAppName, s as getPageConfigInfo, t as getAppConfigInfo, u as getWorkPath, y as art_default } from "./env-DgCLbrQb.js";
1
2
  import path from "node:path";
2
3
  import { fileURLToPath } from "node:url";
3
4
  import { Worker } from "node:worker_threads";
4
5
  import { Listr } from "listr2";
5
6
  import process from "node:process";
6
7
  import fs from "node:fs";
7
- import { e as getTargetPath, d as getAppId, k as getAppName, l as getPageConfigInfo, j as getAppConfigInfo, s as storeInfo, f as getWorkPath, m as getPages } from "./env-QQjdhY-G.js";
8
8
  import os from "node:os";
9
- const artCode = `
10
- ██████╗ ██╗███╗ ███╗██╗███╗ ██╗ █████╗
11
- ██╔══██╗██║████╗ ████║██║████╗ ██║██╔══██╗
12
- ██║ ██║██║██╔████╔██║██║██╔██╗ ██║███████║
13
- ██║ ██║██║██║╚██╔╝██║██║██║╚██╗██║██╔══██║
14
- ██████╔╝██║██║ ╚═╝ ██║██║██║ ╚████║██║ ██║
15
- ╚═════╝ ╚═╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝
16
- `;
17
- function artCode$1() {
18
- console.log(artCode);
19
- }
9
+ //#region src/common/publish.js
20
10
  function createDist() {
21
- const distPath = getTargetPath();
22
- if (fs.existsSync(distPath)) {
23
- fs.rmSync(distPath, { recursive: true, force: true });
24
- }
25
- fs.mkdirSync(distPath, { recursive: true });
11
+ const distPath = getTargetPath();
12
+ if (fs.existsSync(distPath)) fs.rmSync(distPath, {
13
+ recursive: true,
14
+ force: true
15
+ });
16
+ fs.mkdirSync(distPath, { recursive: true });
26
17
  }
18
+ /**
19
+ * 发布到指定目录
20
+ * @param {string} dist 目标路径
21
+ * @param {boolean} useAppIdDir 是否在路径中包含appId
22
+ */
27
23
  function publishToDist(dist, useAppIdDir = true) {
28
- const distPath = getTargetPath();
29
- const appId = getAppId();
30
- const absolutePath = useAppIdDir ? `${path.resolve(process.cwd(), dist)}${path.sep}${appId}` : `${path.resolve(process.cwd(), dist)}`;
31
- if (fs.existsSync(absolutePath)) {
32
- fs.rmSync(absolutePath, { recursive: true, force: true });
33
- }
34
- fs.mkdirSync(absolutePath, { recursive: true });
35
- function copyDir(src, dest) {
36
- fs.mkdirSync(dest, { recursive: true });
37
- const entries = fs.readdirSync(src, { withFileTypes: true });
38
- for (const entry of entries) {
39
- const srcPath = path.join(src, entry.name);
40
- const destPath = path.join(dest, entry.name);
41
- if (entry.isDirectory()) {
42
- copyDir(srcPath, destPath);
43
- } else {
44
- fs.copyFileSync(srcPath, destPath);
45
- }
46
- }
47
- }
48
- copyDir(distPath, absolutePath);
24
+ const distPath = getTargetPath();
25
+ const appId = getAppId();
26
+ const absolutePath = useAppIdDir ? `${path.resolve(process.cwd(), dist)}${path.sep}${appId}` : `${path.resolve(process.cwd(), dist)}`;
27
+ if (fs.existsSync(absolutePath)) fs.rmSync(absolutePath, {
28
+ recursive: true,
29
+ force: true
30
+ });
31
+ fs.mkdirSync(absolutePath, { recursive: true });
32
+ function copyDir(src, dest) {
33
+ fs.mkdirSync(dest, { recursive: true });
34
+ const entries = fs.readdirSync(src, { withFileTypes: true });
35
+ for (const entry of entries) {
36
+ const srcPath = path.join(src, entry.name);
37
+ const destPath = path.join(dest, entry.name);
38
+ if (entry.isDirectory()) copyDir(srcPath, destPath);
39
+ else fs.copyFileSync(srcPath, destPath);
40
+ }
41
+ }
42
+ copyDir(distPath, absolutePath);
49
43
  }
44
+ //#endregion
45
+ //#region src/common/worker-pool.js
50
46
  function getCGroupCPUCount() {
51
- try {
52
- const quotaPath = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us";
53
- const periodPath = "/sys/fs/cgroup/cpu/cpu.cfs_period_us";
54
- if (fs.existsSync(quotaPath) && fs.existsSync(periodPath)) {
55
- const quota = Number.parseInt(fs.readFileSync(quotaPath, "utf8"));
56
- const period = Number.parseInt(fs.readFileSync(periodPath, "utf8"));
57
- if (quota > 0) {
58
- return Math.max(1, Math.floor(quota / period));
59
- }
60
- }
61
- } catch (e) {
62
- console.warn("Failed to read CPU limits from cgroup:", e.message);
63
- }
64
- return os.cpus().length;
47
+ try {
48
+ const quotaPath = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us";
49
+ const periodPath = "/sys/fs/cgroup/cpu/cpu.cfs_period_us";
50
+ if (fs.existsSync(quotaPath) && fs.existsSync(periodPath)) {
51
+ const quota = Number.parseInt(fs.readFileSync(quotaPath, "utf8"));
52
+ const period = Number.parseInt(fs.readFileSync(periodPath, "utf8"));
53
+ if (quota > 0) return Math.max(1, Math.floor(quota / period));
54
+ }
55
+ } catch (e) {
56
+ console.warn("Failed to read CPU limits from cgroup:", e.message);
57
+ }
58
+ return os.cpus().length;
65
59
  }
66
60
  function getCGroupMemoryLimit() {
67
- try {
68
- const memLimitPath = "/sys/fs/cgroup/memory/memory.limit_in_bytes";
69
- if (fs.existsSync(memLimitPath)) {
70
- const memLimit = Number.parseInt(fs.readFileSync(memLimitPath, "utf8"));
71
- if (memLimit < Number.Infinity && memLimit > 0) {
72
- return memLimit;
73
- }
74
- }
75
- } catch (e) {
76
- console.warn("Failed to read memory limits from cgroup:", e.message);
77
- }
78
- return os.totalmem();
79
- }
80
- const MAX_WORKERS = Math.max(1, Math.min(4, Math.floor(getCGroupCPUCount() / 4)));
81
- class WorkerPool {
82
- constructor(maxWorkers = MAX_WORKERS) {
83
- this.maxWorkers = maxWorkers;
84
- this.activeWorkers = 0;
85
- this.queue = [];
86
- this.memoryLimit = Math.floor(getCGroupMemoryLimit() * 0.6 / maxWorkers);
87
- }
88
- async runWorker(workerCreator) {
89
- if (this.activeWorkers >= this.maxWorkers) {
90
- await new Promise((resolve) => this.queue.push(resolve));
91
- }
92
- this.activeWorkers++;
93
- try {
94
- return await workerCreator();
95
- } finally {
96
- this.activeWorkers--;
97
- if (this.queue.length > 0) {
98
- const next = this.queue.shift();
99
- next();
100
- }
101
- }
102
- }
103
- getWorkerOptions() {
104
- const memoryMb = Math.floor(this.memoryLimit / (1024 * 1024));
105
- return {
106
- resourceLimits: {
107
- maxOldGenerationSizeMb: Math.max(256, memoryMb),
108
- // 最少 256MB
109
- maxYoungGenerationSizeMb: Math.max(64, Math.floor(memoryMb / 4)),
110
- // 最少 64MB
111
- codeRangeSizeMb: 64
112
- // 减少代码范围大小从 128MB 到 64MB
113
- }
114
- };
115
- }
116
- }
117
- const workerPool = new WorkerPool();
118
- class NpmBuilder {
119
- constructor(workPath, targetPath) {
120
- this.workPath = workPath;
121
- this.targetPath = targetPath;
122
- this.builtPackages = /* @__PURE__ */ new Set();
123
- this.packageDependencies = /* @__PURE__ */ new Map();
124
- }
125
- /**
126
- * 构建 npm 包
127
- * 扫描 miniprogram_npm 目录并构建相关包
128
- */
129
- async buildNpmPackages() {
130
- const miniprogramNpmPaths = this.findMiniprogramNpmDirs();
131
- for (const npmPath of miniprogramNpmPaths) {
132
- await this.buildNpmDir(npmPath);
133
- }
134
- }
135
- /**
136
- * 查找所有 miniprogram_npm 目录
137
- * @returns {string[]} miniprogram_npm 目录路径数组
138
- */
139
- findMiniprogramNpmDirs() {
140
- const npmDirs = [];
141
- const scanDir = (dir, relativePath = "") => {
142
- if (!fs.existsSync(dir)) {
143
- return;
144
- }
145
- const items = fs.readdirSync(dir, { withFileTypes: true });
146
- for (const item of items) {
147
- if (item.isDirectory()) {
148
- const itemPath = path.join(dir, item.name);
149
- const itemRelativePath = relativePath ? `${relativePath}/${item.name}` : item.name;
150
- if (item.name === "miniprogram_npm") {
151
- npmDirs.push(itemRelativePath);
152
- } else {
153
- scanDir(itemPath, itemRelativePath);
154
- }
155
- }
156
- }
157
- };
158
- scanDir(this.workPath);
159
- return npmDirs;
160
- }
161
- /**
162
- * 构建指定的 miniprogram_npm 目录
163
- * @param {string} npmDirPath miniprogram_npm 目录路径
164
- */
165
- async buildNpmDir(npmDirPath) {
166
- const fullNpmPath = path.join(this.workPath, npmDirPath);
167
- if (!fs.existsSync(fullNpmPath)) {
168
- return;
169
- }
170
- const packages = fs.readdirSync(fullNpmPath, { withFileTypes: true }).filter((item) => item.isDirectory()).map((item) => item.name);
171
- for (const packageName of packages) {
172
- await this.buildPackage(packageName, npmDirPath);
173
- }
174
- }
175
- /**
176
- * 构建单个 npm 包
177
- * @param {string} packageName 包名
178
- * @param {string} npmDirPath miniprogram_npm 目录路径
179
- */
180
- async buildPackage(packageName, npmDirPath) {
181
- const packageKey = `${npmDirPath}/${packageName}`;
182
- if (this.builtPackages.has(packageKey)) {
183
- return;
184
- }
185
- const packagePath = path.join(this.workPath, npmDirPath, packageName);
186
- const targetPackagePath = path.join(this.targetPath, npmDirPath, packageName);
187
- if (!fs.existsSync(path.dirname(targetPackagePath))) {
188
- fs.mkdirSync(path.dirname(targetPackagePath), { recursive: true });
189
- }
190
- await this.copyPackageFiles(packagePath, targetPackagePath);
191
- await this.processDependencies(packageName, packagePath, npmDirPath);
192
- this.builtPackages.add(packageKey);
193
- }
194
- /**
195
- * 复制包文件
196
- * @param {string} sourcePath 源路径
197
- * @param {string} targetPath 目标路径
198
- */
199
- async copyPackageFiles(sourcePath, targetPath) {
200
- if (!fs.existsSync(sourcePath)) {
201
- return;
202
- }
203
- if (!fs.existsSync(targetPath)) {
204
- fs.mkdirSync(targetPath, { recursive: true });
205
- }
206
- const items = fs.readdirSync(sourcePath, { withFileTypes: true });
207
- for (const item of items) {
208
- const sourceItemPath = path.join(sourcePath, item.name);
209
- const targetItemPath = path.join(targetPath, item.name);
210
- if (item.isDirectory()) {
211
- await this.copyPackageFiles(sourceItemPath, targetItemPath);
212
- } else {
213
- if (this.isMiniprogramFile(item.name)) {
214
- fs.copyFileSync(sourceItemPath, targetItemPath);
215
- }
216
- }
217
- }
218
- }
219
- /**
220
- * 检查是否为小程序相关文件
221
- * @param {string} filename 文件名
222
- * @returns {boolean} 是否为小程序文件
223
- */
224
- isMiniprogramFile(filename) {
225
- const miniprogramExts = [".js", ".json", ".wxml", ".wxss", ".wxs", ".ts", ".less", ".scss", ".styl"];
226
- const ext = path.extname(filename).toLowerCase();
227
- return miniprogramExts.includes(ext) || filename === "package.json" || filename === "README.md" || filename.startsWith(".");
228
- }
229
- /**
230
- * 处理包依赖
231
- * @param {string} packageName 包名
232
- * @param {string} packagePath 包路径
233
- * @param {string} npmDirPath npm 目录路径
234
- */
235
- async processDependencies(packageName, packagePath, npmDirPath) {
236
- const packageJsonPath = path.join(packagePath, "package.json");
237
- if (!fs.existsSync(packageJsonPath)) {
238
- return;
239
- }
240
- try {
241
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
242
- const dependencies = {
243
- ...packageJson.dependencies,
244
- ...packageJson.peerDependencies
245
- };
246
- if (dependencies && Object.keys(dependencies).length > 0) {
247
- this.packageDependencies.set(packageName, dependencies);
248
- for (const depName of Object.keys(dependencies)) {
249
- await this.buildPackage(depName, npmDirPath);
250
- }
251
- }
252
- } catch (e) {
253
- console.warn(`[npm-builder] 解析 package.json 失败: ${packageJsonPath}`, e.message);
254
- }
255
- }
256
- /**
257
- * 验证 npm 包的完整性
258
- * @param {string} packageName 包名
259
- * @param {string} packagePath 包路径
260
- * @returns {boolean} 是否有效
261
- */
262
- validatePackage(packageName, packagePath) {
263
- const requiredFiles = ["package.json"];
264
- for (const file of requiredFiles) {
265
- if (!fs.existsSync(path.join(packagePath, file))) {
266
- console.warn(`[npm-builder] 包 ${packageName} 缺少必要文件: ${file}`);
267
- return false;
268
- }
269
- }
270
- try {
271
- const packageJsonPath = path.join(packagePath, "package.json");
272
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
273
- if (!packageJson.name || !packageJson.version) {
274
- console.warn(`[npm-builder] 包 ${packageName} 的 package.json 格式不正确`);
275
- return false;
276
- }
277
- } catch (e) {
278
- console.warn(`[npm-builder] 包 ${packageName} 的 package.json 解析失败:`, e.message);
279
- return false;
280
- }
281
- return true;
282
- }
283
- /**
284
- * 获取已构建的包列表
285
- * @returns {string[]} 已构建的包列表
286
- */
287
- getBuiltPackages() {
288
- return Array.from(this.builtPackages);
289
- }
290
- /**
291
- * 获取包依赖关系
292
- * @returns {Map} 包依赖关系映射
293
- */
294
- getPackageDependencies() {
295
- return this.packageDependencies;
296
- }
297
- /**
298
- * 清理构建缓存
299
- */
300
- clearCache() {
301
- this.builtPackages.clear();
302
- this.packageDependencies.clear();
303
- }
61
+ try {
62
+ const memLimitPath = "/sys/fs/cgroup/memory/memory.limit_in_bytes";
63
+ if (fs.existsSync(memLimitPath)) {
64
+ const memLimit = Number.parseInt(fs.readFileSync(memLimitPath, "utf8"));
65
+ if (memLimit < Number.Infinity && memLimit > 0) return memLimit;
66
+ }
67
+ } catch (e) {
68
+ console.warn("Failed to read memory limits from cgroup:", e.message);
69
+ }
70
+ return os.totalmem();
304
71
  }
72
+ var MAX_WORKERS = Math.max(1, Math.min(4, Math.floor(getCGroupCPUCount() / 4)));
73
+ var WorkerPool = class {
74
+ constructor(maxWorkers = MAX_WORKERS) {
75
+ this.maxWorkers = maxWorkers;
76
+ this.activeWorkers = 0;
77
+ this.queue = [];
78
+ this.memoryLimit = Math.floor(getCGroupMemoryLimit() * .6 / maxWorkers);
79
+ }
80
+ async runWorker(workerCreator) {
81
+ if (this.activeWorkers >= this.maxWorkers) await new Promise((resolve) => this.queue.push(resolve));
82
+ this.activeWorkers++;
83
+ try {
84
+ return await workerCreator();
85
+ } finally {
86
+ this.activeWorkers--;
87
+ if (this.queue.length > 0) this.queue.shift()();
88
+ }
89
+ }
90
+ getWorkerOptions() {
91
+ const memoryMb = Math.floor(this.memoryLimit / (1024 * 1024));
92
+ return { resourceLimits: {
93
+ maxOldGenerationSizeMb: Math.max(256, memoryMb),
94
+ maxYoungGenerationSizeMb: Math.max(64, Math.floor(memoryMb / 4)),
95
+ codeRangeSizeMb: 64
96
+ } };
97
+ }
98
+ };
99
+ var workerPool = new WorkerPool();
100
+ //#endregion
101
+ //#region src/common/npm-builder.js
102
+ /**
103
+ * npm 构建工具
104
+ * 用于处理小程序 npm 包的构建和管理
105
+ */
106
+ var NpmBuilder = class {
107
+ constructor(workPath, targetPath) {
108
+ this.workPath = workPath;
109
+ this.targetPath = targetPath;
110
+ this.builtPackages = /* @__PURE__ */ new Set();
111
+ this.packageDependencies = /* @__PURE__ */ new Map();
112
+ }
113
+ /**
114
+ * 构建 npm 包
115
+ * 扫描 miniprogram_npm 目录并构建相关包
116
+ */
117
+ async buildNpmPackages() {
118
+ const miniprogramNpmPaths = this.findMiniprogramNpmDirs();
119
+ for (const npmPath of miniprogramNpmPaths) await this.buildNpmDir(npmPath);
120
+ }
121
+ /**
122
+ * 查找所有 miniprogram_npm 目录
123
+ * @returns {string[]} miniprogram_npm 目录路径数组
124
+ */
125
+ findMiniprogramNpmDirs() {
126
+ const npmDirs = [];
127
+ const scanDir = (dir, relativePath = "") => {
128
+ if (!fs.existsSync(dir)) return;
129
+ const items = fs.readdirSync(dir, { withFileTypes: true });
130
+ for (const item of items) if (item.isDirectory()) {
131
+ const itemPath = path.join(dir, item.name);
132
+ const itemRelativePath = relativePath ? `${relativePath}/${item.name}` : item.name;
133
+ if (item.name === "miniprogram_npm") npmDirs.push(itemRelativePath);
134
+ else scanDir(itemPath, itemRelativePath);
135
+ }
136
+ };
137
+ scanDir(this.workPath);
138
+ return npmDirs;
139
+ }
140
+ /**
141
+ * 构建指定的 miniprogram_npm 目录
142
+ * @param {string} npmDirPath miniprogram_npm 目录路径
143
+ */
144
+ async buildNpmDir(npmDirPath) {
145
+ const fullNpmPath = path.join(this.workPath, npmDirPath);
146
+ if (!fs.existsSync(fullNpmPath)) return;
147
+ const packages = fs.readdirSync(fullNpmPath, { withFileTypes: true }).filter((item) => item.isDirectory()).map((item) => item.name);
148
+ for (const packageName of packages) await this.buildPackage(packageName, npmDirPath);
149
+ }
150
+ /**
151
+ * 构建单个 npm 包
152
+ * @param {string} packageName 包名
153
+ * @param {string} npmDirPath miniprogram_npm 目录路径
154
+ */
155
+ async buildPackage(packageName, npmDirPath) {
156
+ const packageKey = `${npmDirPath}/${packageName}`;
157
+ if (this.builtPackages.has(packageKey)) return;
158
+ const packagePath = path.join(this.workPath, npmDirPath, packageName);
159
+ const targetPackagePath = path.join(this.targetPath, npmDirPath, packageName);
160
+ if (!fs.existsSync(path.dirname(targetPackagePath))) fs.mkdirSync(path.dirname(targetPackagePath), { recursive: true });
161
+ await this.copyPackageFiles(packagePath, targetPackagePath);
162
+ await this.processDependencies(packageName, packagePath, npmDirPath);
163
+ this.builtPackages.add(packageKey);
164
+ }
165
+ /**
166
+ * 复制包文件
167
+ * @param {string} sourcePath 源路径
168
+ * @param {string} targetPath 目标路径
169
+ */
170
+ async copyPackageFiles(sourcePath, targetPath) {
171
+ if (!fs.existsSync(sourcePath)) return;
172
+ if (!fs.existsSync(targetPath)) fs.mkdirSync(targetPath, { recursive: true });
173
+ const items = fs.readdirSync(sourcePath, { withFileTypes: true });
174
+ for (const item of items) {
175
+ const sourceItemPath = path.join(sourcePath, item.name);
176
+ const targetItemPath = path.join(targetPath, item.name);
177
+ if (item.isDirectory()) await this.copyPackageFiles(sourceItemPath, targetItemPath);
178
+ else if (this.isMiniprogramFile(item.name)) fs.copyFileSync(sourceItemPath, targetItemPath);
179
+ }
180
+ }
181
+ /**
182
+ * 检查是否为小程序相关文件
183
+ * @param {string} filename 文件名
184
+ * @returns {boolean} 是否为小程序文件
185
+ */
186
+ isMiniprogramFile(filename) {
187
+ const miniprogramExts = [
188
+ ".js",
189
+ ".json",
190
+ ".wxml",
191
+ ".wxss",
192
+ ".wxs",
193
+ ".ts",
194
+ ".less",
195
+ ".scss",
196
+ ".styl"
197
+ ];
198
+ const ext = path.extname(filename).toLowerCase();
199
+ return miniprogramExts.includes(ext) || filename === "package.json" || filename === "README.md" || filename.startsWith(".");
200
+ }
201
+ /**
202
+ * 处理包依赖
203
+ * @param {string} packageName 包名
204
+ * @param {string} packagePath 包路径
205
+ * @param {string} npmDirPath npm 目录路径
206
+ */
207
+ async processDependencies(packageName, packagePath, npmDirPath) {
208
+ const packageJsonPath = path.join(packagePath, "package.json");
209
+ if (!fs.existsSync(packageJsonPath)) return;
210
+ try {
211
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
212
+ const dependencies = {
213
+ ...packageJson.dependencies,
214
+ ...packageJson.peerDependencies
215
+ };
216
+ if (dependencies && Object.keys(dependencies).length > 0) {
217
+ this.packageDependencies.set(packageName, dependencies);
218
+ for (const depName of Object.keys(dependencies)) await this.buildPackage(depName, npmDirPath);
219
+ }
220
+ } catch (e) {
221
+ console.warn(`[npm-builder] 解析 package.json 失败: ${packageJsonPath}`, e.message);
222
+ }
223
+ }
224
+ /**
225
+ * 验证 npm 包的完整性
226
+ * @param {string} packageName 包名
227
+ * @param {string} packagePath 包路径
228
+ * @returns {boolean} 是否有效
229
+ */
230
+ validatePackage(packageName, packagePath) {
231
+ for (const file of ["package.json"]) if (!fs.existsSync(path.join(packagePath, file))) {
232
+ console.warn(`[npm-builder] 包 ${packageName} 缺少必要文件: ${file}`);
233
+ return false;
234
+ }
235
+ try {
236
+ const packageJsonPath = path.join(packagePath, "package.json");
237
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
238
+ if (!packageJson.name || !packageJson.version) {
239
+ console.warn(`[npm-builder] 包 ${packageName} 的 package.json 格式不正确`);
240
+ return false;
241
+ }
242
+ } catch (e) {
243
+ console.warn(`[npm-builder] 包 ${packageName} 的 package.json 解析失败:`, e.message);
244
+ return false;
245
+ }
246
+ return true;
247
+ }
248
+ /**
249
+ * 获取已构建的包列表
250
+ * @returns {string[]} 已构建的包列表
251
+ */
252
+ getBuiltPackages() {
253
+ return Array.from(this.builtPackages);
254
+ }
255
+ /**
256
+ * 获取包依赖关系
257
+ * @returns {Map} 包依赖关系映射
258
+ */
259
+ getPackageDependencies() {
260
+ return this.packageDependencies;
261
+ }
262
+ /**
263
+ * 清理构建缓存
264
+ */
265
+ clearCache() {
266
+ this.builtPackages.clear();
267
+ this.packageDependencies.clear();
268
+ }
269
+ };
270
+ //#endregion
271
+ //#region src/core/config-compiler.js
272
+ /**
273
+ *
274
+ * 编译项目配置文件 app-config.json
275
+ */
305
276
  function compileConfig() {
306
- const compileResInfo = {
307
- app: getAppConfigInfo(),
308
- modules: getPageConfigInfo(),
309
- projectName: getAppName()
310
- };
311
- const json = JSON.stringify(compileResInfo, null, 4);
312
- const mainDir = `${getTargetPath()}/main`;
313
- if (!fs.existsSync(mainDir)) {
314
- fs.mkdirSync(mainDir, { recursive: true });
315
- }
316
- fs.writeFileSync(`${mainDir}/app-config.json`, json);
277
+ const compileResInfo = {
278
+ app: getAppConfigInfo(),
279
+ modules: getPageConfigInfo(),
280
+ projectName: getAppName()
281
+ };
282
+ const json = JSON.stringify(compileResInfo, null, 4);
283
+ const mainDir = `${getTargetPath()}/main`;
284
+ if (!fs.existsSync(mainDir)) fs.mkdirSync(mainDir, { recursive: true });
285
+ fs.writeFileSync(`${mainDir}/app-config.json`, json);
317
286
  }
318
- let isPrinted = false;
287
+ //#endregion
288
+ //#region src/index.js
289
+ var isPrinted = false;
290
+ /**
291
+ * 构建命令入口
292
+ * @param {string} targetPath 编译产物目标路径
293
+ * @param {string} workPath 编译工作目录
294
+ * @param {boolean} useAppIdDir 产物根目录是否包含appId
295
+ */
319
296
  async function build(targetPath, workPath, useAppIdDir = true) {
320
- if (!isPrinted) {
321
- artCode$1();
322
- isPrinted = true;
323
- }
324
- const tasks = new Listr(
325
- [
326
- {
327
- title: "准备项目编译环境",
328
- task: (_, task) => task.newListr(
329
- [
330
- {
331
- title: "收集配置信息",
332
- task: (ctx) => {
333
- ctx.storeInfo = storeInfo(workPath);
334
- }
335
- },
336
- {
337
- title: "准备产物目录",
338
- task: () => {
339
- createDist();
340
- }
341
- },
342
- {
343
- title: "编译配置信息",
344
- task: () => {
345
- compileConfig();
346
- }
347
- },
348
- {
349
- title: "构建 npm 包",
350
- task: async () => {
351
- const npmBuilder = new NpmBuilder(getWorkPath(), getTargetPath());
352
- await npmBuilder.buildNpmPackages();
353
- }
354
- }
355
- ],
356
- { concurrent: false }
357
- )
358
- },
359
- {
360
- title: `开始编译:${workPath.split("/").pop()}`,
361
- task: (ctx, task) => {
362
- const pages = getPages();
363
- ctx.pages = pages;
364
- return task.newListr(
365
- [
366
- {
367
- title: "编译页面文件",
368
- task: async (ctx2, task2) => {
369
- return runCompileInWorker("view", ctx2, task2);
370
- }
371
- },
372
- {
373
- title: "编译页面逻辑",
374
- task: async (ctx2, task2) => {
375
- return runCompileInWorker("logic", ctx2, task2);
376
- }
377
- },
378
- {
379
- title: "编译样式文件",
380
- task: async (ctx2, task2) => {
381
- pages.mainPages.unshift({
382
- path: "app",
383
- id: ""
384
- });
385
- return runCompileInWorker("style", ctx2, task2);
386
- }
387
- }
388
- ],
389
- { concurrent: true }
390
- );
391
- }
392
- },
393
- {
394
- title: "输出编译产物",
395
- task: () => {
396
- publishToDist(targetPath, useAppIdDir);
397
- }
398
- }
399
- ],
400
- { concurrent: false }
401
- );
402
- try {
403
- const context = await tasks.run();
404
- return {
405
- appId: getAppId(),
406
- name: getAppName(),
407
- path: getAppConfigInfo().entryPagePath || context.pages.mainPages[1].path
408
- };
409
- } catch (e) {
410
- console.error(`${workPath} 编译出错: ${e.message}
411
- ${e.stack}`);
412
- }
297
+ if (!isPrinted) {
298
+ art_default();
299
+ isPrinted = true;
300
+ }
301
+ const tasks = new Listr([
302
+ {
303
+ title: "准备项目编译环境",
304
+ task: (_, task) => task.newListr([
305
+ {
306
+ title: "收集配置信息",
307
+ task: (ctx) => {
308
+ ctx.storeInfo = storeInfo(workPath);
309
+ }
310
+ },
311
+ {
312
+ title: "准备产物目录",
313
+ task: () => {
314
+ createDist();
315
+ }
316
+ },
317
+ {
318
+ title: "编译配置信息",
319
+ task: () => {
320
+ compileConfig();
321
+ }
322
+ },
323
+ {
324
+ title: "构建 npm 包",
325
+ task: async () => {
326
+ await new NpmBuilder(getWorkPath(), getTargetPath()).buildNpmPackages();
327
+ }
328
+ }
329
+ ], { concurrent: false })
330
+ },
331
+ {
332
+ title: `开始编译:${workPath.split("/").pop()}`,
333
+ task: (ctx, task) => {
334
+ const pages = getPages();
335
+ ctx.pages = pages;
336
+ return task.newListr([
337
+ {
338
+ title: "编译页面文件",
339
+ task: async (ctx, task) => {
340
+ return runCompileInWorker("view", ctx, task);
341
+ }
342
+ },
343
+ {
344
+ title: "编译页面逻辑",
345
+ task: async (ctx, task) => {
346
+ return runCompileInWorker("logic", ctx, task);
347
+ }
348
+ },
349
+ {
350
+ title: "编译样式文件",
351
+ task: async (ctx, task) => {
352
+ pages.mainPages.unshift({
353
+ path: "app",
354
+ id: ""
355
+ });
356
+ return runCompileInWorker("style", ctx, task);
357
+ }
358
+ }
359
+ ], { concurrent: true });
360
+ }
361
+ },
362
+ {
363
+ title: "输出编译产物",
364
+ task: () => {
365
+ publishToDist(targetPath, useAppIdDir);
366
+ }
367
+ }
368
+ ], { concurrent: false });
369
+ try {
370
+ const context = await tasks.run();
371
+ return {
372
+ appId: getAppId(),
373
+ name: getAppName(),
374
+ path: getAppConfigInfo().entryPagePath || context.pages.mainPages[1].path
375
+ };
376
+ } catch (e) {
377
+ console.error(`${workPath} 编译出错: ${e.message}\n${e.stack}`);
378
+ }
413
379
  }
414
380
  function runCompileInWorker(script, ctx, task) {
415
- return workerPool.runWorker(() => new Promise((resolve, reject) => {
416
- const worker = new Worker(
417
- path.join(path.dirname(fileURLToPath(import.meta.url)), `core/${script}-compiler.js`),
418
- workerPool.getWorkerOptions()
419
- );
420
- const totalTasks = Object.keys(ctx.pages.mainPages).length + Object.values(ctx.pages.subPages).reduce((sum, item) => sum + item.info.length, 0);
421
- let isResolved = false;
422
- let workerError = null;
423
- const handleError = (error) => {
424
- if (isResolved) return;
425
- isResolved = true;
426
- worker.terminate();
427
- reject(error);
428
- };
429
- worker.postMessage({ pages: ctx.pages, storeInfo: ctx.storeInfo });
430
- worker.on("message", (message) => {
431
- try {
432
- if (message.completedTasks) {
433
- const progress = message.completedTasks / totalTasks;
434
- const percentage = progress * 100;
435
- const barLength = 30;
436
- const filledLength = Math.ceil(barLength * progress);
437
- const bar = "█".repeat(filledLength) + "░".repeat(barLength - filledLength);
438
- task.output = `[${bar}] ${percentage.toFixed(2)}%`;
439
- }
440
- if (message.success) {
441
- if (isResolved) return;
442
- isResolved = true;
443
- worker.terminate();
444
- resolve();
445
- } else if (message.error) {
446
- const error = new Error(message.error.message || message.error);
447
- if (message.error.stack)
448
- error.stack = message.error.stack;
449
- if (message.error.file)
450
- error.file = message.error.file;
451
- if (message.error.line)
452
- error.line = message.error.line;
453
- handleError(error);
454
- }
455
- } catch (err) {
456
- handleError(new Error(`Error processing worker message: ${err.message}
457
- ${err.stack}`));
458
- }
459
- });
460
- worker.on("error", (err) => {
461
- workerError = err;
462
- handleError(err);
463
- });
464
- worker.on("exit", (code) => {
465
- if (code !== 0 && !isResolved) {
466
- const error = workerError || new Error(
467
- code === 1 ? "Worker terminated due to reaching memory limit: JS heap out of memory" : `Worker stopped with exit code ${code}`
468
- );
469
- handleError(error);
470
- }
471
- });
472
- }));
381
+ return workerPool.runWorker(() => new Promise((resolve, reject) => {
382
+ const worker = new Worker(path.join(path.dirname(fileURLToPath(import.meta.url)), `core/${script}-compiler.js`), workerPool.getWorkerOptions());
383
+ const totalTasks = Object.keys(ctx.pages.mainPages).length + Object.values(ctx.pages.subPages).reduce((sum, item) => sum + item.info.length, 0);
384
+ let isResolved = false;
385
+ let workerError = null;
386
+ const handleError = (error) => {
387
+ if (isResolved) return;
388
+ isResolved = true;
389
+ worker.terminate();
390
+ reject(error);
391
+ };
392
+ worker.postMessage({
393
+ pages: ctx.pages,
394
+ storeInfo: ctx.storeInfo
395
+ });
396
+ worker.on("message", (message) => {
397
+ try {
398
+ if (message.completedTasks) {
399
+ const progress = message.completedTasks / totalTasks;
400
+ const percentage = progress * 100;
401
+ const barLength = 30;
402
+ const filledLength = Math.ceil(barLength * progress);
403
+ task.output = `[${"█".repeat(filledLength) + "░".repeat(barLength - filledLength)}] ${percentage.toFixed(2)}%`;
404
+ }
405
+ if (message.success) {
406
+ if (isResolved) return;
407
+ isResolved = true;
408
+ worker.terminate();
409
+ resolve();
410
+ } else if (message.error) {
411
+ const error = new Error(message.error.message || message.error);
412
+ if (message.error.stack) error.stack = message.error.stack;
413
+ if (message.error.file) error.file = message.error.file;
414
+ if (message.error.line) error.line = message.error.line;
415
+ handleError(error);
416
+ }
417
+ } catch (err) {
418
+ handleError(/* @__PURE__ */ new Error(`Error processing worker message: ${err.message}\n${err.stack}`));
419
+ }
420
+ });
421
+ worker.on("error", (err) => {
422
+ workerError = err;
423
+ handleError(err);
424
+ });
425
+ worker.on("exit", (code) => {
426
+ if (code !== 0 && !isResolved) handleError(workerError || /* @__PURE__ */ new Error(code === 1 ? "Worker terminated due to reaching memory limit: JS heap out of memory" : `Worker stopped with exit code ${code}`));
427
+ });
428
+ }));
473
429
  }
474
- export {
475
- build as default
476
- };
430
+ //#endregion
431
+ export { build as default };