mbler 0.1.4 → 0.1.5-alpha

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.
Files changed (35) hide show
  1. package/lib/build/base.d.ts +1 -1
  2. package/lib/build/base.js +1 -1
  3. package/lib/build/index.js +1 -1
  4. package/package.json +49 -1
  5. package/test/2x sword/.cache__mbler__/config-hash.txt +0 -1
  6. package/test/2x sword/.cache__mbler__/package-hash.txt +0 -1
  7. package/test/2x sword/behavior/scripts/index.js +0 -25
  8. package/test/2x sword/mbler.config.json +0 -12
  9. package/test/2x sword/package.json +0 -14
  10. package/test/README.md +0 -8
  11. package/test/des/index.js +0 -20
  12. package/test/des/mbler.config.json +0 -5
  13. package/test/des/package.json +0 -7
  14. package/test/initializer/index.js +0 -6
  15. package/test/initializer/mbler.config.json +0 -5
  16. package/test/initializer/package.json +0 -7
  17. package/test/initializer/test.js +0 -1
  18. package/test/mbler-int/behavior/res/items/mang_one_int.json +0 -22
  19. package/test/mbler-int/behavior/res/pack_icon.png +0 -0
  20. package/test/mbler-int/behavior/res/recipes/mang_one_int.json +0 -31
  21. package/test/mbler-int/behavior/scripts/index.js +0 -8
  22. package/test/mbler-int/behavior/scripts/lib/event/index.js +0 -20
  23. package/test/mbler-int/behavior/scripts/lib/ui/Lore.js +0 -19
  24. package/test/mbler-int/behavior/scripts/lib/ui/baseUi.js +0 -6
  25. package/test/mbler-int/behavior/scripts/lib/ui/index.js +0 -207
  26. package/test/mbler-int/behavior/scripts/lib/utils/index.js +0 -52
  27. package/test/mbler-int/mbler.config.json +0 -19
  28. package/test/mbler-int/package.json +0 -13
  29. package/test/script-mbler/.cache__mbler__/config-hash.txt +0 -1
  30. package/test/script-mbler/.cache__mbler__/package-hash.txt +0 -1
  31. package/test/script-mbler/behavior/res/pack_icon.png +0 -0
  32. package/test/script-mbler/behavior/scripts/index.js +0 -5
  33. package/test/script-mbler/behavior/scripts/index.ts +0 -6
  34. package/test/script-mbler/mbler.config.json +0 -15
  35. package/test/script-mbler/package.json +0 -16
@@ -20,7 +20,7 @@ export declare abstract class BaseBuild {
20
20
  loadPackageData(): Promise<MblerConfigData>;
21
21
  getCachePath(fileName: string): string;
22
22
  getOutputDir(dir: string | null | undefined, def: string): string;
23
- initNpmDes(_this?: any): Promise<void>;
23
+ initNpmDes(): Promise<void>;
24
24
  getFileHash(filePath: string): Promise<string | null>;
25
25
  chackConfigHash(): Promise<{
26
26
  configChanged: boolean;
package/lib/build/base.js CHANGED
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var i={};if(null!=t)for(var a=e(t),s=0;s<a.length;s++)"default"!==a[s]&&__createBinding(i,t,a[s]);return __setModuleDefault(i,t),i}}(),__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.BaseBuild=void 0;const promises_1=__importDefault(require("fs/promises")),path_1=__importDefault(require("path")),dayjs_1=__importDefault(require("dayjs")),index_js_1=__importDefault(require("./../lang/index.js")),index_js_2=__importDefault(require("./../runTemp/index.js")),child_process_1=require("child_process"),manifest_build_js_1=require("./manifest.build.js"),node_os_1=__importDefault(require("node:os")),time=()=>(0,dayjs_1.default)().format("YYYY-MM-DD HH:mm:ss"),utils_1=__importDefault(require("./utils")),utils=__importStar(require("./../utils/index.js"));class BaseBuild{static times=time();outdir="";ResOutDir=null;baseCwd="";cwd="";ResCwd="";d_data=null;cacheDir="";dependencies={};Modules=[];constructor(){}async rmPackScriptScriptCache(){await Promise.all([this.rmNpmDes(),promises_1.default.rm(path_1.default.join(this.outdir,"scripts/package-lock.json"),{recursive:!0,force:!0}).catch(()=>{})])}async processResources(){if(await utils.FileExsit(this.ResCwd)&&this.ResOutDir){if(await Promise.all((await promises_1.default.readdir(this.ResCwd)).map(e=>utils.copy(path_1.default.join(this.ResCwd,e),path_1.default.join(this.ResOutDir,e)))),null==this.d_data)throw new Error("[build error]: not load config when init");const e=new manifest_build_js_1.ManiFest(this.d_data,"resources").data;await this.writeFile(path_1.default.join(this.ResOutDir,"manifest.json"),JSON.stringify(e))}else(0,utils_1.default)(index_js_1.default.build.no_resources)}async processDist(){if("dist"===process.env.MBLER_BUILD_MODULE){const e=new index_js_2.default(path_1.default.join(node_os_1.default.tmpdir(),"mbler"));await e.init(),await Promise.all([utils.copy(this.outdir,path_1.default.join(e.dir,"behavior")),await utils.FileExsit(this.ResCwd)?utils.copy(this.ResOutDir,path_1.default.join(e.dir,"resources")):Promise.resolve()]);let t=this.d_data?.outdir?.dist||"dist.mcaddon";".mcaddon"!==path_1.default.extname(t)&&(t+=".mcaddon");const i=path_1.default.join(this.baseCwd,t),a=require("./../../package.json");await promises_1.default.writeFile(path_1.default.join(e.dir,"behavior",".mbler.build.info"),JSON.stringify({mbler:{version:a.version,git:a.repository},time:BaseBuild.times})),await utils.zip([e.dir],i),await e.remove(),(0,utils_1.default)(`${index_js_1.default.build.ziped} ${i}`)}}async loadPackageData(){const e=await utils.GetData(this.baseCwd);if(!e)throw new Error(index_js_1.default.buildBase.cannot_read_project_config);if("object"!=typeof e||null===e)throw new Error(index_js_1.default.buildBase.invalid_project_config_format);return e}getCachePath(e){return path_1.default.join(this.cacheDir,e)}getOutputDir(e,t){const i=e;return i?path_1.default.join(this.baseCwd,i):t}async initNpmDes(e=this){const t=JSON.parse(await promises_1.default.readFile(path_1.default.join(e.baseCwd,"package.json"),"utf-8"));Object.keys(t.dependencies||{}).length;await promises_1.default.writeFile(path_1.default.join(e.outdir,"scripts/package.json"),JSON.stringify(t)),await this.#e(path_1.default.join(e.outdir,"scripts"))}#e(e){return new Promise((t,i)=>{const a=(0,child_process_1.spawn)("npm",["install"],{cwd:e,stdio:"ignore"});a.on("close",e=>{0===e?((0,utils_1.default)(index_js_1.default.buildBase.npm_install_completed),t(e)):((0,utils_1.default)(index_js_1.default.buildBase.npm_install_exit_code+e),t(e))}),a.on("error",e=>{(0,utils_1.default)(`${index_js_1.default.buildBase.npm_install_error} ${e.stack}`),i(e)})})}async getFileHash(e){if(!await utils.FileExsit(e))return null;const t=await promises_1.default.readFile(e),i=(await import("crypto")).createHash("sha1");return i.update(t),i.digest("hex")}async chackConfigHash(){const e=path_1.default.join(this.cwd,"mbler.config.json"),t=path_1.default.join(this.cwd,"package.json"),i=this.getCachePath("config-hash.txt"),a=this.getCachePath("package-hash.txt"),s=await this.getFileHash(e),r=await this.getFileHash(t);let l=null,o=null;await promises_1.default.access(i).then(()=>!0).catch(()=>!1)&&(l=await promises_1.default.readFile(i,"utf-8")),await promises_1.default.access(a).then(()=>!0).catch(()=>!1)&&(o=await promises_1.default.readFile(a,"utf-8"));const n=!s||s!==l,d=!r||r!==o;return s&&await promises_1.default.writeFile(i,s),r&&await promises_1.default.writeFile(a,r),{configChanged:n,packageChanged:d}}async removeJsFiles(e){try{for(const t of await promises_1.default.readdir(e,{withFileTypes:!0})){const i=path_1.default.join(e,t.name);if(!i.includes("node_modules"))if(t.isDirectory())await this.removeJsFiles(i);else if(t.isFile()&&t.name.endsWith(".js"))try{await promises_1.default.unlink(i)}catch(e){}}}catch(e){}}async rmNpmDes(){const e=path_1.default.join(this.outdir,"scripts/node_modules"),t=this.Modules||Object.keys(this.dependencies),i=[];for(let a of await promises_1.default.readdir(e).catch(()=>[]))t.includes(a)||"@mbler/mcx"===a||i.push(promises_1.default.rm(path_1.default.join(e,a),{recursive:!0,force:!0}).catch(()=>{}));await Promise.all(i)}async copyCompiledOnly(e,t){try{for(const i of await promises_1.default.readdir(e,{withFileTypes:!0})){const a=path_1.default.join(e,i.name),s=path_1.default.join(t,i.name);if(i.isDirectory())await promises_1.default.mkdir(s,{recursive:!0}).catch(()=>{}),await this.copyCompiledOnly(a,s);else if(i.isFile()){const e=path_1.default.extname(i.name).toLowerCase();[".js",".json"].includes(e)&&(await promises_1.default.mkdir(path_1.default.dirname(s),{recursive:!0}).catch(()=>{}),await promises_1.default.copyFile(a,s).catch(()=>{}))}}}catch(e){(0,utils_1.default)(`ERR: ${e&&e.stack?e.stack:e}`)}}async getAllTsFiles(e){const t=[];try{for(const i of await promises_1.default.readdir(e,{withFileTypes:!0})){const a=path_1.default.join(e,i.name);if(i.isDirectory()){const e=await this.getAllTsFiles(a);t.push(...e)}else i.isFile()&&i.name.endsWith(".ts")&&t.push(a)}}catch(e){}return t}async writeFile(e,t){try{await utils.waitGC(),await promises_1.default.mkdir(path_1.default.dirname(e),{recursive:!0});const i="string"==typeof t?t:JSON.stringify(t,null,2);await promises_1.default.writeFile(e,i,"utf-8")}catch(t){throw(0,utils_1.default)(`WRITE FILE ERR: ${e}`),t}await utils.waitGC()}}exports.BaseBuild=BaseBuild;
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var i={};if(null!=t)for(var a=e(t),s=0;s<a.length;s++)"default"!==a[s]&&__createBinding(i,t,a[s]);return __setModuleDefault(i,t),i}}(),__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.BaseBuild=void 0;const promises_1=__importDefault(require("fs/promises")),path_1=__importDefault(require("path")),dayjs_1=__importDefault(require("dayjs")),index_js_1=__importDefault(require("./../lang/index.js")),index_js_2=__importDefault(require("./../runTemp/index.js")),child_process_1=require("child_process"),manifest_build_js_1=require("./manifest.build.js"),node_os_1=__importDefault(require("node:os")),time=()=>(0,dayjs_1.default)().format("YYYY-MM-DD HH:mm:ss"),utils_1=__importDefault(require("./utils")),utils=__importStar(require("./../utils/index.js"));class BaseBuild{static times=time();outdir="";ResOutDir=null;baseCwd="";cwd="";ResCwd="";d_data=null;cacheDir="";dependencies={};Modules=[];constructor(){}async rmPackScriptScriptCache(){await Promise.all([this.rmNpmDes(),promises_1.default.rm(path_1.default.join(this.outdir,"scripts/package-lock.json"),{recursive:!0,force:!0}).catch(()=>{})])}async processResources(){if(await utils.FileExsit(this.ResCwd)&&this.ResOutDir){if(await Promise.all((await promises_1.default.readdir(this.ResCwd)).map(e=>utils.copy(path_1.default.join(this.ResCwd,e),path_1.default.join(this.ResOutDir,e)))),null==this.d_data)throw new Error("[build error]: not load config when init");const e=new manifest_build_js_1.ManiFest(this.d_data,"resources").data;await this.writeFile(path_1.default.join(this.ResOutDir,"manifest.json"),JSON.stringify(e))}else(0,utils_1.default)(index_js_1.default.build.no_resources)}async processDist(){if("dist"===process.env.MBLER_BUILD_MODULE){const e=new index_js_2.default(path_1.default.join(node_os_1.default.tmpdir(),"mbler"));await e.init(),await Promise.all([utils.copy(this.outdir,path_1.default.join(e.dir,"behavior")),await utils.FileExsit(this.ResCwd)?utils.copy(this.ResOutDir,path_1.default.join(e.dir,"resources")):Promise.resolve()]);let t=this.d_data?.outdir?.dist||"dist.mcaddon";".mcaddon"!==path_1.default.extname(t)&&(t+=".mcaddon");const i=path_1.default.join(this.baseCwd,t),a=require("./../../package.json");await promises_1.default.writeFile(path_1.default.join(e.dir,"behavior",".mbler.build.info"),JSON.stringify({mbler:{version:a.version,git:a.repository},time:BaseBuild.times})),await utils.zip([e.dir],i),await e.remove(),(0,utils_1.default)(`${index_js_1.default.build.ziped} ${i}`)}}async loadPackageData(){const e=await utils.GetData(this.baseCwd);if(!e)throw new Error(index_js_1.default.buildBase.cannot_read_project_config);if("object"!=typeof e||null===e)throw new Error(index_js_1.default.buildBase.invalid_project_config_format);return e}getCachePath(e){return path_1.default.join(this.cacheDir,e)}getOutputDir(e,t){const i=e;return i?path_1.default.join(this.baseCwd,i):t}async initNpmDes(){const e=JSON.parse(await promises_1.default.readFile(path_1.default.join(this.baseCwd,"package.json"),"utf-8"));Object.keys(e.dependencies||{}).length;await promises_1.default.writeFile(path_1.default.join(this.outdir,"scripts/package.json"),JSON.stringify(e)),await this.#e(path_1.default.join(this.outdir,"scripts"))}#e(e){return new Promise((t,i)=>{const a=(0,child_process_1.spawn)("npm",["install"],{cwd:e,stdio:"ignore"});a.on("close",e=>{0===e?((0,utils_1.default)(index_js_1.default.buildBase.npm_install_completed),t(e)):((0,utils_1.default)(index_js_1.default.buildBase.npm_install_exit_code+e),t(e))}),a.on("error",e=>{(0,utils_1.default)(`${index_js_1.default.buildBase.npm_install_error} ${e.stack}`),i(e)})})}async getFileHash(e){if(!await utils.FileExsit(e))return null;const t=await promises_1.default.readFile(e),i=(await import("crypto")).createHash("sha1");return i.update(t),i.digest("hex")}async chackConfigHash(){const e=path_1.default.join(this.cwd,"mbler.config.json"),t=path_1.default.join(this.cwd,"package.json"),i=this.getCachePath("config-hash.txt"),a=this.getCachePath("package-hash.txt"),s=await this.getFileHash(e),r=await this.getFileHash(t);let l=null,o=null;await promises_1.default.access(i).then(()=>!0).catch(()=>!1)&&(l=await promises_1.default.readFile(i,"utf-8")),await promises_1.default.access(a).then(()=>!0).catch(()=>!1)&&(o=await promises_1.default.readFile(a,"utf-8"));const n=!s||s!==l,d=!r||r!==o;return s&&await promises_1.default.writeFile(i,s),r&&await promises_1.default.writeFile(a,r),{configChanged:n,packageChanged:d}}async removeJsFiles(e){try{for(const t of await promises_1.default.readdir(e,{withFileTypes:!0})){const i=path_1.default.join(e,t.name);if(!i.includes("node_modules"))if(t.isDirectory())await this.removeJsFiles(i);else if(t.isFile()&&t.name.endsWith(".js"))try{await promises_1.default.unlink(i)}catch(e){}}}catch(e){}}async rmNpmDes(){const e=path_1.default.join(this.outdir,"scripts/node_modules"),t=this.Modules||Object.keys(this.dependencies),i=[];for(let a of await promises_1.default.readdir(e).catch(()=>[]))t.includes(a)||"@mbler/mcx"===a||i.push(promises_1.default.rm(path_1.default.join(e,a),{recursive:!0,force:!0}).catch(()=>{}));await Promise.all(i)}async copyCompiledOnly(e,t){try{for(const i of await promises_1.default.readdir(e,{withFileTypes:!0})){const a=path_1.default.join(e,i.name),s=path_1.default.join(t,i.name);if(i.isDirectory())await promises_1.default.mkdir(s,{recursive:!0}).catch(()=>{}),await this.copyCompiledOnly(a,s);else if(i.isFile()){const e=path_1.default.extname(i.name).toLowerCase();[".js",".json"].includes(e)&&(await promises_1.default.mkdir(path_1.default.dirname(s),{recursive:!0}).catch(()=>{}),await promises_1.default.copyFile(a,s).catch(()=>{}))}}}catch(e){(0,utils_1.default)(`ERR: ${e&&e.stack?e.stack:e}`)}}async getAllTsFiles(e){const t=[];try{for(const i of await promises_1.default.readdir(e,{withFileTypes:!0})){const a=path_1.default.join(e,i.name);if(i.isDirectory()){const e=await this.getAllTsFiles(a);t.push(...e)}else i.isFile()&&i.name.endsWith(".ts")&&t.push(a)}}catch(e){}return t}async writeFile(e,t){try{await utils.waitGC(),await promises_1.default.mkdir(path_1.default.dirname(e),{recursive:!0});const i="string"==typeof t?t:JSON.stringify(t,null,2);await promises_1.default.writeFile(e,i,"utf-8")}catch(t){throw(0,utils_1.default)(`WRITE FILE ERR: ${e}`),t}await utils.waitGC()}}exports.BaseBuild=BaseBuild;
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var a=Object.getOwnPropertyDescriptor(t,i);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,a)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var i={};if(null!=t)for(var s=e(t),a=0;a<s.length;a++)"default"!==s[a]&&__createBinding(i,t,s[a]);return __setModuleDefault(i,t),i}}(),__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});const fs=__importStar(require("fs/promises")),path=__importStar(require("path")),ts=__importStar(require("typescript")),index_js_1=__importDefault(require("./../lang/index.js")),index_js_2=require("./../uuid/index.js"),index_js_3=__importDefault(require("./../code-processor/index.js")),utils=__importStar(require("./../utils/index.js")),getModule_js_1=__importDefault(require("./getModule.js")),includes_json_1=__importDefault(require("./../data/includes.json")),clean_js_1=__importDefault(require("./../start/clean.js")),index_js_4=__importDefault(require("./../runTemp/index.js")),base_js_1=require("./base.js"),manifest_build_js_1=require("./manifest.build.js"),mcx_core_1=__importDefault(require("@mbler/mcx-core")),node_os_1=__importDefault(require("node:os")),utils_1=__importDefault(require("./utils"));class Build extends base_js_1.BaseBuild{baseDir;baseModDir;gamelibModule;constructor(e,t){super(),e||utils.Exit(index_js_1.default.build.config_invalid),this.baseDir=t,this.baseCwd=path.isAbsolute(e)?e:path.join(t,e),this.cwd=path.join(this.baseCwd,"behavior"),this.ResOutDir=null,this.ResCwd=path.join(this.baseCwd,"resources"),this.dependencies={},this.gamelibModule=null,this.baseModDir=path.join(this.baseDir,"lib/modules"),this.#e(["baseModDir","baseDir"]),this.#t(["outdir","dependencies","gamelibModule","cwd","ResCwd","baseModDir","baseCwd"]),this.cacheDir=path.join(this.baseCwd,".cache__mbler__")}#e(e){if(Array.isArray(e))for(let t of e)Object.defineProperty(this,t,{enumerable:!1,writable:!1})}#t(e){if(Array.isArray(e))for(let t of e)Object.defineProperty(this,t,{enumerable:!1})}async#i(){try{await fs.mkdir(this.cacheDir,{recursive:!0})}catch(e){if("EEXIST"!==e.code)throw e}}build(){return this.start().catch(e=>{const t=utils.toString(e);(0,utils_1.default)(index_js_1.default.build.error_message_log+t)})}async start(){const e=Date.now();await this.#i();const{configChanged:t,packageChanged:i}=await this.chackConfigHash(),s=new clean_js_1.default(this.baseCwd,this.baseDir);await s.run(),await utils.waitGC();const a=await this.loadPackageData();this.d_data=a,this.outdir=this.getOutputDir(a.outdir?.behavior,path.join(this.baseCwd,"dist/dep")),this.ResOutDir=this.getOutputDir(a.outdir?.resources,path.join(this.baseCwd,"dist/res"));const r=["name","description","version","mcVersion"];if(!utils.hasKeys(a,r,r.length))throw new Error(`${index_js_1.default.build.package_file} 字段缺失:必需字段 ${JSON.stringify(r)}`);switch(this.gamelibModule=await(0,getModule_js_1.default)(this.baseDir),console.log(index_js_1.default.build.build_info_header),console.table({[index_js_1.default.build.project_path]:this.baseCwd,[index_js_1.default.build.output_dir]:JSON.stringify(a.outdir),[index_js_1.default.build.minify_enabled]:Boolean(a.minify),[index_js_1.default.build.build_time]:Build.times,[index_js_1.default.build.tip_dist]:process.env.MBLER_BUILD_MODULE||"dev"}),await Promise.all([this.writeManifest(a),this.handleScripts(a),this.handleIncludes(),this.processSubpacks(a)]),a.script?.lang&&(0,utils_1.default)("对特定语言进行处理:"+a.script.lang),a.script?.lang||""){case"ts":await this.compileTypeScriptUnified();break;case"mcx":this.initNpmDes({baseCwd:this.baseCwd,outdir:this.cwd}),await mcx_core_1.default.load({ProjectDir:path.join(this.baseCwd),config:{},output:path.join(this.outdir,"scripts"),main:path.join(this.cwd,"scripts",a.script?.main||"index.js"),moduleDir:path.join(this.outdir,"scripts/node_modules")});break;default:console.error("无效的语言设置")}await Promise.all([this.processMinification(a),this.processResources()]),await this.processDist(),console.log(`${index_js_1.default.build.build_success} ${(Date.now()-e)/1e3}`)}async writeManifest(e){const t=await this.buildManifest(e);await this.writeFile(path.join(this.outdir,"manifest.json"),t)}async buildManifest(e){const t=new manifest_build_js_1.ManiFest(e,"data").data,i=e.subpack||{};return"object"==typeof e.ResDes&&this.processResourceDependencies(e,t),"object"==typeof e.subpack&&Object.keys(e.subpack).length>0&&(t.subpack=Object.keys(e.subpack).map(e=>({folder_name:e,name:i[e]||"",memory_tier:1}))),t}processResourceDependencies(e,t){const{name:i="unknown",version:s}=e.ResDes||{};s&&utils.isVerison(s)&&t.dependencies.push({name:(0,index_js_2.fromString)(i),version:utils.ToArray(s)})}async handleScripts(e){if(!e.script||"object"!=typeof e.script)return;const t=path.join(this.cwd,"scripts"),i=path.join(this.outdir,"scripts");await utils.FileExsit(t)&&(await utils.copy(t,i),this.dependencies=e.script.dependencies||{},await this.initNpmDes(),Object.keys(this.dependencies).length>0&&(this.Modules=await this.handlerMod(this.dependencies,new Set)))}async processSubpacks(e){if("object"!=typeof e.subpack)return;const t=this.outdir,i=new Build(this.cwd,this.baseDir);for(let[s,a]of Object.entries(e.subpack))try{const e=path.join(this.cwd,"subpacks",s),a=path.join(t,"subpacks",s);if(await fs.mkdir(a,{recursive:!0}),!await utils.FileExsit(e)){(0,utils_1.default)(index_js_1.default.build.subpack_folder_not_found.replace("{id}",s));continue}const r=path.join(e,"scripts"),n=path.join(a,"scripts");await utils.FileExsit(r)&&await utils.copy(r,n),i.cwd=e,i.outdir=a,await i.handleIncludes()}catch(e){(0,utils_1.default)(index_js_1.default.build.error_processing_subpack.replace("{id}",s).replace("{error}",e.stack))}}async compileTypeScriptUnified(){const e=new index_js_4.default(path.join(node_os_1.default.tmpdir(),"mbler"));await e.init();const t=e.dir;try{const e=await this.getAllTsFiles(this.outdir);if(!e||0===e.length)return void(0,utils_1.default)(index_js_1.default.build.ts_no_files);let i={compilerOptions:{target:"esnext",module:"esnext",moduleResolution:"NodeNext",esModuleInterop:!0,verbatimModuleSyntax:!1,allowSyntheticDefaultImports:!0,outDir:t,rootDir:this.outdir,strict:!0,allowJs:!0,sourceMap:!1,incremental:!0,tsBuildInfoFile:path.join(this.cacheDir,"tsbuildinfo")},include:["**/*.ts"]};await utils.FileExsit(path.join(this.baseCwd,"tsconfig.json"))&&(i=JSON.parse(await fs.readFile(path.join(this.baseCwd,"tsconfig.json"),"utf-8")));const s=ts.parseJsonConfigFileContent(i,ts.sys,this.outdir,void 0,"tsconfig.json"),a=ts.createProgram({rootNames:e,options:s.options}),r=a.emit();ts.getPreEmitDiagnostics(a).concat(r.diagnostics).forEach(e=>{const t=ts.flattenDiagnosticMessageText(e.messageText,"\n");if(e.file){const{line:i,character:s}=e.file.getLineAndCharacterOfPosition(e.start);(0,utils_1.default)(index_js_1.default.build.ts_diagnostics.replace("{file}",e.file.fileName).replace("{line}",(i+1).toString()).replace("{character}",(s+1).toString()).replace("{message}",t))}else(0,utils_1.default)(t)}),await this.removeJsFiles(path.join(this.outdir,"scripts")),await this.copyCompiledOnly(t,this.outdir),(0,utils_1.default)(index_js_1.default.build.ts_compilation_error+" 完成")}catch(e){throw(0,utils_1.default)(index_js_1.default.build.ts_compilation_error+e.stack),e}finally{await e.remove()}}async handlerMod(e,t=new Set){const i=this.gamelibModule.getAll(),s=path.join(this.outdir,"scripts/node_modules");let a={};for(const[r,n]of Object.entries(e)){if(!i.includes(r)||t.has(r))continue;const e=await this.gamelibModule.getDir(r,{gitUrl:n,v:this.d_data.mcVersion});if(!e||!await utils.FileExsit(e))continue;const o=await utils.handlerPackage(e,{des:Array.from(t)});o.des&&Object.assign(a,o.des),await utils.copy(e,path.join(s,r)),await utils.waitGC(),t.add(r)}return Object.keys(a).length>0&&await this.handlerMod(a,t),Array.from(t)}handleIncludes(){if(!Array.isArray(includes_json_1.default))return;const e=includes_json_1.default.filter(e=>"string"==typeof e).map(async e=>{const t=path.join(this.cwd,"res",e),i=path.join(this.outdir,e);await utils.FileExsit(t)&&await utils.copy(t,i)});return Promise.all(e)}async processMinification(e){try{if(!Array.isArray(includes_json_1.default))return void(0,utils_1.default)(index_js_1.default.build.includes_not_array);await(0,index_js_3.default)(this.outdir,{modules:this.Modules,sourceDir:path.join(this.outdir,"scripts"),baseDir:this.baseDir,minify:Boolean(e.minify)}),await utils.waitGC()}catch(e){(0,utils_1.default)(index_js_1.default.build.minification_error+e)}}}exports.default=Build;
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var a=Object.getOwnPropertyDescriptor(t,i);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,a)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var i={};if(null!=t)for(var s=e(t),a=0;a<s.length;a++)"default"!==s[a]&&__createBinding(i,t,s[a]);return __setModuleDefault(i,t),i}}(),__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});const fs=__importStar(require("fs/promises")),path=__importStar(require("path")),ts=__importStar(require("typescript")),index_js_1=__importDefault(require("./../lang/index.js")),index_js_2=require("./../uuid/index.js"),index_js_3=__importDefault(require("./../code-processor/index.js")),utils=__importStar(require("./../utils/index.js")),getModule_js_1=__importDefault(require("./getModule.js")),includes_json_1=__importDefault(require("./../data/includes.json")),clean_js_1=__importDefault(require("./../start/clean.js")),index_js_4=__importDefault(require("./../runTemp/index.js")),base_js_1=require("./base.js"),manifest_build_js_1=require("./manifest.build.js"),mcx_core_1=__importDefault(require("@mbler/mcx-core")),node_os_1=__importDefault(require("node:os")),utils_1=__importDefault(require("./utils"));class Build extends base_js_1.BaseBuild{baseDir;baseModDir;gamelibModule;constructor(e,t){super(),e||utils.Exit(index_js_1.default.build.config_invalid),this.baseDir=t,this.baseCwd=path.isAbsolute(e)?e:path.join(t,e),this.cwd=path.join(this.baseCwd,"behavior"),this.ResOutDir=null,this.ResCwd=path.join(this.baseCwd,"resources"),this.dependencies={},this.gamelibModule=null,this.baseModDir=path.join(this.baseDir,"lib/modules"),this.#e(["baseModDir","baseDir"]),this.#t(["outdir","dependencies","gamelibModule","cwd","ResCwd","baseModDir","baseCwd"]),this.cacheDir=path.join(this.baseCwd,".cache__mbler__")}#e(e){if(Array.isArray(e))for(let t of e)Object.defineProperty(this,t,{enumerable:!1,writable:!1})}#t(e){if(Array.isArray(e))for(let t of e)Object.defineProperty(this,t,{enumerable:!1})}async#i(){try{await fs.mkdir(this.cacheDir,{recursive:!0})}catch(e){if("EEXIST"!==e.code)throw e}}build(){return this.start().catch(e=>{const t=utils.toString(e);(0,utils_1.default)(index_js_1.default.build.error_message_log+t)})}async start(){const e=Date.now();await this.#i();const{configChanged:t,packageChanged:i}=await this.chackConfigHash(),s=new clean_js_1.default(this.baseCwd,this.baseDir);await s.run(),await utils.waitGC();const a=await this.loadPackageData();this.d_data=a,this.outdir=this.getOutputDir(a.outdir?.behavior,path.join(this.baseCwd,"dist/dep")),this.ResOutDir=this.getOutputDir(a.outdir?.resources,path.join(this.baseCwd,"dist/res"));const r=["name","description","version","mcVersion"];if(!utils.hasKeys(a,r,r.length))throw new Error(`${index_js_1.default.build.package_file} 字段缺失:必需字段 ${JSON.stringify(r)}`);switch(this.gamelibModule=await(0,getModule_js_1.default)(this.baseDir),console.log(index_js_1.default.build.build_info_header),console.table({[index_js_1.default.build.project_path]:this.baseCwd,[index_js_1.default.build.output_dir]:JSON.stringify(a.outdir),[index_js_1.default.build.minify_enabled]:Boolean(a.minify),[index_js_1.default.build.build_time]:Build.times,[index_js_1.default.build.tip_dist]:process.env.MBLER_BUILD_MODULE||"dev"}),await Promise.all([this.writeManifest(a),this.handleScripts(a),this.handleIncludes(),this.processSubpacks(a)]),a.script?.lang&&(0,utils_1.default)("对特定语言进行处理:"+a.script.lang),a.script?.lang||""){case"ts":await this.compileTypeScriptUnified();break;case"mcx":await mcx_core_1.default.load({ProjectDir:path.join(this.baseCwd),config:{},output:path.join(this.outdir,"scripts"),main:path.join(this.cwd,"scripts",a.script?.main||"index.js"),moduleDir:path.join(this.outdir,"scripts/node_modules")});break;default:console.error("无效的语言设置")}await Promise.all([this.processMinification(a),this.processResources()]),await this.processDist(),console.log(`${index_js_1.default.build.build_success} ${(Date.now()-e)/1e3}`)}async writeManifest(e){const t=await this.buildManifest(e);await this.writeFile(path.join(this.outdir,"manifest.json"),t)}async buildManifest(e){const t=new manifest_build_js_1.ManiFest(e,"data").data,i=e.subpack||{};return"object"==typeof e.ResDes&&this.processResourceDependencies(e,t),"object"==typeof e.subpack&&Object.keys(e.subpack).length>0&&(t.subpack=Object.keys(e.subpack).map(e=>({folder_name:e,name:i[e]||"",memory_tier:1}))),t}processResourceDependencies(e,t){const{name:i="unknown",version:s}=e.ResDes||{};s&&utils.isVerison(s)&&t.dependencies.push({name:(0,index_js_2.fromString)(i),version:utils.ToArray(s)})}async handleScripts(e){if(!e.script||"object"!=typeof e.script)return;const t=path.join(this.cwd,"scripts"),i=path.join(this.outdir,"scripts");await utils.FileExsit(t)&&(await utils.copy(t,i),this.dependencies=e.script.dependencies||{},await this.initNpmDes(),Object.keys(this.dependencies).length>0&&(this.Modules=await this.handlerMod(this.dependencies,new Set)))}async processSubpacks(e){if("object"!=typeof e.subpack)return;const t=this.outdir,i=new Build(this.cwd,this.baseDir);for(let[s,a]of Object.entries(e.subpack))try{const e=path.join(this.cwd,"subpacks",s),a=path.join(t,"subpacks",s);if(await fs.mkdir(a,{recursive:!0}),!await utils.FileExsit(e)){(0,utils_1.default)(index_js_1.default.build.subpack_folder_not_found.replace("{id}",s));continue}const r=path.join(e,"scripts"),n=path.join(a,"scripts");await utils.FileExsit(r)&&await utils.copy(r,n),i.cwd=e,i.outdir=a,await i.handleIncludes()}catch(e){(0,utils_1.default)(index_js_1.default.build.error_processing_subpack.replace("{id}",s).replace("{error}",e.stack))}}async compileTypeScriptUnified(){const e=new index_js_4.default(path.join(node_os_1.default.tmpdir(),"mbler"));await e.init();const t=e.dir;try{const e=await this.getAllTsFiles(this.outdir);if(!e||0===e.length)return void(0,utils_1.default)(index_js_1.default.build.ts_no_files);let i={compilerOptions:{target:"esnext",module:"esnext",moduleResolution:"NodeNext",esModuleInterop:!0,verbatimModuleSyntax:!1,allowSyntheticDefaultImports:!0,outDir:t,rootDir:this.outdir,strict:!0,allowJs:!0,sourceMap:!1,incremental:!0,tsBuildInfoFile:path.join(this.cacheDir,"tsbuildinfo")},include:["**/*.ts"]};await utils.FileExsit(path.join(this.baseCwd,"tsconfig.json"))&&(i=JSON.parse(await fs.readFile(path.join(this.baseCwd,"tsconfig.json"),"utf-8")));const s=ts.parseJsonConfigFileContent(i,ts.sys,this.outdir,void 0,"tsconfig.json"),a=ts.createProgram({rootNames:e,options:s.options}),r=a.emit();ts.getPreEmitDiagnostics(a).concat(r.diagnostics).forEach(e=>{const t=ts.flattenDiagnosticMessageText(e.messageText,"\n");if(e.file){const{line:i,character:s}=e.file.getLineAndCharacterOfPosition(e.start);(0,utils_1.default)(index_js_1.default.build.ts_diagnostics.replace("{file}",e.file.fileName).replace("{line}",(i+1).toString()).replace("{character}",(s+1).toString()).replace("{message}",t))}else(0,utils_1.default)(t)}),await this.removeJsFiles(path.join(this.outdir,"scripts")),await this.copyCompiledOnly(t,this.outdir),(0,utils_1.default)(index_js_1.default.build.ts_compilation_error+" 完成")}catch(e){throw(0,utils_1.default)(index_js_1.default.build.ts_compilation_error+e.stack),e}finally{await e.remove()}}async handlerMod(e,t=new Set){const i=this.gamelibModule.getAll(),s=path.join(this.outdir,"scripts/node_modules");let a={};for(const[r,n]of Object.entries(e)){if(!i.includes(r)||t.has(r))continue;const e=await this.gamelibModule.getDir(r,{gitUrl:n,v:this.d_data.mcVersion});if(!e||!await utils.FileExsit(e))continue;const o=await utils.handlerPackage(e,{des:Array.from(t)});o.des&&Object.assign(a,o.des),await utils.copy(e,path.join(s,r)),await utils.waitGC(),t.add(r)}return Object.keys(a).length>0&&await this.handlerMod(a,t),Array.from(t)}handleIncludes(){if(!Array.isArray(includes_json_1.default))return;const e=includes_json_1.default.filter(e=>"string"==typeof e).map(async e=>{const t=path.join(this.cwd,"res",e),i=path.join(this.outdir,e);await utils.FileExsit(t)&&await utils.copy(t,i)});return Promise.all(e)}async processMinification(e){try{if(!Array.isArray(includes_json_1.default))return void(0,utils_1.default)(index_js_1.default.build.includes_not_array);await(0,index_js_3.default)(this.outdir,{modules:this.Modules,sourceDir:path.join(this.outdir,"scripts"),baseDir:this.baseDir,minify:Boolean(e.minify)}),await utils.waitGC()}catch(e){(0,utils_1.default)(index_js_1.default.build.minification_error+e)}}}exports.default=Build;
package/package.json CHANGED
@@ -1 +1,49 @@
1
- {"name":"mbler","version":"0.1.4","description":"一个针对Minecraft JavaScript API 的CLI工具,让你的附加包版本管理更简单","repository":{"type":"git","url":"git+https://github.com/RuanhoR/mbler.git"},"keywords":["Minecraft","build","cli"],"engines":{"node":">=16.0.0"},"license":"MIT","type":"commonjs","main":"./lib/start/index.js","scripts":{"cli":"node bin/mbler.js","build":"node bin/minify.js"},"dependencies":{"@babel/generator":"7.28.5","@babel/parser":"7.28.5","@babel/traverse":"7.28.5","@babel/types":"7.28.6","@mbler/mcx-core":"0.0.2-beta.r2","adm-zip":"0.5.16","chokidar":"4.0.3","dayjs":"1.11.18","terser":"5.44.0","typescript":"^5.9.3"},"files":["lib","test","bin","README.md","LICENSE"],"publishConfig":{"registry":"https://registry.npmjs.org"},"bin":{"mbler":"bin/mbler.js"}}
1
+ {
2
+ "name": "mbler",
3
+ "version": "0.1.5-alpha",
4
+ "description": "一个针对Minecraft JavaScript API 的CLI工具,让你的附加包版本管理更简单",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/RuanhoR/mbler.git"
8
+ },
9
+ "keywords": [
10
+ "Minecraft",
11
+ "build",
12
+ "cli"
13
+ ],
14
+ "engines": {
15
+ "node": ">=16.0.0"
16
+ },
17
+ "license": "MIT",
18
+ "type": "commonjs",
19
+ "main": "./lib/start/index.js",
20
+ "scripts": {
21
+ "cli": "node bin/mbler.js",
22
+ "build": "node bin/minify.js"
23
+ },
24
+ "dependencies": {
25
+ "@babel/generator": "7.28.5",
26
+ "@babel/parser": "7.28.5",
27
+ "@babel/traverse": "7.28.5",
28
+ "@babel/types": "7.28.6",
29
+ "@mbler/mcx-core": "0.0.2-beta.r2",
30
+ "adm-zip": "0.5.16",
31
+ "chokidar": "4.0.3",
32
+ "dayjs": "1.11.18",
33
+ "terser": "5.44.0",
34
+ "typescript": "^5.9.3"
35
+ },
36
+ "files": [
37
+ "lib",
38
+ "test",
39
+ "bin",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "publishConfig": {
44
+ "registry": "https://registry.npmjs.org"
45
+ },
46
+ "bin": {
47
+ "mbler": "bin/mbler.js"
48
+ }
49
+ }
@@ -1 +0,0 @@
1
- ba9e19e27533c85678ae256b688d8daeb7672d47
@@ -1 +0,0 @@
1
- 656d6fae1681c5cda2ad25f63d34b39f48a334ce
@@ -1,25 +0,0 @@
1
- const config = {
2
- itemId: "§r§6§lmbler_test_2xsword:as§r§l §8 二倍剑",
3
- ForRanger: 2
4
- }
5
- import {
6
- EntityComponentTypes,
7
- EquipmentSlot,
8
- world,
9
- system
10
- } from "@minecraft/server"
11
- world.afterEvents.entityDie.subscribe(({
12
- deadEntity: entity,
13
- damageSource: source
14
- }) => {
15
- system.run(()=>{ try { // 排除非正常人
16
- if (!source.typeId.includes("player") || !getMainHand(source).nameTag.includes(config.itemId)) return;
17
- } catch {}
18
- for (let i = 0; i < config.ForRanger; i++) {
19
- try {
20
- entity.dimension.spawnEntity(entity.typeId)
21
- } catch (err){
22
- console.error(err)
23
- }
24
- }})
25
- })
@@ -1,12 +0,0 @@
1
- {
2
- "name": "双倍剑",
3
- "description": "打生物会再生成一个的奇葩剑",
4
- "mcVersion": "1.21.80",
5
- "version": "0.0.2",
6
- "script": {
7
- "main": "index",
8
- "ui": true
9
- },
10
- "minify": false,
11
- "outdir": "/storage/emulated/0/Android/data/com.mojang.minecraftpe/files/games/com.mojang/development_behavior_packs/test/"
12
- }
@@ -1,14 +0,0 @@
1
- {
2
- "name": "双倍剑",
3
- "description": "打生物会再生成一个的奇葩剑",
4
- "version": "0.0.2",
5
- "engines": {
6
- "node": ">=20.0.0"
7
- },
8
- "scripts": {
9
- "dev": "mbler dev",
10
- "build": "MBLER_BUILD_MODULE=dist mbler build",
11
- "dev-build": "MBLER_BUILD_MODULE=dev mbler build"
12
- },
13
- "dependencies": {}
14
- }
package/test/README.md DELETED
@@ -1,8 +0,0 @@
1
- # 欢迎来到测试脚本列表 !
2
-
3
- 这里有两个文件夹,分别是包测试,你可以使用
4
-
5
- > mbler <
6
-
7
- 构建成Minecraft行为包 !
8
- 这些包可供你学习mbler的用法
package/test/des/index.js DELETED
@@ -1,20 +0,0 @@
1
- exports.main = async function main(content) {
2
- const name = await MblerApi.input("名称")
3
- const desc = await MblerApi.input(`描述 `)
4
- const main = await MblerApi.input(`主脚本 `)
5
- content.setWorkDir
6
- .writeFile("./mbler.config.json", JSON.stringify({
7
- name,
8
- description: desc,
9
- script: {
10
- main: "src/index.js",
11
- dependencies: {}
12
- },
13
- type: "scriptsDes",
14
- version: "0.0.1",
15
- mcVersion: [
16
- "1.21.00",
17
- "1.21.100"
18
- ]
19
- }, null, 2))
20
- }
@@ -1,5 +0,0 @@
1
- {
2
- "name": "",
3
- "description": "",
4
- "version": ""
5
- }
@@ -1,7 +0,0 @@
1
- {
2
- "name": "",
3
- "description": "",
4
- "version": "0.0.1",
5
- "module": "commjs",
6
- "main": "./index.js"
7
- }
@@ -1,6 +0,0 @@
1
- require("./test.js")
2
- exports.main = function({
3
- work
4
- }) {
5
- console.log(work)
6
- }
@@ -1,5 +0,0 @@
1
- {
2
- "name": "",
3
- "description": "",
4
- "version": ""
5
- }
@@ -1,7 +0,0 @@
1
- {
2
- "name": "",
3
- "description": "",
4
- "version": "0.0.1",
5
- "module": "commjs",
6
- "main": "./index.js"
7
- }
@@ -1 +0,0 @@
1
- console.log("Test Load")
@@ -1,22 +0,0 @@
1
- {
2
- "format_version": "1.20.100",
3
- "minecraft:item": {
4
- "description": {
5
- "identifier": "mbler_int:mang_one_int"
6
- },
7
- "components": {
8
- "minecraft:hand_equipped": false,
9
- "minecraft:foil": true,
10
- "minecraft:glint": true,
11
- "allow_off_hand": {
12
- "value": true
13
- },
14
- "minecraft:max_stack_size": 1,
15
- "minecraft:stacked_by_data": true,
16
- "minecraft:icon": "iconMangOneIntMbler",
17
- "minecraft:display_name": {
18
- "value": "无尽袋子 \n能存入无限的单种物品 右键打开"
19
- }
20
- }
21
- }
22
- }
@@ -1,31 +0,0 @@
1
- {
2
- "format_version": "1.21",
3
- "minecraft:recipe_shaped": {
4
- "description": {
5
- "identifier": "mbler_int:recipes_mang_one_int"
6
- },
7
- "tags": [
8
- "crafting_table"
9
- ],
10
- "unlock": [
11
- {
12
- "item": "minecraft:leather"
13
- }
14
- ],
15
- "pattern": [
16
- "A ",
17
- "AB "
18
- ],
19
- "key": {
20
- "A": {
21
- "item": "minecraft:leather"
22
- },
23
- "B": {
24
- "item": "minecraft:stick"
25
- }
26
- },
27
- "result": {
28
- "item": "mbler_int:mang_one_int"
29
- }
30
- }
31
- }
@@ -1,8 +0,0 @@
1
- import {
2
- GameLib
3
- } from "gameLib"
4
- import {
5
- regEvent
6
- } from "./lib/event/index"
7
- const game = new GameLib(true);
8
- regEvent(game);
@@ -1,20 +0,0 @@
1
- import ui from "./../ui/index"
2
- import {
3
- world
4
- } from "@minecraft/server"
5
- let scriptUi;
6
- const useItem = ({
7
- source: player,
8
- itemStack: item
9
- }) => {
10
- if (!player.typeId.includes('player')) return;
11
- if (item.typeId === "mbler_int:mang_one_int")
12
- scriptUi.openHomeForm(player, item)
13
- }
14
- const regEvent = (game) => {
15
- world.afterEvents.itemUse.subscribe(useItem);
16
- scriptUi = new ui(game)
17
- }
18
- export {
19
- regEvent
20
- }
@@ -1,19 +0,0 @@
1
- export class Lore {
2
- name;
3
- count;
4
- constructor(item) {
5
- const LoreArr = item.getLore();
6
- let count = parseInt(`0x${LoreArr[1]}`) // 加上16进制表明式
7
- if (!/^[a-z0-9_]+(\:)?[a-z0-9_]+$/.test(LoreArr[0] + ''))
8
- LoreArr[0] = undefined;
9
- if (isNaN(count)) count = 0;
10
- this.count = count;
11
- this.name = LoreArr[0];
12
- }
13
- parseArr() {
14
- return [
15
- this.name,
16
- this.count.toString(16)
17
- ]
18
- }
19
- }
@@ -1,6 +0,0 @@
1
- export class baseUi {
2
- game;
3
- constructor(game) {
4
- this.game = game;
5
- };
6
- }
@@ -1,207 +0,0 @@
1
- import {
2
- baseUi
3
- } from "./baseUi";
4
- import {
5
- utils
6
- } from "./../utils/index";
7
- import {
8
- Lore
9
- } from "./Lore";
10
- class ItemBagUI extends baseUi {
11
- initLayout() {
12
- this.layouts = this.game.regLayout({
13
- regIds: ["Home", "NumSelect", "showInNoFound"],
14
- Home: {
15
- title: "菜单",
16
- layout: [{
17
- type: "button",
18
- param: ["存入物品"]
19
- },
20
- {
21
- type: "button",
22
- param: ["取出物品"]
23
- },
24
- ],
25
- },
26
- NumSelect: {
27
- title: "选择数量",
28
- layout: []
29
- },
30
- showInNoFound: {
31
- title: "请选择要存入的物品",
32
- layout: [{
33
- type: "label",
34
- param: ["点击你想要存放的物品"]
35
- }]
36
- }
37
- })
38
- }
39
- /**
40
- * 打开主菜单:存入物品 / 取出物品
41
- */
42
- openHomeForm(player, itemOnHand) {
43
- if (!this.layouts) this.initLayout();
44
- const lore = new Lore(itemOnHand);
45
- const form = this.game.createForm("Action", this.layouts[0]);
46
- form.addLayout({
47
- type: "label",
48
- param: [`无尽袋子 - 菜单\n物品 : ${lore.name} , 数量 : ${lore.count}`]
49
- })
50
- form.show(player, true).onCommit(({
51
- selection
52
- }) => {
53
- switch (selection) {
54
- case 0:
55
- this.openAddItemForm(player, itemOnHand);
56
- break;
57
- case 1:
58
- this.hanlerTakeOutItems(player, itemOnHand);
59
- break;
60
- default:
61
- player.sendMessage("请选择存入或取出");
62
- }
63
- });
64
- }
65
- hanlerTakeOutItems(player, itemOnHand) {
66
- const lore = new Lore(itemOnHand)
67
- if (!lore.name) return player.sendMessage('没有存入任何东西');
68
- this.selectionNum({
69
- min: 1,
70
- max: lore.count,
71
- tit: lore.name,
72
- callback: ({
73
- formValues
74
- }) => {
75
- const TakeOutCount = formValues[0];
76
- player.runCommand(`give @s ${lore.name} ${TakeOutCount}`)
77
- lore.count = lore.count - TakeOutCount;
78
- itemOnHand.setLore(lore.parseArr())
79
- utils.setMainHand(player, itemOnHand);
80
- },
81
- lastUi: () => this.openHomeForm(player, itemOnHand)
82
- }, player)
83
- }
84
- /**
85
- * 打开“存入物品”表单(自动识别物品类型)
86
- */
87
- openAddItemForm(player, itemOnHand) {
88
- const currencyLore = new Lore(itemOnHand);
89
- // 如果 Lore 无法识别此物品(比如没有 name 字段),则进入手动选择模式
90
- if (currencyLore.name === undefined) {
91
- return this.showInNoData(player, currencyLore, itemOnHand);
92
- }
93
- const inventoryData = utils.getAllPlayerInt(player);
94
- let totalItemAmount = 0;
95
- // 统计当前玩家拥有该物品的总数量
96
- for (const [itemId, itemData] of inventoryData) {
97
- const [itemName, itemCount] = itemData;
98
- if (itemName === currencyLore.name) {
99
- totalItemAmount += itemCount;
100
- }
101
- }
102
- // 如果该物品数量为 0,则提示无法存入
103
- if (totalItemAmount <= 0) {
104
- return player.sendMessage("你没有该物品,无法存入!");
105
- }
106
- // 弹出滑条,让用户选择存入多少个
107
- this.selectionNum({
108
- min: 0,
109
- max: totalItemAmount,
110
- tit: currencyLore.name,
111
- callback: ({
112
- formValues
113
- }) => {
114
- const countToStore = formValues[0];
115
- currencyLore.count = countToStore + totalItemAmount;
116
- this.handlerAdd(currencyLore, player, itemOnHand, countToStore);
117
- },
118
- lastUi: () => this.openHomeForm(player, itemOnHand),
119
- },
120
- player
121
- );
122
- }
123
- /**
124
- * 当物品无法自动识别时,让用户从列表中手动选择要存入的物品
125
- */
126
- showInNoData(player, placeholderLore, itemOnHand) {
127
- const form = this.game.createForm("Action", this.layouts[2]);
128
- const inventoryData = utils.getAllPlayerInt(player);
129
- const itemButtons = [];
130
- const itemKeys = [];
131
- let buttonIndex = 0;
132
- for (const [itemId, itemData] of inventoryData) {
133
- if (!Array.isArray(itemData)) continue;
134
- const [itemName, itemCount] = itemData;
135
- form.addLayout({
136
- type: "button",
137
- param: [`${itemName} x${itemCount}`],
138
- });
139
- itemKeys[buttonIndex] = itemId;
140
- buttonIndex++;
141
- }
142
- form.show(player).then(({
143
- selection,
144
- canceled
145
- }) => {
146
- if (canceled) {
147
- return this.openHomeForm(player, itemOnHand);
148
- }
149
- if (selection === undefined || selection >= itemKeys.length) {
150
- return player.sendMessage("你选择的物品无效");
151
- }
152
- const selectedItemId = itemKeys[selection];
153
- const selectedItemData = inventoryData.get(selectedItemId);
154
- if (!selectedItemData || !Array.isArray(selectedItemData)) {
155
- return player.sendMessage("该物品数据异常");
156
- }
157
- const [selectedItemName, selectedItemCount] = selectedItemData;
158
- this.selectionNum({
159
- tit: `存入 ${selectedItemName}`,
160
- min: 0,
161
- max: selectedItemCount,
162
- callback: ({
163
- formValues
164
- }) => {
165
- const countToStore = formValues[0];
166
- const manualLore = new Lore(itemOnHand);
167
- manualLore.name = selectedItemName;
168
- manualLore.count = countToStore + selectedItemCount;
169
- this.handlerAdd(manualLore, player, itemOnHand, countToStore);
170
- },
171
- lastUi: () => this.openHomeForm(player, itemOnHand),
172
- },
173
- player
174
- );
175
- });
176
- }
177
- handlerAdd(lore, player, originalItem, countToStore) {
178
- utils.removeItems(player, {
179
- name: lore.name,
180
- count: countToStore,
181
- });
182
- originalItem.setLore(lore.parseArr())
183
- utils.setMainHand(player, originalItem);
184
- player.sendMessage(`成功存入 ${countToStore} 个「${lore.name}」`);
185
- }
186
- selectionNum({
187
- min = 0,
188
- max = 1,
189
- tit = "",
190
- callback = () => {},
191
- lastUi = () => {},
192
- } = {},
193
- player
194
- ) {
195
- const form = this.game
196
- .createForm("Modal", this.layouts[1])
197
- form.addLayout({
198
- type: "slider",
199
- param: [tit, min, max]
200
- })
201
- const show = form.show(player, true)
202
- show.onCancel(lastUi)
203
- show.onCommit(callback);
204
- }
205
- }
206
-
207
- export default ItemBagUI;
@@ -1,52 +0,0 @@
1
- import {
2
- EntityComponentTypes,
3
- EquipmentSlot
4
- } from "@minecraft/server"
5
-
6
- export class utils {
7
- static getAllPlayerInt(player) {
8
- const data = new Map();
9
- const inventory = player
10
- .getComponent("inventory")
11
- .container;
12
- for (let i = 0; i < inventory.size; i++) {
13
- const item = inventory.getItem(i);
14
- if (!item) continue;
15
- let num = item.amount;
16
- // 自动合并
17
- const it = data.get(item.typeId);
18
- if (Array.isArray(it)) num += it[1]
19
- data.set(item.typeId, [item.typeId, num]);
20
- }
21
- return data;
22
- }
23
- static setMainHand(player, item) {
24
- const Equippable = player
25
- .getComponent(EntityComponentTypes.Equippable);
26
- Equippable
27
- .setEquipment(EquipmentSlot.Mainhand, item);
28
- }
29
- static removeItems(player, {
30
- name,
31
- count
32
- } = {}) {
33
- const inventory = player
34
- .getComponent("inventory")
35
- .container;
36
- let RemoveNum = count;
37
- for (let i = 0; i < inventory.size; i++) {
38
- const item = inventory.getItem(i);
39
- if (!item || !item.typeId || item.typeId !== name) continue;
40
- const num = item.amount;
41
- if (RemoveNum >= num) {
42
- inventory.setItem(i, null);
43
- RemoveNum -= num;
44
- } else {
45
- const remNum = RemoveNum >= 64 ? 64 : Math.max(RemoveNum, item.amount) - Math.min(RemoveNum, item.amount)
46
- item.amount = remNum;
47
- RemoveNum -= remNum
48
- inventory.setItem(i, item);
49
- }
50
- }
51
- }
52
- }
@@ -1,19 +0,0 @@
1
- {
2
- "name": "无尽袋子",
3
- "description": "一个袋子装无限的单种物品",
4
- "mcVersion": "1.21.120",
5
- "version": "0.0.1",
6
- "script": {
7
- "main": "index.js",
8
- "ui": true,
9
- "dependencies": {
10
- "gameLib": "inner"
11
- }
12
- },
13
- "minify": true,
14
- "outdir": {
15
- "resources": "./dist/res",
16
- "behavior": "./dist/dep",
17
- "dist": "./dist.mcaddon"
18
- }
19
- }
@@ -1,13 +0,0 @@
1
- {
2
- "name": "mbler/test mbler-int",
3
- "description": "能存无数物品的袋子 !",
4
- "version": "0.0.1",
5
- "engines": {
6
- "node": ">=16.0.0"
7
- },
8
- "scripts": {
9
- "dev": "mbler dev",
10
- "build": "MBLER_BUILD_MODULE=dist mbler build",
11
- "dev-build": "MBLER_BUILD_MODULE=dev mbler build"
12
- }
13
- }
@@ -1 +0,0 @@
1
- 80fa1241600cf387733e2616d0212ba44aafb473
@@ -1 +0,0 @@
1
- dabb5660e507e23f52e1a5dbbd14f86b38f49e2b
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const server_1 = require("@minecraft/server");
4
- console.log('console in ts minecraft');
5
- server_1.world.getPlayers().sendMessage('text');
@@ -1,6 +0,0 @@
1
- import {
2
- world
3
- } from "@minecraft/server"
4
- console.log('console in ts minecraft')
5
-
6
- world.getPlayers().sendMessage('text')
@@ -1,15 +0,0 @@
1
- {
2
- "name": "test",
3
- "description": "test",
4
- "version": "0.1.1",
5
- "mcVersion": "1.21.100",
6
- "script": {
7
- "ui": true,
8
- "lang": "ts",
9
- "main": "main",
10
- "dependencies": {
11
- "gameLib": "inner"
12
- }
13
- },
14
- "minify": true
15
- }
@@ -1,16 +0,0 @@
1
- {
2
- "name": "test",
3
- "description": "Hello world",
4
- "version": "0.0.1",
5
- "engines": {
6
- "node": ">=16.0.0"
7
- },
8
- "scripts": {
9
- "dev": "mbler dev",
10
- "build": "MBLER_BUILD_MODULE=dist mbler build",
11
- "dev-build": "MBLER_BUILD_MODULE=dev mbler build"
12
- },
13
- "dependencies": {
14
- "@minecraft/server": "2.1.0"
15
- }
16
- }