mbler 0.2.0 → 0.2.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.
package/dist/index.esm.js CHANGED
@@ -1,2016 +1,2 @@
1
- import { env, cwd, argv } from 'node:process';
2
- import * as fs$1 from 'node:fs';
3
- import fs__default from 'node:fs';
4
- import * as path from 'node:path';
5
- import path__default, { isAbsolute } from 'node:path';
6
- import * as fs from 'node:fs/promises';
7
- import fs__default$1, { readFile, writeFile, unlink, stat, mkdir, readdir, cp } from 'node:fs/promises';
8
- import os, { tmpdir, homedir } from 'node:os';
9
- import * as readline from 'readline';
10
- import { json } from 'npm-registry-fetch';
11
- import { spawn } from 'node:child_process';
12
- import * as mcxDef from '@mbler/mcx-core';
13
- import _chalk from 'chalk';
14
- import jsonPlugin from '@rollup/plugin-json';
15
- import resolvePlugin from '@rollup/plugin-node-resolve';
16
- import minifyPlugin from '@rollup/plugin-terser';
17
- import { watch as watch$1 } from 'chokidar';
18
- import * as rollup from 'rollup';
19
- import crypto from 'node:crypto';
20
- import AdmZip from 'adm-zip';
21
- import commonjs from '@rollup/plugin-commonjs';
22
- import { createMCXLanguagePlugin } from '@mbler/mcx-server';
23
- import typescript from '@rollup/plugin-typescript';
24
- import { runTsc } from '@volar/typescript/lib/quickstart/runTsc';
25
-
26
- const LanguageNames = ['zh', 'en'];
27
- const cmdList = ['c', 'work', 'help', 'h', 'init', 'version', 'build', 'watch', 'lang', 'set-work-dir'];
28
- const templateMblerConfig = {
29
- name: 'demo',
30
- description: 'demo',
31
- version: '0.0.0',
32
- mcVersion: '1.21.100',
33
- script: {
34
- main: '',
35
- },
36
- minify: false,
37
- outdir: {
38
- behavior: '',
39
- resources: '',
40
- dist: '',
41
- },
42
- };
43
-
44
- var types = /*#__PURE__*/Object.freeze({
45
- __proto__: null,
46
- LanguageNames: LanguageNames,
47
- cmdList: cmdList,
48
- templateMblerConfig: templateMblerConfig
49
- });
50
-
51
- var MBLERVersion = { commit: `commit da7bebe8ce53a502c75fcc7ad53e510fcb233137
52
- Author: Ruanhor <3915264929@qq.com>
53
- Date: Sun Apr 19 12:42:06 2026 +0800
54
-
55
- feat: use script config when init
56
- `, version: "0.2.0" };
57
-
58
- var ZhLang = {
59
- description: `MBLER
60
- Minecraft Bedrock Edition
61
- Addon Bulider In Nodejs
62
- 在基岩版我的世界上的 nodejs 构建工具
63
- 命令 : ${cmdList.join(", ")}
64
- 帮助命令 :
65
- help
66
- 显示帮助信息
67
- 第二个参数为要查询的命令名称或空
68
- 别名: h
69
- git https://github.com/RuanhoR/mbler/`,
70
- help: {
71
- cmds: cmdList,
72
- help: "mbler [help/h] [?:查看的命令名称]\n - 查看帮助",
73
- h: "$help",
74
- work: "mbler [work/c] [?:相对或绝对路径]\n - 没有输入路径:查询当前工作目录\n - 输入路径:设置工作目录",
75
- c: "$work",
76
- init: "mbler init\n - 初始化当前工作目录,可使用 mbler work 指定工作目录或使用参数一次确定(例: mbler init -in ./)\n - 将会询问选项以完成初始化",
77
- build: "mbler build\n - 在工作目录执行构建",
78
- watch: "mbler watch\n - 启动构建并开启监视模式,文件变化会自动重新构建",
79
- lang: 'mbler lang\n- 无参数:显示当前语言\n- 跟 zh 或 en(如 mbler lang en): 设置语言',
80
- version: "mbler version - 版本管理命令\n- 无参数:显示当前版本和提交哈希\n- --show=<commit|version>:筛选显示内容\n- <新版本号>:更新package.json和配置文件的版本",
81
- 'set-work-dir': "mbler set-work-dir <on|off>\n - on: 启用工作目录功能\n - off: 禁用工作目录功能,直接使用 process.cwd()"
82
- },
83
- init: {
84
- useUI: '使用UI模块? (y/n): ',
85
- useGIT: '初始化GIT仓库? (y/n): ',
86
- name: '项目名称: ',
87
- welcome: '欢迎使用Mbler初始化向导 语言:中文 mbler 版本: ' + MBLERVersion.version,
88
- description: "项目描述: ",
89
- initDes: "初始化依赖? (y/n): ",
90
- lang: "选择项目语言: ",
91
- betaApi: "使用Beta Api? (y/n): ",
92
- mcVersion: "项目使用的mc版本(x.x.x): ",
93
- noLanguare: "没有输入项目语言,这是必要的",
94
- noName: "没有项目名称,这是必要的",
95
- noMCVersion: "输入的 '支持的mc版本' 格式不对"
96
- },
97
- default: {
98
- unexpected: "不正确的命令,",
99
- youis: "你是否想说: ",
100
- },
101
- workdir: {
102
- set: "[工作目录] 设置为: ",
103
- nfound: "找不到输入文件夹(无法创建或不是文件夹)",
104
- disabled: "工作目录功能已禁用,将使用当前目录",
105
- enabled: "工作目录功能已启用",
106
- invalidParam: "参数错误,请使用 on 或 off",
107
- },
108
- };
109
-
110
- var enLang = {
111
- description: 'MBLER\nMinecraft Bedrock Edition\nAddon Bulider In Nodejs\nnodejs build tools on bedrock version of minecraft\nCommands: ' +
112
- cmdList.join(', ') +
113
- '\nHelp command:\n help\n Show help information\n The second parameter is the name of the command to be queried or empty\n Alias: -h, -help\n git https://github.com/RuanhoR/mbler/',
114
- help: {
115
- cmds: cmdList,
116
- help: 'mbler [help/h] [?: command name]\n - see tip',
117
- h: '$help',
118
- work: 'mbler [work/c] [?: path]\n - No input path: see current work dir\n - input path: set as current dir',
119
- c: '$work',
120
- init: 'mbler init\n - Init current work dir, you can use `mbler work` command or use command param(like be: mbler init -in ./)',
121
- build: 'mbler build\n - perform a build using the library API',
122
- b: '$build',
123
- watch: 'mbler watch\n - run build and enter watch mode; changes will trigger rebuilds',
124
- lang: 'mbler lang [?:languare]\n- No args: show current languare\n- languare = "zh” | “en": set languare',
125
- version: 'mbler version\n - Version control command\n- No args: Shows version + commit hash\n- --show=<commit|version>: Filters output\n- <new_version>: Updates version in both package.json and config file',
126
- 'set-work-dir': "mbler set-work-dir <on|off>\n - on: Enable work dir feature\n - off: Disable work dir feature, use process.cwd() directly"
127
- },
128
- init: {
129
- useUI: 'Use UI? (y/n): ',
130
- useGIT: 'Initialize GIT repository? (y/n): ',
131
- name: 'Project name: ',
132
- description: "Project description: ",
133
- initDes: "Initialize dependencies? (y/n): ",
134
- welcome: 'Welcome to use Mbler init wizard! Language: English mbler version: ' + MBLERVersion.version,
135
- lang: "Project languare: ",
136
- betaApi: "use beta api(y/n): ",
137
- mcVersion: 'Minecraft version(be like: x.x.x): ',
138
- noLanguare: 'project languare is required',
139
- noMCVersion: "project mcVersion format is not right",
140
- noName: "project name is required"
141
- },
142
- default: {
143
- unexpected: 'Not found this command,',
144
- youis: 'You want to input: ',
145
- },
146
- workdir: {
147
- set: '[path to]: ',
148
- nfound: "not found this dir(can't create or not directory)",
149
- disabled: "Work dir disabled, will use current directory",
150
- enabled: "Work dir enabled",
151
- invalidParam: "Invalid parameter, use on or off",
152
- },
153
- };
154
-
155
- const configPath = path__default.join(require("node:os").homedir(), ".cache/mbler/lang.db");
156
- function isLanguareName(language) {
157
- return LanguageNames.includes(language);
158
- }
159
- class Lang {
160
- currenyLang = "zh";
161
- init() {
162
- try {
163
- const TheyLang = fs__default.readFileSync(configPath, "utf-8").toString().trim();
164
- if (isLanguareName(TheyLang)) {
165
- this.currenyLang = TheyLang;
166
- }
167
- else {
168
- throw new Error("[setup lang]: set lang error");
169
- }
170
- }
171
- catch {
172
- this.currenyLang = "zh";
173
- }
174
- }
175
- set(newLang) {
176
- if (LanguageNames.includes(newLang)) {
177
- if (!fs__default.existsSync(configPath)) {
178
- fs__default.mkdirSync(path__default.dirname(configPath), {
179
- recursive: true,
180
- });
181
- }
182
- fs__default.writeFileSync(configPath, newLang);
183
- this.currenyLang = newLang;
184
- return true;
185
- }
186
- return false;
187
- }
188
- get() {
189
- try {
190
- if (this.currenyLang == "zh")
191
- return ZhLang;
192
- return enLang;
193
- }
194
- catch {
195
- return ZhLang;
196
- }
197
- }
198
- }
199
- const lang = new Lang();
200
- let i18n = {};
201
- function Export(lang) {
202
- const obj = lang.get();
203
- // 用原型来让导入后切换语言不需要再次导入,相同引用
204
- Object.setPrototypeOf(i18n, {
205
- ...obj,
206
- __internal: {
207
- class: lang,
208
- set: (newLang) => {
209
- lang.set(newLang);
210
- Export(lang);
211
- },
212
- },
213
- });
214
- }
215
- lang.init();
216
- Export(lang);
217
-
218
- var index$2 = /*#__PURE__*/Object.freeze({
219
- __proto__: null,
220
- default: i18n
221
- });
222
-
223
- // 启用 raw mode 和键盘事件(仅在 TTY 环境中)
224
- if (process.stdin.isTTY) {
225
- process.stdin.setRawMode(true);
226
- readline.emitKeypressEvents(process.stdin);
227
- }
228
- const promises = [];
229
- const tasks = [];
230
- process.on("exit", (code) => {
231
- process.stdout.write("\x1b[?25h");
232
- });
233
- const endTasks = [];
234
- function onEnd(task) {
235
- endTasks.push(task);
236
- }
237
- click("c", {
238
- ctrl: true,
239
- }).then(() => {
240
- endTasks.forEach((task) => task());
241
- process.exit(0);
242
- });
243
- /**
244
- * 监听键盘输入并触发对应的 Promise 或任务
245
- */
246
- function handler(name, { ctrl, alt, }, raw) {
247
- // 查找是否有匹配的 Promise 等待触发
248
- const find = promises.find((e) => e.name === name && e.ctrl === ctrl && e.alt === alt);
249
- if (find) {
250
- find.resolve();
251
- promises.splice(promises.indexOf(find), 1);
252
- }
253
- // 通知所有注册的监听任务
254
- tasks.forEach((item) => item(name, ctrl, alt, raw));
255
- }
256
- /**
257
- * 模拟等待某个按键被按下,返回一个 Promise
258
- */
259
- function click(name, { ctrl = false, alt = false, }) {
260
- return new Promise((resolve) => {
261
- promises.push({
262
- name,
263
- ctrl: ctrl || false,
264
- alt: alt || false,
265
- resolve,
266
- });
267
- });
268
- }
269
- /**
270
- * 工具类:提供控制台交互功能,比如高亮菜单渲染、交互式选择等
271
- */
272
- class Input {
273
- /**
274
- * 渲染一个字符串数组,高亮当前选中的项
275
- * @param arr 菜单项数组
276
- * @param index 当前选中索引
277
- * @returns 格式化后的字符串
278
- */
279
- static render(arr, index) {
280
- return arr
281
- .map((item, pindex) => {
282
- if (pindex === index)
283
- return "\x1b[1m\x1b[32m" + item + "\x1b[0m"; // 亮绿,高亮
284
- return "\x1b[1m\x1b[33m" + item + "\x1b[0m"; // 亮黄
285
- })
286
- .join(" ");
287
- }
288
- /**
289
- * 提供一个交互式菜单选择器
290
- * @param tip 提示文本
291
- * @param arr 选项数组
292
- * @returns 用户选中的选项内容(Promise<string>)
293
- */
294
- static select(tip, arr) {
295
- let index = 0;
296
- let win = false;
297
- console.log(`\x1b[2K\x1b[47m\x1b[1m\x1b[30m${tip} (按 b 确认,n 键选择下一个) \x1b[0m\x1b[?25l`);
298
- console.log(Input.render(arr, index) + "\n\x1b[1A");
299
- const handlerNext = () => {
300
- if (win)
301
- return;
302
- index++;
303
- if (index >= arr.length)
304
- index = 0;
305
- console.log(`\x1b[1A${Input.render(arr, index)}\n\x1b[1A`);
306
- click("n", {
307
- ctrl: false,
308
- alt: false,
309
- }).then(handlerNext);
310
- };
311
- return new Promise((resolve) => {
312
- // 监听 n 按键来切换选项
313
- click("n", {
314
- ctrl: false,
315
- alt: false,
316
- }).then(handlerNext);
317
- // 监听 b 按键来确认选择
318
- click("b", {
319
- ctrl: false,
320
- alt: false,
321
- }).then(() => {
322
- win = true;
323
- process.stdout.write("\x1b[?25h");
324
- resolve(arr[index]);
325
- });
326
- });
327
- }
328
- /**
329
- * 注册一个全局任务,每次按键都会被调用
330
- * @param task 回调函数
331
- */
332
- static use(task) {
333
- tasks.push(task);
334
- }
335
- }
336
- // 监听键盘输入事件
337
- process.stdin.on("keypress", (str, key) => {
338
- const rawKeyName = key?.name || "";
339
- const ctrl = Boolean(key?.ctrl);
340
- const alt = Boolean(key?.alt);
341
- handler(rawKeyName, {
342
- ctrl,
343
- alt,
344
- }, str);
345
- });
346
-
347
- var index$1 = /*#__PURE__*/Object.freeze({
348
- __proto__: null,
349
- Input: Input,
350
- click: click,
351
- onEnd: onEnd
352
- });
353
-
354
- const BuildConfig = {
355
- ConfigFile: "mbler.config.js",
356
- salt: {
357
- header: "d61e721d-a2c9-4535-8054-0183bce24767",
358
- sapi: "33e2c698-908f-45ab-8a9f-66018f8486ed",
359
- module: "cbbacfa4-8b1e-4a9c-9cbd-7a0d2e5f0b3c",
360
- },
361
- behavior: "behavior",
362
- resources: "resources",
363
- includes: {
364
- public: {
365
- "pack_icon.png": "file",
366
- "manifest.json": "file",
367
- },
368
- resources: {
369
- "biomes_client.json": "file",
370
- "blocks.json": "file",
371
- "bug_pack_icon.png": "file",
372
- "contents.json": "file",
373
- "loading_messages.json": "file",
374
- "manifest_publish.json": "file",
375
- "signatures.json": "file",
376
- "sounds.json": "file",
377
- "splashes.json": "file",
378
- animation_controllers: "directory",
379
- animations: "directory",
380
- attachables: "directory",
381
- biomes: "directory",
382
- cameras: "directory",
383
- entity: "directory",
384
- fogs: "directory",
385
- font: "directory",
386
- items: "directory",
387
- library: "directory",
388
- materials: "directory",
389
- models: "directory",
390
- particles: "directory",
391
- render_controllers: "directory",
392
- sounds: "directory",
393
- texts: "directory",
394
- textures: "directory",
395
- },
396
- behavior: {
397
- aim_assist: "directory",
398
- animation_controllers: "directory",
399
- animations: "directory",
400
- behavior_trees: "directory",
401
- biomes: "directory",
402
- blocks: "directory",
403
- cameras: "directory",
404
- dimensions: "directory",
405
- entities: "directory",
406
- feature_rules: "directory",
407
- features: "directory",
408
- functions: "directory",
409
- item_catalog: "directory",
410
- items: "directory",
411
- loot_tables: "directory",
412
- recipes: "directory",
413
- scripts: "skip", // special handling
414
- spawn_rules: "directory",
415
- structures: "directory",
416
- texts: "directory",
417
- trading: "directory",
418
- worldgen: "directory",
419
- "contents.json": "file",
420
- "manifest_publish.json": "file",
421
- "signatures.json": "file",
422
- },
423
- },
424
- };
425
-
426
- async function FileExsit(file) {
427
- try {
428
- const f = await fs.stat(file);
429
- if (f)
430
- return true;
431
- }
432
- catch {
433
- return false;
434
- }
435
- return false;
436
- }
437
- function join(baseDir, inputPath) {
438
- return path.isAbsolute(inputPath) ? inputPath : path.join(baseDir, inputPath);
439
- }
440
- async function ReadProjectMblerConfig(project) {
441
- const fileExport = await import(path.join(project, BuildConfig.ConfigFile));
442
- const file = fileExport.default;
443
- for (const key in file) {
444
- if (!(key in templateMblerConfig)) {
445
- throw new Error(`[read config]: read config from '${project}' error: Unexpected '${key}'`);
446
- }
447
- }
448
- return file;
449
- }
450
- async function readFileAsJson(filePath) {
451
- try {
452
- const content = await fs.readFile(filePath, 'utf-8');
453
- const json = JSON.parse(content);
454
- return json;
455
- }
456
- catch (err) {
457
- if (err instanceof Error) {
458
- throw err;
459
- }
460
- else {
461
- throw new Error(err);
462
- }
463
- }
464
- }
465
- /**
466
- * Print a single-line message to stdout with a trailing newline.
467
- * Exported here so other modules (for example `build`) do not need
468
- * to import from `cli`, avoiding a circular dependency.
469
- */
470
- // IO缓冲队列,避免多线程写入冲突
471
- let outputQueue = [];
472
- let isFlushing = false;
473
- async function flushOutputQueue() {
474
- if (isFlushing || outputQueue.length === 0)
475
- return;
476
- isFlushing = true;
477
- try {
478
- while (outputQueue.length > 0) {
479
- const chunk = outputQueue.shift();
480
- if (chunk) {
481
- process.stdout.write(chunk);
482
- }
483
- }
484
- }
485
- finally {
486
- isFlushing = false;
487
- }
488
- }
489
- process.on("exit", flushOutputQueue);
490
- function showText(text, needNextLine = true) {
491
- outputQueue.push(text + (needNextLine ? '\n' : ""));
492
- if (!isFlushing) {
493
- Promise.resolve().then(() => flushOutputQueue()).catch(() => {
494
- outputQueue = [];
495
- isFlushing = false;
496
- });
497
- }
498
- }
499
- function stringToNumberArray(str) {
500
- return str
501
- .split('.')
502
- .map((s) => parseInt(s, 10))
503
- .slice(0, 3);
504
- }
505
- async function writeJSON(filePath, data) {
506
- const content = JSON.stringify(data, null, 2);
507
- if (!(await FileExsit(path.dirname(filePath)))) {
508
- await fs
509
- .mkdir(path.dirname(filePath), { recursive: true })
510
- .catch(() => void 0);
511
- }
512
- return await fs.writeFile(filePath, content, 'utf-8');
513
- }
514
- function compareVersion(a, b) {
515
- const pa = a.split('.').map((x) => parseInt(x, 10) || 0);
516
- const pb = b.split('.').map((x) => parseInt(x, 10) || 0);
517
- for (let i = 0; i < 3; i++) {
518
- const na = pa[i] || 0;
519
- const nb = pb[i] || 0;
520
- if (na !== nb)
521
- return na - nb;
522
- }
523
- return 0;
524
- }
525
- const input = (function () {
526
- let curr;
527
- let currstr = '';
528
- let tip = '';
529
- let show = true;
530
- // 在输入时使用输入中间件
531
- Input.use(function (raw, ctrl, alt, name) {
532
- if (typeof curr !== 'function')
533
- return;
534
- if (ctrl || alt)
535
- return;
536
- if (raw) {
537
- if (raw === 'return' || raw === 'enter') {
538
- curr(currstr);
539
- curr = null;
540
- currstr = '';
541
- console.log('');
542
- return;
543
- }
544
- if (raw === 'backspace') {
545
- currstr = currstr.slice(0, -1);
546
- refreshInput();
547
- return;
548
- }
549
- }
550
- if (name && typeof name === 'string') {
551
- currstr += name;
552
- refreshInput();
553
- }
554
- });
555
- function refreshInput() {
556
- const out = `\x1b[2K\r${tip}${show ? currstr : ''}`;
557
- process.stdout.write(out);
558
- }
559
- /**
560
- * 输入文本
561
- * @param{string} tip 提示
562
- * @param{boolean} show 是否显示输入
563
- */
564
- return async function (t = '', g = true) {
565
- return new Promise((resolve) => {
566
- show = g;
567
- tip = t;
568
- refreshInput();
569
- curr = resolve;
570
- });
571
- };
572
- })();
573
- function isVaildVersion(version) {
574
- const split = version.split("-");
575
- if (!split[0])
576
- return false;
577
- if (split[0].split(".").map(Number).filter(i => !Number.isNaN(i)).length !== 3)
578
- return false;
579
- return true;
580
- }
581
- function runCommand(param, cwd, stdio) {
582
- let resolve;
583
- let data = "";
584
- const promise = new Promise((r) => resolve = r);
585
- const p = spawn(param[0], param.slice(1), {
586
- cwd: cwd,
587
- shell: false,
588
- stdio: stdio,
589
- timeout: 1000 * 60 * 10
590
- });
591
- p.on("error", (err) => {
592
- resolve(data + "(code: error)");
593
- });
594
- p.on("data", (...args) => {
595
- data += args.join("");
596
- });
597
- p.on("exit", (code) => {
598
- if (!code) {
599
- resolve(`${data}(code: ${code})`);
600
- }
601
- else {
602
- resolve(data);
603
- }
604
- });
605
- return promise;
606
- }
607
-
608
- const logFile = path__default.join(os.homedir(), ".cache/mbler/latest.log");
609
- function _clean(promise) {
610
- return () => {
611
- Logger.run = Logger.run.filter((item) => {
612
- return item !== promise;
613
- });
614
- };
615
- }
616
- function writeLog(logContent) {
617
- async function write() {
618
- try {
619
- const dir = path__default.dirname(logFile);
620
- if (!(await FileExsit(dir))) {
621
- // ensure the directory exists, root-to-leaf
622
- await fs__default$1.mkdir(dir, { recursive: true }).catch(() => void 0);
623
- }
624
- // if file does not exist, create it (touch)
625
- if (!(await FileExsit(logFile))) {
626
- await fs__default$1.writeFile(logFile, "");
627
- }
628
- }
629
- catch (err) {
630
- // if we can't prepare the log file, output to stderr but don't crash
631
- console.error("[logger] unable to prepare log file:", err);
632
- return;
633
- }
634
- try {
635
- await fs__default$1.appendFile(logFile, "\n" + logContent);
636
- }
637
- catch (err) {
638
- console.error("[logger] failed to append to log file:", err);
639
- }
640
- }
641
- const asy = write();
642
- Logger.run.push(asy.then(_clean(asy)));
643
- }
644
- class Logger {
645
- // 写入日志池
646
- static LogFile = logFile;
647
- static run = [];
648
- static _b(tag, msg, t) {
649
- const date = new Date();
650
- const logContent = [
651
- `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`,
652
- `[${t} ${tag}]`,
653
- msg,
654
- ].join(" ");
655
- writeLog(logContent);
656
- }
657
- static w(tag, msg) {
658
- Logger._b(tag, msg, "WARN");
659
- }
660
- static e(tag, msg) {
661
- Logger._b(tag, msg, "ERROR");
662
- }
663
- static i(tag, msg) {
664
- Logger._b(tag, msg, "INFO");
665
- }
666
- static d(tag, msg) {
667
- Logger._b(tag, msg, "DEBUG");
668
- }
669
- }
670
-
671
- // 该模块用于从字符串生成哈希转 uuid
672
- const fromString = (input, salt = '') => {
673
- const combinedInput = salt + input;
674
- const hash = crypto
675
- .createHash('sha256')
676
- .update(combinedInput)
677
- .digest('hex');
678
- const base = hash
679
- .slice(0, 32); // 取前 32 个 hex 字符(16 字节)
680
- const ls = '89ab';
681
- const r = (t) => ls[(combinedInput.length + t + salt.length) % ls.length];
682
- // 构造成标准 UUID v4 格式:xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
683
- const uuid = `${base.substring(0, 8)}-${base.substring(8, 12)}-4${base.substring(12, 15)}-8${r(1)}${r(2)}${r(3)}-${base.substring(18, 30)}`;
684
- return uuid;
685
- };
686
- ({
687
- uuid: crypto.randomUUID
688
- });
689
-
690
- const config = {
691
- tmpdir: path.join(tmpdir(), ".mbler"),
692
- mcxVersion: "0.0.2-beta.r7"
693
- };
694
-
695
- /**
696
- * Compare two dotted version strings ("major.minor.patch").
697
- * Returns negative if a < b, positive if a > b, zero if equal.
698
- */
699
- const exp = (function () {
700
- const cacheFile = path.join(config.tmpdir, "_sapi_version.json");
701
- // cacheData is an array of entries keyed by the embedded mc version string
702
- let cacheData = null;
703
- /**
704
- * Pull every published version for a package and reduce it to a mapping
705
- * from the embedded Minecraft version (e.g. "1.21.60") to the most
706
- * recent formal/beta release we were able to parse.
707
- */
708
- async function fetchData(pkgName) {
709
- const data = (await json(`/${pkgName}`));
710
- const pkgVersions = Object.keys(data.versions);
711
- const reValue = {};
712
- // helper to extract the embedded MC version ("yyyy") from a full
713
- // npm package version string. returns null when the expected pattern
714
- // cannot be found.
715
- const mcVersionFrom = (str) => {
716
- const m = str.match(/-(?:rc|beta)(?:\.[^-.]+)*?\.((?:\d+\.){2}\d+)/);
717
- return m ? m[1] : null;
718
- };
719
- for (const v of pkgVersions) {
720
- const mcVersion = mcVersionFrom(v);
721
- if (!mcVersion)
722
- continue;
723
- const isStable = /(?:-stable)(?:$|[-.])/.test(v);
724
- let entry = reValue[mcVersion];
725
- if (!entry) {
726
- entry = { formal: "", beta: "", _v: -1 };
727
- reValue[mcVersion] = entry;
728
- }
729
- if (isStable) {
730
- // pick the lexically greatest stable version string
731
- if (!entry.formal || v > entry.formal) {
732
- entry.formal = v;
733
- }
734
- entry._v = Infinity;
735
- }
736
- else {
737
- // non-stable release; treat everything else as a beta candidate
738
- if (!entry.beta || v > entry.beta) {
739
- entry.beta = v;
740
- }
741
- if (entry._v !== Infinity)
742
- entry._v = 1;
743
- }
744
- }
745
- return reValue;
746
- }
747
- async function refresh() {
748
- // grab the two packages we care about and merge the keys
749
- const serverMap = await fetchData("@minecraft/server");
750
- const uiMap = await fetchData("@minecraft/server-ui");
751
- const versions = new Set([
752
- ...Object.keys(serverMap),
753
- ...Object.keys(uiMap),
754
- ]);
755
- const arr = [];
756
- for (const ver of Array.from(versions)) {
757
- arr.push({
758
- version: ver,
759
- server: serverMap[ver]
760
- ? { formal: serverMap[ver].formal, beta: serverMap[ver].beta }
761
- : { formal: "", beta: "" },
762
- "server-ui": uiMap[ver]
763
- ? { formal: uiMap[ver].formal, beta: uiMap[ver].beta }
764
- : { formal: "", beta: "" },
765
- });
766
- }
767
- arr.sort((a, b) => compareVersion(a.version, b.version));
768
- cacheData = arr;
769
- await fs$1.promises
770
- .mkdir(config.tmpdir, { recursive: true })
771
- .catch(() => void 0);
772
- await fs$1.promises.writeFile(cacheFile, JSON.stringify(arr, null, 2), "utf-8");
773
- }
774
- async function generateVersion(module, mcVersion, isBeta) {
775
- if (!cacheData) {
776
- try {
777
- const txt = await fs$1.promises.readFile(cacheFile, "utf-8");
778
- cacheData = JSON.parse(txt);
779
- }
780
- catch {
781
- await refresh();
782
- }
783
- }
784
- if (!cacheData) {
785
- throw new Error("unable to load sapi cache data");
786
- }
787
- // try exact match first
788
- let entry = cacheData.find((e) => e.version === mcVersion);
789
- if (!entry) {
790
- // find closest entry less than or equal to requested version
791
- const sorted = cacheData.slice();
792
- let candidate = null;
793
- for (const e of sorted) {
794
- if (compareVersion(e.version, mcVersion) <= 0) {
795
- candidate = e;
796
- }
797
- else {
798
- break;
799
- }
800
- }
801
- if (!candidate) {
802
- candidate = sorted[0];
803
- }
804
- entry = candidate;
805
- }
806
- const moduleKey = module === "@minecraft/server" ? "server" : "server-ui";
807
- const entryModule = entry[moduleKey];
808
- let result = isBeta ? entryModule.beta : entryModule.formal;
809
- if (!result) {
810
- // fall back to whatever is available
811
- result = entryModule.formal || entryModule.beta;
812
- }
813
- return result || "";
814
- }
815
- return {
816
- refresh,
817
- generateVersion,
818
- };
819
- })();
820
-
821
- async function generateManifest(config, type) {
822
- const manifest = {
823
- format_version: 2,
824
- header: {
825
- name: config.name,
826
- description: config.description,
827
- uuid: fromString(config.name, BuildConfig.salt.header + type),
828
- version: stringToNumberArray(config.version),
829
- min_engine_version: stringToNumberArray(typeof config.mcVersion === "string"
830
- ? config.mcVersion
831
- : (() => {
832
- throw new Error("mcVersion in mblerconfig should be a string");
833
- })()),
834
- },
835
- modules: [
836
- {
837
- type: type,
838
- uuid: fromString(config.name, BuildConfig.salt.module + type),
839
- description: `From Mbler(https://github.com/RuanhoR/mbler). welcome to star and contribute!`,
840
- version: stringToNumberArray(config.version),
841
- },
842
- ],
843
- };
844
- if (type === "data" && config.script) {
845
- manifest.modules.push({
846
- type: "script",
847
- uuid: fromString(config.name, BuildConfig.salt.sapi + type),
848
- description: `sapi generate by mbler, weclome to download and star at https://github.com/RuanhoR/mbler`,
849
- version: stringToNumberArray(config.version),
850
- });
851
- manifest.capabilities = ["script_eval"];
852
- manifest.dependencies = [
853
- {
854
- module_name: "@minecraft/server",
855
- version: (await exp.generateVersion("@minecraft/server", config.mcVersion, config.script?.UseBeta || false)).split("-")[0], // only major.minor.patch, remove -beta or -rc
856
- },
857
- ];
858
- if (config.script.ui) {
859
- manifest.dependencies.push({
860
- module_name: "@minecraft/server-ui",
861
- version: (await exp.generateVersion("@minecraft/server-ui", config.mcVersion, config.script?.UseBeta || false)).split("-")[0], // only major.minor.patch, remove -beta or -rc
862
- });
863
- }
864
- }
865
- return manifest;
866
- }
867
-
868
- function createFullZip(dir) {
869
- const zip = new AdmZip();
870
- zip.addLocalFolder(dir);
871
- return zip;
872
- }
873
- async function createZipWithMoreFolder(dir) {
874
- const zip = new AdmZip();
875
- for (const folder of dir) {
876
- await zip.addLocalFolderPromise(folder[0], {
877
- zipPath: folder[1]
878
- });
879
- }
880
- return zip;
881
- }
882
- async function generateRelease(build) {
883
- if (!build.srcDirs)
884
- throw new Error("invaild Build");
885
- if (env.BUILD_MODULE !== "release")
886
- return;
887
- let zip;
888
- if (build.module == "all") {
889
- zip = await createZipWithMoreFolder([
890
- [build.srcDirs?.behavior, "behavior"],
891
- [build.srcDirs.resources, "resources"]
892
- ]);
893
- }
894
- else if (build.module == "behavior") {
895
- zip = createFullZip(build.srcDirs.behavior);
896
- }
897
- else {
898
- zip = createFullZip(build.srcDirs.resources);
899
- }
900
- await zip.writeZipPromise(build.outdirs?.dist);
901
- }
902
-
903
- // cjs support
904
- const chalk$1 = _chalk instanceof Function ? _chalk : _chalk.default;
905
- class Postgress {
906
- max;
907
- constructor(max) {
908
- this.max = max;
909
- }
910
- update(current) {
911
- const percentage = Math.min(current, this.max) / this.max;
912
- const barWidth = 30;
913
- const filledWidth = Math.round(barWidth * percentage);
914
- const emptyWidth = barWidth - filledWidth;
915
- const filledBar = chalk$1.green('█'.repeat(filledWidth));
916
- const emptyBar = chalk$1.white('█'.repeat(emptyWidth));
917
- const progressBar = `${filledBar}${emptyBar}`;
918
- const percentText = chalk$1.blue(`${Math.round(percentage * 100)}%`);
919
- const progressText = `\n\u001B[1A\r[${progressBar}] ${percentText} (${current}/${this.max})`;
920
- showText(progressText, false);
921
- if (current == this.max) {
922
- showText("", true);
923
- }
924
- }
925
- }
926
-
927
- /**
928
- * 运行 MCX TypeScript 编译器
929
- * 为 .mcx 文件提供 TypeScript 类型检查支持
930
- */
931
- function runTSC(tscpath = require.resolve("typescript/lib/tsc")) {
932
- runTsc(tscpath, {
933
- extraSupportedExtensions: ['.mcx'],
934
- extraExtensionsToRemove: ['.mcx'],
935
- }, (ts) => {
936
- return [createMCXLanguagePlugin(ts)];
937
- });
938
- }
939
-
940
- // cjs support
941
- const chalk = _chalk instanceof Function ? _chalk : _chalk.default;
942
- class Build {
943
- baseBuildDir;
944
- resolve;
945
- isWatch;
946
- currentConfig = null;
947
- srcDirs = null;
948
- outdirs = null;
949
- mcxTs;
950
- mcxLanguagePluginCreator = null;
951
- constructor(opts, baseBuildDir, resolve, isWatch = false) {
952
- this.baseBuildDir = baseBuildDir;
953
- this.resolve = resolve;
954
- this.isWatch = isWatch;
955
- // 初始化 MCX 语言插件创建器,传入 tsHook.ts 使用
956
- try {
957
- const tsModule = require("typescript");
958
- this.mcxLanguagePluginCreator = createMCXLanguagePlugin;
959
- this.mcxTs = tsModule;
960
- Logger.i("Build", "MCX Volar language plugin creator initialized successfully");
961
- }
962
- catch (error) {
963
- this.mcxTs = require("typescript");
964
- Logger.w("Build", `Failed to initialize MCX language plugin: ${error}`);
965
- }
966
- }
967
- /**
968
- * Start the watch mode.
969
- * This will perform an initial build (if not already done) and then
970
- * start filesystem and rollup watchers.
971
- * Returns the watcher handles once they are created so that callers
972
- * (for example tests) can clean them up later.
973
- */
974
- async watch() {
975
- try {
976
- onEnd(() => {
977
- if (this.watchers) {
978
- this.watchers.chokidar.close();
979
- this.watchers.rollup.close();
980
- }
981
- });
982
- await this._watch();
983
- }
984
- catch (e) {
985
- if (e instanceof Error) {
986
- Logger.e('Watcher', e.stack || e.message);
987
- }
988
- else {
989
- Logger.e('Watcher', e + '');
990
- }
991
- showText('MBLER__ERR__WATCHER: ' + e + ' Log at ' + Logger.LogFile);
992
- this.resolve(1);
993
- return null;
994
- }
995
- }
996
- async start() {
997
- try {
998
- return await this.build();
999
- }
1000
- catch (e) {
1001
- if (e instanceof Error) {
1002
- Logger.e('Build', e.stack || e.message);
1003
- }
1004
- else {
1005
- Logger.e('Build', e + '');
1006
- }
1007
- showText('MBLER__ERR__BUILD: ' + e.stack + ' Log at ' + Logger.LogFile);
1008
- this.resolve(1);
1009
- }
1010
- }
1011
- /**
1012
- * Handles returned from the currently-active watchers.
1013
- * Set by {@link createWatcher} and exposed via {@link getWatchers}
1014
- * so that external callers can close them when necessary (e.g. tests).
1015
- */
1016
- watchers = null;
1017
- /**
1018
- * Returns the watcher handles if watch mode has been started.
1019
- * Can be safely called even before `watch()` has been invoked.
1020
- */
1021
- getWatchers() {
1022
- return this.watchers;
1023
- }
1024
- /**
1025
- * Close any active watchers. The build process does not automatically
1026
- * terminate the watchers unless the process exits; tests or CLI wrappers
1027
- * can call this method to clean up resources.
1028
- */
1029
- closeWatchers() {
1030
- if (this.watchers) {
1031
- this.watchers.chokidar.close();
1032
- this.watchers.rollup.close();
1033
- this.watchers = null;
1034
- }
1035
- }
1036
- rollupPlugin = null;
1037
- init = false;
1038
- /**
1039
- * Which modules are present in the current project.
1040
- * - "behavior" when only behavior code exists
1041
- * - "resources" when only resource files exist
1042
- * - "all" when both are present
1043
- * This field is populated during `handlerOtherAddon`.
1044
- */
1045
- module = null;
1046
- /**
1047
- * Determine whether a path refers to a regular file or a directory.
1048
- * Follows symbolic links recursively. Throws if the path exists but
1049
- * is not one of the expected types.
1050
- *
1051
- * @param filePath file system path to inspect
1052
- * @returns "file" or "directory"
1053
- */
1054
- async fileType(filePath) {
1055
- const stat = await fs.lstat(filePath);
1056
- if (stat.isFile()) {
1057
- return 'file';
1058
- }
1059
- if (stat.isDirectory()) {
1060
- return 'directory';
1061
- }
1062
- if (stat.isSymbolicLink()) {
1063
- return await this.fileType(await fs.readlink(filePath));
1064
- }
1065
- throw new Error('[build addon]: invaild file type');
1066
- }
1067
- /**
1068
- * Perform a single build of the project located at {@link baseBuildDir}.
1069
- * The process is roughly:
1070
- * 1. load and validate the configuration file
1071
- * 2. prepare source and output directory information
1072
- * 3. copy addon files (behavior/resources)
1073
- * 4. generate manifest.json files
1074
- * 5. run rollup to bundle any script entry point
1075
- *
1076
- * If anything goes wrong the promise returned by the public wrapper
1077
- * (`build()` function exported at the bottom of this file) will be
1078
- * resolved with a non-zero code and appropriate log entries will be
1079
- * emitted.
1080
- */
1081
- async build() {
1082
- const progress = new Postgress(100);
1083
- this.init = true;
1084
- if (!isAbsolute(this.baseBuildDir)) {
1085
- throw new Error('[init build]: build dir is not absolute path');
1086
- }
1087
- this.currentConfig = await ReadProjectMblerConfig(this.baseBuildDir);
1088
- this.loadData();
1089
- if (!this.isWatch)
1090
- progress.update(10);
1091
- await this.handlerOtherAddon();
1092
- await this.handlerManifest();
1093
- if (!this.isWatch)
1094
- progress.update(30);
1095
- const rBuild = (await this.createRollup());
1096
- if (!this.rollupPlugin || !this.outdirs) {
1097
- throw new Error(`[build addon]: can't resolve rollup instance`);
1098
- }
1099
- if (!this.isWatch)
1100
- progress.update(50);
1101
- // write script
1102
- let output = this.currentConfig.script?.main;
1103
- if (!output)
1104
- output = "index.js";
1105
- if (path__default.extname(output) !== "js")
1106
- output = output.slice(0, output.length - path__default.extname(output).length) + ".js";
1107
- if (this.currentConfig.script)
1108
- await rBuild.write({
1109
- file: join(path__default.join(this.outdirs.behavior, "scripts"), output),
1110
- format: 'esm',
1111
- sourcemap: false,
1112
- });
1113
- if (!this.isWatch)
1114
- progress.update(70);
1115
- await generateRelease(this);
1116
- if (!this.isWatch)
1117
- progress.update(80);
1118
- if (!this.isWatch)
1119
- this.resolve(0);
1120
- if (!this.isWatch)
1121
- progress.update(100);
1122
- }
1123
- /**
1124
- * Create and return a Rollup build instance configured for the
1125
- * project's script. The Rollup configuration mirrors the options
1126
- * used by the CLI when running manual builds.
1127
- *
1128
- * Returns undefined if the project does not define a script section
1129
- * (in which case nothing needs to be bundled).
1130
- */
1131
- async createRollup() {
1132
- if (!this.currentConfig || !this.srcDirs || !this.outdirs)
1133
- throw new Error(`[build addon]: can't first can this method`);
1134
- if (!this.currentConfig.script)
1135
- return;
1136
- const main = path__default.join(this.srcDirs.behavior, 'scripts', this.currentConfig.script.main);
1137
- if (!(await FileExsit(main))) {
1138
- throw new Error(`[build addon]: main script ${main} is not exist: can't resolve entry`);
1139
- }
1140
- const plugin = [
1141
- jsonPlugin(),
1142
- resolvePlugin({
1143
- extensions: ['.ts', '.js', '.json'],
1144
- }),
1145
- commonjs()
1146
- ];
1147
- const moduleDir = path__default.join(this.baseBuildDir, 'node_modules');
1148
- if (!(await FileExsit(moduleDir))) {
1149
- throw new Error(`[build addon]: node_modules is not exist in project root: can't resolve node_modules for rollup: ${moduleDir}`);
1150
- }
1151
- if (this.currentConfig.minify) {
1152
- plugin.push(minifyPlugin({
1153
- format: {
1154
- comments: false,
1155
- },
1156
- compress: {
1157
- unused: true,
1158
- },
1159
- }));
1160
- }
1161
- if (this.currentConfig.script.lang == "ts") {
1162
- const tsconfigPath = path__default.join(this.baseBuildDir, 'tsconfig.json');
1163
- if (!(await FileExsit(tsconfigPath))) {
1164
- throw new Error(`[build addon]: ts-lang: tsconfig.json is not exist in project root: can't resolve tsconfig for rollup: ${tsconfigPath}`);
1165
- }
1166
- plugin.push(typescript({
1167
- sourceMap: false,
1168
- tsconfig: tsconfigPath,
1169
- exclude: [
1170
- this.outdirs.behavior,
1171
- this.outdirs.resources
1172
- ],
1173
- include: [
1174
- this.srcDirs.behavior
1175
- ]
1176
- }));
1177
- }
1178
- if (this.currentConfig.script?.lang == 'mcx') {
1179
- try {
1180
- const tsconfigPath = path__default.join(this.baseBuildDir, 'tsconfig.json');
1181
- if (!(await FileExsit(tsconfigPath))) {
1182
- throw new Error(`[build addon]: ts-lang: tsconfig.json is not exist in project root: can't resolve tsconfig for rollup: ${tsconfigPath}`);
1183
- }
1184
- const pluginConfig = {
1185
- moduleDir: moduleDir,
1186
- tsconfigPath: tsconfigPath,
1187
- sourcemap: false,
1188
- ts: this.mcxTs,
1189
- mcxLanguagePlugin: this.mcxLanguagePluginCreator
1190
- };
1191
- if (this.mcxLanguagePluginCreator) {
1192
- pluginConfig.mcxLanguagePlugin = this.mcxLanguagePluginCreator;
1193
- }
1194
- plugin.push(mcxDef.plugin(pluginConfig, this.outdirs));
1195
- }
1196
- catch (err) {
1197
- throw new Error(`[build addon]: mcx plugin is required but '@mbler/mcx-core' could not be loaded: ${err}`);
1198
- }
1199
- }
1200
- // save plugin array for watcher re-use
1201
- this.rollupPlugin = plugin;
1202
- return await rollup.rollup({
1203
- input: main,
1204
- external: ['@minecraft/server', '@minecraft/server-ui'],
1205
- plugins: plugin,
1206
- });
1207
- }
1208
- /**
1209
- * Internal helper invoked by {@link watch}.
1210
- * Ensures a build has been run before starting the watchers.
1211
- */
1212
- async _watch() {
1213
- // init build
1214
- if (!this.init) {
1215
- await this.build();
1216
- }
1217
- this.createWatcher();
1218
- // watchers field is populated by createWatcher
1219
- }
1220
- isParent(parent, dir) {
1221
- const relative = path__default.relative(parent, dir);
1222
- return (!!relative && !relative.startsWith('..') && !path__default.isAbsolute(relative));
1223
- }
1224
- isChange(oldObj, newObj, checkKeys) {
1225
- for (const key of checkKeys) {
1226
- if (typeof oldObj[key] === 'object' &&
1227
- typeof newObj[key] === 'object' &&
1228
- oldObj[key] !== null &&
1229
- newObj[key] !== null) {
1230
- if (this.isChange(oldObj[key], newObj[key], Object.getOwnPropertyNames(oldObj[key]))) {
1231
- return true;
1232
- }
1233
- }
1234
- else if (oldObj[key] !== newObj[key]) {
1235
- return true;
1236
- }
1237
- }
1238
- return false;
1239
- }
1240
- createRollupWatcher() {
1241
- if (!this.srcDirs ||
1242
- !this.outdirs ||
1243
- !this.currentConfig ||
1244
- !this.rollupPlugin)
1245
- throw new Error(`[build addon]: can't first can this method`);
1246
- let output = this.currentConfig.script?.main;
1247
- if (!output)
1248
- output = "index.js";
1249
- if (path__default.extname(output) !== "js")
1250
- output = output.slice(0, output.length - path__default.extname(output).length) + ".js";
1251
- const rollupWatcher = rollup.watch({
1252
- input: path__default.join(this.srcDirs.behavior, 'scripts', this.currentConfig?.script?.main || ''),
1253
- external: ['@minecraft/server', '@minecraft/server-ui'],
1254
- plugins: this.rollupPlugin,
1255
- output: {
1256
- file: join(path__default.join(this.outdirs.behavior, "scripts"), output),
1257
- format: 'esm',
1258
- sourcemap: false,
1259
- },
1260
- cache: true,
1261
- watch: {
1262
- clearScreen: false,
1263
- include: path__default.join(this.srcDirs.behavior, 'scripts/**/*'),
1264
- exclude: [
1265
- path__default.join(this.baseBuildDir, 'node_modules/**/*'),
1266
- this.outdirs.behavior,
1267
- this.outdirs.resources,
1268
- this.outdirs.dist,
1269
- ],
1270
- },
1271
- });
1272
- rollupWatcher.on('change', async (filePath) => {
1273
- Logger.i('Watcher', `file changed: ${filePath}, start rebuild`);
1274
- });
1275
- rollupWatcher.on('event', async (event) => {
1276
- if (event.code === 'ERROR') {
1277
- Logger.e('Watcher', `rollup error: ${event.error.stack || event.error}`);
1278
- showText('MBLER__ERR__ROLLUP: ' +
1279
- (event.error.stack || event.error) +
1280
- ' Log at ' +
1281
- Logger.LogFile);
1282
- }
1283
- else if (event.code === 'END') {
1284
- Logger.i('Watcher', `rebuild success`);
1285
- }
1286
- });
1287
- return rollupWatcher;
1288
- }
1289
- async onChange(filePath) {
1290
- if (!this.srcDirs ||
1291
- !this.outdirs ||
1292
- !this.currentConfig ||
1293
- !this.rollupPlugin ||
1294
- !this.watchers)
1295
- throw new Error(`[build addon]: can't first can this method`);
1296
- const isConfigChange = path__default.relative(path__default.join(this.baseBuildDir, 'mbler.config.json'), filePath) === '';
1297
- const isBehaviorChange = this.isParent(this.srcDirs.behavior, filePath) && !this.isParent(path__default.join(this.srcDirs.behavior, 'scripts'), filePath);
1298
- const isResourcesChange = this.isParent(this.srcDirs.resources, filePath);
1299
- if (isConfigChange) {
1300
- const oldConfig = this.currentConfig;
1301
- Logger.i('Watcher', 'detected mbler.config.json change, reload config');
1302
- this.currentConfig = await ReadProjectMblerConfig(this.baseBuildDir);
1303
- this.loadData();
1304
- if (this.isChange(oldConfig, this.currentConfig, [
1305
- 'name',
1306
- 'version',
1307
- 'description',
1308
- 'mcVersion',
1309
- ])) {
1310
- await this.handlerManifest();
1311
- }
1312
- if (this.isChange(oldConfig, this.currentConfig, ['script', 'outdir'])) {
1313
- this.watchers.rollup.close();
1314
- await this.createRollup();
1315
- this.watchers.rollup = rollup.watch({
1316
- input: path__default.join(this.srcDirs.behavior, 'scripts', this.currentConfig?.script?.main || ''),
1317
- external: ['@minecraft/server', '@minecraft/server-ui'],
1318
- plugins: this.rollupPlugin,
1319
- output: {
1320
- file: path__default.join(this.outdirs.behavior, 'scripts', this.currentConfig?.script?.main || ''),
1321
- format: 'esm',
1322
- },
1323
- });
1324
- }
1325
- }
1326
- // if behavior or resources change, we can just copy the changed file instead of copy all files again.
1327
- if (isBehaviorChange || isResourcesChange) {
1328
- const handlerBP = async () => {
1329
- if (!this.srcDirs || !this.outdirs)
1330
- throw new Error(`[build addon]: can't first can this method`);
1331
- const relativePath = path__default.relative(this.srcDirs.behavior, filePath);
1332
- await fs.cp(path__default.join(this.srcDirs.behavior, relativePath), path__default.join(this.outdirs.behavior, relativePath), {
1333
- recursive: true,
1334
- force: true,
1335
- });
1336
- };
1337
- const handlerRP = async () => {
1338
- if (!this.srcDirs || !this.outdirs)
1339
- throw new Error(`[build addon]: can't first can this method`);
1340
- const relativePath = path__default.relative(this.srcDirs.resources, filePath);
1341
- await fs.cp(path__default.join(this.srcDirs.resources, relativePath), path__default.join(this.outdirs.resources, relativePath), {
1342
- recursive: true,
1343
- force: true,
1344
- });
1345
- };
1346
- if (isBehaviorChange) {
1347
- await handlerBP();
1348
- }
1349
- if (isResourcesChange) {
1350
- await handlerRP();
1351
- }
1352
- }
1353
- showText(`[${chalk.green('mbler')}] ${chalk.bgYellow(`file changed: ${filePath}`)}`);
1354
- }
1355
- createWatcher() {
1356
- if (!this.srcDirs || !this.outdirs || !this.rollupPlugin)
1357
- throw new Error(`[build addon]: can't first can this method`);
1358
- const chokidar = watch$1(this.baseBuildDir, {
1359
- ignored: [
1360
- this.outdirs.behavior,
1361
- this.outdirs.resources,
1362
- this.outdirs.dist,
1363
- path__default.join(this.baseBuildDir, 'node_modules'),
1364
- ],
1365
- ignoreInitial: true,
1366
- interval: 100,
1367
- });
1368
- const onChange = async (filePath) => {
1369
- await this.onChange(filePath);
1370
- };
1371
- chokidar.on('change', onChange);
1372
- const rollupWatcher = this.createRollupWatcher();
1373
- this.watchers = {
1374
- chokidar,
1375
- rollup: rollupWatcher,
1376
- };
1377
- }
1378
- async handlerManifest() {
1379
- if (!this.currentConfig || !this.outdirs || !this.srcDirs || !this.module)
1380
- throw new Error(`[build addon]: can't first can this method`);
1381
- const otherManifestOption = {
1382
- behavior: {},
1383
- resources: {},
1384
- };
1385
- const handlerBP = async () => {
1386
- if (!this.outdirs || !this.currentConfig)
1387
- throw new Error(`[build addon]: can't first can this method`);
1388
- const manifest = await generateManifest(this.currentConfig, 'data');
1389
- await writeJSON(path__default.join(this.outdirs.behavior, 'manifest.json'), {
1390
- ...manifest,
1391
- ...otherManifestOption.behavior,
1392
- });
1393
- };
1394
- const handlerRP = async () => {
1395
- if (!this.outdirs || !this.currentConfig)
1396
- throw new Error(`[build addon]: can't first can this method`);
1397
- const manifest = await generateManifest(this.currentConfig, 'resources');
1398
- await writeJSON(path__default.join(this.outdirs.resources, 'manifest.json'), {
1399
- ...manifest,
1400
- ...otherManifestOption.resources,
1401
- });
1402
- };
1403
- if (this.module == 'behavior' || this.module == 'all') {
1404
- const filePath = path__default.join(this.srcDirs.behavior, 'manifest.json');
1405
- if (await FileExsit(filePath)) {
1406
- try {
1407
- const content = await fs.readFile(filePath, 'utf-8');
1408
- const json = JSON.parse(content);
1409
- otherManifestOption.behavior = json;
1410
- }
1411
- catch (err) {
1412
- Logger.w('Build', 'invalid manifest.json in behavior');
1413
- }
1414
- }
1415
- await handlerBP();
1416
- }
1417
- if (this.module == 'resources' || this.module == 'all') {
1418
- const filePath = path__default.join(this.srcDirs.resources, 'manifest.json');
1419
- if (await FileExsit(filePath)) {
1420
- try {
1421
- const content = await fs.readFile(filePath, 'utf-8');
1422
- const json = JSON.parse(content);
1423
- otherManifestOption.resources = json;
1424
- }
1425
- catch (err) {
1426
- Logger.w('Build', 'invalid manifest.json in resources');
1427
- }
1428
- }
1429
- await handlerRP();
1430
- }
1431
- }
1432
- loadData() {
1433
- // check run time
1434
- if (!this.currentConfig || !this.baseBuildDir)
1435
- throw new Error("[build data]: can't resolve again");
1436
- // source code dir
1437
- this.srcDirs = {
1438
- behavior: path__default.join(this.baseBuildDir, BuildConfig.behavior),
1439
- resources: path__default.join(this.baseBuildDir, BuildConfig.resources), // res
1440
- };
1441
- // output dir
1442
- this.outdirs = {
1443
- behavior: this.currentConfig.outdir?.behavior
1444
- ? join(this.baseBuildDir, this.currentConfig.outdir.behavior)
1445
- : path__default.join(this.baseBuildDir, 'dist/dep'),
1446
- resources: this.currentConfig.outdir?.resources
1447
- ? join(this.baseBuildDir, this.currentConfig.outdir.resources)
1448
- : path__default.join(this.baseBuildDir, 'dist/res'),
1449
- dist: this.currentConfig.outdir?.dist
1450
- ? join(this.baseBuildDir, this.currentConfig.outdir.dist)
1451
- : path__default.join(this.baseBuildDir, 'dist-pkg'),
1452
- };
1453
- }
1454
- /**
1455
- * Copy the various files (behavior/resources) into the corresponding
1456
- * output directories and determine which modules exist in the project
1457
- * by inspecting the source directories.
1458
- */
1459
- async handlerOtherAddon() {
1460
- if (!this.srcDirs)
1461
- throw new Error("[build addon]: can't first can this method");
1462
- const isHasBp = await FileExsit(this.srcDirs.behavior);
1463
- if (!isHasBp)
1464
- throw new Error("[build addon]: can't resolve behavior");
1465
- // init copy resources
1466
- const handlerBP = async () => {
1467
- if (!this.srcDirs || !this.outdirs)
1468
- throw new Error("[build addon]: can't first can this method");
1469
- for (const f of await fs.readdir(this.srcDirs.behavior)) {
1470
- const fType = await this.fileType(path__default.join(this.srcDirs.behavior, f));
1471
- const includeType = BuildConfig.includes.behavior[f] || BuildConfig.includes.public[f];
1472
- if (includeType == fType) {
1473
- await fs.cp(path__default.join(this.srcDirs.behavior, f), path__default.join(this.outdirs.behavior, f), {
1474
- recursive: true,
1475
- force: true,
1476
- });
1477
- }
1478
- else if (includeType == 'skip') {
1479
- continue;
1480
- }
1481
- else {
1482
- throw new Error(`[build addon]: invaild file: ${path__default.join(this.srcDirs.behavior, f)}: type: ${fType}`);
1483
- }
1484
- }
1485
- };
1486
- const handlerRP = async () => {
1487
- if (!this.srcDirs || !this.outdirs)
1488
- throw new Error("[build addon]: can't first can this method");
1489
- for (const f of await fs.readdir(this.srcDirs.resources)) {
1490
- const fType = await this.fileType(path__default.join(this.srcDirs.resources, f));
1491
- const includeType = BuildConfig.includes.resources[f] || BuildConfig.includes.public[f];
1492
- if (includeType == fType) {
1493
- await fs.cp(path__default.join(this.srcDirs.resources, f), path__default.join(this.outdirs.resources, f), {
1494
- recursive: true,
1495
- force: true,
1496
- });
1497
- }
1498
- else if (includeType == 'skip') {
1499
- continue;
1500
- }
1501
- else {
1502
- throw new Error(`[build addon]: invaild file: ${path__default.join(this.srcDirs.resources, f)}: type: ${fType}`);
1503
- }
1504
- }
1505
- };
1506
- const tasks = [];
1507
- if (await FileExsit(this.srcDirs.behavior)) {
1508
- this.module = 'behavior';
1509
- tasks.push(handlerBP());
1510
- }
1511
- if (await FileExsit(this.srcDirs.resources)) {
1512
- if (this.module == 'behavior') {
1513
- this.module = 'all';
1514
- }
1515
- else {
1516
- this.module = 'resources';
1517
- }
1518
- tasks.push(handlerRP());
1519
- }
1520
- if (!this.module) {
1521
- throw new Error("[build addon]: couldn't resolve source code(your behaivor or reources code is not found)");
1522
- }
1523
- await Promise.all(tasks);
1524
- }
1525
- }
1526
- function build(cliParam, work) {
1527
- return new Promise((resolve) => {
1528
- new Build(cliParam.opts, work, resolve).start();
1529
- });
1530
- }
1531
- function watch(cliParam, work) {
1532
- return new Promise((resolve, reject) => {
1533
- try {
1534
- const build = new Build(cliParam.opts, work, resolve, true);
1535
- build.start().then(() => {
1536
- build.watch();
1537
- showText(`[${chalk.green('mbler')}] ${chalk.bgYellow('watching for file changes...')}`);
1538
- });
1539
- }
1540
- catch (err) {
1541
- if (err instanceof Error) {
1542
- reject(`[watcher]: error ${err.stack || err.message}`);
1543
- }
1544
- else {
1545
- reject(err);
1546
- }
1547
- }
1548
- });
1549
- }
1550
-
1551
- var index = /*#__PURE__*/Object.freeze({
1552
- __proto__: null,
1553
- Build: Build,
1554
- McxTsc: runTSC,
1555
- build: build,
1556
- default: Build,
1557
- watch: watch
1558
- });
1559
-
1560
- async function tryMkdir(point) {
1561
- try {
1562
- await mkdir(point);
1563
- return true;
1564
- }
1565
- catch {
1566
- return false;
1567
- }
1568
- }
1569
- class WorkDirManage {
1570
- cacheDir;
1571
- currentWorkPoint = null;
1572
- enabledPath = path__default.join(homedir(), ".cache/mbler/workdir_enabled.db");
1573
- constructor(cacheDir = path__default.join(homedir(), ".cache/mbler/mp.db")) {
1574
- this.cacheDir = cacheDir;
1575
- }
1576
- async isDisabled() {
1577
- try {
1578
- await readFile(this.enabledPath, "utf-8");
1579
- return false; // 文件存在,表示启用
1580
- }
1581
- catch {
1582
- return true; // 文件不存在,默认禁用
1583
- }
1584
- }
1585
- async setDisabled(disabled) {
1586
- if (!disabled) {
1587
- // 启用:创建文件
1588
- await writeFile(this.enabledPath, "1", { encoding: "utf-8" });
1589
- }
1590
- else {
1591
- try {
1592
- await unlink(this.enabledPath);
1593
- }
1594
- catch {
1595
- // 文件不存在,忽略
1596
- }
1597
- }
1598
- }
1599
- async set(newPointDir) {
1600
- // check
1601
- try {
1602
- const s = await stat(newPointDir);
1603
- if (!s.isDirectory()) {
1604
- throw new Error("Not Dir (0xcvb)");
1605
- }
1606
- }
1607
- catch (err) {
1608
- const code = err.code;
1609
- if (err.message && err.message.includes("0xcvb"))
1610
- return i18n.workdir.nfound;
1611
- if (code == "ENOENT") {
1612
- const res = tryMkdir(newPointDir);
1613
- if (!res) {
1614
- return i18n.workdir.nfound;
1615
- }
1616
- }
1617
- }
1618
- try {
1619
- if (!(await FileExsit(path__default.dirname(this.cacheDir)))) {
1620
- const isC = await tryMkdir(path__default.dirname(this.cacheDir));
1621
- if (!isC)
1622
- return i18n.workdir.nfound;
1623
- }
1624
- await writeFile(this.cacheDir, newPointDir, {
1625
- encoding: "utf-8",
1626
- });
1627
- }
1628
- catch (err) {
1629
- Logger.e("WorkDir", err.stack);
1630
- }
1631
- return i18n.workdir.set + newPointDir;
1632
- }
1633
- async get() {
1634
- if (await this.isDisabled()) {
1635
- return cwd();
1636
- }
1637
- if (this.currentWorkPoint) {
1638
- return this.currentWorkPoint;
1639
- }
1640
- const file = await readFile(this.cacheDir, "utf-8").catch((e) => {
1641
- this.set(cwd());
1642
- return cwd();
1643
- });
1644
- return (this.currentWorkPoint = file);
1645
- }
1646
- }
1647
-
1648
- async function isInit(dir) {
1649
- return (await Promise.all([BuildConfig.ConfigFile, 'package.json', 'behavior'].map((item) => {
1650
- return FileExsit(path__default.join(dir, item));
1651
- }))).every((value) => {
1652
- return value;
1653
- });
1654
- }
1655
- async function findTemplatedir() {
1656
- if (await FileExsit(path__default.join(__dirname, '../template')))
1657
- return path__default.join(__dirname, '../template');
1658
- if (await FileExsit(path__default.join(__dirname, './template')))
1659
- return path__default.join(__dirname, './template');
1660
- }
1661
- async function initCommand(cliParam, workdir) {
1662
- await exp.refresh();
1663
- const cmdParams = cliParam.params.slice(1);
1664
- if (await isInit(workdir)) {
1665
- return 0;
1666
- }
1667
- showText(i18n.init.welcome);
1668
- const initOpts = {
1669
- name: cmdParams[0] || (await input(i18n.init.name)),
1670
- description: cmdParams[1] || (await input(i18n.init.description)),
1671
- lang: (cmdParams[2] ||
1672
- (await Input.select(i18n.init.lang, ['ts', 'js', 'mcx']))),
1673
- initDeependencies: await Input.select(i18n.init.initDes, [
1674
- 'no',
1675
- 'pnpm',
1676
- 'npm',
1677
- ]),
1678
- useUI: (await input(i18n.init.useUI)) === 'y',
1679
- useGIT: (await input(i18n.init.useGIT)) === 'y',
1680
- useBetaApi: (await input(i18n.init.betaApi)) === 'y',
1681
- mcVersion: await input(i18n.init.mcVersion),
1682
- };
1683
- if (!initOpts.name) {
1684
- showText(i18n.init.noName);
1685
- return 1;
1686
- }
1687
- if (!initOpts.lang) {
1688
- showText(i18n.init.noLanguare);
1689
- return 1;
1690
- }
1691
- if (!initOpts.mcVersion || !isVaildVersion(initOpts.mcVersion)) {
1692
- showText(i18n.init.noMCVersion);
1693
- return 1;
1694
- }
1695
- const mblerConfig = {
1696
- name: initOpts.name,
1697
- description: initOpts.description,
1698
- version: '0.0.0',
1699
- script: {
1700
- lang: initOpts.lang,
1701
- main: 'index.js',
1702
- ui: initOpts.useUI,
1703
- UseBeta: initOpts.useBetaApi,
1704
- },
1705
- mcVersion: initOpts.mcVersion,
1706
- minify: false,
1707
- };
1708
- const packageJSON = {
1709
- name: initOpts.name,
1710
- version: '0.0.0',
1711
- description: initOpts.description,
1712
- module: 'module',
1713
- scripts: {
1714
- build: 'mcx-tsc && BUILD_MODULE=release mbler build',
1715
- 'dev:build': 'mbler build',
1716
- install: 'pnpm i -g mbler',
1717
- watch: 'mbler watch',
1718
- },
1719
- devDependencies: {
1720
- '@minecraft/server': await exp.generateVersion('@minecraft/server', initOpts.mcVersion, initOpts.useBetaApi),
1721
- },
1722
- };
1723
- if (initOpts.useUI) {
1724
- packageJSON.devDependencies['@minecraft/server-ui'] =
1725
- await exp.generateVersion('@minecraft/server-ui', initOpts.mcVersion, initOpts.useBetaApi);
1726
- }
1727
- const tsconfig = {
1728
- compilerOptions: {
1729
- module: 'nodenext',
1730
- noEmit: true,
1731
- target: 'esnext',
1732
- types: ["@mbler/mcx-core/client"],
1733
- sourceMap: true,
1734
- declaration: true,
1735
- declarationMap: false,
1736
- noUncheckedIndexedAccess: true,
1737
- exactOptionalPropertyTypes: true,
1738
- allowJs: true,
1739
- strict: true,
1740
- moduleResolution: 'nodenext',
1741
- verbatimModuleSyntax: false,
1742
- isolatedModules: true,
1743
- noUncheckedSideEffectImports: true,
1744
- moduleDetection: 'force',
1745
- skipLibCheck: true,
1746
- },
1747
- include: ['./behavior/scripts/**/*'],
1748
- };
1749
- const mblerConfigPath = path__default.join(workdir, BuildConfig.ConfigFile);
1750
- const packageJSONPath = path__default.join(workdir, 'package.json');
1751
- const tsconfigPath = path__default.join(workdir, 'tsconfig.json');
1752
- if (initOpts.lang == 'mcx') {
1753
- mblerConfig.script.main = 'index.mjs';
1754
- packageJSON.devDependencies['@mbler/mcx'] = config.mcxVersion;
1755
- }
1756
- if (initOpts.lang !== 'js') {
1757
- await writeJSON(tsconfigPath, tsconfig);
1758
- }
1759
- await writeJSON(packageJSONPath, packageJSON);
1760
- await writeJSON(mblerConfigPath, `import { defineConfig } from "mbler";\nexport default ${JSON.stringify(mblerConfig, null, 2)}`);
1761
- // write template
1762
- const templatedir = await findTemplatedir();
1763
- if (!templatedir) {
1764
- showText("can't find template folder");
1765
- return 1;
1766
- }
1767
- const templateTagerFolder = path__default.join(templatedir, initOpts.lang);
1768
- if (!(await FileExsit(templateTagerFolder))) {
1769
- showText("can't resolve template folder");
1770
- return 1;
1771
- }
1772
- const tasks = [];
1773
- for (const item of await readdir(templateTagerFolder)) {
1774
- tasks.push(cp(path__default.join(templateTagerFolder, item), path__default.join(workdir, item), {
1775
- recursive: true,
1776
- force: true,
1777
- }));
1778
- }
1779
- await Promise.all(tasks);
1780
- tasks.length = 0;
1781
- if (initOpts.initDeependencies !== 'no') {
1782
- tasks.push(runCommand([initOpts.initDeependencies, 'install'], workdir, 'pipe'));
1783
- }
1784
- if (initOpts.useGIT) {
1785
- tasks.push(runCommand(['git', 'init', '-b', 'main'], workdir, 'pipe'));
1786
- }
1787
- await Promise.all(tasks);
1788
- tasks.length = 0;
1789
- return 0;
1790
- }
1791
-
1792
- async function handlerVersion(cliParam, workdir) {
1793
- if (cliParam.params.length > 1) {
1794
- if (!await FileExsit(workdir)) {
1795
- showText("can't set workdir version, because not exists");
1796
- return 1;
1797
- }
1798
- const version = cliParam.params[1];
1799
- if (!version || !isVaildVersion(version)) {
1800
- showText("can't set version, it is not a vaild version");
1801
- return 1;
1802
- }
1803
- const pkgJSON = await readFileAsJson(path.join(workdir, "package.json"));
1804
- const mblerConfigJSON = await readFileAsJson(path.join(workdir, BuildConfig.ConfigFile));
1805
- mblerConfigJSON.version = pkgJSON.version = version;
1806
- }
1807
- else {
1808
- showVersion(cliParam);
1809
- }
1810
- return 0;
1811
- }
1812
- function showVersion(cliParam) {
1813
- let show = "";
1814
- if (Object.getOwnPropertyNames(cliParam.opts).length < 1) {
1815
- show = `commit: ${MBLERVersion.commit}\nversion: ${MBLERVersion.version}`;
1816
- }
1817
- else if (cliParam.opts.show) {
1818
- if (cliParam.opts.show == "commit") {
1819
- show = `commit: ${MBLERVersion.commit}`;
1820
- }
1821
- else if (cliParam.opts.show == "version") {
1822
- show = `version: ${MBLERVersion.version}`;
1823
- }
1824
- else {
1825
- show = 'invaild "show" param';
1826
- }
1827
- }
1828
- showText(show);
1829
- }
1830
-
1831
- function langCommand(cliParam, workdir) {
1832
- let show = '';
1833
- if (cliParam.params.length < 2) {
1834
- show = i18n.__internal.class.currenyLang;
1835
- }
1836
- else {
1837
- i18n.__internal.set(cliParam.params[1]);
1838
- show = i18n.__internal.class.currenyLang;
1839
- }
1840
- showText(show);
1841
- return 0;
1842
- }
1843
-
1844
- // `showText` moved to `utils` to avoid circular dependency with `build`.
1845
- const main = (function () {
1846
- let currentWDManage;
1847
- function parseParam() {
1848
- const opts = {};
1849
- const params = [];
1850
- let InValue = null;
1851
- argv.slice(2).forEach((item, index, arr) => {
1852
- if (InValue) {
1853
- opts[InValue] = item;
1854
- InValue = null;
1855
- return;
1856
- }
1857
- if (item.startsWith('-')) {
1858
- InValue = item.slice(1);
1859
- if (index == arr.length - 1)
1860
- opts[InValue] = '';
1861
- }
1862
- else {
1863
- params.push(item);
1864
- }
1865
- });
1866
- return {
1867
- params,
1868
- opts,
1869
- };
1870
- }
1871
- function handlerHelp(cliParam, _) {
1872
- if (!cliParam || !_)
1873
- return 1;
1874
- const seeCmd = cliParam.params[1];
1875
- if (!seeCmd) {
1876
- showText(i18n.description);
1877
- return 0;
1878
- }
1879
- let text = i18n.help[seeCmd];
1880
- if (!text)
1881
- return 0;
1882
- if (text.startsWith('$')) {
1883
- text = i18n.help[text.slice(1)];
1884
- }
1885
- showText(text);
1886
- return 0;
1887
- }
1888
- function getMatchChance(a, b) {
1889
- let match = 0;
1890
- // b = 比较值,a = 待比较值
1891
- for (let i = 0; i < b.length; i++) {
1892
- if (a[i] == b[i])
1893
- match++;
1894
- }
1895
- return match / b.length;
1896
- }
1897
- async function handlerWorkDirCommand(cliParam, workDir) {
1898
- if (!currentWDManage)
1899
- return 0;
1900
- if (cliParam.params.length > 1) {
1901
- const newPointWorkDir = path__default.resolve(cliParam.params[1]);
1902
- showText(await currentWDManage.set(newPointWorkDir));
1903
- }
1904
- else {
1905
- showText(workDir);
1906
- }
1907
- return 0;
1908
- }
1909
- async function handlerSetWorkDirCommand(cliParam, _) {
1910
- if (!currentWDManage)
1911
- return 0;
1912
- const param = cliParam.params[1];
1913
- if (param === 'off') {
1914
- await currentWDManage.setDisabled(true);
1915
- showText(i18n.workdir.disabled);
1916
- }
1917
- else if (param === 'on') {
1918
- await currentWDManage.setDisabled(false);
1919
- showText(i18n.workdir.enabled);
1920
- }
1921
- else {
1922
- showText(i18n.workdir.invalidParam);
1923
- }
1924
- return 0;
1925
- }
1926
- function defaultCommand(commandcc) {
1927
- console.log(`\x1b[31m${i18n.default.unexpected}: ${commandcc}\x1b[0m`);
1928
- const didvalue = cmdList
1929
- .map((item) => getMatchChance(commandcc, item))
1930
- .reduce((acc, cur, index) => {
1931
- try {
1932
- if (cur > acc.max) {
1933
- return {
1934
- max: cur,
1935
- index: index,
1936
- indices: [],
1937
- }; // 更新最大值及索引
1938
- }
1939
- else if (cur === acc.max) {
1940
- acc.indices.push(index); // 记录重复最大值的索引
1941
- return acc;
1942
- }
1943
- }
1944
- catch (err) {
1945
- Logger.w('matchDefault', err.stack);
1946
- }
1947
- return acc;
1948
- }, {
1949
- max: -Infinity,
1950
- index: -1,
1951
- indices: [],
1952
- });
1953
- const value = cmdList[didvalue.index];
1954
- if (value)
1955
- console.log(`${i18n.default.youis} ${value}`);
1956
- }
1957
- return async function cli() {
1958
- const cliParam = parseParam();
1959
- const handlerBuild = async (cliParam, workDir) => {
1960
- return await build(cliParam, workDir);
1961
- };
1962
- const handlerWatch = async (cliParam, workDir) => {
1963
- return await watch(cliParam, workDir);
1964
- };
1965
- const cmdMap = {
1966
- help: handlerHelp,
1967
- h: handlerHelp,
1968
- work: handlerWorkDirCommand,
1969
- c: handlerWorkDirCommand,
1970
- build: handlerBuild,
1971
- watch: handlerWatch,
1972
- init: initCommand,
1973
- version: handlerVersion,
1974
- lang: langCommand,
1975
- 'set-work-dir': handlerSetWorkDirCommand
1976
- };
1977
- const cmd = cliParam.params[0];
1978
- if (cliParam.opts.cwp) {
1979
- currentWDManage = new WorkDirManage(path__default.resolve(cliParam.opts.cwp));
1980
- }
1981
- else {
1982
- currentWDManage = new WorkDirManage();
1983
- }
1984
- if (!cmd) {
1985
- handlerHelp(cliParam, await currentWDManage.get());
1986
- process.exit(0);
1987
- }
1988
- const handler = cmdMap[cmd];
1989
- if (typeof handler !== 'function') {
1990
- defaultCommand(cmd);
1991
- }
1992
- else {
1993
- const r = handler(cliParam, await currentWDManage.get());
1994
- if (r instanceof Promise) {
1995
- const code = await r;
1996
- process.exit(code);
1997
- }
1998
- else {
1999
- process.exit(r);
2000
- }
2001
- }
2002
- process.exit(0);
2003
- };
2004
- })();
2005
-
2006
- /**
2007
- * Define Mbler config with type
2008
- * @param {MblerConfigData} config - config
2009
- * @returns config
2010
- */
2011
- function defineConfig(config) {
2012
- return config;
2013
- }
2014
-
2015
- export { index as Build, types as Types, main as cli, index$1 as commander, defineConfig, index$2 as i18n };
1
+ import{cwd as e,argv as n}from"node:process";import*as t from"node:fs";import i from"node:fs";import*as r from"node:path";import o from"node:path";import*as a from"node:fs/promises";import s,{readFile as c,writeFile as l,unlink as u,stat as m,mkdir as d,readdir as p,cp as f}from"node:fs/promises";import h,{homedir as b,tmpdir as w}from"node:os";import*as g from"readline";import{json as y}from"npm-registry-fetch";import{spawn as v}from"node:child_process";const k=["zh","en"],x=["c","work","help","h","init","version","build","watch","lang","set-work-dir","publish","unpublish","install","uninstall","login"];var j=Object.freeze({__proto__:null,LanguageNames:k,cmdList:x,templateMblerConfig:{name:"demo",description:"demo",version:"0.0.0",mcVersion:"1.21.100",script:{main:""},minify:!1,outdir:{behavior:"",resources:"",dist:""}}}),_="commit da7bebe8ce53a502c75fcc7ad53e510fcb233137\nAuthor: Ruanhor <3915264929@qq.com>\nDate: Sun Apr 19 12:42:06 2026 +0800\n\n feat: use script config when init\n",D="0.2.1",I={description:`MBLER\nMinecraft Bedrock Edition\nAddon Bulider In Nodejs\n在基岩版我的世界上的 nodejs 构建工具\n命令 : ${x.join(", ")}\n帮助命令 : \n help\n 显示帮助信息\n 第二个参数为要查询的命令名称或空\n 别名: h\ngit https://github.com/RuanhoR/mbler/`,help:{cmds:x,help:"mbler [help/h] [?:查看的命令名称]\n - 查看帮助",h:"$help",work:"mbler [work/c] [?:相对或绝对路径]\n - 没有输入路径:查询当前工作目录\n - 输入路径:设置工作目录",c:"$work",init:"mbler init\n - 初始化当前工作目录,可使用 mbler work 指定工作目录或使用参数一次确定(例: mbler init -in ./)\n - 将会询问选项以完成初始化",build:"mbler build\n - 在工作目录执行构建",watch:"mbler watch\n - 启动构建并开启监视模式,文件变化会自动重新构建",lang:"mbler lang\n- 无参数:显示当前语言\n- 跟 zh 或 en(如 mbler lang en): 设置语言",version:"mbler version - 版本管理命令\n- 无参数:显示当前版本和提交哈希\n- --show=<commit|version>:筛选显示内容\n- <新版本号>:更新package.json和配置文件的版本","set-work-dir":"mbler set-work-dir <on|off>\n - on: 启用工作目录功能\n - off: 禁用工作目录功能,直接使用 process.cwd()",publish:"mbler publish\n - 将你的附加包发布到 pmnx\n- 参数:\n- -tag: 版本标签名称",uninstall:"mbler uninstall @<scope>/<name>@version\n从你的游戏中移除一个包",install:"mbler install @<scope>/<name>@version\n将一个包安装到你的游戏中",unpublish:"mbler unpublish @<scope>/<name>@version\n从 pmnx 取消发布一个包",login:"mbler login <?:token>\n使用 token 登录你的 pmnx 账户\n- 如果没有 token,会向你请求"},init:{useUI:"使用UI模块? (y/n): ",useGIT:"初始化GIT仓库? (y/n): ",name:"项目名称: ",welcome:"欢迎使用Mbler初始化向导 语言:中文 mbler 版本: "+D,description:"项目描述: ",initDes:"初始化依赖? (y/n): ",lang:"选择项目语言: ",betaApi:"使用Beta Api? (y/n): ",mcVersion:"项目使用的mc版本(x.x.x): ",noLanguare:"没有输入项目语言,这是必要的",noName:"没有项目名称,这是必要的",noMCVersion:"输入的 '支持的mc版本' 格式不对"},default:{unexpected:"不正确的命令,",youis:"你是否想说: "},workdir:{set:"[工作目录] 设置为: ",nfound:"找不到输入文件夹(无法创建或不是文件夹)",disabled:"工作目录功能已禁用,将使用当前目录",enabled:"工作目录功能已启用",invalidParam:"参数错误,请使用 on 或 off"}},P={description:"MBLER\nMinecraft Bedrock Edition\nAddon Bulider In Nodejs\nnodejs build tools on bedrock version of minecraft\nCommands: "+x.join(", ")+"\nHelp command:\n help\n Show help information\n The second parameter is the name of the command to be queried or empty\n Alias: -h, -help\n git https://github.com/RuanhoR/mbler/",help:{cmds:x,help:"mbler [help/h] [?: command name]\n - see tip",h:"$help",work:"mbler [work/c] [?: path]\n - No input path: see current work dir\n - input path: set as current dir",c:"$work",init:"mbler init\n - Init current work dir, you can use `mbler work` command or use command param(like be: mbler init -in ./)",build:"mbler build\n - perform a build using the library API",b:"$build",watch:"mbler watch\n - run build and enter watch mode; changes will trigger rebuilds",lang:'mbler lang [?:languare]\n- No args: show current languare\n- languare = "zh” | “en": set languare',version:"mbler version\n - Version control command\n- No args: Shows version + commit hash\n- --show=<commit|version>: Filters output\n- <new_version>: Updates version in both package.json and config file","set-work-dir":"mbler set-work-dir <on|off>\n - on: Enable work dir feature\n - off: Disable work dir feature, use process.cwd() directly",publish:"mbler publish\n - Publish your package to pmnx\n- Params:\n- -tag: version tag name",uninstall:"mbler uninstall @<scope>/<name>@version\nRemove a package from your game",install:"mbler install @<scope>/<name>@version\nInstall a package to your game",unpublish:"mbler unpublish @<scope>/<name>@version\nUnpublish a package from pmnx",login:"mbler login <?:token>\nUse token login your pmnx account"},init:{useUI:"Use UI? (y/n): ",useGIT:"Initialize GIT repository? (y/n): ",name:"Project name: ",description:"Project description: ",initDes:"Initialize dependencies? (y/n): ",welcome:"Welcome to use Mbler init wizard! Language: English mbler version: "+D,lang:"Project languare: ",betaApi:"use beta api(y/n): ",mcVersion:"Minecraft version(be like: x.x.x): ",noLanguare:"project languare is required",noMCVersion:"project mcVersion format is not right",noName:"project name is required"},default:{unexpected:"Not found this command,",youis:"You want to input: "},workdir:{set:"[path to]: ",nfound:"not found this dir(can't create or not directory)",disabled:"Work dir disabled, will use current directory",enabled:"Work dir enabled",invalidParam:"Invalid parameter, use on or off"}};const $=o.join(require("node:os").homedir(),".cache/mbler/lang.db");const N=new class{currenyLang="zh";init(){try{const n=i.readFileSync($,"utf-8").toString().trim();if(e=n,!k.includes(e))throw new Error("[setup lang]: set lang error");this.currenyLang=n}catch{this.currenyLang="zh"}var e}set(e){return!!k.includes(e)&&(i.existsSync($)||i.mkdirSync(o.dirname($),{recursive:!0}),i.writeFileSync($,e),this.currenyLang=e,!0)}get(){try{return"zh"==this.currenyLang?I:P}catch{return I}}};let E={};N.init(),function e(n){const t=n.get();Object.setPrototypeOf(E,{...t,__internal:{class:n,set:t=>{n.set(t),e(n)}}})}(N);var V=Object.freeze({__proto__:null,default:E});process.stdin.isTTY&&(process.stdin.setRawMode(!0),g.emitKeypressEvents(process.stdin));const O=[],A=[];process.on("exit",e=>{process.stdout.write("[?25h")});const L=[];function S(e,{ctrl:n=!1,alt:t=!1}){return new Promise(i=>{O.push({name:e,ctrl:n||!1,alt:t||!1,resolve:i})})}S("c",{ctrl:!0}).then(()=>{L.forEach(e=>e()),process.exit(0)});class U{static render(e,n){return e.map((e,t)=>t===n?""+e+"":""+e+"").join(" ")}static select(e,n){let t=0,i=!1;console.log(`${e} (按 b 确认,n 键选择下一个) [?25l`),console.log(U.render(n,t)+"\n");const r=()=>{i||(t++,t>=n.length&&(t=0),console.log(`${U.render(n,t)}\n`),S("n",{ctrl:!1,alt:!1}).then(r))};return new Promise(e=>{S("n",{ctrl:!1,alt:!1}).then(r),S("b",{ctrl:!1,alt:!1}).then(()=>{i=!0,process.stdout.write("[?25h"),e(n[t])})})}static use(e){A.push(e)}}process.stdin.on("keypress",(e,n)=>{!function(e,{ctrl:n,alt:t},i){const r=O.find(i=>i.name===e&&i.ctrl===n&&i.alt===t);r&&(r.resolve(),O.splice(O.indexOf(r),1)),A.forEach(r=>r(e,n,t,i))}(n?.name||"",{ctrl:Boolean(n?.ctrl),alt:Boolean(n?.alt)},e)});var M=Object.freeze({__proto__:null,Input:U,click:S,onEnd:function(e){L.push(e)}});const B={ConfigFile:"mbler.config.js"};async function F(e){try{if(await a.stat(e))return!0}catch{return!1}return!1}async function R(e){try{const n=await a.readFile(e,"utf-8");return JSON.parse(n)}catch(e){throw e instanceof Error?e:new Error(e)}}let T=[],C=!1;async function z(){if(!C&&0!==T.length){C=!0;try{for(;T.length>0;){const e=T.shift();e&&process.stdout.write(e)}}finally{C=!1}}}function W(e,n=!0){T.push(e+(n?"\n":"")),C||Promise.resolve().then(()=>z()).catch(()=>{T=[],C=!1})}async function q(e,n){const t=JSON.stringify(n,null,2);return await F(r.dirname(e))||await a.mkdir(r.dirname(e),{recursive:!0}).catch(()=>{}),await a.writeFile(e,t,"utf-8")}function G(e,n){const t=e.split(".").map(e=>parseInt(e,10)||0),i=n.split(".").map(e=>parseInt(e,10)||0);for(let e=0;e<3;e++){const n=t[e]||0,r=i[e]||0;if(n!==r)return n-r}return 0}process.on("exit",z);const J=function(){let e,n="",t="",i=!0;function r(){const e=`\r${t}${i?n:""}`;process.stdout.write(e)}return U.use(function(t,i,o,a){if("function"==typeof e&&!i&&!o){if(t){if("return"===t||"enter"===t)return e(n),e=null,n="",void console.log("");if("backspace"===t)return n=n.slice(0,-1),void r()}a&&"string"==typeof a&&(n+=a,r())}}),async function(n="",o=!0){return new Promise(a=>{i=o,t=n,r(),e=a})}}();function K(e){const n=e.split("-");return!!n[0]&&3===n[0].split(".").map(Number).filter(e=>!Number.isNaN(e)).length}function Y(e,n,t){let i,r="";const o=new Promise(e=>i=e),a=v(e[0],e.slice(1),{cwd:n,shell:!1,stdio:t,timeout:6e5});return a.on("error",e=>{i(r+"(code: error)")}),a.on("data",(...e)=>{r+=e.join("")}),a.on("exit",e=>{i(e?r:`${r}(code: ${e})`)}),o}const H=o.join(h.homedir(),".cache/mbler/latest.log");function Q(e){const n=async function(){try{const e=o.dirname(H);await F(e)||await s.mkdir(e,{recursive:!0}).catch(()=>{}),await F(H)||await s.writeFile(H,"")}catch(e){return void console.error("[logger] unable to prepare log file:",e)}try{await s.appendFile(H,"\n"+e)}catch(e){console.error("[logger] failed to append to log file:",e)}}();var t;X.run.push(n.then((t=n,()=>{X.run=X.run.filter(e=>e!==t)})))}class X{static LogFile=H;static run=[];static _b(e,n,t){const i=new Date;Q([`${i.toLocaleDateString()} ${i.toLocaleTimeString()}`,`[${t} ${e}]`,n].join(" "))}static w(e,n){X._b(e,n,"WARN")}static e(e,n){X._b(e,n,"ERROR")}static i(e,n){X._b(e,n,"INFO")}static d(e,n){X._b(e,n,"DEBUG")}}async function Z(e){try{return await d(e),!0}catch{return!1}}class ee{cacheDir;currentWorkPoint=null;enabledPath=o.join(b(),".cache/mbler/workdir_enabled.db");constructor(e=o.join(b(),".cache/mbler/mp.db")){this.cacheDir=e}async isDisabled(){try{return await c(this.enabledPath,"utf-8"),!1}catch{return!0}}async setDisabled(e){if(e)try{await u(this.enabledPath)}catch{}else await l(this.enabledPath,"1",{encoding:"utf-8"})}async set(e){try{if(!(await m(e)).isDirectory())throw new Error("Not Dir (0xcvb)")}catch(n){const t=n.code;if(n.message&&n.message.includes("0xcvb"))return E.workdir.nfound;if("ENOENT"==t){if(!Z(e))return E.workdir.nfound}}try{if(!await F(o.dirname(this.cacheDir))){if(!await Z(o.dirname(this.cacheDir)))return E.workdir.nfound}await l(this.cacheDir,e,{encoding:"utf-8"})}catch(e){X.e("WorkDir",e.stack)}return E.workdir.set+e}async get(){if(await this.isDisabled())return e();if(this.currentWorkPoint)return this.currentWorkPoint;const n=await c(this.cacheDir,"utf-8").catch(n=>(this.set(e()),e()));return this.currentWorkPoint=n}}const ne={tmpdir:r.join(w(),".mbler"),mcxVersion:"0.0.2-beta.r7",mcxCoreVersion:"0.0.6"},te=function(){const e=r.join(ne.tmpdir,"_sapi_version.json");let n=null;async function i(e){const n=await y(`/${e}`),t=Object.keys(n.versions),i={},r=e=>{const n=e.match(/-(?:rc|beta)(?:\.[^-.]+)*?\.((?:\d+\.){2}\d+)/);return n?n[1]:null};for(const e of t){const n=r(e);if(!n)continue;const t=/(?:-stable)(?:$|[-.])/.test(e);let o=i[n];o||(o={formal:"",beta:"",_v:-1},i[n]=o),t?((!o.formal||e>o.formal)&&(o.formal=e),o._v=1/0):((!o.beta||e>o.beta)&&(o.beta=e),o._v!==1/0&&(o._v=1))}return i}async function o(){const r=await i("@minecraft/server"),o=await i("@minecraft/server-ui"),a=new Set([...Object.keys(r),...Object.keys(o)]),s=[];for(const e of Array.from(a))s.push({version:e,server:r[e]?{formal:r[e].formal,beta:r[e].beta}:{formal:"",beta:""},"server-ui":o[e]?{formal:o[e].formal,beta:o[e].beta}:{formal:"",beta:""}});s.sort((e,n)=>G(e.version,n.version)),n=s,await t.promises.mkdir(ne.tmpdir,{recursive:!0}).catch(()=>{}),await t.promises.writeFile(e,JSON.stringify(s,null,2),"utf-8")}return{refresh:o,generateVersion:async function(i,r,a){if(!n)try{const i=await t.promises.readFile(e,"utf-8");n=JSON.parse(i)}catch{await o()}if(!n)throw new Error("unable to load sapi cache data");let s=n.find(e=>e.version===r);if(!s){const e=n.slice();let t=null;for(const n of e){if(!(G(n.version,r)<=0))break;t=n}t||(t=e[0]),s=t}const c=s["@minecraft/server"===i?"server":"server-ui"];let l=a?c.beta:c.formal;return l||(l=c.formal||c.beta),l||""}}}();async function ie(e,n){await te.refresh();const t=e.params.slice(1);if(await async function(e){return(await Promise.all([B.ConfigFile,"package.json","behavior"].map(n=>F(o.join(e,n))))).every(e=>e)}(n))return 0;W(E.init.welcome);const i={name:t[0]||await J(E.init.name),description:t[1]||await J(E.init.description),lang:t[2]||await U.select(E.init.lang,["ts","js","mcx"]),initDeependencies:await U.select(E.init.initDes,["no","pnpm","npm"]),useUI:"y"===await J(E.init.useUI),useGIT:"y"===await J(E.init.useGIT),useBetaApi:"y"===await J(E.init.betaApi),mcVersion:await J(E.init.mcVersion)};if(!i.name)return W(E.init.noName),1;if(!i.lang)return W(E.init.noLanguare),1;if(!i.mcVersion||!K(i.mcVersion))return W(E.init.noMCVersion),1;const r={name:i.name,description:i.description,version:"0.0.0",script:{lang:i.lang,main:"index.js",ui:i.useUI,UseBeta:i.useBetaApi},mcVersion:i.mcVersion,minify:!1},a={name:i.name,version:"0.0.0",description:i.description,module:"module",scripts:{build:"mcx-tsc && BUILD_MODULE=release mbler build","dev:build":"mbler build",install:"pnpm i -g mbler",watch:"mbler watch"},devDependencies:{"@minecraft/server":await te.generateVersion("@minecraft/server",i.mcVersion,i.useBetaApi)}};i.useUI&&(a.devDependencies["@minecraft/server-ui"]=await te.generateVersion("@minecraft/server-ui",i.mcVersion,i.useBetaApi));const s={compilerOptions:{module:"nodenext",noEmit:!0,target:"esnext",types:["@mbler/mcx-core/client"],sourceMap:!0,declaration:!0,declarationMap:!1,noUncheckedIndexedAccess:!0,exactOptionalPropertyTypes:!0,allowJs:!0,strict:!0,moduleResolution:"nodenext",verbatimModuleSyntax:!1,isolatedModules:!0,noUncheckedSideEffectImports:!0,moduleDetection:"force",skipLibCheck:!0},include:["./behavior/scripts/**/*"]},c=o.join(n,B.ConfigFile),l=o.join(n,"package.json"),u=o.join(n,"tsconfig.json");"mcx"==i.lang&&(r.script.main="index.mjs",a.devDependencies["@mbler/mcx"]=ne.mcxVersion,a.devDependencies["@mbler/mcx-core"]=ne.mcxCoreVersion),"js"!==i.lang&&await q(u,s),await q(l,a),await q(c,`import { defineConfig } from "mbler";\nexport default ${JSON.stringify(r,null,2)}`);const m=await async function(){return await F(o.join(__dirname,"../template"))?o.join(__dirname,"../template"):await F(o.join(__dirname,"./template"))?o.join(__dirname,"./template"):void 0}();if(!m)return W("can't find template folder"),1;const d=o.join(m,i.lang);if(!await F(d))return W("can't resolve template folder"),1;const h=[];for(const e of await p(d))h.push(f(o.join(d,e),o.join(n,e),{recursive:!0,force:!0}));return await Promise.all(h),h.length=0,"no"!==i.initDeependencies&&h.push(Y([i.initDeependencies,"install"],n,"pipe")),i.useGIT&&h.push(Y(["git","init","-b","main"],n,"pipe")),await Promise.all(h),h.length=0,0}async function re(e,n){if(e.params.length>1){if(!await F(n))return W("can't set workdir version, because not exists"),1;const t=e.params[1];if(!t||!K(t))return W("can't set version, it is not a vaild version"),1;const i=await R(r.join(n,"package.json"));(await R(r.join(n,B.ConfigFile))).version=i.version=t}else!function(e){let n="";Object.getOwnPropertyNames(e.opts).length<1?n=`commit: ${_}\nversion: ${D}`:e.opts.show&&(n="commit"==e.opts.show?`commit: ${_}`:"version"==e.opts.show?`version: ${D}`:'invaild "show" param');W(n)}(e);return 0}function oe(e,n){let t="";return e.params.length<2||E.__internal.set(e.params[1]),t=E.__internal.class.currenyLang,W(t),0}function ae(e,n){return W("unpublish is planing"),1}function se(e,n){return W("publish is planing"),1}function ce(e,n){return W("uninstall is planing"),1}function le(e,n){return W("install is planing"),1}function ue(e,n){return W("login is planing"),1}const me=function(){let e;function t(e,n){if(!e||!n)return 1;const t=e.params[1];if(!t)return W(E.description),0;let i=E.help[t];return i?(i.startsWith("$")&&(i=E.help[i.slice(1)]),W(i),0):0}async function i(n,t){if(!e)return 0;if(n.params.length>1){const t=o.resolve(n.params[1]);W(await e.set(t))}else W(t);return 0}async function r(n,t){if(!e)return 0;const i=n.params[1];return"off"===i?(await e.setDisabled(!0),W(E.workdir.disabled)):"on"===i?(await e.setDisabled(!1),W(E.workdir.enabled)):W(E.workdir.invalidParam),0}return async function(){const a=function(){const e={},t=[];let i=null;return n.slice(2).forEach((n,r,o)=>{if(i)return e[i]=n,void(i=null);n.startsWith("-")?(i=n.slice(1),r==o.length-1&&(e[i]="")):t.push(n)}),{params:t,opts:e}}(),s={help:t,h:t,work:i,c:i,build:async(e,n)=>{const{build:t}=require("mbler/build");return await t(e,n)},watch:async(e,n)=>{const{watch:t}=require("mbler/build");return await t(e,n)},init:ie,version:re,lang:oe,"set-work-dir":r,unpublish:ae,publish:se,uninstall:ce,install:le,login:ue},c=a.params[0];e=a.opts.cwp?new ee(o.resolve(a.opts.cwp)):new ee,c||(t(a,await e.get()),process.exit(0));const l=s[c];if("function"!=typeof l)!function(e){console.log(`${E.default.unexpected}: ${e}`);const n=x.map(n=>function(e,n){let t=0;for(let i=0;i<n.length;i++)e[i]==n[i]&&t++;return t/n.length}(e,n)).reduce((e,n,t)=>{try{if(n>e.max)return{max:n,index:t,indices:[]};if(n===e.max)return e.indices.push(t),e}catch(e){X.w("matchDefault",e.stack)}return e},{max:-1/0,index:-1,indices:[]}),t=x[n.index];t&&console.log(`${E.default.youis} ${t}`)}(c);else{const n=l(a,await e.get());if(n instanceof Promise){const e=await n;process.exit(e)}else process.exit(n)}process.exit(0)}}();function de(e){return e}export{j as Types,me as cli,M as commander,de as defineConfig,V as i18n};
2016
2
  //# sourceMappingURL=index.esm.js.map