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