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