sapdon 3.0.2 → 3.0.3

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 (208) hide show
  1. package/dist/cli/build.d.ts +7 -0
  2. package/dist/cli/build.js +234 -0
  3. package/dist/cli/dev-server/client.d.ts +2 -0
  4. package/dist/cli/dev-server/client.js +21 -0
  5. package/dist/cli/dev-server/config.d.ts +3 -0
  6. package/dist/cli/dev-server/config.js +3 -0
  7. package/dist/cli/dev-server/handles.d.ts +4 -0
  8. package/dist/cli/dev-server/handles.js +5 -0
  9. package/dist/cli/dev-server/hmr.d.ts +1 -0
  10. package/dist/cli/dev-server/hmr.js +13 -0
  11. package/dist/cli/dev-server/index.d.ts +4 -0
  12. package/dist/cli/dev-server/index.js +17 -0
  13. package/dist/cli/dev-server/server.d.ts +14 -0
  14. package/dist/cli/dev-server/server.js +59 -0
  15. package/dist/cli/dev-server/syncFiles.d.ts +3 -0
  16. package/dist/cli/dev-server/syncFiles.js +37 -0
  17. package/dist/cli/index.d.ts +23 -0
  18. package/dist/cli/index.js +1 -0
  19. package/dist/cli/init.d.ts +9 -0
  20. package/dist/cli/init.js +80 -0
  21. package/dist/cli/load.d.ts +3 -0
  22. package/dist/cli/load.js +94 -0
  23. package/dist/cli/start.d.ts +2 -0
  24. package/dist/cli/start.js +2 -0
  25. package/dist/cli/tools/textureSet.d.ts +13 -0
  26. package/dist/cli/tools/textureSet.js +103 -0
  27. package/dist/cli/utils.d.ts +13 -0
  28. package/dist/cli/utils.js +89 -0
  29. package/dist/core/addon/biome.d.ts +22 -0
  30. package/dist/core/addon/biome.js +27 -0
  31. package/dist/core/addon/block/block.d.ts +41 -0
  32. package/dist/core/addon/block/block.js +46 -0
  33. package/dist/core/addon/controllers/animationController.d.ts +43 -0
  34. package/dist/core/addon/controllers/animationController.js +73 -0
  35. package/dist/core/addon/entity/clientEntity.d.ts +107 -0
  36. package/dist/core/addon/entity/clientEntity.js +149 -0
  37. package/dist/core/addon/entity/entity.d.ts +42 -0
  38. package/dist/core/addon/entity/entity.js +50 -0
  39. package/dist/core/addon/feature/oreFeature.d.ts +19 -0
  40. package/dist/core/addon/feature/oreFeature.js +24 -0
  41. package/dist/core/addon/featureRule.d.ts +20 -0
  42. package/dist/core/addon/featureRule.js +25 -0
  43. package/dist/core/addon/item/attachable.d.ts +94 -0
  44. package/dist/core/addon/item/attachable.js +134 -0
  45. package/dist/core/addon/item/item.d.ts +19 -0
  46. package/dist/core/addon/item/item.js +26 -0
  47. package/dist/core/addon/manifest.d.ts +49 -0
  48. package/dist/core/addon/manifest.js +65 -0
  49. package/dist/core/addon/menuCategory.d.ts +6 -0
  50. package/dist/core/addon/menuCategory.js +7 -0
  51. package/dist/core/addon/recipe/baseRecipe.d.ts +12 -0
  52. package/dist/core/addon/recipe/baseRecipe.js +23 -0
  53. package/dist/core/addon/recipe/data.d.ts +66 -0
  54. package/dist/core/addon/recipe/data.js +74 -0
  55. package/dist/core/addon/recipe/furnace.d.ts +17 -0
  56. package/dist/core/addon/recipe/furnace.js +43 -0
  57. package/dist/core/addon/recipe/shaped.d.ts +26 -0
  58. package/dist/core/addon/recipe/shaped.js +53 -0
  59. package/dist/core/addon/recipe/shapeless.d.ts +18 -0
  60. package/dist/core/addon/recipe/shapeless.js +36 -0
  61. package/dist/core/biome/biome.d.ts +14 -0
  62. package/dist/core/biome/biome.js +23 -0
  63. package/dist/core/biome/biomeComponent.d.ts +46 -0
  64. package/dist/core/biome/biomeComponent.js +77 -0
  65. package/dist/core/block/basicBlock.d.ts +48 -0
  66. package/dist/core/block/basicBlock.js +105 -0
  67. package/dist/core/block/block.d.ts +32 -0
  68. package/dist/core/block/block.js +92 -0
  69. package/dist/core/block/blockComponent.d.ts +187 -0
  70. package/dist/core/block/blockComponent.js +500 -0
  71. package/dist/core/block/cropBlock.d.ts +4 -0
  72. package/dist/core/block/cropBlock.js +27 -0
  73. package/dist/core/block/geometryBlock.d.ts +12 -0
  74. package/dist/core/block/geometryBlock.js +16 -0
  75. package/dist/core/block/oreBlock.d.ts +9 -0
  76. package/dist/core/block/oreBlock.js +25 -0
  77. package/dist/core/block/rotatableBlock.d.ts +27 -0
  78. package/dist/core/block/rotatableBlock.js +107 -0
  79. package/dist/core/block/tileBlock.d.ts +17 -0
  80. package/dist/core/block/tileBlock.js +125 -0
  81. package/dist/core/entity/basicEntity.d.ts +111 -0
  82. package/dist/core/entity/basicEntity.js +170 -0
  83. package/dist/core/entity/behavior/followMob.d.ts +12 -0
  84. package/dist/core/entity/behavior/followMob.js +35 -0
  85. package/dist/core/entity/behavior/followParent.d.ts +7 -0
  86. package/dist/core/entity/behavior/followParent.js +15 -0
  87. package/dist/core/entity/behavior/randomStroll.d.ts +31 -0
  88. package/dist/core/entity/behavior/randomStroll.js +63 -0
  89. package/dist/core/entity/behavior/tempt.d.ts +73 -0
  90. package/dist/core/entity/behavior/tempt.js +134 -0
  91. package/dist/core/entity/bundles/basicBundle.d.ts +13 -0
  92. package/dist/core/entity/bundles/basicBundle.js +45 -0
  93. package/dist/core/entity/clientEntity.d.ts +20 -0
  94. package/dist/core/entity/clientEntity.js +37 -0
  95. package/dist/core/entity/componets/entityComponet.d.ts +202 -0
  96. package/dist/core/entity/componets/entityComponet.js +347 -0
  97. package/dist/core/entity/data/nativeEntityData.d.ts +9 -0
  98. package/dist/core/entity/data/nativeEntityData.js +38 -0
  99. package/dist/core/entity/entity.d.ts +15 -0
  100. package/dist/core/entity/entity.js +18 -0
  101. package/dist/core/entity/nativeEntity.d.ts +8 -0
  102. package/dist/core/entity/nativeEntity.js +28 -0
  103. package/dist/core/entity/navigation/walk.d.ts +23 -0
  104. package/dist/core/entity/navigation/walk.js +56 -0
  105. package/dist/core/entity/projectile.d.ts +3 -0
  106. package/dist/core/entity/projectile.js +7 -0
  107. package/dist/core/factory/biomeFactory.d.ts +4 -0
  108. package/dist/core/factory/biomeFactory.js +13 -0
  109. package/dist/core/factory/blockFactory.d.ts +34 -0
  110. package/dist/core/factory/blockFactory.js +143 -0
  111. package/dist/core/factory/entityFactory.d.ts +17 -0
  112. package/dist/core/factory/entityFactory.js +75 -0
  113. package/dist/core/factory/featureFactory.d.ts +6 -0
  114. package/dist/core/factory/featureFactory.js +23 -0
  115. package/dist/core/factory/itemExtra.d.ts +8 -0
  116. package/dist/core/factory/itemExtra.js +9 -0
  117. package/dist/core/factory/itemFactory.d.ts +27 -0
  118. package/dist/core/factory/itemFactory.js +112 -0
  119. package/dist/core/factory/recipeFactory.d.ts +18 -0
  120. package/dist/core/factory/recipeFactory.js +39 -0
  121. package/dist/core/factory/uiFactory.d.ts +12 -0
  122. package/dist/core/factory/uiFactory.js +32 -0
  123. package/dist/core/feature/oreFeature.d.ts +10 -0
  124. package/dist/core/feature/oreFeature.js +11 -0
  125. package/dist/core/feature-rule/condition/biomeFilter.d.ts +26 -0
  126. package/dist/core/feature-rule/condition/biomeFilter.js +36 -0
  127. package/dist/core/feature-rule/condition/featureConditions.d.ts +27 -0
  128. package/dist/core/feature-rule/condition/featureConditions.js +37 -0
  129. package/dist/core/feature-rule/distribution/coordinateDistribution.d.ts +17 -0
  130. package/dist/core/feature-rule/distribution/coordinateDistribution.js +23 -0
  131. package/dist/core/feature-rule/distribution/featureDistribution.d.ts +31 -0
  132. package/dist/core/feature-rule/distribution/featureDistribution.js +41 -0
  133. package/dist/core/feature-rule/featureRule.d.ts +17 -0
  134. package/dist/core/feature-rule/featureRule.js +26 -0
  135. package/dist/core/index.d.ts +2062 -0
  136. package/dist/core/index.js +1 -0
  137. package/dist/core/item/armor.d.ts +21 -0
  138. package/dist/core/item/armor.js +90 -0
  139. package/dist/core/item/attachable.d.ts +6 -0
  140. package/dist/core/item/attachable.js +26 -0
  141. package/dist/core/item/food.d.ts +24 -0
  142. package/dist/core/item/food.js +38 -0
  143. package/dist/core/item/item.d.ts +36 -0
  144. package/dist/core/item/item.js +69 -0
  145. package/dist/core/item/itemComponents.d.ts +113 -0
  146. package/dist/core/item/itemComponents.js +225 -0
  147. package/dist/core/registry.d.ts +12 -0
  148. package/dist/core/registry.js +16 -0
  149. package/dist/core/texture.d.ts +18 -0
  150. package/dist/core/texture.js +38 -0
  151. package/dist/core/ui/buttonMapping.d.ts +97 -0
  152. package/dist/core/ui/buttonMapping.js +132 -0
  153. package/dist/core/ui/dataBindingObject.d.ts +97 -0
  154. package/dist/core/ui/dataBindingObject.js +134 -0
  155. package/dist/core/ui/elements/button.d.ts +21 -0
  156. package/dist/core/ui/elements/button.js +101 -0
  157. package/dist/core/ui/elements/collectionPanel.d.ts +12 -0
  158. package/dist/core/ui/elements/collectionPanel.js +53 -0
  159. package/dist/core/ui/elements/grid.d.ts +8 -0
  160. package/dist/core/ui/elements/grid.js +33 -0
  161. package/dist/core/ui/elements/image.d.ts +13 -0
  162. package/dist/core/ui/elements/image.js +55 -0
  163. package/dist/core/ui/elements/label.d.ts +14 -0
  164. package/dist/core/ui/elements/label.js +61 -0
  165. package/dist/core/ui/elements/panel.d.ts +11 -0
  166. package/dist/core/ui/elements/panel.js +49 -0
  167. package/dist/core/ui/elements/scrollingPanel.d.ts +14 -0
  168. package/dist/core/ui/elements/scrollingPanel.js +59 -0
  169. package/dist/core/ui/elements/stackPanel.d.ts +14 -0
  170. package/dist/core/ui/elements/stackPanel.js +37 -0
  171. package/dist/core/ui/elements/uiElement.d.ts +53 -0
  172. package/dist/core/ui/elements/uiElement.js +129 -0
  173. package/dist/core/ui/properties/control.d.ts +214 -0
  174. package/dist/core/ui/properties/control.js +286 -0
  175. package/dist/core/ui/properties/dataBinding.d.ts +6 -0
  176. package/dist/core/ui/properties/dataBinding.js +16 -0
  177. package/dist/core/ui/properties/factory.d.ts +37 -0
  178. package/dist/core/ui/properties/factory.js +62 -0
  179. package/dist/core/ui/properties/gridProp.d.ts +65 -0
  180. package/dist/core/ui/properties/gridProp.js +90 -0
  181. package/dist/core/ui/properties/input.d.ts +97 -0
  182. package/dist/core/ui/properties/input.js +134 -0
  183. package/dist/core/ui/properties/layout.d.ts +105 -0
  184. package/dist/core/ui/properties/layout.js +145 -0
  185. package/dist/core/ui/properties/scrollView.d.ts +105 -0
  186. package/dist/core/ui/properties/scrollView.js +145 -0
  187. package/dist/core/ui/properties/sound.d.ts +47 -0
  188. package/dist/core/ui/properties/sound.js +66 -0
  189. package/dist/core/ui/properties/sprite.d.ts +161 -0
  190. package/dist/core/ui/properties/sprite.js +222 -0
  191. package/dist/core/ui/properties/text.d.ts +135 -0
  192. package/dist/core/ui/properties/text.js +187 -0
  193. package/dist/core/ui/registry/uiSystemRegistry.d.ts +8 -0
  194. package/dist/core/ui/registry/uiSystemRegistry.js +26 -0
  195. package/dist/core/ui/systems/chest.d.ts +5 -0
  196. package/dist/core/ui/systems/chest.js +21 -0
  197. package/dist/core/ui/systems/containerUISystem.d.ts +67 -0
  198. package/dist/core/ui/systems/containerUISystem.js +214 -0
  199. package/dist/core/ui/systems/guidebook.d.ts +9 -0
  200. package/dist/core/ui/systems/guidebook.js +206 -0
  201. package/dist/core/ui/systems/serverForm.d.ts +13 -0
  202. package/dist/core/ui/systems/serverForm.js +116 -0
  203. package/dist/core/ui/systems/system.d.ts +16 -0
  204. package/dist/core/ui/systems/system.js +37 -0
  205. package/dist/oc/index.d.ts +142 -0
  206. package/dist/oc/index.js +1 -0
  207. package/doc/sapdon-ts.md +35 -1
  208. package/package.json +6 -8
@@ -0,0 +1,7 @@
1
+ export function projectCanBuild(projectPath: any, projectName: any): boolean;
2
+ export namespace scriptBundler {
3
+ let __projectPath: string;
4
+ function js(source: any, target: any): void;
5
+ function ts(source: any, target: any, tname?: string, sname?: string): Promise<void>;
6
+ }
7
+ export function buildProject(projectPath: string, projectName: string): Promise<void>;
@@ -0,0 +1,234 @@
1
+ import path from 'path';
2
+ import { pathNotExist, readFile, generateUUID, saveFile, copyFileSync, copyFolder, asyncImport } from "./utils.js";
3
+ import { generateAddonClient } from './load.js';
4
+ import { AddonManifestHeader, AddonManifestModule, AddonManifest, AddonManifestMetadata } from '../core/addon/manifest.js';
5
+ import { fileURLToPath } from 'url';
6
+ import fs from 'fs';
7
+ import { rollup } from 'rollup';
8
+ import commonjs from '@rollup/plugin-commonjs';
9
+ import { nodeResolve } from '@rollup/plugin-node-resolve';
10
+ import ts from '@rollup/plugin-typescript';
11
+ import { typescriptPaths as paths } from 'rollup-plugin-typescript-paths';
12
+ import json from '@rollup/plugin-json';
13
+ import { visualizer } from 'rollup-plugin-visualizer';
14
+ import { syncDevFilesClient } from './dev-server/syncFiles.js';
15
+ import { hmr } from './dev-server/hmr.js';
16
+ import cp from 'child_process';
17
+ // 获取当前文件的目录路径
18
+ const __filename = fileURLToPath(import.meta.url);
19
+ const __dirname = path.dirname(__filename);
20
+ //读取配置文件
21
+ // const pathConfig = JSON.parse(readFile(path.join(__dirname, "./build.config")))
22
+ const rollupIgnores = [
23
+ 'rollup',
24
+ 'typescript',
25
+ '@sapdon',
26
+ ];
27
+ //脚本打包器
28
+ export const scriptBundler = {
29
+ __projectPath: path.join(__dirname, '../../'),
30
+ js: (source, target) => {
31
+ copyFolder(source, target);
32
+ },
33
+ //ts先通过rollup处理后再复制
34
+ ts: async (source, target, tname = 'index.js', sname = 'index.ts') => {
35
+ // console.log(source, target, tname)
36
+ const tmpFile = path.join(scriptBundler.__projectPath, '.tmp', `sapdon-${crypto.randomUUID()}.js`);
37
+ try {
38
+ const bundle = await rollup({
39
+ input: path.join(source, sname),
40
+ plugins: [
41
+ paths(),
42
+ nodeResolve({
43
+ preferBuiltins: true
44
+ }),
45
+ //@ts-ignore
46
+ ts({
47
+ tsconfig: path.join(scriptBundler.__projectPath, 'tsconfig.json'),
48
+ }),
49
+ //@ts-ignore
50
+ commonjs(),
51
+ //@ts-ignore
52
+ json(),
53
+ // visualizer({ open: true }), //可视化分析, 打包出问题取消注释这一行
54
+ ],
55
+ external(name) {
56
+ for (const candidate of rollupIgnores) {
57
+ if (name.includes(candidate)) {
58
+ return true;
59
+ }
60
+ }
61
+ return false;
62
+ }
63
+ });
64
+ await bundle.write({
65
+ file: tmpFile,
66
+ format: 'esm',
67
+ });
68
+ bundle.close();
69
+ fs.cpSync(tmpFile, path.join(target, tname));
70
+ }
71
+ catch (e) {
72
+ console.error(e);
73
+ }
74
+ finally {
75
+ fs.rmSync(tmpFile, {
76
+ recursive: true,
77
+ force: true
78
+ });
79
+ }
80
+ }
81
+ };
82
+ async function bundleScripts(projectPath, scriptPath, element) {
83
+ const sourcePath = path.join(projectPath, element.path);
84
+ const elementType = element.type || 'js';
85
+ scriptBundler.__projectPath = projectPath;
86
+ scriptBundler[elementType](sourcePath, scriptPath);
87
+ }
88
+ function preload(filePath) {
89
+ fs.appendFileSync(filePath, `
90
+ ;(async () => {
91
+ const { startDevServer } = await import('@sapdon/cli')
92
+ const { GRegistry, UISystemRegistry } = await import('@sapdon/core')
93
+ startDevServer(GRegistry, UISystemRegistry)
94
+ })();
95
+ `);
96
+ }
97
+ async function runOnChild(targetFilePath) {
98
+ const { promise, resolve } = Promise.withResolvers();
99
+ const child = cp.fork(targetFilePath, { stdio: 'inherit' });
100
+ child.once('message', message => {
101
+ if (message !== 'initialized') {
102
+ child.kill();
103
+ }
104
+ resolve();
105
+ });
106
+ await promise;
107
+ }
108
+ async function runScript(src) {
109
+ if (src.endsWith('.ts')) {
110
+ const randomName = crypto.randomUUID() + '.js';
111
+ const sourceDir = path.dirname(src);
112
+ const sourceFileName = src.replace(sourceDir, '');
113
+ const targetFilePath = path.join(sourceDir, randomName);
114
+ await scriptBundler.ts(sourceDir, sourceDir, randomName, sourceFileName);
115
+ preload(targetFilePath);
116
+ try {
117
+ await runOnChild(targetFilePath);
118
+ }
119
+ finally {
120
+ fs.rmSync(targetFilePath, { force: true });
121
+ }
122
+ return;
123
+ }
124
+ await runOnChild(src);
125
+ }
126
+ export function projectCanBuild(projectPath, projectName) {
127
+ console.log("开始构建项目");
128
+ console.log("项目路径:" + projectPath);
129
+ //检查项目是否存在
130
+ if (pathNotExist(projectPath)) {
131
+ console.log("项目不存在");
132
+ return false;
133
+ }
134
+ //检查项目是否有build.config文件
135
+ if (pathNotExist(path.join(projectPath, "build.config"))) {
136
+ console.log("项目没有build.config文件");
137
+ return false;
138
+ }
139
+ return true;
140
+ }
141
+ //构建项目
142
+ /**
143
+ * `client`
144
+ *
145
+ * 在使用前使用 `projectCanBuild` 确保项目可以构建
146
+ * @param {string} projectPath
147
+ * @param {string} projectName
148
+ */
149
+ export const buildProject = async (projectPath, projectName) => {
150
+ //读取build.config文件
151
+ const buildConfigPath = path.join(projectPath, "build.config");
152
+ const buildConfig = JSON.parse(readFile(buildConfigPath));
153
+ //console.log(buildConfig)
154
+ //读取mod.info文件
155
+ const modInfoPath = path.join(projectPath, "mod.info");
156
+ const modInfo = JSON.parse(readFile(modInfoPath));
157
+ const min_engine_version = versionStringToArray(modInfo.min_engine_version);
158
+ const buildDirPath = path.join(projectPath, buildConfig.defaultConfig.buildDir);
159
+ const buildBehDirPath = path.join(buildDirPath, `${projectName}_BP/`);
160
+ const buildResDirPath = path.join(buildDirPath, `${projectName}_RP/`);
161
+ //生成manifest.json文件
162
+ //判断manifest.json是否已经生成过了,生成过了就不用生成
163
+ const manifestPath = path.join(buildBehDirPath, "manifest.json");
164
+ if (pathNotExist(manifestPath)) {
165
+ const behManifest = generateBehManifest(modInfo.name, modInfo.description, modInfo.version, {
166
+ min_engine_version: min_engine_version,
167
+ }, buildConfig.defaultConfig.dependencies, buildConfig.defaultConfig.scriptEntry);
168
+ const resManifest = generateResManifest(modInfo.name, modInfo.description, modInfo.version, {
169
+ min_engine_version: min_engine_version,
170
+ }, []);
171
+ //BP
172
+ saveFile(path.join(buildBehDirPath, "manifest.json"), behManifest);
173
+ //RP
174
+ saveFile(path.join(buildResDirPath, "manifest.json"), resManifest);
175
+ }
176
+ //复制pack_icon.png
177
+ const packIconPath = path.join(projectPath, "pack_icon.png");
178
+ copyFileSync(packIconPath, path.join(buildBehDirPath, "pack_icon.png"));
179
+ copyFileSync(packIconPath, path.join(buildResDirPath, "pack_icon.png"));
180
+ const resources = buildConfig.resources;
181
+ resources.forEach(element => {
182
+ const sourcePath = path.join(projectPath, element.path);
183
+ copyFolder(sourcePath, buildResDirPath);
184
+ });
185
+ const scripts = buildConfig.scripts;
186
+ const scriptPath = path.join(buildBehDirPath, "scripts/");
187
+ for (const element of scripts) {
188
+ await bundleScripts(projectPath, scriptPath, element);
189
+ }
190
+ const absoluteModPath = path.join(projectPath, buildConfig.defaultConfig.buildEntry);
191
+ await runScript(absoluteModPath);
192
+ //只有当buildMode为development时才加载用户modjs文件
193
+ if (buildConfig.defaultConfig.buildMode === "development") {
194
+ //动态加载用户modjs文件
195
+ await generateAddonClient(absoluteModPath, buildDirPath, projectName);
196
+ }
197
+ syncDevFilesClient(projectPath, projectName);
198
+ if (buildConfig.useHMR === true) {
199
+ hmr(projectPath, projectName);
200
+ }
201
+ };
202
+ function versionStringToArray(versionString) {
203
+ // 使用 split 方法将字符串按 '.' 分割成数组
204
+ const parts = versionString.split('.');
205
+ // 使用 map 方法将每个部分转换为数字
206
+ const versionArray = parts.map(part => Number(part));
207
+ return versionArray;
208
+ }
209
+ const generateBehManifest = (name, description, version, options = {}, dependencies = [], entry) => {
210
+ console.log("开始生成behavior_packs/manifest.json");
211
+ console.log("Entry:", entry);
212
+ const header = new AddonManifestHeader((name + "_BP"), description, versionStringToArray(version), generateUUID(), options);
213
+ const module = new AddonManifestModule("行为模块", "data", generateUUID(), versionStringToArray(version));
214
+ const script_module = new AddonManifestModule("脚本模块", "script", generateUUID(), versionStringToArray(version));
215
+ if (entry) {
216
+ script_module.entry = entry;
217
+ }
218
+ const metadata = new AddonManifestMetadata(["@sapdon"], "MIT", {
219
+ "sapdon": ["1.0.0"]
220
+ }, "addon", "https://github.com/junjun260/sapdon");
221
+ const manifest = new AddonManifest(2, //格式版本
222
+ header, [module, script_module], dependencies, null, metadata);
223
+ return JSON.stringify(manifest, null, 2);
224
+ };
225
+ const generateResManifest = (name, description, version, options = {}, dependencies = []) => {
226
+ const header = new AddonManifestHeader((name + "_RP"), description, versionStringToArray(version), generateUUID(), options);
227
+ const module = new AddonManifestModule("资源模块", "resources", generateUUID(), versionStringToArray(version));
228
+ const metadata = new AddonManifestMetadata(["@sapdon"], "MIT", {
229
+ "sapdon": ["1.0.0"]
230
+ }, "addon", "https://github.com/junjun260/sapdon");
231
+ const manifest = new AddonManifest(2, //格式版本
232
+ header, [module], [], null, metadata);
233
+ return JSON.stringify(manifest, null, 2);
234
+ };
@@ -0,0 +1,2 @@
1
+ export function cliRequest(path: any, ...params: any[]): Promise<void>;
2
+ export function writeAddon(modPath: any, buildPath: any, projectName: any): Promise<void>;
@@ -0,0 +1,21 @@
1
+ import { devServerConfig } from './config.js';
2
+ import { ServerHandles } from './handles.js';
3
+ const { port } = devServerConfig;
4
+ export async function cliRequest(path, ...params) {
5
+ try {
6
+ await fetch(`http://localhost:${port}/${path}`, {
7
+ method: 'POST',
8
+ headers: {
9
+ 'Content-Type': 'application/json'
10
+ },
11
+ body: JSON.stringify(params)
12
+ });
13
+ }
14
+ catch (error) {
15
+ console.error(error);
16
+ console.error('尝试在构建脚本中使用 server.startDevServer() 启动开发服务器');
17
+ }
18
+ }
19
+ export async function writeAddon(modPath, buildPath, projectName) {
20
+ await cliRequest(ServerHandles.WRITE_ADDON, modPath, buildPath, projectName);
21
+ }
@@ -0,0 +1,3 @@
1
+ export namespace devServerConfig {
2
+ let port: number;
3
+ }
@@ -0,0 +1,3 @@
1
+ export const devServerConfig = {
2
+ port: 49037
3
+ };
@@ -0,0 +1,4 @@
1
+ export declare enum ServerHandles {
2
+ WRITE_ADDON = "write-addon",
3
+ WRITE_GAME_DEV = "write-dev"
4
+ }
@@ -0,0 +1,5 @@
1
+ export var ServerHandles;
2
+ (function (ServerHandles) {
3
+ ServerHandles["WRITE_ADDON"] = "write-addon";
4
+ ServerHandles["WRITE_GAME_DEV"] = "write-dev";
5
+ })(ServerHandles || (ServerHandles = {}));
@@ -0,0 +1 @@
1
+ export function hmr(projectPath: any, projectName: any): void;
@@ -0,0 +1,13 @@
1
+ import fs from 'fs';
2
+ import lodash from 'lodash';
3
+ import { buildProject } from '../build.js';
4
+ const debounce = lodash.debounce;
5
+ export function hmr(projectPath, projectName) {
6
+ // fs.watch(projectPath, { recursive: true }, debounce(async (eventType, filename) => {
7
+ // if (filename.endsWith('.js') || filename.endsWith('.ts')) {
8
+ // process.stdout.write(`File ${filename} changed, reloading...\r`)
9
+ // await buildProject(projectPath, projectName)
10
+ // console.log(`Reloaded ${filename}`)
11
+ // }
12
+ // }), 1000)
13
+ }
@@ -0,0 +1,4 @@
1
+ import { ServerHandles } from "./handles.js";
2
+ import { server } from "./server.js";
3
+ export declare function startDevServer(GRegistry: any, UIRegistry: any): void;
4
+ export { server, ServerHandles, };
@@ -0,0 +1,17 @@
1
+ import { generateAddon } from "../load.js";
2
+ import { ServerHandles } from "./handles.js";
3
+ import { server } from "./server.js";
4
+ import { syncDevFilesServer } from "./syncFiles.js";
5
+ function startup(GRegistry, UIRegistry) {
6
+ server.bootstrap();
7
+ server.handle(ServerHandles.WRITE_ADDON, generateAddon(GRegistry, UIRegistry));
8
+ server.handle(ServerHandles.WRITE_GAME_DEV, syncDevFilesServer);
9
+ }
10
+ export function startDevServer(GRegistry, UIRegistry) {
11
+ if (server.isListening()) {
12
+ return;
13
+ }
14
+ startup(GRegistry, UIRegistry);
15
+ process.send('initialized');
16
+ }
17
+ export { server, ServerHandles, };
@@ -0,0 +1,14 @@
1
+ import http from 'http';
2
+ type ServerHandler = (...args: Transferable[]) => void;
3
+ type HandlerInterceptor = (handler: ServerHandler) => ServerHandler;
4
+ declare class DevelopmentServer {
5
+ readonly cliServerHandlers: Map<string, ServerHandler>;
6
+ listening: boolean;
7
+ isListening(): boolean;
8
+ bootstrap(): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
9
+ handle(url: string, handler: ServerHandler): void;
10
+ getHandler(url: string): ServerHandler | undefined;
11
+ interceptHandler(url: string, interceptor: HandlerInterceptor): ServerHandler;
12
+ }
13
+ export declare const server: DevelopmentServer;
14
+ export {};
@@ -0,0 +1,59 @@
1
+ import http from 'http';
2
+ import { devServerConfig } from './config.js';
3
+ const { port } = devServerConfig;
4
+ class DevelopmentServer {
5
+ cliServerHandlers = new Map();
6
+ listening = false;
7
+ isListening() {
8
+ return this.listening;
9
+ }
10
+ bootstrap() {
11
+ this.listening = true;
12
+ const svr = http.createServer(async (req, res) => {
13
+ const handler = this.cliServerHandlers.get((req.url ?? '/').slice(1));
14
+ if (handler) {
15
+ try {
16
+ const { promise, resolve, reject } = Promise.withResolvers();
17
+ let buf = Buffer.alloc(0);
18
+ req.on('data', chunk => buf = Buffer.concat([buf, chunk]));
19
+ req.on('end', () => {
20
+ try {
21
+ resolve(JSON.parse(buf));
22
+ }
23
+ catch (error) {
24
+ reject(error);
25
+ }
26
+ });
27
+ await handler(...await promise);
28
+ }
29
+ catch (error) {
30
+ console.error(error);
31
+ res.writeHead(500);
32
+ res.end();
33
+ return;
34
+ }
35
+ res.writeHead(200);
36
+ res.end();
37
+ }
38
+ else {
39
+ res.writeHead(404);
40
+ res.end();
41
+ }
42
+ }).listen(port, () => console.log(`Dev Server listening on port ${port}`));
43
+ svr.on('error', () => this.listening = false);
44
+ return svr;
45
+ }
46
+ handle(url, handler) {
47
+ this.cliServerHandlers.set(url, handler);
48
+ }
49
+ getHandler(url) {
50
+ return this.cliServerHandlers.get(url);
51
+ }
52
+ interceptHandler(url, interceptor) {
53
+ const currentHandler = this.getHandler(url) ?? Function.prototype;
54
+ const newHandler = interceptor(currentHandler);
55
+ this.cliServerHandlers.set(url, newHandler);
56
+ return newHandler;
57
+ }
58
+ }
59
+ export const server = new DevelopmentServer();
@@ -0,0 +1,3 @@
1
+ export function syncDevFilesClient(projectPath: any, projectName: any): Promise<void>;
2
+ export function syncDevFilesServer(projectPath: any, projectName: any): Promise<void>;
3
+ export function writeLib(projectPath: any): Promise<void>;
@@ -0,0 +1,37 @@
1
+ import { readFileSync } from "fs";
2
+ import { cliRequest } from "./client.js";
3
+ import { copyFolder, dirname } from "../utils.js";
4
+ import path from "path";
5
+ import fs from 'fs';
6
+ import { ServerHandles } from "./handles.js";
7
+ export async function syncDevFilesClient(projectPath, projectName) {
8
+ await cliRequest(ServerHandles.WRITE_GAME_DEV, projectPath, projectName);
9
+ }
10
+ export async function syncDevFilesServer(projectPath, projectName) {
11
+ const buildConfig = JSON.parse(readFileSync(path.join(projectPath, "build.config")));
12
+ const buildDir = path.join(projectPath, buildConfig.defaultConfig.buildDir);
13
+ const buildBehDirPath = path.join(buildDir, `${projectName}_BP`);
14
+ const buildResDirPath = path.join(buildDir, `${projectName}_RP`);
15
+ copyFolder(buildBehDirPath, path.join(buildConfig.mojangPath, "development_behavior_packs/", `${projectName}_BP/`));
16
+ copyFolder(buildResDirPath, path.join(buildConfig.mojangPath, "development_resource_packs/", `${projectName}_RP/`));
17
+ }
18
+ export async function writeLib(projectPath) {
19
+ const projectModules = path.join(projectPath, "node_modules");
20
+ const rootDir = path.join(dirname(import.meta), '../../');
21
+ const corePath = path.join(rootDir, 'core');
22
+ const cliPath = path.join(rootDir, 'cli');
23
+ const targetCorePath = path.join(projectModules, '@sapdon/core');
24
+ const targetCliPath = path.join(projectModules, '@sapdon/cli');
25
+ fs.cpSync(corePath, targetCorePath, { recursive: true, force: true });
26
+ fs.cpSync(cliPath, targetCliPath, { recursive: true, force: true });
27
+ fs.writeFileSync(path.join(targetCorePath, 'package.json'), JSON.stringify({
28
+ name: '@sapdon/core',
29
+ main: 'index.js',
30
+ version: '1.0.0',
31
+ }));
32
+ fs.writeFileSync(path.join(targetCliPath, 'package.json'), JSON.stringify({
33
+ name: '@sapdon/cli',
34
+ main: 'index.js',
35
+ version: '1.0.0',
36
+ }));
37
+ }
@@ -0,0 +1,23 @@
1
+ import http from 'http';
2
+
3
+ declare enum ServerHandles {
4
+ WRITE_ADDON = "write-addon",
5
+ WRITE_GAME_DEV = "write-dev"
6
+ }
7
+
8
+ type ServerHandler = (...args: Transferable[]) => void;
9
+ type HandlerInterceptor = (handler: ServerHandler) => ServerHandler;
10
+ declare class DevelopmentServer {
11
+ readonly cliServerHandlers: Map<string, ServerHandler>;
12
+ listening: boolean;
13
+ isListening(): boolean;
14
+ bootstrap(): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
15
+ handle(url: string, handler: ServerHandler): void;
16
+ getHandler(url: string): ServerHandler | undefined;
17
+ interceptHandler(url: string, interceptor: HandlerInterceptor): ServerHandler;
18
+ }
19
+ declare const server: DevelopmentServer;
20
+
21
+ declare function startDevServer(GRegistry: any, UIRegistry: any): void;
22
+
23
+ export { ServerHandles, server as devServer, startDevServer };
@@ -0,0 +1 @@
1
+ import e from"path";import t,{readFileSync as r}from"fs";import"crypto";import"node:url";import s from"fs/promises";import n from"http";const i=(r,s)=>{t.mkdirSync(e.dirname(r),{recursive:!0}),t.writeFile(r,s,(e=>{if(e)return console.error(e)}))},o=(r,s)=>{if(t.mkdirSync(e.dirname(s),{recursive:!0}),!t.existsSync(r))return void console.log(`Source path ${r} does not exist.`);t.existsSync(s)||t.mkdirSync(s);t.readdirSync(r).forEach((n=>{const i=e.join(r,n),a=e.join(s,n);t.lstatSync(i).isDirectory()?o(i,a):t.copyFileSync(i,a)}))},a=async(t,r,n="")=>{const i={},o=await s.readdir(t);for(const c of o){const o=e.join(t,c);if((await s.stat(o)).isDirectory()){const e=await a(o,r,n);Object.assign(i,e)}else if(c.endsWith(".png")){const t=e.basename(c,".png"),s=`${n}${e.relative(r,o).replace(/\.png$/,"").replace(/\\/g,"/")}`;i[t]={textures:s}}}return i},c=async(e,t,r)=>{try{const n=JSON.stringify(t,null,2);await s.writeFile(e,n),console.log(r)}catch(e){console.error("Error writing JSON file:",e)}};class l{static item_texture_sets=new Map;static getItemTextureSet(){return this.item_texture_sets}static getItemTextures(){return Object.fromEntries(this.item_texture_sets)}static registerTextureData(e,t){this.item_texture_sets.set(e,t)}static registerTexture(e,t){this.registerTextureData(e,{textures:t})}}class u{static terrain_texture_sets=new Map;static getTerrainTextureSet(){return this.terrain_texture_sets}static getTerrainTextures(){return Object.fromEntries(this.terrain_texture_sets)}static registerTextureData(e,t){this.terrain_texture_sets.set(e,t)}static registerTexture(e,t){this.registerTextureData(e,{textures:t})}}const g={flipbook_textures:[],registerFlipbookTexture(e,t,r,s={}){const n={atlas_tile:e,flipbook_texture:t,ticks_per_frame:r};Object.assign(n,s),this.flipbook_textures.push(n)}};var _;!function(e){e.WRITE_ADDON="write-addon",e.WRITE_GAME_DEV="write-dev"}(_||(_={}));const d=(t,r)=>async(s,n,o)=>{try{const _=e.join(n,`${o}_BP`),d=e.join(n,`${o}_RP`),f=t=>e.join(d,t),x=e.join(_,"blocks.json"),p={format_version:"1.20.20"},m=f("textures/items");!async function(e,t,r,s){try{const n=await a(e,e,"textures/items/");s&&Object.assign(n,s);const i={resource_pack_name:r,texture_name:"atlas.items",texture_data:n};await c(t,i,"Item texture JSON file generated successfully.")}catch(e){console.error("Error generating item texture JSON:",e)}}(m,f("textures/item_texture.json"),o,l.getItemTextures());const h=f("textures/blocks");!async function(e,t,r,s){try{const n=await a(e,e,"textures/blocks/");s&&Object.assign(n,s);const i={texture_name:"atlas.terrain",resource_pack_name:r,padding:8,num_mip_levels:4,texture_data:n};await c(t,i,"Block texture JSON file generated successfully.")}catch(e){console.error("Error generating block texture JSON:",e)}}(h,f("textures/terrain_texture.json"),o,u.getTerrainTextures());const y=f("textures/flipbook_textures.json");i(y,JSON.stringify(g.flipbook_textures,null,2));const j=r.getUIdefList();i(f("ui/_ui_defs.json"),JSON.stringify({ui_defs:j},null,2)),r.getUISystemList().forEach((e=>{i(f(e.path,`${e.name}.json`),JSON.stringify(e.toJson(),null,2))}));t.getDataList().forEach((({name:t,root:r,path:s,data:a})=>{if("blocks/"===s){const e=(e=>{const t=e.textures;if(6!==t.length)return console.warn(`blocks.json 的 textures 数组长度不为 6,实际长度: ${t.length}`),{};const r={};return r[e.identifier]={textures:{up:t[0],down:t[1],east:t[2],west:t[3],south:t[4],north:t[5]}},r})(a);Object.assign(p,e)}const c="behavior"===r?`${o}_BP`:`${o}_RP`,l=e.join(n,c),u=e.join(l,s,`${t}.json`);i(u,JSON.stringify(a.toJson(),null,2))})),console.log("保存 blocks.json 文件:",x),i(x,JSON.stringify(p,null,2)),console.log(`已加载并执行 ${s} 文件!`)}catch(e){console.error(`加载或执行 ${s} 失败:${e.message}`),console.error(e.stack)}},{port:f}={port:49037};const x=new class{cliServerHandlers=new Map;listening=!1;isListening(){return this.listening}bootstrap(){this.listening=!0;const e=n.createServer((async(e,t)=>{const r=this.cliServerHandlers.get((e.url??"/").slice(1));if(r){try{const{promise:t,resolve:s,reject:n}=Promise.withResolvers();let i=Buffer.alloc(0);e.on("data",(e=>i=Buffer.concat([i,e]))),e.on("end",(()=>{try{s(JSON.parse(i))}catch(e){n(e)}})),await r(...await t)}catch(e){return console.error(e),t.writeHead(500),void t.end()}t.writeHead(200),t.end()}else t.writeHead(404),t.end()})).listen(f,(()=>console.log(`Dev Server listening on port ${f}`)));return e.on("error",(()=>this.listening=!1)),e}handle(e,t){this.cliServerHandlers.set(e,t)}getHandler(e){return this.cliServerHandlers.get(e)}interceptHandler(e,t){const r=t(this.getHandler(e)??Function.prototype);return this.cliServerHandlers.set(e,r),r}};async function p(t,s){const n=JSON.parse(r(e.join(t,"build.config"))),i=e.join(t,n.defaultConfig.buildDir),a=e.join(i,`${s}_BP`),c=e.join(i,`${s}_RP`);o(a,e.join(n.mojangPath,"development_behavior_packs/",`${s}_BP/`)),o(c,e.join(n.mojangPath,"development_resource_packs/",`${s}_RP/`))}function m(e,t){x.isListening()||(!function(e,t){x.bootstrap(),x.handle(_.WRITE_ADDON,d(e,t)),x.handle(_.WRITE_GAME_DEV,p)}(e,t),process.send("initialized"))}export{_ as ServerHandles,x as devServer,m as startDevServer};
@@ -0,0 +1,9 @@
1
+ export function initMojangPath(projectPath: any): void;
2
+ export function initProject(projectPath: any, data: any): void;
3
+ export function initNPMProject(projectPath: any, data: any): void;
4
+ export function readPackageJson(dir: any): {
5
+ name: string;
6
+ description: any;
7
+ author: any;
8
+ version: any;
9
+ } | null;
@@ -0,0 +1,80 @@
1
+ import path from 'path';
2
+ import { fileURLToPath } from 'url';
3
+ import { pathNotExist, copyFolder, saveFile } from './utils.js';
4
+ import fs from "fs";
5
+ import cp from "child_process";
6
+ import os from "os";
7
+ // 获取当前文件的路径
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ // 获取当前文件的目录
10
+ const __dirname = path.dirname(__filename);
11
+ const templateMapping = {
12
+ js: 'test_sapdon',
13
+ ts: 'ts_sapdon'
14
+ };
15
+ export function initMojangPath(projectPath) {
16
+ const mojangPath = path.join(os.homedir(), "AppData/Local/Packages/Microsoft.MinecraftUWP_8wekyb3d8bbwe/LocalState/games/com.mojang/");
17
+ const betaPath = path.join(os.homedir(), "AppData/Local/Packages/Microsoft.MinecraftUWP_8wekyb3d8bbwe/LocalState/games/com.mojang/");
18
+ const buildConfigPath = path.join(projectPath, './build.config');
19
+ const buildConfig = JSON.parse(fs.readFileSync(buildConfigPath));
20
+ buildConfig.mojangPath = mojangPath;
21
+ buildConfig.betaPath = betaPath;
22
+ saveFile(buildConfigPath, JSON.stringify(buildConfig, null, 2));
23
+ }
24
+ export const initProject = (projectPath, data) => {
25
+ console.log(1, data);
26
+ //检查项目目录是否存在
27
+ //如果不存在则创建项目目录
28
+ //从模板下载项目文件
29
+ //根据用户输入的项目信息生成项目配置文件
30
+ //根据用户选择是否生成脚本文件,生成脚本文件
31
+ if (!pathNotExist(projectPath)) {
32
+ console.log("项目名称已存在,创建项目目录失败");
33
+ return;
34
+ }
35
+ //模版目录
36
+ const templateDir = path.join(__dirname, `../../src/templates/${templateMapping[data.language || 'js']}`);
37
+ copyFolder(templateDir, projectPath);
38
+ //生成模组介绍文件
39
+ saveFile(path.join(projectPath, "mod.info"), JSON.stringify(data, null, 2));
40
+ //执行npm i
41
+ cp.execSync('npm i', { cwd: projectPath, stdio: 'inherit' });
42
+ };
43
+ export const initNPMProject = (projectPath, data) => {
44
+ //检查项目文件是否存在
45
+ //如果不存在则创建项目
46
+ //从模板下载项目文件
47
+ //根据用户输入的项目信息生成项目配置文件
48
+ //根据用户选择是否生成脚本文件,生成脚本文件
49
+ if (!pathNotExist(path.join(projectPath, "mod.info")) || !pathNotExist(path.join(projectPath, "main.mjs")) || !pathNotExist(path.join(projectPath, "scripts")) || !pathNotExist(path.join(projectPath, "build.config"))) {
50
+ console.log("项目已存在...");
51
+ return;
52
+ }
53
+ //模版目录
54
+ const templateDir = path.join(__dirname, "../templates/test_sapdon");
55
+ copyFolder(templateDir, projectPath);
56
+ //生成模组介绍文件
57
+ saveFile(path.join(projectPath, "mod.info"), JSON.stringify(data, null, 2));
58
+ };
59
+ // 读取package.json文件并提取信息
60
+ export const readPackageJson = (dir) => {
61
+ const packageJsonPath = path.join(dir, 'package.json');
62
+ if (fs.existsSync(packageJsonPath)) {
63
+ try {
64
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
65
+ return {
66
+ name: path.basename(dir),
67
+ description: packageJson.description || "A new sapdon project",
68
+ author: packageJson.author || "Sapdon",
69
+ version: packageJson.version || "1.0.0"
70
+ };
71
+ }
72
+ catch (error) {
73
+ console.error("读取package.json文件时出错:", error);
74
+ return null;
75
+ }
76
+ }
77
+ else {
78
+ return null;
79
+ }
80
+ };
@@ -0,0 +1,3 @@
1
+ export function processBlocksData(data: Object): Object;
2
+ export function generateAddonClient(modPath: any, buildPath: any, projectName: any): Promise<void>;
3
+ export function generateAddon(GRegistry: any, UISystemRegistry: any): (modPath: any, buildPath: any, projectName: any) => Promise<void>;