sapdon 3.1.0 → 3.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.
Files changed (220) hide show
  1. package/README.md +8 -1
  2. package/doc/api.md +2 -2
  3. package/package.json +18 -19
  4. package/{dist → prod}/cli/index.d.ts +1 -1
  5. package/prod/cli/index.js +1 -0
  6. package/{dist → prod}/cli/start.js +1027 -967
  7. package/{dist → prod}/core/index.d.ts +2156 -1652
  8. package/prod/core/index.js +59015 -0
  9. package/{dist → prod}/oc/index.d.ts +2 -1
  10. package/prod/utils/index.d.ts +42 -0
  11. package/prod/utils/index.js +1 -0
  12. package/dist/cli/build.d.ts +0 -7
  13. package/dist/cli/build.js +0 -236
  14. package/dist/cli/dev-server/client.d.ts +0 -2
  15. package/dist/cli/dev-server/client.js +0 -21
  16. package/dist/cli/dev-server/config.d.ts +0 -3
  17. package/dist/cli/dev-server/config.js +0 -3
  18. package/dist/cli/dev-server/handles.d.ts +0 -4
  19. package/dist/cli/dev-server/handles.js +0 -5
  20. package/dist/cli/dev-server/hmr.d.ts +0 -1
  21. package/dist/cli/dev-server/hmr.js +0 -13
  22. package/dist/cli/dev-server/index.d.ts +0 -4
  23. package/dist/cli/dev-server/index.js +0 -17
  24. package/dist/cli/dev-server/server.d.ts +0 -14
  25. package/dist/cli/dev-server/server.js +0 -59
  26. package/dist/cli/dev-server/syncFiles.d.ts +0 -3
  27. package/dist/cli/dev-server/syncFiles.js +0 -45
  28. package/dist/cli/index.js +0 -90
  29. package/dist/cli/init.d.ts +0 -9
  30. package/dist/cli/init.js +0 -80
  31. package/dist/cli/load.d.ts +0 -3
  32. package/dist/cli/load.js +0 -94
  33. package/dist/cli/start.d.ts +0 -2
  34. package/dist/cli/tools/textureSet.d.ts +0 -13
  35. package/dist/cli/tools/textureSet.js +0 -103
  36. package/dist/cli/utils.d.ts +0 -13
  37. package/dist/cli/utils.js +0 -89
  38. package/dist/core/addon/biome.d.ts +0 -22
  39. package/dist/core/addon/biome.js +0 -27
  40. package/dist/core/addon/block/block.d.ts +0 -41
  41. package/dist/core/addon/block/block.js +0 -46
  42. package/dist/core/addon/controllers/animationController.d.ts +0 -43
  43. package/dist/core/addon/controllers/animationController.js +0 -73
  44. package/dist/core/addon/controllers/render_controllers.js +0 -162
  45. package/dist/core/addon/entity/clientEntity.d.ts +0 -107
  46. package/dist/core/addon/entity/clientEntity.js +0 -149
  47. package/dist/core/addon/entity/entity.d.ts +0 -42
  48. package/dist/core/addon/entity/entity.js +0 -50
  49. package/dist/core/addon/feature/oreFeature.d.ts +0 -19
  50. package/dist/core/addon/feature/oreFeature.js +0 -24
  51. package/dist/core/addon/featureRule.d.ts +0 -20
  52. package/dist/core/addon/featureRule.js +0 -25
  53. package/dist/core/addon/item/attachable.d.ts +0 -94
  54. package/dist/core/addon/item/attachable.js +0 -134
  55. package/dist/core/addon/item/item.d.ts +0 -19
  56. package/dist/core/addon/item/item.js +0 -26
  57. package/dist/core/addon/manifest.d.ts +0 -49
  58. package/dist/core/addon/manifest.js +0 -65
  59. package/dist/core/addon/menuCategory.d.ts +0 -6
  60. package/dist/core/addon/menuCategory.js +0 -7
  61. package/dist/core/addon/recipe/baseRecipe.d.ts +0 -12
  62. package/dist/core/addon/recipe/baseRecipe.js +0 -23
  63. package/dist/core/addon/recipe/data.d.ts +0 -66
  64. package/dist/core/addon/recipe/data.js +0 -74
  65. package/dist/core/addon/recipe/furnace.d.ts +0 -17
  66. package/dist/core/addon/recipe/furnace.js +0 -43
  67. package/dist/core/addon/recipe/shaped.d.ts +0 -26
  68. package/dist/core/addon/recipe/shaped.js +0 -53
  69. package/dist/core/addon/recipe/shapeless.d.ts +0 -18
  70. package/dist/core/addon/recipe/shapeless.js +0 -36
  71. package/dist/core/biome/biome.d.ts +0 -14
  72. package/dist/core/biome/biome.js +0 -23
  73. package/dist/core/biome/biomeComponent.d.ts +0 -46
  74. package/dist/core/biome/biomeComponent.js +0 -77
  75. package/dist/core/block/basicBlock.d.ts +0 -48
  76. package/dist/core/block/basicBlock.js +0 -105
  77. package/dist/core/block/block.d.ts +0 -32
  78. package/dist/core/block/block.js +0 -92
  79. package/dist/core/block/blockComponent.d.ts +0 -187
  80. package/dist/core/block/blockComponent.js +0 -500
  81. package/dist/core/block/cropBlock.d.ts +0 -4
  82. package/dist/core/block/cropBlock.js +0 -27
  83. package/dist/core/block/geometryBlock.d.ts +0 -12
  84. package/dist/core/block/geometryBlock.js +0 -16
  85. package/dist/core/block/oreBlock.d.ts +0 -9
  86. package/dist/core/block/oreBlock.js +0 -25
  87. package/dist/core/block/rotatableBlock.d.ts +0 -27
  88. package/dist/core/block/rotatableBlock.js +0 -107
  89. package/dist/core/block/tileBlock.d.ts +0 -17
  90. package/dist/core/block/tileBlock.js +0 -125
  91. package/dist/core/entity/basicEntity.d.ts +0 -111
  92. package/dist/core/entity/basicEntity.js +0 -170
  93. package/dist/core/entity/behavior/followMob.d.ts +0 -12
  94. package/dist/core/entity/behavior/followMob.js +0 -35
  95. package/dist/core/entity/behavior/followParent.d.ts +0 -7
  96. package/dist/core/entity/behavior/followParent.js +0 -15
  97. package/dist/core/entity/behavior/randomStroll.d.ts +0 -31
  98. package/dist/core/entity/behavior/randomStroll.js +0 -63
  99. package/dist/core/entity/behavior/tempt.d.ts +0 -73
  100. package/dist/core/entity/behavior/tempt.js +0 -134
  101. package/dist/core/entity/bundles/BasicMoveBundle.js +0 -8
  102. package/dist/core/entity/bundles/basicBundle.d.ts +0 -13
  103. package/dist/core/entity/bundles/basicBundle.js +0 -38
  104. package/dist/core/entity/clientEntity.d.ts +0 -20
  105. package/dist/core/entity/clientEntity.js +0 -37
  106. package/dist/core/entity/componets/entityComponet.d.ts +0 -202
  107. package/dist/core/entity/componets/entityComponet.js +0 -354
  108. package/dist/core/entity/data/nativeEntityData.d.ts +0 -9
  109. package/dist/core/entity/data/nativeEntityData.js +0 -38
  110. package/dist/core/entity/dummyEntity.js +0 -14
  111. package/dist/core/entity/entity.d.ts +0 -15
  112. package/dist/core/entity/entity.js +0 -11
  113. package/dist/core/entity/nativeEntity.d.ts +0 -8
  114. package/dist/core/entity/nativeEntity.js +0 -28
  115. package/dist/core/entity/navigation/walk.d.ts +0 -23
  116. package/dist/core/entity/navigation/walk.js +0 -56
  117. package/dist/core/entity/projectile.d.ts +0 -3
  118. package/dist/core/entity/projectile.js +0 -7
  119. package/dist/core/factory/biomeFactory.d.ts +0 -4
  120. package/dist/core/factory/biomeFactory.js +0 -13
  121. package/dist/core/factory/blockFactory.d.ts +0 -34
  122. package/dist/core/factory/blockFactory.js +0 -143
  123. package/dist/core/factory/entityFactory.d.ts +0 -17
  124. package/dist/core/factory/entityFactory.js +0 -75
  125. package/dist/core/factory/featureFactory.d.ts +0 -6
  126. package/dist/core/factory/featureFactory.js +0 -23
  127. package/dist/core/factory/itemExtra.d.ts +0 -8
  128. package/dist/core/factory/itemExtra.js +0 -9
  129. package/dist/core/factory/itemFactory.d.ts +0 -27
  130. package/dist/core/factory/itemFactory.js +0 -112
  131. package/dist/core/factory/recipeFactory.d.ts +0 -18
  132. package/dist/core/factory/recipeFactory.js +0 -39
  133. package/dist/core/factory/uiFactory.d.ts +0 -12
  134. package/dist/core/factory/uiFactory.js +0 -32
  135. package/dist/core/feature/oreFeature.d.ts +0 -10
  136. package/dist/core/feature/oreFeature.js +0 -11
  137. package/dist/core/feature-rule/condition/biomeFilter.d.ts +0 -26
  138. package/dist/core/feature-rule/condition/biomeFilter.js +0 -36
  139. package/dist/core/feature-rule/condition/featureConditions.d.ts +0 -27
  140. package/dist/core/feature-rule/condition/featureConditions.js +0 -37
  141. package/dist/core/feature-rule/distribution/coordinateDistribution.d.ts +0 -17
  142. package/dist/core/feature-rule/distribution/coordinateDistribution.js +0 -23
  143. package/dist/core/feature-rule/distribution/featureDistribution.d.ts +0 -31
  144. package/dist/core/feature-rule/distribution/featureDistribution.js +0 -41
  145. package/dist/core/feature-rule/featureRule.d.ts +0 -17
  146. package/dist/core/feature-rule/featureRule.js +0 -26
  147. package/dist/core/index.js +0 -1
  148. package/dist/core/item/armor.d.ts +0 -21
  149. package/dist/core/item/armor.js +0 -90
  150. package/dist/core/item/attachable.d.ts +0 -6
  151. package/dist/core/item/attachable.js +0 -26
  152. package/dist/core/item/food.d.ts +0 -24
  153. package/dist/core/item/food.js +0 -38
  154. package/dist/core/item/item.d.ts +0 -36
  155. package/dist/core/item/item.js +0 -69
  156. package/dist/core/item/itemComponents.d.ts +0 -113
  157. package/dist/core/item/itemComponents.js +0 -225
  158. package/dist/core/registry.d.ts +0 -12
  159. package/dist/core/registry.js +0 -17
  160. package/dist/core/texture.d.ts +0 -18
  161. package/dist/core/texture.js +0 -38
  162. package/dist/core/ui/buttonMapping.d.ts +0 -97
  163. package/dist/core/ui/buttonMapping.js +0 -132
  164. package/dist/core/ui/dataBindingObject.d.ts +0 -97
  165. package/dist/core/ui/dataBindingObject.js +0 -134
  166. package/dist/core/ui/elements/button.d.ts +0 -21
  167. package/dist/core/ui/elements/button.js +0 -101
  168. package/dist/core/ui/elements/collectionPanel.d.ts +0 -12
  169. package/dist/core/ui/elements/collectionPanel.js +0 -53
  170. package/dist/core/ui/elements/grid.d.ts +0 -8
  171. package/dist/core/ui/elements/grid.js +0 -33
  172. package/dist/core/ui/elements/image.d.ts +0 -13
  173. package/dist/core/ui/elements/image.js +0 -55
  174. package/dist/core/ui/elements/label.d.ts +0 -14
  175. package/dist/core/ui/elements/label.js +0 -61
  176. package/dist/core/ui/elements/panel.d.ts +0 -11
  177. package/dist/core/ui/elements/panel.js +0 -49
  178. package/dist/core/ui/elements/scrollingPanel.d.ts +0 -14
  179. package/dist/core/ui/elements/scrollingPanel.js +0 -59
  180. package/dist/core/ui/elements/stackPanel.d.ts +0 -14
  181. package/dist/core/ui/elements/stackPanel.js +0 -37
  182. package/dist/core/ui/elements/uiElement.d.ts +0 -53
  183. package/dist/core/ui/elements/uiElement.js +0 -129
  184. package/dist/core/ui/properties/control.d.ts +0 -214
  185. package/dist/core/ui/properties/control.js +0 -286
  186. package/dist/core/ui/properties/dataBinding.d.ts +0 -6
  187. package/dist/core/ui/properties/dataBinding.js +0 -16
  188. package/dist/core/ui/properties/factory.d.ts +0 -37
  189. package/dist/core/ui/properties/factory.js +0 -62
  190. package/dist/core/ui/properties/gridProp.d.ts +0 -65
  191. package/dist/core/ui/properties/gridProp.js +0 -90
  192. package/dist/core/ui/properties/input.d.ts +0 -97
  193. package/dist/core/ui/properties/input.js +0 -134
  194. package/dist/core/ui/properties/layout.d.ts +0 -105
  195. package/dist/core/ui/properties/layout.js +0 -145
  196. package/dist/core/ui/properties/scrollView.d.ts +0 -105
  197. package/dist/core/ui/properties/scrollView.js +0 -145
  198. package/dist/core/ui/properties/sound.d.ts +0 -47
  199. package/dist/core/ui/properties/sound.js +0 -66
  200. package/dist/core/ui/properties/sprite.d.ts +0 -161
  201. package/dist/core/ui/properties/sprite.js +0 -222
  202. package/dist/core/ui/properties/text.d.ts +0 -135
  203. package/dist/core/ui/properties/text.js +0 -187
  204. package/dist/core/ui/registry/uiSystemRegistry.d.ts +0 -8
  205. package/dist/core/ui/registry/uiSystemRegistry.js +0 -26
  206. package/dist/core/ui/systems/chest.d.ts +0 -5
  207. package/dist/core/ui/systems/chest.js +0 -21
  208. package/dist/core/ui/systems/containerUISystem.d.ts +0 -67
  209. package/dist/core/ui/systems/containerUISystem.js +0 -214
  210. package/dist/core/ui/systems/guidebook.d.ts +0 -9
  211. package/dist/core/ui/systems/guidebook.js +0 -206
  212. package/dist/core/ui/systems/serverForm.d.ts +0 -13
  213. package/dist/core/ui/systems/serverForm.js +0 -116
  214. package/dist/core/ui/systems/system.d.ts +0 -16
  215. package/dist/core/ui/systems/system.js +0 -37
  216. package/dist/oc/actor.js +0 -44
  217. package/dist/oc/core.js +0 -201
  218. package/dist/oc/input.js +0 -67
  219. package/dist/oc/optional.js +0 -31
  220. /package/{dist → prod}/oc/index.js +0 -0
@@ -1,8 +1,7 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env node
2
2
  import { program } from 'commander';
3
3
  import inquirer from 'inquirer';
4
4
  import path from 'path';
5
- import os from 'os';
6
5
  import { fileURLToPath as fileURLToPath$1 } from 'url';
7
6
  import fs, { readFileSync } from 'fs';
8
7
  import { randomUUID } from 'crypto';
@@ -17,6 +16,8 @@ import ts from '@rollup/plugin-typescript';
17
16
  import { typescriptPaths } from 'rollup-plugin-typescript-paths';
18
17
  import json from '@rollup/plugin-json';
19
18
  import 'rollup-plugin-visualizer';
19
+ import terser from '@rollup/plugin-terser';
20
+ import os from 'os';
20
21
  import lodash from 'lodash';
21
22
 
22
23
  const generateUUID = () => {
@@ -104,272 +105,377 @@ function dirname(importMeta) {
104
105
  const __dirname = path.dirname(__filename);
105
106
  return __dirname;
106
107
  }
108
+ function parseJsonWithComments(jsonStr) {
109
+ return JSON.parse(String(jsonStr).replace(/\/\/.*|\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, "$1"));
110
+ }
111
+
112
+ const caches = new Map();
113
+ function cacheSync(uri, setter) {
114
+ let value = caches.get(uri);
115
+ if (value) {
116
+ return value;
117
+ }
118
+ value = setter(uri);
119
+ caches.set(uri, value);
120
+ return value;
121
+ }
122
+
107
123
  function getBuildConfig() {
108
- const pwd = globalObject.projectPath ?? process.cwd();
124
+ const pwd = getProjectPath();
109
125
  const configFile = path.join(pwd, 'build.config');
110
126
  if (!fs.existsSync(configFile)) {
111
127
  throw new Error('未找到项目配置文件,请先初始化项目');
112
128
  }
113
- return JSON.parse(fs.readFileSync(configFile));
129
+ return cacheSync(configFile, file => parseBuildConfig(file));
130
+ }
131
+ function transferV1ToV2({ defaultConfig, resources, scripts }) {
132
+ const buildConfig = {
133
+ formatVersion: 2,
134
+ buildOptions: {
135
+ useHMR: true,
136
+ buildMode: 'development',
137
+ buildEntry: defaultConfig.buildEntry,
138
+ scriptEntry: defaultConfig.scriptEntry,
139
+ scriptOutput: defaultConfig.scriptEntry.replace('.ts', '.js'),
140
+ useJs: scripts[0].type === 'ts' ? false : true,
141
+ buildDir: defaultConfig.buildDir,
142
+ dependencies: defaultConfig.dependencies,
143
+ resource: {
144
+ path: resources[0].path,
145
+ resourceHints: true
146
+ }
147
+ },
148
+ versionType: 'release'
149
+ };
150
+ return buildConfig;
151
+ }
152
+ function parseBuildConfig(file) {
153
+ const obj = parseJsonWithComments(fs.readFileSync(file));
154
+ if (obj.formatVersion === 2) {
155
+ return obj;
156
+ }
157
+ const upgratedConfig = transferV1ToV2(obj);
158
+ fs.writeFileSync(file, JSON.stringify(upgratedConfig, null, 2));
159
+ return upgratedConfig;
114
160
  }
115
161
 
116
- // 获取当前文件的路径
117
- const __filename$2 = fileURLToPath$1(import.meta.url);
118
- // 获取当前文件的目录
119
- const __dirname$2 = path.dirname(__filename$2);
120
-
121
- const templateMapping = {
122
- js: 'test_sapdon',
123
- ts: 'ts_sapdon'
124
- };
125
-
126
- function initMojangPath(projectPath) {
127
- const mojangPath = path.join(os.homedir(), "AppData/Local/Packages/Microsoft.MinecraftUWP_8wekyb3d8bbwe/LocalState/games/com.mojang/");
128
- const betaPath = path.join(os.homedir(), "AppData/Local/Packages/Microsoft.MinecraftUWP_8wekyb3d8bbwe/LocalState/games/com.mojang/");
129
- const buildConfigPath = path.join(projectPath, './build.config');
130
- const buildConfig = JSON.parse(fs.readFileSync(buildConfigPath));
131
- buildConfig.mojangPath = mojangPath;
132
- buildConfig.betaPath = betaPath;
133
- saveFile(buildConfigPath, JSON.stringify(buildConfig, null, 2));
134
- }
135
-
136
- const initProject = (projectPath, data) => {
137
- console.log(1, data);
138
- //检查项目目录是否存在
139
- //如果不存在则创建项目目录
140
- //从模板下载项目文件
141
- //根据用户输入的项目信息生成项目配置文件
142
- //根据用户选择是否生成脚本文件,生成脚本文件
143
- if(!pathNotExist(projectPath)) {
144
- console.log("项目名称已存在,创建项目目录失败");
145
- return
146
- }
147
- //模版目录
148
- const templateDir = path.join(__dirname$2, `../../src/templates/${templateMapping[data.language || 'js']}`);
149
- copyFolder(templateDir, projectPath);
150
-
151
- //生成模组介绍文件
152
- saveFile(path.join(projectPath, "mod.info"), JSON.stringify(data, null, 2));
153
-
154
- //执行npm i
155
- cp.execSync('npm i', { cwd: projectPath, stdio: 'inherit' });
156
- };
157
-
158
- const initNPMProject = (projectPath, data) => {
159
- //检查项目文件是否存在
160
- //如果不存在则创建项目
161
- //从模板下载项目文件
162
- //根据用户输入的项目信息生成项目配置文件
163
- //根据用户选择是否生成脚本文件,生成脚本文件
164
- if(!pathNotExist(path.join(projectPath, "mod.info"))||!pathNotExist(path.join(projectPath, "main.mjs"))||!pathNotExist(path.join(projectPath, "scripts"))||!pathNotExist(path.join(projectPath, "build.config"))) {
165
- console.log("项目已存在...");
166
- return
167
- }
168
- //模版目录
169
- const templateDir = path.join(__dirname$2, "../templates/test_sapdon");
170
- copyFolder(templateDir, projectPath);
171
-
172
- //生成模组介绍文件
173
- saveFile(path.join(projectPath, "mod.info"), JSON.stringify(data, null, 2));
174
- };
175
-
176
- // 读取package.json文件并提取信息
177
- const readPackageJson = (dir) => {
178
- const packageJsonPath = path.join(dir, 'package.json');
179
- if (fs.existsSync(packageJsonPath)) {
180
- try {
181
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
182
- return {
183
- name: path.basename(dir),
184
- description: packageJson.description || "A new sapdon project",
185
- author: packageJson.author || "Sapdon",
186
- version: packageJson.version || "1.0.0"
187
- }
188
- } catch (error) {
189
- console.error("读取package.json文件时出错:", error);
190
- return null
191
- }
192
- } else {
193
- return null
194
- }
195
- };
196
-
162
+ // 获取当前文件的路径
163
+ const __filename$2 = fileURLToPath$1(import.meta.url);
164
+ // 获取当前文件的目录
165
+ const __dirname$1 = path.dirname(__filename$2);
166
+ const templateMapping = {
167
+ js: 'js_sapdon',
168
+ ts: 'ts_sapdon'
169
+ };
170
+ const initProject = (projectPath, data) => {
171
+ console.log(1, data);
172
+ //检查项目目录是否存在
173
+ //如果不存在则创建项目目录
174
+ //从模板下载项目文件
175
+ //根据用户输入的项目信息生成项目配置文件
176
+ //根据用户选择是否生成脚本文件,生成脚本文件
177
+ if (!pathNotExist(projectPath)) {
178
+ console.log("项目名称已存在,创建项目目录失败");
179
+ return;
180
+ }
181
+ //模版目录
182
+ const templateDir = path.join(__dirname$1, `../../src/templates/${templateMapping[data.language || 'js']}`);
183
+ copyFolder(templateDir, projectPath);
184
+ //生成模组介绍文件
185
+ saveFile(path.join(projectPath, "mod.info"), JSON.stringify(data, null, 2));
186
+ //执行npm i
187
+ cp.execSync('npm i', { cwd: projectPath, stdio: 'inherit' });
188
+ };
189
+ const initNPMProject = (projectPath, data) => {
190
+ //检查项目文件是否存在
191
+ //如果不存在则创建项目
192
+ //从模板下载项目文件
193
+ //根据用户输入的项目信息生成项目配置文件
194
+ //根据用户选择是否生成脚本文件,生成脚本文件
195
+ if (!pathNotExist(path.join(projectPath, "mod.info")) || !pathNotExist(path.join(projectPath, "main.mjs")) || !pathNotExist(path.join(projectPath, "scripts")) || !pathNotExist(path.join(projectPath, "build.config"))) {
196
+ console.log("项目已存在...");
197
+ return;
198
+ }
199
+ //模版目录
200
+ const templateDir = path.join(__dirname$1, "../templates/js_sapdon");
201
+ copyFolder(templateDir, projectPath);
202
+ //生成模组介绍文件
203
+ saveFile(path.join(projectPath, "mod.info"), JSON.stringify(data, null, 2));
204
+ };
205
+ // 读取package.json文件并提取信息
206
+ const readPackageJson = (dir) => {
207
+ const packageJsonPath = path.join(dir, 'package.json');
208
+ if (fs.existsSync(packageJsonPath)) {
209
+ try {
210
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
211
+ return {
212
+ name: path.basename(dir),
213
+ description: packageJson.description || "A new sapdon project",
214
+ author: packageJson.author || "Sapdon",
215
+ version: packageJson.version || "1.0.0"
216
+ };
217
+ }
218
+ catch (error) {
219
+ console.error("读取package.json文件时出错:", error);
220
+ return null;
221
+ }
222
+ }
223
+ else {
224
+ return null;
225
+ }
226
+ };
197
227
  const globalObject = {};
228
+ function getProjectPath() {
229
+ const projectPath = globalObject.projectPath ?? process.cwd();
230
+ if (!fs.existsSync(path.join(projectPath, "build.config"))) {
231
+ throw new Error("无效的项目路径");
232
+ }
233
+ return projectPath;
234
+ }
235
+ function getProjectName() {
236
+ return cacheSync('projectName', () => path.basename(getProjectPath()));
237
+ }
238
+ function getBuildDirBp() {
239
+ const { buildDir } = getBuildConfig().buildOptions;
240
+ const name = getProjectName();
241
+ return path.join(getProjectPath(), buildDir, name + '_bp');
242
+ }
198
243
 
199
- /**
200
- * 递归遍历目录,收集所有 PNG 文件的路径
201
- * @param {string} directory - 要遍历的目录
202
- * @param {string} basePath - 基础路径(用于计算相对路径)
203
- * @param {string} prefix - 路径前缀(如 "textures/items/")
204
- * @returns {Promise<Object>} - 返回一个对象,键为文件名,值为相对路径(不带 .png 后缀)
205
- */
206
- const traverseDirectory = async (directory, basePath, prefix = "") => {
207
- const texturesSet = {};
208
-
209
- const files = await fs$1.readdir(directory);
210
-
211
- for (const file of files) {
212
- const filePath = path.join(directory, file);
213
- const fileStats = await fs$1.stat(filePath);
214
-
215
- if (fileStats.isDirectory()) {
216
- // 如果是目录,递归遍历
217
- const subDirectoryTextures = await traverseDirectory(filePath, basePath, prefix);
218
- Object.assign(texturesSet, subDirectoryTextures);
219
- } else if (file.endsWith(".png")) {
220
- // 如果是 PNG 文件,提取文件名并生成 texture_data
221
- const fileName = path.basename(file, ".png"); // 去掉 .png 后缀
222
- const relativePath = path.relative(basePath, filePath).replace(/\.png$/, ""); // 去掉 .png 后缀
223
- const normalizedPath = `${prefix}${relativePath.replace(/\\/g, "/")}`; // 确保路径使用正斜杠
224
-
225
- texturesSet[fileName] = {
226
- textures: normalizedPath,
227
- };
228
- }
229
- }
230
-
231
- return texturesSet;
232
- };
233
-
234
- /**
235
- * 生成 JSON 文件
236
- * @param {string} outputPath - 输出的 JSON 文件路径
237
- * @param {Object} jsonData - 要写入的 JSON 数据
238
- * @param {string} successMessage - 成功时的日志消息
239
- */
240
- const generateJsonFile = async (outputPath, jsonData, successMessage) => {
241
- try {
242
- const jsonString = JSON.stringify(jsonData, null, 2);
243
- await fs$1.writeFile(outputPath, jsonString);
244
- console.log(successMessage);
245
- } catch (err) {
246
- console.error("Error writing JSON file:", err);
247
- }
248
- };
249
-
250
- /**
251
- * 生成 block_texture.json 文件
252
- * @param {string} itemTexturesPath - 包含 PNG 文件的根目录
253
- * @param {string} outputPath - 输出的 JSON 文件路径
254
- * @param {string} projectName - 项目名称
255
- */
256
- async function generateBlockTextureJson(itemTexturesPath, outputPath, projectName, userTerrainTextures) {
257
- try {
258
- // 递归遍历目录,获取所有 PNG 文件的路径
259
- const itemTexturesSet = await traverseDirectory(itemTexturesPath, itemTexturesPath,"textures/blocks/");
260
-
261
- // 合并用户自定义的texture_data
262
- if(userTerrainTextures){
263
- Object.assign(itemTexturesSet,userTerrainTextures);
264
- }
265
-
266
- // 生成 JSON 数据
267
- const jsonData = {
268
- texture_name: "atlas.terrain",
269
- resource_pack_name: projectName,
270
- padding: 8,
271
- num_mip_levels: 4,
272
- texture_data: itemTexturesSet,
273
- };
274
-
275
- // 写入文件
276
- await generateJsonFile(outputPath, jsonData, "Block texture JSON file generated successfully.");
277
- } catch (err) {
278
- console.error("Error generating block texture JSON:", err);
279
- }
280
- }
281
-
282
- /**
283
- * 生成 item_texture.json 文件
284
- * @param {string} itemTexturesPath - 包含 PNG 文件的根目录
285
- * @param {string} outputPath - 输出的 JSON 文件路径
286
- */
287
- async function generateItemTextureJson(itemTexturesPath, outputPath,projectName,userItemTextures) {
288
- try {
289
- // 递归遍历目录,获取所有 PNG 文件的路径
290
- const itemTexturesSet = await traverseDirectory(itemTexturesPath, itemTexturesPath, "textures/items/");
291
-
292
- // 合并用户自定义的texture_data
293
- if(userItemTextures){
294
- Object.assign(itemTexturesSet,userItemTextures);
295
- }
296
-
297
- // 生成 JSON 数据
298
- const jsonData = {
299
- resource_pack_name: projectName,
300
- texture_name: "atlas.items",
301
- texture_data: itemTexturesSet,
302
- };
303
-
304
- // 写入文件
305
- await generateJsonFile(outputPath, jsonData, "Item texture JSON file generated successfully.");
306
- } catch (err) {
307
- console.error("Error generating item texture JSON:", err);
308
- }
244
+ /**
245
+ * 递归遍历目录,收集所有 PNG 文件的路径
246
+ * @param {string} directory - 要遍历的目录
247
+ * @param {string} basePath - 基础路径(用于计算相对路径)
248
+ * @param {string} prefix - 路径前缀(如 "textures/items/")
249
+ * @returns {Promise<Object>} - 返回一个对象,键为文件名,值为相对路径(不带 .png 后缀)
250
+ */
251
+ const traverseDirectory = async (directory, basePath, prefix = "") => {
252
+ const texturesSet = {};
253
+ const files = await fs$1.readdir(directory);
254
+ for (const file of files) {
255
+ const filePath = path.join(directory, file);
256
+ const fileStats = await fs$1.stat(filePath);
257
+ if (fileStats.isDirectory()) {
258
+ // 如果是目录,递归遍历
259
+ const subDirectoryTextures = await traverseDirectory(filePath, basePath, prefix);
260
+ Object.assign(texturesSet, subDirectoryTextures);
261
+ }
262
+ else if (file.endsWith(".png")) {
263
+ // 如果是 PNG 文件,提取文件名并生成 texture_data
264
+ const fileName = path.basename(file, ".png"); // 去掉 .png 后缀
265
+ const relativePath = path.relative(basePath, filePath).replace(/\.png$/, ""); // 去掉 .png 后缀
266
+ const normalizedPath = `${prefix}${relativePath.replace(/\\/g, "/")}`; // 确保路径使用正斜杠
267
+ texturesSet[fileName] = {
268
+ textures: normalizedPath,
269
+ };
270
+ }
271
+ }
272
+ return texturesSet;
273
+ };
274
+ /**
275
+ * 生成 JSON 文件
276
+ * @param {string} outputPath - 输出的 JSON 文件路径
277
+ * @param {Object} jsonData - 要写入的 JSON 数据
278
+ * @param {string} successMessage - 成功时的日志消息
279
+ */
280
+ const generateJsonFile = async (outputPath, jsonData, successMessage) => {
281
+ try {
282
+ const jsonString = JSON.stringify(jsonData, null, 2);
283
+ await fs$1.writeFile(outputPath, jsonString);
284
+ console.log(successMessage);
285
+ }
286
+ catch (err) {
287
+ console.error("Error writing JSON file:", err);
288
+ }
289
+ };
290
+ /**
291
+ * 生成 block_texture.json 文件
292
+ * @param {string} itemTexturesPath - 包含 PNG 文件的根目录
293
+ * @param {string} outputPath - 输出的 JSON 文件路径
294
+ * @param {string} projectName - 项目名称
295
+ */
296
+ async function generateBlockTextureJson(itemTexturesPath, outputPath, projectName, userTerrainTextures) {
297
+ try {
298
+ // 递归遍历目录,获取所有 PNG 文件的路径
299
+ const itemTexturesSet = await traverseDirectory(itemTexturesPath, itemTexturesPath, "textures/blocks/");
300
+ // 合并用户自定义的texture_data
301
+ if (userTerrainTextures) {
302
+ Object.assign(itemTexturesSet, userTerrainTextures);
303
+ }
304
+ // 生成 JSON 数据
305
+ const jsonData = {
306
+ texture_name: "atlas.terrain",
307
+ resource_pack_name: projectName,
308
+ padding: 8,
309
+ num_mip_levels: 4,
310
+ texture_data: itemTexturesSet,
311
+ };
312
+ // 写入文件
313
+ await generateJsonFile(outputPath, jsonData, "Block texture JSON file generated successfully.");
314
+ }
315
+ catch (err) {
316
+ console.error("Error generating block texture JSON:", err);
317
+ }
318
+ }
319
+ /**
320
+ * 生成 item_texture.json 文件
321
+ * @param {string} itemTexturesPath - 包含 PNG 文件的根目录
322
+ * @param {string} outputPath - 输出的 JSON 文件路径
323
+ */
324
+ async function generateItemTextureJson(itemTexturesPath, outputPath, projectName, userItemTextures) {
325
+ try {
326
+ // 递归遍历目录,获取所有 PNG 文件的路径
327
+ const itemTexturesSet = await traverseDirectory(itemTexturesPath, itemTexturesPath, "textures/items/");
328
+ // 合并用户自定义的texture_data
329
+ if (userItemTextures) {
330
+ Object.assign(itemTexturesSet, userItemTextures);
331
+ }
332
+ // 生成 JSON 数据
333
+ const jsonData = {
334
+ resource_pack_name: projectName,
335
+ texture_name: "atlas.items",
336
+ texture_data: itemTexturesSet,
337
+ };
338
+ // 写入文件
339
+ await generateJsonFile(outputPath, jsonData, "Item texture JSON file generated successfully.");
340
+ }
341
+ catch (err) {
342
+ console.error("Error generating item texture JSON:", err);
343
+ }
309
344
  }
310
345
 
311
- class ItemTextureManager {
312
- static item_texture_sets = new Map();
313
- static getItemTextureSet(){
314
- return this.item_texture_sets;
315
- }
316
- static getItemTextures(){
317
- return Object.fromEntries(this.item_texture_sets);
318
- }
319
- static registerTextureData(texture_name,texture_data){
320
- this.item_texture_sets.set(texture_name,texture_data);
321
- }
322
- static registerTexture(texture_name,texture_path){
323
- this.registerTextureData(texture_name,{textures:texture_path});
324
- }
325
- }
326
-
327
- class terrainTextureManager {
328
- static terrain_texture_sets = new Map();
329
- static getTerrainTextureSet(){
330
- return this.terrain_texture_sets;
331
- }
332
- static getTerrainTextures(){
333
- return Object.fromEntries(this.terrain_texture_sets);
334
- }
335
- static registerTextureData(texture_name,texture_data){
336
- this.terrain_texture_sets.set(texture_name,texture_data);
337
- }
338
- static registerTexture(texture_name,texture_path){
339
- this.registerTextureData(texture_name,{textures:texture_path});
340
- }
341
- }
342
-
343
- const FlipbookTextures = {
344
- flipbook_textures: [],
345
- registerFlipbookTexture(atlas_tile,texture,ticks_per_frame,options = {}){
346
- const flipbook_texture = {"atlas_tile":atlas_tile,"flipbook_texture":texture,ticks_per_frame};
347
- Object.assign(flipbook_texture,options);
348
- this.flipbook_textures.push(flipbook_texture);
349
- }
346
+ class ItemTextureManager {
347
+ static item_texture_sets = new Map();
348
+ static getItemTextureSet() {
349
+ return this.item_texture_sets;
350
+ }
351
+ static getItemTextures() {
352
+ return Object.fromEntries(this.item_texture_sets);
353
+ }
354
+ static registerTextureData(texture_name, texture_data) {
355
+ this.item_texture_sets.set(texture_name, texture_data);
356
+ }
357
+ static registerTexture(texture_name, texture_path) {
358
+ this.registerTextureData(texture_name, { textures: texture_path });
359
+ }
360
+ }
361
+ class terrainTextureManager {
362
+ static terrain_texture_sets = new Map();
363
+ static getTerrainTextureSet() {
364
+ return this.terrain_texture_sets;
365
+ }
366
+ static getTerrainTextures() {
367
+ return Object.fromEntries(this.terrain_texture_sets);
368
+ }
369
+ static registerTextureData(texture_name, texture_data) {
370
+ this.terrain_texture_sets.set(texture_name, texture_data);
371
+ }
372
+ static registerTexture(texture_name, texture_path) {
373
+ this.registerTextureData(texture_name, { textures: texture_path });
374
+ }
375
+ }
376
+ const FlipbookTextures = {
377
+ flipbook_textures: [],
378
+ registerFlipbookTexture(atlas_tile, texture, ticks_per_frame, options = {}) {
379
+ const flipbook_texture = { "atlas_tile": atlas_tile, "flipbook_texture": texture, ticks_per_frame };
380
+ Object.assign(flipbook_texture, options);
381
+ this.flipbook_textures.push(flipbook_texture);
382
+ }
383
+ };
384
+
385
+ if (!Symbol.metadata) {
386
+ //@ts-ignore
387
+ Symbol.metadata = Symbol('[[metadata]]');
388
+ }
389
+ function getMetadata(target) {
390
+ return target?.[Symbol.metadata];
391
+ }
392
+
393
+ // 因为无法判断其他代码实现的接口是否真的是RawType,所以用Symbol来标记
394
+ // 只要不export,其他代码就无法访问这个Symbol, 确保了唯一性
395
+ const IS_RAW_SYMBOL = Symbol('isRawJSON');
396
+ function isRawJSON(v) {
397
+ return v?.[IS_RAW_SYMBOL] === true;
398
+ }
399
+
400
+ const rawTypes = [
401
+ 'boolean', 'number'
402
+ ];
403
+ const transferableTypes = [
404
+ 'string', 'undefined'
405
+ ];
406
+ function jsonEncoderReplacer(_, v) {
407
+ const typeOf = typeof v;
408
+ if (typeOf === null) {
409
+ return null;
410
+ }
411
+ if (transferableTypes.includes(typeOf)) {
412
+ return v;
413
+ }
414
+ if (rawTypes.includes(typeOf)) {
415
+ return JSON.rawJSON(v);
416
+ }
417
+ if (typeOf === 'object') {
418
+ if (JSON.isRawJSON(v)) {
419
+ return v;
420
+ }
421
+ if (isRawJSON(v)) {
422
+ // 字符串再包装一遍
423
+ return JSON.rawJSON(v.rawJSON);
424
+ }
425
+ return v;
426
+ }
427
+ if (typeOf === 'bigint') {
428
+ return JSON.rawJSON(v.toString());
429
+ }
430
+ throw new Error('Unexpected value');
431
+ }
432
+ const defaultSerializer = instance => {
433
+ return structuredClone(instance);
434
+ };
435
+ const serializerSymbol = Symbol('serializer');
436
+ const serializerMapping = new WeakMap();
437
+ function serialize(inst) {
438
+ const ctor = Reflect.getPrototypeOf(inst)?.constructor;
439
+ if (!ctor) {
440
+ throw new Error('Cannot serialize an instance of an anonymous class');
441
+ }
442
+ const serializer = getMetadata(ctor)?.[serializerSymbol]
443
+ ?? serializerMapping.get(ctor)
444
+ ?? defaultSerializer;
445
+ return serializer.call(inst, inst);
446
+ }
447
+ const jsonEncodeDecoder = {
448
+ encode(value) {
449
+ return JSON.stringify(value, jsonEncoderReplacer);
450
+ },
451
+ decode: JSON.parse
350
452
  };
453
+ function encode(value, encodeDecoder = jsonEncodeDecoder) {
454
+ return encodeDecoder.encode(value);
455
+ }
456
+ function decode(value, encodeDecoder = jsonEncodeDecoder) {
457
+ return encodeDecoder.decode(value);
458
+ }
351
459
 
352
- const devServerConfig = {
353
- port: 49037
460
+ const devServerConfig = {
461
+ port: 49037,
354
462
  };
355
463
 
356
- const {
357
- port: port$1
358
- } = devServerConfig;
359
-
360
- async function cliRequest(path, ...params) {
361
- try {
362
- await fetch(`http://localhost:${port$1}/${path}`, {
363
- method: 'POST',
364
- headers: {
365
- 'Content-Type': 'application/json'
366
- },
367
- body: JSON.stringify(params)
368
- });
369
- } catch (error) {
370
- console.error(error);
371
- console.error('尝试在构建脚本中使用 server.startDevServer() 启动开发服务器');
372
- }
464
+ const { port: port$1 } = devServerConfig;
465
+ async function cliRequest(path, ...params) {
466
+ try {
467
+ await fetch(`http://localhost:${port$1}/${path}`, {
468
+ method: 'POST',
469
+ headers: {
470
+ 'Content-Type': 'application/json'
471
+ },
472
+ body: encode(params)
473
+ });
474
+ }
475
+ catch (error) {
476
+ console.error(error);
477
+ console.error('尝试在构建脚本中使用 server.startDevServer() 启动开发服务器');
478
+ }
373
479
  }
374
480
 
375
481
  const { port } = devServerConfig;
@@ -390,7 +496,7 @@ class DevelopmentServer {
390
496
  req.on('data', chunk => buf = Buffer.concat([buf, chunk]));
391
497
  req.on('end', () => {
392
498
  try {
393
- resolve(JSON.parse(buf));
499
+ resolve(decode(buf));
394
500
  }
395
501
  catch (error) {
396
502
  reject(error);
@@ -430,54 +536,51 @@ class DevelopmentServer {
430
536
  }
431
537
  const server = new DevelopmentServer();
432
538
 
433
- class UISystemRegistry {
434
- static #ui_system_map = {}
435
- static #ui_def_list = []
436
- // 注册 UISystem
437
- static registerUISystem(ui_system) {
438
- const ui_system_path = ui_system.path + ui_system.name + ".json";
439
- this.#ui_system_map[ui_system_path] = ui_system;
440
- }
441
-
442
- // 添加外部 UI 定义
443
- static addOuterUIdefs(ui_defs) {
444
- if (!Array.isArray(ui_defs)) {
445
- throw new Error("参数必须是一个数组")
446
- }
447
- this.#ui_def_list.concat(ui_defs);
448
- }
449
-
450
- static submit() {
451
- cliRequest("register-ui/def", this.#ui_def_list);
452
- cliRequest("register-ui/system", this.#ui_system_map);
453
- }
454
- }
455
-
456
- class UISystemRegistryServer {
457
- // 私有静态字段
458
- static #ui_system_map = {}
459
- static #ui_def_list = []
460
-
461
- // 获取所有注册的 UISystem
462
- static getUISystemList() {
463
- return Object.values(this.#ui_system_map)
464
- }
465
-
466
- // 获取 UI 定义列表(剔除 "ui/server_form")
467
- static getUIdefList() {
468
- const combinedList = this.#ui_def_list.concat(Object.keys(this.#ui_system_map));
469
- return combinedList.filter(item => item !== "ui/server_form")
470
- }
471
-
472
- static startServer() {
473
- server.handle('register-ui/system', systems => {
474
- this.#ui_system_map = systems;
475
- });
476
-
477
- server.handle('register-ui/def', defs => {
478
- this.#ui_def_list = defs;
479
- });
480
- }
539
+ class UISystemRegistry {
540
+ static #ui_system_map = {};
541
+ static #ui_def_list = [];
542
+ // 注册 UISystem
543
+ static registerUISystem(ui_system) {
544
+ const ui_system_path = ui_system.path + ui_system.name + ".json";
545
+ this.#ui_system_map[ui_system_path] = ui_system;
546
+ }
547
+ // 添加外部 UI 定义
548
+ static addOuterUIdefs(ui_defs) {
549
+ if (!Array.isArray(ui_defs)) {
550
+ throw new Error("参数必须是一个数组");
551
+ }
552
+ this.#ui_def_list.concat(ui_defs);
553
+ }
554
+ static submit() {
555
+ cliRequest("register-ui/def", this.#ui_def_list);
556
+ cliRequest("register-ui/system", this.#ui_system_map);
557
+ }
558
+ }
559
+ class UISystemRegistryServer {
560
+ // 私有静态字段
561
+ static #ui_system_map = {};
562
+ static #ui_def_list = [];
563
+ // 获取所有注册的 UISystem
564
+ static getUISystemList() {
565
+ return Object.values(this.#ui_system_map);
566
+ }
567
+ // 获取 UI 定义列表(剔除 "ui/server_form")
568
+ static getUIdefList() {
569
+ const combinedList = this.#ui_def_list.concat(Object.keys(this.#ui_system_map));
570
+ return combinedList.filter(item => item !== "ui/server_form");
571
+ }
572
+ static startServer() {
573
+ server.handle('register-ui/system', systems => {
574
+ this.#ui_system_map = systems;
575
+ });
576
+ server.handle('register-ui/def', defs => {
577
+ this.#ui_def_list = defs;
578
+ });
579
+ }
580
+ }
581
+
582
+ async function handleRemoteLogger({ level, message, timeStamp, stack }) {
583
+ console[level](message, stack, `\nat ${new Date(timeStamp).toLocaleString()}`);
481
584
  }
482
585
 
483
586
  const clientRegistryData = [];
@@ -490,11 +593,12 @@ class GRegistry {
490
593
  * @param {string} name 文件名字
491
594
  * @param {string} root 根目录,如 "behavior"、"resource" 等
492
595
  * @param {string} path 数据的路径,如 "blocks/"、"items/"、"recipes/" 等
493
- * @param {string} data 实例 必须包含 toJson 方法
596
+ * @param {string | object} data 实例 必须包含 toJson 方法
494
597
  */
495
598
  static register(name, root, path, data) {
496
- data = data === 'string' ? data = JSON.parse(data)
497
- : (data?.toJson?.() ?? data);
599
+ data = data === 'string'
600
+ ? JSON.parse(data)
601
+ : serialize(data);
498
602
  clientRegistryData.push({ name, root, path, data });
499
603
  }
500
604
  static submit() {
@@ -515,129 +619,109 @@ class GRegistryServer {
515
619
  // console.log(data.map(item => item.data.description))
516
620
  this.dataList = data;
517
621
  });
518
- server.handle('log', (...info) => {
519
- console.log.apply(console, info);
520
- });
622
+ server.handle('remote-logger', handleRemoteLogger);
521
623
  }
522
624
  }
523
625
  var registry;
524
626
  (function (registry) {
525
- function sumbit() {
627
+ function submit() {
526
628
  GRegistry.submit();
527
629
  UISystemRegistry.submit();
528
630
  cliRequest('submit', {});
529
631
  }
530
- registry.sumbit = sumbit;
531
- function log(...info) {
532
- cliRequest('log', ...info);
533
- }
534
- registry.log = log;
632
+ registry.submit = submit;
535
633
  })(registry || (registry = {}));
536
634
 
537
- /**
538
- * 处理 blocks.json 数据
539
- * @param {Object} data blocks.json 数据
540
- * @returns {Object} 处理后的 blocks 数据
541
- */
542
- const processBlocksData = (data) => {
543
- const textures_arr = data.textures;
544
-
545
- // 检查 textures 数组长度
546
- if (textures_arr.length !== 6) {
547
- console.warn(`blocks.json 的 textures 数组长度不为 6,实际长度: ${textures_arr.length}`);
548
- return {}
549
- }
550
-
551
- // 构建 blocks 数据
552
- const blocks = {};
553
- blocks[data.identifier] = {
554
- textures: {
555
- up: textures_arr[0],
556
- down: textures_arr[1],
557
- east: textures_arr[2],
558
- west: textures_arr[3],
559
- south: textures_arr[4],
560
- north: textures_arr[5]
561
- }
562
- };
563
-
564
- return blocks
565
- };
566
-
567
- /**
568
- * Server
569
- * 加载并执行模组文件
570
- * @param {string} modPath 模组文件路径
571
- * @param {string} buildPath 构建目录路径
572
- * @param {string} projectName 项目名
573
- */
574
- const generateAddon = async (modPath, buildPath, projectName) => {
575
- try {
576
- const buildBehDirPath = path.join(buildPath, `${projectName}_BP`);
577
- const buildResDirPath = path.join(buildPath, `${projectName}_RP`);
578
- const resDir = (...name) => path.join(buildResDirPath, ...name);
579
-
580
- // 初始化 blocks.json 数据
581
- const blocksJsonPath = path.join(buildBehDirPath, "blocks.json");
582
- const blocks = { "format_version": "1.20.20" };
583
-
584
- //生成item_texture.json
585
- const item_texture_dir = resDir("textures/items");
586
- const item_texture_json_path = resDir("textures/item_texture.json");
587
- generateItemTextureJson(item_texture_dir, item_texture_json_path, projectName, ItemTextureManager.getItemTextures());
588
-
589
- //生成terrain_texture.json
590
- const terrain_texture_dir = resDir("textures/blocks");
591
- const terrain_texture_json_path = resDir("textures/terrain_texture.json");
592
- generateBlockTextureJson(terrain_texture_dir, terrain_texture_json_path, projectName, terrainTextureManager.getTerrainTextures());
593
-
594
- //生成flipbook_textures.json
595
- const flipbook_textures_path = resDir("textures/flipbook_textures.json");
596
- saveFile(flipbook_textures_path, JSON.stringify(FlipbookTextures.flipbook_textures, null, 2));
597
-
598
- //_ui_defs.json
599
- const ui_def = UISystemRegistryServer.getUIdefList();
600
- saveFile(resDir("ui/_ui_defs.json"), JSON.stringify({ "ui_defs": ui_def }, null, 2));
601
-
602
- UISystemRegistryServer.getUISystemList().forEach((ui_system) => {
603
- if (ui_system.path) {
604
- saveFile(resDir(ui_system.path, `${ui_system.name}.json`), JSON.stringify(ui_system, null, 2));
605
- }
606
- });
607
-
608
- // 从全局注册表中获取数据
609
- const dataList = GRegistryServer.getDataList();
610
- // console.log("dataList:", dataList)
611
- // 遍历数据并保存到相应的目录
612
- dataList.forEach(({ name, root, path: dataPath, data }) => {
613
- // 处理 blocks.json 数据
614
- if (dataPath === "blocks/") {
615
- const processedBlocks = processBlocksData(data);
616
- Object.assign(blocks, processedBlocks);
617
- }
618
-
619
- // 根据数据类型确定根目录
620
- const rootPath = root === "behavior" ? `${projectName}_BP` : `${projectName}_RP`;
621
- const buildRootPath = path.join(buildPath, rootPath);
622
-
623
- // 拼接文件路径
624
- const filePath = path.join(buildRootPath, dataPath, `${name}.json`);
625
-
626
- // 保存文件
627
- saveFile(filePath, JSON.stringify(data, null, 2));
628
- });
629
-
630
- // 保存 blocks.json
631
- console.log("保存 blocks.json 文件:", blocksJsonPath);
632
- saveFile(blocksJsonPath, JSON.stringify(blocks, null, 2));
633
-
634
- console.log(`已加载并执行 ${modPath} 文件!`);
635
- } catch (err) {
636
- console.error(`加载或执行 ${modPath} 失败:${err.message}`);
637
- console.error(err.stack); // 打印堆栈跟踪以便调试
638
- }
635
+ /**
636
+ * 处理 blocks.json 数据
637
+ * @param {Object} data blocks.json 数据
638
+ * @returns {Object} 处理后的 blocks 数据
639
+ */
640
+ const processBlocksData = (data) => {
641
+ const textures_arr = data.textures;
642
+ // 检查 textures 数组长度
643
+ if (textures_arr.length !== 6) {
644
+ console.warn(`blocks.json textures 数组长度不为 6,实际长度: ${textures_arr.length}`);
645
+ return {};
646
+ }
647
+ // 构建 blocks 数据
648
+ const blocks = {};
649
+ blocks[data.identifier] = {
650
+ textures: {
651
+ up: textures_arr[0],
652
+ down: textures_arr[1],
653
+ east: textures_arr[2],
654
+ west: textures_arr[3],
655
+ south: textures_arr[4],
656
+ north: textures_arr[5]
657
+ }
658
+ };
659
+ return blocks;
660
+ };
661
+ /**
662
+ * Server
663
+ * 加载并执行模组文件
664
+ * @param {string} modPath 模组文件路径
665
+ * @param {string} buildPath 构建目录路径
666
+ * @param {string} projectName 项目名
667
+ */
668
+ const generateAddon = async (modPath, buildPath, projectName) => {
669
+ try {
670
+ const buildBehDirPath = path.join(buildPath, `${projectName}_BP`);
671
+ const buildResDirPath = path.join(buildPath, `${projectName}_RP`);
672
+ const resDir = (...name) => path.join(buildResDirPath, ...name);
673
+ // 初始化 blocks.json 数据
674
+ const blocksJsonPath = path.join(buildBehDirPath, "blocks.json");
675
+ const blocks = { "format_version": "1.20.20" };
676
+ //生成item_texture.json
677
+ const item_texture_dir = resDir("textures/items");
678
+ const item_texture_json_path = resDir("textures/item_texture.json");
679
+ generateItemTextureJson(item_texture_dir, item_texture_json_path, projectName, ItemTextureManager.getItemTextures());
680
+ //生成terrain_texture.json
681
+ const terrain_texture_dir = resDir("textures/blocks");
682
+ const terrain_texture_json_path = resDir("textures/terrain_texture.json");
683
+ generateBlockTextureJson(terrain_texture_dir, terrain_texture_json_path, projectName, terrainTextureManager.getTerrainTextures());
684
+ //生成flipbook_textures.json
685
+ const flipbook_textures_path = resDir("textures/flipbook_textures.json");
686
+ saveFile(flipbook_textures_path, JSON.stringify(FlipbookTextures.flipbook_textures, null, 2));
687
+ //_ui_defs.json
688
+ const ui_def = UISystemRegistryServer.getUIdefList();
689
+ saveFile(resDir("ui/_ui_defs.json"), JSON.stringify({ "ui_defs": ui_def }, null, 2));
690
+ UISystemRegistryServer.getUISystemList().forEach((ui_system) => {
691
+ if (ui_system.path) {
692
+ saveFile(resDir(ui_system.path, `${ui_system.name}.json`), JSON.stringify(ui_system, null, 2));
693
+ }
694
+ });
695
+ // 从全局注册表中获取数据
696
+ const dataList = GRegistryServer.getDataList();
697
+ // console.log("dataList:", dataList)
698
+ // 遍历数据并保存到相应的目录
699
+ dataList.forEach(({ name, root, path: dataPath, data }) => {
700
+ // 处理 blocks.json 数据
701
+ if (dataPath === "blocks/") {
702
+ const processedBlocks = processBlocksData(data);
703
+ Object.assign(blocks, processedBlocks);
704
+ }
705
+ // 根据数据类型确定根目录
706
+ const rootPath = root === "behavior" ? `${projectName}_BP` : `${projectName}_RP`;
707
+ const buildRootPath = path.join(buildPath, rootPath);
708
+ // 拼接文件路径
709
+ const filePath = path.join(buildRootPath, dataPath, `${name}.json`);
710
+ // 保存文件
711
+ saveFile(filePath, JSON.stringify(data, null, 2));
712
+ });
713
+ // 保存 blocks.json
714
+ console.log("保存 blocks.json 文件:", blocksJsonPath);
715
+ saveFile(blocksJsonPath, JSON.stringify(blocks, null, 2));
716
+ console.log(`已加载并执行 ${modPath} 文件!`);
717
+ }
718
+ catch (err) {
719
+ console.error(`加载或执行 ${modPath} 失败:${err.message}`);
720
+ console.error(err.stack); // 打印堆栈跟踪以便调试
721
+ }
639
722
  };
640
723
 
724
+ // 定义语义化版本号类
641
725
  // 定义头部信息类
642
726
  class AddonManifestHeader {
643
727
  constructor(name, description, version, uuid, options = {}) {
@@ -652,7 +736,6 @@ class AddonManifestHeader {
652
736
  this.min_engine_version = options.min_engine_version;
653
737
  }
654
738
  }
655
-
656
739
  // 定义模块信息类
657
740
  class AddonManifestModule {
658
741
  constructor(description, moduleType, uuid, version) {
@@ -662,7 +745,6 @@ class AddonManifestModule {
662
745
  this.version = version;
663
746
  }
664
747
  }
665
-
666
748
  // 定义元数据信息类
667
749
  class AddonManifestMetadata {
668
750
  constructor(authors, license, generatedWith, productType, url) {
@@ -673,59 +755,388 @@ class AddonManifestMetadata {
673
755
  this.url = url;
674
756
  }
675
757
  }
676
-
677
758
  // 定义清单文件类
678
759
  class AddonManifest {
679
- constructor(formatVersion, header, modules, dependencies, capabilities=null, metadata=null) {
760
+ constructor(formatVersion, header, modules, dependencies, capabilities = null, metadata = null) {
680
761
  this.format_version = formatVersion;
681
762
  this.header = header;
682
763
  this.modules = modules;
683
764
  this.dependencies = dependencies;
684
- if(capabilities != null) this.capabilities = capabilities;
685
- if(metadata != null) this.metadata = metadata;
765
+ if (capabilities != null)
766
+ this.capabilities = capabilities;
767
+ if (metadata != null)
768
+ this.metadata = metadata;
686
769
  }
687
770
  }
688
771
 
689
- async function syncDevFilesServer(projectPath, projectName) {
690
- const buildConfig = JSON.parse(readFileSync(path.join(projectPath, "build.config")));
691
- const buildDir = path.join(projectPath, buildConfig.defaultConfig.buildDir);
692
- const buildBehDirPath = path.join(buildDir, `${projectName}_BP`);
693
- const buildResDirPath = path.join(buildDir, `${projectName}_RP`);
694
- copyFolder(buildBehDirPath, path.join(buildConfig.mojangPath, "development_behavior_packs/", `${projectName}_BP/`));
695
- copyFolder(buildResDirPath, path.join(buildConfig.mojangPath, "development_resource_packs/", `${projectName}_RP/`));
696
- }
697
-
698
- async function writeLib(projectPath) {
699
- const projectModules = path.join(projectPath, "node_modules");
700
- const rootDir = path.join(dirname(import.meta), '../');
701
- const corePath = path.join(rootDir, 'core');
702
- const cliPath = path.join(rootDir, 'cli');
703
- const ocPath = path.join(rootDir, 'oc');
704
- const targetCorePath = path.join(projectModules, '@sapdon/core');
705
- const targetCliPath = path.join(projectModules, '@sapdon/cli');
706
- const targetOcPath = path.join(projectModules, '@sapdon/oc');
707
-
708
- fs.cpSync(corePath, targetCorePath, { recursive: true, force: true });
709
- fs.cpSync(cliPath, targetCliPath, { recursive: true, force: true });
710
- fs.cpSync(ocPath, targetOcPath, { recursive: true, force: true });
711
-
712
- fs.writeFileSync(path.join(targetCorePath, 'package.json'), JSON.stringify({
713
- name: '@sapdon/core',
714
- main: 'index.js',
715
- version: '1.0.0',
716
- }));
717
- fs.writeFileSync(path.join(targetCliPath, 'package.json'), JSON.stringify({
718
- name: '@sapdon/cli',
719
- main: 'index.js',
720
- version: '1.0.0',
721
- }));
722
- fs.writeFileSync(path.join(targetOcPath, 'package.json'), JSON.stringify({
723
- name: '@sapdon/oc',
724
- main: 'index.js',
725
- version: '1.0.0',
726
- }));
772
+ const MC_INSTALL_PATH = {
773
+ MAIN: 'AppData/Local/Packages/Microsoft.MinecraftUWP_8wekyb3d8bbwe/LocalState/games/com.mojang/',
774
+ BETA: 'AppData/Local/Packages/Microsoft.MinecraftWindowsBeta_8wekyb3d8bbwe/LocalState/games/com.mojang/'
775
+ };
776
+ function mojangPath() {
777
+ return cacheSync('McInstallPath.Main', () => path.join(os.homedir(), MC_INSTALL_PATH.MAIN));
778
+ }
779
+ function betaPath() {
780
+ return cacheSync('McInstallPath.Beta', () => path.join(os.homedir(), MC_INSTALL_PATH.BETA));
781
+ }
782
+ function getGamePath() {
783
+ return getBuildConfig().versionType === 'beta' ? betaPath() : mojangPath();
784
+ }
785
+
786
+ var name = "sapdon";
787
+ var version = "3.2.1";
788
+ var scripts = {
789
+ build: "node scripts/build.cjs",
790
+ pub: "npm run build && npm publish"
791
+ };
792
+ var keywords = [
793
+ "bedrock",
794
+ "tools",
795
+ "addon"
796
+ ];
797
+ var author = "Meteage";
798
+ var license = "ISC";
799
+ var type = "module";
800
+ var bin = {
801
+ sapdon: "prod/cli/start.js"
802
+ };
803
+ var description = "Sapdon is a Node.js toolkit designed for building Bedrock Edition Minecraft addon packs.";
804
+ var devDependencies = {
805
+ "@minecraft/server": "^2.0.0-beta.1.21.80-preview.20",
806
+ "@minecraft/server-ui": "^1.3.0",
807
+ "@types/lodash": "^4.17.16",
808
+ "@types/node": "^22.14.0",
809
+ "tsc-alias": "^1.8.13"
810
+ };
811
+ var dependencies = {
812
+ "@rollup/plugin-commonjs": "^28.0.2",
813
+ "@rollup/plugin-json": "^6.1.0",
814
+ "@rollup/plugin-node-resolve": "^16.0.0",
815
+ "@rollup/plugin-terser": "^0.4.4",
816
+ "@rollup/plugin-typescript": "^12.1.2",
817
+ chalk: "^5.4.1",
818
+ commander: "^13.0.0",
819
+ "download-git-repo": "^3.0.2",
820
+ inquirer: "^12.3.1",
821
+ lodash: "^4.17.21",
822
+ ora: "^8.1.1",
823
+ rollup: "^4.39.0",
824
+ "rollup-plugin-dts": "^6.2.1",
825
+ "rollup-plugin-typescript-paths": "^1.5.0",
826
+ "rollup-plugin-visualizer": "^5.14.0",
827
+ "tsconfig-paths": "^4.2.0",
828
+ tslib: "^2.8.1",
829
+ typescript: "^5.8.2"
830
+ };
831
+ var files = [
832
+ "prod/**/*",
833
+ "doc/**/*"
834
+ ];
835
+ var packageJson = {
836
+ name: name,
837
+ version: version,
838
+ scripts: scripts,
839
+ keywords: keywords,
840
+ author: author,
841
+ license: license,
842
+ type: type,
843
+ bin: bin,
844
+ description: description,
845
+ devDependencies: devDependencies,
846
+ dependencies: dependencies,
847
+ files: files
848
+ };
849
+
850
+ function getPackageJson() {
851
+ return cacheSync(path.join(dirname(import.meta), '../../../package.json'), () => packageJson);
852
+ }
853
+
854
+ async function syncDevFilesServer(projectPath, projectName) {
855
+ const buildConfig = JSON.parse(readFileSync(path.join(projectPath, "build.config")));
856
+ const buildDir = path.join(projectPath, buildConfig.buildOptions.buildDir);
857
+ const buildBehDirPath = path.join(buildDir, `${projectName}_BP`);
858
+ const buildResDirPath = path.join(buildDir, `${projectName}_RP`);
859
+ fs.cpSync(buildBehDirPath, path.join(getGamePath(), "development_behavior_packs/", `${projectName}_BP/`), { recursive: true, force: true });
860
+ fs.cpSync(buildResDirPath, path.join(getGamePath(), "development_resource_packs/", `${projectName}_RP/`), { recursive: true, force: true });
861
+ }
862
+ async function writeLib(projectPath) {
863
+ const projectModules = path.join(projectPath, "node_modules");
864
+ const rootDir = path.join(dirname(import.meta), '../');
865
+ const corePath = path.join(rootDir, 'core');
866
+ const cliPath = path.join(rootDir, 'cli');
867
+ const ocPath = path.join(rootDir, 'oc');
868
+ const targetCorePath = path.join(projectModules, '@sapdon/core');
869
+ const targetCliPath = path.join(projectModules, '@sapdon/cli');
870
+ const targetOcPath = path.join(projectModules, '@sapdon/oc');
871
+ const packageJson = getPackageJson();
872
+ fs.cpSync(corePath, targetCorePath, { recursive: true, force: true });
873
+ fs.cpSync(cliPath, targetCliPath, { recursive: true, force: true });
874
+ fs.cpSync(ocPath, targetOcPath, { recursive: true, force: true });
875
+ fs.writeFileSync(path.join(targetCorePath, 'package.json'), JSON.stringify({
876
+ name: '@sapdon/core',
877
+ main: 'index.js',
878
+ version: packageJson.version,
879
+ }));
880
+ fs.writeFileSync(path.join(targetCliPath, 'package.json'), JSON.stringify({
881
+ name: '@sapdon/cli',
882
+ main: 'index.js',
883
+ version: packageJson.version,
884
+ }));
885
+ fs.writeFileSync(path.join(targetOcPath, 'package.json'), JSON.stringify({
886
+ name: '@sapdon/oc',
887
+ main: 'index.js',
888
+ version: packageJson.version,
889
+ }));
890
+ }
891
+
892
+ function startDevServer() {
893
+ if (server.isListening()) {
894
+ return;
895
+ }
896
+ server.bootstrap();
727
897
  }
728
898
 
899
+ // 获取当前文件的目录路径
900
+ const __filename$1 = fileURLToPath$1(import.meta.url);
901
+ path.dirname(__filename$1);
902
+ //读取配置文件
903
+ // const pathConfig = JSON.parse(readFile(path.join(__dirname, "./build.config")))
904
+ const rollupIgnores = [
905
+ 'rollup',
906
+ 'typescript',
907
+ '@sapdon/core',
908
+ '@sapdon/cli',
909
+ '@minecraft',
910
+ ];
911
+ //脚本打包器
912
+ const scriptBundler = {
913
+ js: async (source, target, sourcemap) => {
914
+ const buildConfig = getBuildConfig();
915
+ try {
916
+ const bundle = await rollup({
917
+ input: source,
918
+ plugins: [
919
+ nodeResolve({
920
+ preferBuiltins: true
921
+ }),
922
+ //@ts-ignore
923
+ commonjs(),
924
+ //@ts-ignore
925
+ json(),
926
+ // visualizer({ open: true }), //可视化分析, 打包出问题取消注释这一行
927
+ ...(buildConfig.buildOptions.buildMode === 'development' ? [] : [
928
+ terser(),
929
+ ]),
930
+ ],
931
+ external(name) {
932
+ for (const candidate of rollupIgnores) {
933
+ if (name.includes(candidate)) {
934
+ return true;
935
+ }
936
+ }
937
+ return false;
938
+ }
939
+ });
940
+ await bundle.write({
941
+ file: target,
942
+ format: 'esm',
943
+ sourcemap,
944
+ });
945
+ bundle.close();
946
+ }
947
+ catch (e) {
948
+ console.error(e);
949
+ }
950
+ },
951
+ //ts先通过rollup处理后再复制
952
+ ts: async (source, target, sourcemap) => {
953
+ const projectPath = getProjectPath();
954
+ const buildConfig = getBuildConfig();
955
+ try {
956
+ const bundle = await rollup({
957
+ input: source,
958
+ plugins: [
959
+ typescriptPaths(),
960
+ nodeResolve({
961
+ preferBuiltins: true
962
+ }),
963
+ //@ts-ignore
964
+ ts({
965
+ tsconfig: path.join(projectPath, 'tsconfig.json'),
966
+ }),
967
+ //@ts-ignore
968
+ commonjs(),
969
+ //@ts-ignore
970
+ json(),
971
+ // visualizer({ open: true }), //可视化分析, 打包出问题取消注释这一行
972
+ ...(buildConfig.buildOptions.buildMode === 'development' ? [] : [
973
+ terser(),
974
+ ]),
975
+ ],
976
+ external(name) {
977
+ for (const candidate of rollupIgnores) {
978
+ if (name.includes(candidate)) {
979
+ return true;
980
+ }
981
+ }
982
+ return false;
983
+ }
984
+ });
985
+ await bundle.write({
986
+ file: target,
987
+ format: 'esm',
988
+ sourcemap,
989
+ });
990
+ bundle.close();
991
+ }
992
+ catch (e) {
993
+ console.error(e);
994
+ }
995
+ },
996
+ any: async (a, b) => {
997
+ const buildConfig = getBuildConfig();
998
+ buildConfig.buildOptions.useJs
999
+ ? await scriptBundler.js(a, b)
1000
+ : await scriptBundler.ts(a, b);
1001
+ },
1002
+ };
1003
+ async function bundleScripts(useJs = false) {
1004
+ const elementType = useJs ? 'js' : 'ts';
1005
+ const projectPath = getProjectPath();
1006
+ const buildConfig = getBuildConfig();
1007
+ const { scriptEntry, scriptOutput, buildMode } = buildConfig.buildOptions;
1008
+ scriptBundler[elementType](path.join(projectPath, scriptEntry), path.join(getBuildDirBp(), scriptOutput), buildMode === 'development' ? true : false);
1009
+ }
1010
+ async function runOnChild(targetFilePath) {
1011
+ const { promise, resolve } = Promise.withResolvers();
1012
+ cp.fork(targetFilePath, { stdio: 'inherit' }).on('exit', resolve);
1013
+ return promise;
1014
+ }
1015
+ async function runScript(src) {
1016
+ const randomName = '.' + crypto.randomUUID() + '.js';
1017
+ const targetFilePath = path.join(path.dirname(src), '.tmp', randomName);
1018
+ await scriptBundler.any(src, targetFilePath);
1019
+ try {
1020
+ await runOnChild(targetFilePath);
1021
+ }
1022
+ catch (e) {
1023
+ console.error(e);
1024
+ }
1025
+ finally {
1026
+ fs.rmSync(targetFilePath, { force: true });
1027
+ }
1028
+ return;
1029
+ }
1030
+ function projectCanBuild(projectPath) {
1031
+ console.log("开始构建项目");
1032
+ console.log("项目路径:" + projectPath);
1033
+ //检查项目是否存在
1034
+ if (pathNotExist(projectPath)) {
1035
+ console.log("项目不存在");
1036
+ return false;
1037
+ }
1038
+ //检查项目是否有build.config文件
1039
+ if (pathNotExist(path.join(projectPath, "build.config"))) {
1040
+ console.log("项目没有build.config文件");
1041
+ return false;
1042
+ }
1043
+ return true;
1044
+ }
1045
+ //构建项目
1046
+ /**
1047
+ * `server`
1048
+ *
1049
+ * 在使用前使用 `projectCanBuild` 确保项目可以构建
1050
+ * @param {string} projectPath
1051
+ * @param {string} projectName
1052
+ */
1053
+ const buildProject = async (projectPath, projectName) => {
1054
+ //读取build.config文件
1055
+ const buildConfig = getBuildConfig();
1056
+ //读取mod.info文件
1057
+ const modInfoPath = path.join(projectPath, "mod.info");
1058
+ const modInfo = JSON.parse(readFile(modInfoPath));
1059
+ const min_engine_version = versionStringToArray(modInfo.min_engine_version);
1060
+ const buildDirPath = path.join(projectPath, buildConfig.buildOptions.buildDir);
1061
+ const buildBehDirPath = path.join(buildDirPath, `${projectName}_BP/`);
1062
+ const buildResDirPath = path.join(buildDirPath, `${projectName}_RP/`);
1063
+ const absoluteModPath = path.join(projectPath, buildConfig.buildOptions.buildEntry);
1064
+ if (!server.isListening()) {
1065
+ //生成manifest.json文件
1066
+ //判断manifest.json是否已经生成过了,生成过了就不用生成
1067
+ const manifestPath = path.join(buildBehDirPath, "manifest.json");
1068
+ if (pathNotExist(manifestPath)) {
1069
+ const behManifest = generateBehManifest(modInfo.name, modInfo.description, modInfo.version, {
1070
+ min_engine_version: min_engine_version,
1071
+ }, buildConfig.buildOptions.dependencies, buildConfig.buildOptions.scriptEntry);
1072
+ const resManifest = generateResManifest(modInfo.name, modInfo.description, modInfo.version, {
1073
+ min_engine_version: min_engine_version,
1074
+ }, []);
1075
+ //BP
1076
+ saveFile(path.join(buildBehDirPath, "manifest.json"), behManifest);
1077
+ //RP
1078
+ saveFile(path.join(buildResDirPath, "manifest.json"), resManifest);
1079
+ }
1080
+ //复制pack_icon.png
1081
+ const packIconPath = path.join(projectPath, "pack_icon.png");
1082
+ copyFileSync(packIconPath, path.join(buildBehDirPath, "pack_icon.png"));
1083
+ copyFileSync(packIconPath, path.join(buildResDirPath, "pack_icon.png"));
1084
+ // 现在只有一个resource
1085
+ const resource = buildConfig.buildOptions.resource;
1086
+ const sourcePath = path.join(projectPath, resource.path);
1087
+ copyFolder(sourcePath, buildResDirPath);
1088
+ // 在客户端启动前启动服务器
1089
+ startDevServer();
1090
+ GRegistryServer.startServer();
1091
+ UISystemRegistryServer.startServer();
1092
+ server.handle('submit', () => {
1093
+ //只有当buildMode为development时才加载用户modjs文件
1094
+ if (buildConfig.buildOptions.buildMode === "development") {
1095
+ //动态加载用户modjs文件
1096
+ generateAddon(absoluteModPath, buildDirPath, projectName);
1097
+ }
1098
+ });
1099
+ }
1100
+ // buildEntry (有可能生成ts或js文件, 所以需要先编译)
1101
+ await runScript(absoluteModPath);
1102
+ // scriptEntry
1103
+ await bundleScripts(buildConfig.buildOptions.useJs);
1104
+ await syncDevFilesServer(projectPath, projectName);
1105
+ };
1106
+ function versionStringToArray(versionString) {
1107
+ // 使用 split 方法将字符串按 '.' 分割成数组
1108
+ const parts = versionString.split('.');
1109
+ // 使用 map 方法将每个部分转换为数字
1110
+ const versionArray = parts.map(part => Number(part));
1111
+ return versionArray;
1112
+ }
1113
+ const generateBehManifest = (name, description, version, options = {}, dependencies = [], entry) => {
1114
+ console.log("开始生成behavior_packs/manifest.json");
1115
+ console.log("Entry:", entry);
1116
+ const header = new AddonManifestHeader((name + "_BP"), description, versionStringToArray(version), generateUUID(), options);
1117
+ const module = new AddonManifestModule("行为模块", "data", generateUUID(), versionStringToArray(version));
1118
+ const script_module = new AddonManifestModule("脚本模块", "script", generateUUID(), versionStringToArray(version));
1119
+ if (entry) {
1120
+ script_module.entry = entry;
1121
+ }
1122
+ const metadata = new AddonManifestMetadata(["@sapdon"], "MIT", {
1123
+ "sapdon": ["1.0.0"]
1124
+ }, "addon", "https://github.com/junjun260/sapdon");
1125
+ const manifest = new AddonManifest(2, //格式版本
1126
+ header, [module, script_module], dependencies, null, metadata);
1127
+ return JSON.stringify(manifest, null, 2);
1128
+ };
1129
+ const generateResManifest = (name, description, version, options = {}, dependencies = []) => {
1130
+ const header = new AddonManifestHeader((name + "_RP"), description, versionStringToArray(version), generateUUID(), options);
1131
+ const module = new AddonManifestModule("资源模块", "resources", generateUUID(), versionStringToArray(version));
1132
+ const metadata = new AddonManifestMetadata(["@sapdon"], "MIT", {
1133
+ "sapdon": ["1.0.0"]
1134
+ }, "addon", "https://github.com/junjun260/sapdon");
1135
+ const manifest = new AddonManifest(2, //格式版本
1136
+ header, [module], [], null, metadata);
1137
+ return JSON.stringify(manifest, null, 2);
1138
+ };
1139
+
729
1140
  const classStr = `import fs from 'fs'
730
1141
  export class FileResource {
731
1142
  static cache: Record<string, FileResource> = {}
@@ -872,8 +1283,8 @@ function watchResourceDir() {
872
1283
  }
873
1284
  function initResourceDir() {
874
1285
  // js 项目无法使用资源目录短链接
875
- const { defaultConfig } = getBuildConfig();
876
- if (defaultConfig.buildEntry.endsWith('js')) {
1286
+ const { buildOptions } = getBuildConfig();
1287
+ if (buildOptions.buildEntry.endsWith('js')) {
877
1288
  return;
878
1289
  }
879
1290
  const cwd = process.cwd();
@@ -885,514 +1296,163 @@ function initResourceDir() {
885
1296
  fs.mkdirSync(resDir);
886
1297
  }
887
1298
  const resourceHint = generateResourceHint(resDir);
888
- generateHintFile(resourceHint, path.join(cwd, 'res.ts'));
1299
+ generateHintFile(resourceHint, path.join(cwd, 'res.hint.ts'));
889
1300
  }
890
1301
 
891
- const debounce = lodash.debounce;
892
-
893
- function hmr(projectPath, projectName) {
894
- const { buildDir, useHMR } = getBuildConfig().defaultConfig;
895
- watchResourceDir();
896
- if (useHMR) {
897
- fs.watch(projectPath, { recursive: true }, debounce(async (eventType, filename) => {
898
- if (!eventType || !filename) {
899
- return
900
- }
901
-
902
- if (filename.startsWith('.') || filename.startsWith(buildDir)) {
903
- return
904
- }
905
-
906
- if (filename.endsWith('.js') || filename.endsWith('.ts')) {
907
- process.stdout.write(`File ${filename} changed, reloading...\r`);
908
- await buildProject(projectPath, projectName);
909
- console.log(`Reloaded ${filename}`);
910
- }
911
- }), 1000);
912
- }
913
- }
914
-
915
- function startDevServer() {
916
- if (server.isListening()) {
917
- return;
1302
+ const debounce = lodash.debounce;
1303
+ function hmr(projectPath, projectName) {
1304
+ const { buildDir, useHMR } = getBuildConfig().buildOptions;
1305
+ watchResourceDir();
1306
+ if (useHMR) {
1307
+ fs.watch(projectPath, { recursive: true }, debounce(async (eventType, filename) => {
1308
+ if (!eventType || !filename) {
1309
+ return;
1310
+ }
1311
+ if (filename.startsWith('.') ||
1312
+ filename.startsWith(buildDir)) {
1313
+ return;
1314
+ }
1315
+ if (filename.endsWith('.js') ||
1316
+ filename.endsWith('.ts') ||
1317
+ filename === 'build.config' ||
1318
+ filename === 'mod.info') {
1319
+ process.stdout.write(`File ${filename} changed, reloading...\r`);
1320
+ await buildProject(projectPath, projectName);
1321
+ console.log(`Reloaded ${filename}`);
1322
+ }
1323
+ }), 1000);
918
1324
  }
919
- server.bootstrap();
920
1325
  }
921
1326
 
922
- // 获取当前文件的目录路径
923
- const __filename$1 = fileURLToPath$1(import.meta.url);
924
- const __dirname$1 = path.dirname(__filename$1);
925
-
926
- //读取配置文件
927
- // const pathConfig = JSON.parse(readFile(path.join(__dirname, "./build.config")))
928
-
929
- const rollupIgnores = [
930
- 'rollup',
931
- 'typescript',
932
- '@sapdon/core',
933
- '@sapdon/cli',
934
- '@minecraft',
935
- ];
936
-
937
- //脚本打包器
938
- const scriptBundler = {
939
- __projectPath: path.join(__dirname$1, '../../'),
940
-
941
- js: (source, target) => {
942
- copyFolder(source, target);
943
- },
944
-
945
- //ts先通过rollup处理后再复制
946
- ts: async (source, target, tname='index.js', sname='index.ts') => {
947
- // console.log(source, target, tname)
948
- const tmpFile = path.join(scriptBundler.__projectPath, '.tmp', `sapdon-${crypto.randomUUID()}.js`);
949
- try {
950
- const bundle = await rollup({
951
- input: path.join(source, sname),
952
- plugins: [
953
- typescriptPaths(),
954
- nodeResolve({
955
- preferBuiltins: true
956
- }),
957
- //@ts-ignore
958
- ts({
959
- tsconfig: path.join(scriptBundler.__projectPath, 'tsconfig.json'),
960
- }),
961
- //@ts-ignore
962
- commonjs(),
963
- //@ts-ignore
964
- json(),
965
- // visualizer({ open: true }), //可视化分析, 打包出问题取消注释这一行
966
- ],
967
- external(name) {
968
- for (const candidate of rollupIgnores) {
969
- if (name.includes(candidate)) {
970
- return true
971
- }
972
- }
973
- return false
974
- }
975
- });
976
-
977
- await bundle.write({
978
- file: tmpFile,
979
- format: 'esm',
980
- });
981
-
982
- bundle.close();
983
- fs.cpSync(tmpFile, path.join(target, tname));
984
- } catch (e) {
985
- console.error(e);
986
- } finally {
987
- fs.rmSync(tmpFile, {
988
- recursive: true,
989
- force: true
990
- });
991
- }
992
- }
993
- };
994
-
995
- async function bundleScripts(projectPath, scriptPath, element) {
996
- const sourcePath = path.join(projectPath, element.path);
997
- const elementType = element.type || 'js';
998
-
999
- scriptBundler.__projectPath = projectPath;
1000
- scriptBundler[elementType](sourcePath, scriptPath);
1001
- }
1002
-
1003
- async function runOnChild(targetFilePath) {
1004
- const { promise, resolve } = Promise.withResolvers();
1005
- cp.fork(targetFilePath, { stdio: 'inherit' }).on('exit', resolve);
1006
- return promise
1007
- }
1008
-
1009
- async function runScript(src) {
1010
- if (src.endsWith('.ts')) {
1011
- const randomName = '.' + crypto.randomUUID() + '.js';
1012
- const sourceDir = path.dirname(src);
1013
- const sourceFileName = src.replace(sourceDir, '');
1014
- const targetFilePath = path.join(sourceDir, '.tmp', randomName);
1015
-
1016
- await scriptBundler.ts(sourceDir, sourceDir + '/.tmp', randomName, sourceFileName);
1017
- try {
1018
- await runOnChild(targetFilePath);
1019
- } catch (e) {
1020
- console.error(e);
1021
- } finally {
1022
- fs.rmSync(targetFilePath, { force: true });
1023
- }
1024
- return
1025
- }
1026
-
1027
- await runOnChild(src);
1028
- }
1029
-
1030
- function projectCanBuild(projectPath) {
1031
- console.log("开始构建项目");
1032
- console.log("项目路径:" + projectPath);
1033
- //检查项目是否存在
1034
- if (pathNotExist(projectPath)) {
1035
- console.log("项目不存在");
1036
- return false
1037
- }
1038
- //检查项目是否有build.config文件
1039
- if (pathNotExist(path.join(projectPath, "build.config"))) {
1040
- console.log("项目没有build.config文件");
1041
- return false
1042
- }
1043
-
1044
- return true
1045
- }
1046
-
1047
- //构建项目
1048
- /**
1049
- * `server`
1050
- *
1051
- * 在使用前使用 `projectCanBuild` 确保项目可以构建
1052
- * @param {string} projectPath
1053
- * @param {string} projectName
1054
- */
1055
- const buildProject = async (projectPath, projectName) => {
1056
- //读取build.config文件
1057
- const buildConfigPath = path.join(projectPath, "build.config");
1058
- const buildConfig = JSON.parse(readFile(buildConfigPath));
1059
- //读取mod.info文件
1060
- const modInfoPath = path.join(projectPath, "mod.info");
1061
- const modInfo = JSON.parse(readFile(modInfoPath));
1062
- const min_engine_version = versionStringToArray(modInfo.min_engine_version);
1063
-
1064
- const buildDirPath = path.join(projectPath, buildConfig.defaultConfig.buildDir);
1065
- const buildBehDirPath = path.join(buildDirPath, `${projectName}_BP/`);
1066
- const buildResDirPath = path.join(buildDirPath, `${projectName}_RP/`);
1067
-
1068
- const absoluteModPath = path.join(projectPath, buildConfig.defaultConfig.buildEntry);
1069
-
1070
- if (!server.isListening()) {
1071
- //生成manifest.json文件
1072
- //判断manifest.json是否已经生成过了,生成过了就不用生成
1073
- const manifestPath = path.join(buildBehDirPath, "manifest.json");
1074
- if (pathNotExist(manifestPath)) {
1075
- const behManifest = generateBehManifest(
1076
- modInfo.name,
1077
- modInfo.description,
1078
- modInfo.version,
1079
- {
1080
- min_engine_version: min_engine_version,
1081
- },
1082
- buildConfig.defaultConfig.dependencies,
1083
- buildConfig.defaultConfig.scriptEntry
1084
- );
1085
-
1086
- const resManifest = generateResManifest(
1087
- modInfo.name,
1088
- modInfo.description,
1089
- modInfo.version,
1090
- {
1091
- min_engine_version: min_engine_version,
1092
- },
1093
- []
1094
- );
1095
-
1096
- //BP
1097
- saveFile(path.join(buildBehDirPath, "manifest.json"), behManifest);
1098
- //RP
1099
- saveFile(path.join(buildResDirPath, "manifest.json"), resManifest);
1100
- }
1101
-
1102
- //复制pack_icon.png
1103
- const packIconPath = path.join(projectPath, "pack_icon.png");
1104
-
1105
- copyFileSync(packIconPath, path.join(buildBehDirPath, "pack_icon.png"));
1106
- copyFileSync(packIconPath, path.join(buildResDirPath, "pack_icon.png"));
1107
-
1108
- const resources = buildConfig.resources;
1109
- resources.forEach(element => {
1110
- const sourcePath = path.join(projectPath, element.path);
1111
- copyFolder(sourcePath, buildResDirPath);
1112
- });
1113
-
1114
- // 在客户端启动前启动服务器
1115
- startDevServer();
1116
- GRegistryServer.startServer();
1117
- UISystemRegistryServer.startServer();
1118
- server.handle('submit', () => {
1119
- //只有当buildMode为development时才加载用户modjs文件
1120
- if (buildConfig.defaultConfig.buildMode === "development") {
1121
- //动态加载用户modjs文件
1122
- generateAddon(absoluteModPath, buildDirPath, projectName);
1123
- }
1124
- });
1125
-
1126
- hmr(projectPath, projectName);
1127
- }
1128
-
1129
- const scripts = buildConfig.scripts;
1130
- const scriptPath = path.join(buildBehDirPath, "scripts/");
1131
-
1132
- for (const element of scripts) {
1133
- await bundleScripts(projectPath, scriptPath, element);
1134
- }
1135
-
1136
- await runScript(absoluteModPath);
1137
- await syncDevFilesServer(projectPath, projectName);
1138
- };
1139
-
1140
- function versionStringToArray(versionString) {
1141
- // 使用 split 方法将字符串按 '.' 分割成数组
1142
- const parts = versionString.split('.');
1143
-
1144
- // 使用 map 方法将每个部分转换为数字
1145
- const versionArray = parts.map(part => Number(part));
1146
-
1147
- return versionArray
1148
- }
1149
-
1150
- const generateBehManifest = (name, description, version, options = {}, dependencies = [], entry) => {
1151
- console.log("开始生成behavior_packs/manifest.json");
1152
- console.log("Entry:", entry);
1153
- const header = new AddonManifestHeader(
1154
- (name + "_BP"),
1155
- description,
1156
- versionStringToArray(version),
1157
- generateUUID(),
1158
- options
1159
- );
1160
- const module = new AddonManifestModule(
1161
- "行为模块",
1162
- "data",
1163
- generateUUID(),
1164
- versionStringToArray(version)
1165
- );
1166
- const script_module = new AddonManifestModule(
1167
- "脚本模块",
1168
- "script",
1169
- generateUUID(),
1170
- versionStringToArray(version)
1171
- );
1172
- if (entry) { script_module.entry = entry; }
1173
-
1174
- const metadata = new AddonManifestMetadata(
1175
- ["@sapdon"],
1176
- "MIT",
1177
- {
1178
- "sapdon": ["1.0.0"]
1179
- },
1180
- "addon",
1181
- "https://github.com/junjun260/sapdon"
1182
- );
1183
-
1184
- const manifest = new AddonManifest(
1185
- 2,//格式版本
1186
- header,
1187
- [module, script_module],
1188
- dependencies,
1189
- null,
1190
- metadata
1191
- );
1192
-
1193
- return JSON.stringify(manifest, null, 2)
1194
- };
1195
-
1196
- const generateResManifest = (name, description, version, options = {}, dependencies = []) => {
1197
- const header = new AddonManifestHeader(
1198
- (name + "_RP"),
1199
- description,
1200
- versionStringToArray(version),
1201
- generateUUID(),
1202
- options
1203
- );
1204
- const module = new AddonManifestModule(
1205
- "资源模块",
1206
- "resources",
1207
- generateUUID(),
1208
- versionStringToArray(version)
1209
- );
1210
-
1211
- const metadata = new AddonManifestMetadata(
1212
- ["@sapdon"],
1213
- "MIT",
1214
- {
1215
- "sapdon": ["1.0.0"]
1216
- },
1217
- "addon",
1218
- "https://github.com/junjun260/sapdon"
1219
- );
1220
-
1221
- const manifest = new AddonManifest(
1222
- 2,//格式版本
1223
- header,
1224
- [module],
1225
- [],
1226
- null,
1227
- metadata
1228
- );
1229
-
1230
- return JSON.stringify(manifest, null, 2)
1231
- };
1232
-
1233
- const __filename = fileURLToPath$1(import.meta.url);
1234
- const __dirname = path.dirname(__filename);
1235
-
1236
- process.removeAllListeners('warning');
1237
-
1238
- async function start() {
1239
- // 额外添加的init方法
1240
- program.command("init").description("初始化一个基于NodeJS的项目").action(() => {
1241
- const currentDir = process.cwd();
1242
- const packageJsonPath = path.join(currentDir, 'package.json');
1243
- let packageJsonData;
1244
- if (!fs.existsSync(packageJsonPath)) {
1245
- console.error("没有找到package.json文件,请使改用create命令进行创建。");
1246
- return
1247
- }
1248
-
1249
- try {
1250
- packageJsonData = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
1251
- } catch (error) {
1252
- console.error("读取package.json文件时出错:", error);
1253
- console.log("请使改用create命令进行创建。");
1254
- return
1255
- }
1256
-
1257
- // 添加或更新scripts字段
1258
- packageJsonData.scripts = {
1259
- ...packageJsonData.scripts,
1260
- init: "sapdon init",
1261
- pack: "sapdon pack",
1262
- config: "sapdon config"
1263
- };
1264
-
1265
- try {
1266
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJsonData, null, 2), 'utf-8');
1267
- } catch (error) {
1268
- console.error("写入package.json文件时出错:", error);
1269
- return
1270
- }
1271
-
1272
- inquirer.prompt([
1273
- {
1274
- type: "input",
1275
- name: "min_engine_version",
1276
- message: "最低引擎版本:",
1277
- default: "1.19.50"
1278
- }
1279
- ]).then((answers) => {
1280
- initNPMProject(currentDir, { ...readPackageJson(currentDir), ...answers });
1281
- console.log("请使用命令sapdon config配置框架的build.config文件。");
1282
- });
1283
- });
1284
-
1285
- program.command("create <project-name>").description("Create a new project").action((projectName) => {
1286
- inquirer.prompt([
1287
- {
1288
- type: "input",
1289
- name: "name",
1290
- message: "Project Name:",
1291
- default: path.basename(projectName)
1292
- },
1293
- {
1294
- type: "input",
1295
- name: "description",
1296
- message: "Project Description:",
1297
- default: "A new sapdon project"
1298
- },
1299
- {
1300
- type: "input",
1301
- name: "author",
1302
- message: "Author Name:",
1303
- default: "Sapdon"
1304
- },
1305
- {
1306
- type: "input",
1307
- name: "version",
1308
- message: "Project Version:",
1309
- default: "1.0.0"
1310
- },
1311
- {
1312
- type: "input",
1313
- name: "min_engine_version",
1314
- message: "Minimum Engine Version:",
1315
- default: "1.19.50",
1316
- },
1317
- {
1318
- type: "input",
1319
- name: "language",
1320
- message: "Language:(js/ts)",
1321
- default: "ts",
1322
- },
1323
- ]).then((answers) => {
1324
- const projectPath = path.join(process.cwd(), projectName);
1325
- console.log('项目路径:', projectPath);
1326
- initProject(projectPath, answers);
1327
- initMojangPath(projectPath);
1328
- writeLib(projectPath);
1329
- });
1330
- });
1331
-
1332
- program.command("build <project-name>").description("Build the project").action((projectName) => {
1333
- console.log("Building the project...");
1334
- const projectPath = path.join(process.cwd(), projectName);
1335
- globalObject.projectPath = projectPath;
1336
- initResourceDir();
1337
- if (projectCanBuild(projectPath)) {
1338
- buildProject(projectPath, path.basename(projectPath));
1339
- }
1340
- });
1341
-
1342
- // pack 命令
1343
- program.command("pack").description("Pack the current project").action(() => {
1344
- console.log("Packing the current project...");
1345
- const projectPath = process.cwd();
1346
- if (projectCanBuild(projectPath)) {
1347
- buildProject(projectPath, path.basename(projectPath));
1348
- }
1349
- });
1350
-
1351
- program.command('lib').description('Generate lib files for development server.').action(() => {
1352
- const projectPath = process.cwd();
1353
- writeLib(projectPath);
1354
- });
1355
-
1356
- program.command('res').description('Generate resource hints.').action(() => {
1357
- initResourceDir();
1358
- });
1359
-
1360
- // 配置build.config文件的命令
1361
- program.command("config").description("Configure build.config file").action(() => {
1362
- const buildConfigPath = path.join(__dirname, "./build.config");
1363
- let buildConfigData;
1364
-
1365
- try {
1366
- buildConfigData = JSON.parse(readFile(buildConfigPath));
1367
- } catch (error) {
1368
- console.error("读取build.config文件时出错:", error);
1369
- return
1370
- }
1371
-
1372
- inquirer.prompt([
1373
- {
1374
- type: "input",
1375
- name: "mojangPath",
1376
- message: "Mojang Path (must end with LocalState/games/com.mojang/):",
1377
- default: path.join(os.homedir(), "AppData/Local/Packages/Microsoft.MinecraftUWP_8wekyb3d8bbwe/LocalState/games/com.mojang/")
1378
- },
1379
- {
1380
- type: "input",
1381
- name: "mojangBetaPath",
1382
- message: "Mojang Beta Path (must end with LocalState/games/com.mojang/):",
1383
- default: path.join(os.homedir(), "AppData/Local/Packages/Microsoft.MinecraftUWP_8wekyb3d8bbwe/LocalState/games/com.mojang/")
1384
- }
1385
- ]).then((answers) => {
1386
- try {
1387
- fs.writeFileSync(buildConfigPath, JSON.stringify({ ...buildConfigData, ...answers }, null, 2), 'utf-8');
1388
- console.log("build.config文件已更新。");
1389
- } catch (error) {
1390
- console.error("写入build.config文件时出错:", error);
1391
- }
1392
- });
1393
- });
1394
-
1395
- program.parse(program.argv);
1396
- }
1397
-
1327
+ const __filename = fileURLToPath$1(import.meta.url);
1328
+ const __dirname = path.dirname(__filename);
1329
+ process.removeAllListeners('warning');
1330
+ async function start() {
1331
+ // 额外添加的init方法
1332
+ program.command("init").description("初始化一个基于NodeJS的项目").action(() => {
1333
+ const currentDir = process.cwd();
1334
+ const packageJsonPath = path.join(currentDir, 'package.json');
1335
+ let packageJsonData;
1336
+ if (!fs.existsSync(packageJsonPath)) {
1337
+ console.error("没有找到package.json文件,请使改用create命令进行创建。");
1338
+ return;
1339
+ }
1340
+ try {
1341
+ packageJsonData = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
1342
+ }
1343
+ catch (error) {
1344
+ console.error("读取package.json文件时出错:", error);
1345
+ console.log("请使改用create命令进行创建。");
1346
+ return;
1347
+ }
1348
+ // 添加或更新scripts字段
1349
+ packageJsonData.scripts = {
1350
+ ...packageJsonData.scripts,
1351
+ init: "sapdon init",
1352
+ pack: "sapdon pack",
1353
+ config: "sapdon config"
1354
+ };
1355
+ try {
1356
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJsonData, null, 2), 'utf-8');
1357
+ }
1358
+ catch (error) {
1359
+ console.error("写入package.json文件时出错:", error);
1360
+ return;
1361
+ }
1362
+ inquirer.prompt([
1363
+ {
1364
+ type: "input",
1365
+ name: "min_engine_version",
1366
+ message: "最低引擎版本:",
1367
+ default: "1.19.50"
1368
+ }
1369
+ ]).then((answers) => {
1370
+ initNPMProject(currentDir, { ...readPackageJson(currentDir), ...answers });
1371
+ console.log("请使用命令sapdon config配置框架的build.config文件。");
1372
+ });
1373
+ });
1374
+ program.command("create <project-name>").description("Create a new project").action((projectName) => {
1375
+ inquirer.prompt([
1376
+ {
1377
+ type: "input",
1378
+ name: "name",
1379
+ message: "Project Name:",
1380
+ default: path.basename(projectName)
1381
+ },
1382
+ {
1383
+ type: "input",
1384
+ name: "description",
1385
+ message: "Project Description:",
1386
+ default: "A new sapdon project"
1387
+ },
1388
+ {
1389
+ type: "input",
1390
+ name: "author",
1391
+ message: "Author Name:",
1392
+ default: "Sapdon"
1393
+ },
1394
+ {
1395
+ type: "input",
1396
+ name: "version",
1397
+ message: "Project Version:",
1398
+ default: "1.0.0"
1399
+ },
1400
+ {
1401
+ type: "input",
1402
+ name: "min_engine_version",
1403
+ message: "Minimum Engine Version:",
1404
+ default: "1.19.50",
1405
+ },
1406
+ {
1407
+ type: "input",
1408
+ name: "language",
1409
+ message: "Language:(js/ts)",
1410
+ default: "ts",
1411
+ },
1412
+ ]).then((answers) => {
1413
+ const projectPath = path.join(process.cwd(), projectName);
1414
+ console.log('项目路径:', projectPath);
1415
+ initProject(projectPath, answers);
1416
+ writeLib(projectPath);
1417
+ });
1418
+ });
1419
+ program.command("build <project-name>").description("Build the project").action((projectName) => {
1420
+ console.log("Building the project...");
1421
+ const projectPath = path.join(process.cwd(), projectName);
1422
+ globalObject.projectPath = projectPath;
1423
+ initResourceDir();
1424
+ if (projectCanBuild(projectPath)) {
1425
+ buildProject(projectPath, path.basename(projectPath));
1426
+ hmr(projectPath, projectName);
1427
+ }
1428
+ });
1429
+ // pack 命令
1430
+ program.command("pack").description("Pack the current project").action(() => {
1431
+ console.log("Packing the current project...");
1432
+ const projectPath = process.cwd();
1433
+ if (projectCanBuild(projectPath)) {
1434
+ buildProject(projectPath, path.basename(projectPath));
1435
+ }
1436
+ });
1437
+ program.command('lib').description('Generate lib files for development server.').action(() => {
1438
+ const projectPath = process.cwd();
1439
+ writeLib(projectPath);
1440
+ });
1441
+ program.command('res').description('Generate resource hints.').action(() => {
1442
+ initResourceDir();
1443
+ });
1444
+ // 配置build.config文件的命令
1445
+ program.command("config").description("Configure build.config file").action(() => {
1446
+ const buildConfigPath = path.join(__dirname, "./build.config");
1447
+ let buildConfigData;
1448
+ try {
1449
+ buildConfigData = JSON.parse(readFile(buildConfigPath));
1450
+ }
1451
+ catch (error) {
1452
+ console.error("读取build.config文件时出错:", error);
1453
+ return;
1454
+ }
1455
+ });
1456
+ program.parse(program.argv);
1457
+ }
1398
1458
  start();