@mafly/bdev-cli 1.0.2 → 1.0.4

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.
@@ -96,59 +96,79 @@ export async function devCommand(dirArg, options = {}) {
96
96
  logger.info(`Starting file watcher on: ${watchPaths.map((p) => path.relative(rootDir, p)).join(", ")}`);
97
97
  logger.info("Press Ctrl+C to stop.");
98
98
  let isRebuilding = false;
99
+ let rebuildPending = false;
99
100
  let rebuildTimeout = null;
101
+ const ignoredPatterns = [
102
+ /(^|[/\\])\../, // dotfiles
103
+ /node_modules/,
104
+ /dist/,
105
+ ];
106
+ if (fs.existsSync(srcDir)) {
107
+ // Ignore entire scripts directory in behavior pack when compiling from src
108
+ ignoredPatterns.push(/(^|[/\\])behavior_pack[/\\]scripts([/\\].*)?$/);
109
+ }
110
+ else {
111
+ ignoredPatterns.push(/\.map$/);
112
+ }
100
113
  const watcher = chokidar.watch(watchPaths, {
101
- ignored: [
102
- /(^|[/\\])\../, // dotfiles
103
- /node_modules/,
104
- /dist/,
105
- /behavior_pack[/\\]scripts[/\\]main\.js(\.map)?$/, // ignore build output
106
- ],
114
+ ignored: ignoredPatterns,
107
115
  persistent: true,
108
116
  ignoreInitial: true,
109
117
  });
110
- const triggerRebuild = (filePath) => {
111
- const rel = path.relative(rootDir, filePath);
112
- logger.info(`Change detected in ${rel}`);
113
- if (rebuildTimeout) {
114
- clearTimeout(rebuildTimeout);
115
- }
116
- rebuildTimeout = setTimeout(async () => {
117
- if (isRebuilding)
118
- return;
119
- isRebuilding = true;
120
- try {
121
- if (filePath.endsWith("manifest.json")) {
122
- const res = validateManifest(filePath);
123
- if (res.valid) {
124
- logger.success(`Validated ${rel}`);
118
+ const runRebuildCycle = async (triggerPath) => {
119
+ isRebuilding = true;
120
+ rebuildPending = false;
121
+ const rel = path.relative(rootDir, triggerPath);
122
+ try {
123
+ if (triggerPath.endsWith("manifest.json")) {
124
+ const res = validateManifest(triggerPath);
125
+ if (res.valid) {
126
+ logger.success(`Validated ${rel}`);
127
+ }
128
+ else {
129
+ logger.error(`Invalid manifest in ${rel}:`);
130
+ res.errors.forEach((e) => console.error(` - ${e}`));
131
+ }
132
+ }
133
+ // Run build if src changed or if script output needed
134
+ if (fs.existsSync(srcDir)) {
135
+ const buildOk = await buildCommand(rootDir);
136
+ if (buildOk && hotReloadServer) {
137
+ if (hotReloadServer.clientCount > 0) {
138
+ // Buffer 150ms before reload command so Proton/Wine file cache flushes
139
+ await new Promise((resolve) => setTimeout(resolve, 150));
140
+ hotReloadServer.reload();
141
+ logger.success("Sent /reload to Minecraft via WebSocket");
125
142
  }
126
143
  else {
127
- logger.error(`Invalid manifest in ${rel}:`);
128
- res.errors.forEach((e) => console.error(` - ${e}`));
129
- }
130
- }
131
- // Run build if src changed or if script output needed
132
- if (fs.existsSync(srcDir)) {
133
- const buildOk = await buildCommand(rootDir);
134
- if (buildOk && hotReloadServer) {
135
- if (hotReloadServer.clientCount > 0) {
136
- hotReloadServer.reload();
137
- logger.success("Sent /reload to Minecraft via WebSocket");
138
- }
139
- else {
140
- logger.info(`Hot reload skipped (no Minecraft client connected; run /connect localhost:${wsPort} in game)`);
141
- }
144
+ logger.info(`Hot reload skipped (no Minecraft client connected; run /connect localhost:${wsPort} in game)`);
142
145
  }
143
146
  }
144
147
  }
145
- catch (err) {
146
- logger.error(`Error during rebuild: ${err.message}`);
147
- }
148
- finally {
149
- isRebuilding = false;
148
+ }
149
+ catch (err) {
150
+ logger.error(`Error during rebuild: ${err.message}`);
151
+ }
152
+ finally {
153
+ isRebuilding = false;
154
+ if (rebuildPending) {
155
+ runRebuildCycle(triggerPath);
150
156
  }
151
- }, 100);
157
+ }
158
+ };
159
+ const triggerRebuild = (filePath) => {
160
+ const rel = path.relative(rootDir, filePath);
161
+ logger.info(`Change detected in ${rel}`);
162
+ if (isRebuilding) {
163
+ rebuildPending = true;
164
+ return;
165
+ }
166
+ if (rebuildTimeout) {
167
+ clearTimeout(rebuildTimeout);
168
+ }
169
+ rebuildTimeout = setTimeout(() => {
170
+ runRebuildCycle(filePath);
171
+ }, 300);
152
172
  };
153
173
  watcher.on("change", triggerRebuild);
154
174
  watcher.on("add", triggerRebuild);
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { generateManifests } from "../utils/manifest.js";
4
4
  import { saveConfig } from "../utils/config.js";
5
+ import { resolveMinecraftDependencies } from "../utils/npm.js";
5
6
  import { logger } from "../utils/logger.js";
6
7
  const DEFAULT_ICON_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
7
8
  export async function initCommand(targetDirArg, options) {
@@ -16,13 +17,21 @@ export async function initCommand(targetDirArg, options) {
16
17
  if (!fs.existsSync(targetDir)) {
17
18
  fs.mkdirSync(targetDir, { recursive: true });
18
19
  }
20
+ const spinner = logger.spinner("Fetching latest @minecraft/* versions from npm...");
21
+ const mcVersions = await resolveMinecraftDependencies([
22
+ "@minecraft/server",
23
+ "@minecraft/server-ui",
24
+ ]);
25
+ const serverVersion = mcVersions["@minecraft/server"] || "2.11.0";
26
+ const serverUiVersion = mcVersions["@minecraft/server-ui"] || "2.3.0";
27
+ spinner.succeed(`Resolved dependencies: @minecraft/server@${serverVersion}, @minecraft/server-ui@${serverUiVersion}`);
19
28
  const { bpManifest, rpManifest } = generateManifests({
20
29
  name: projectName,
21
30
  description: projectDesc,
22
31
  hasScript: true,
23
32
  hasRp,
24
33
  minEngineVersion: [1, 21, 0],
25
- serverVersion: "1.16.0",
34
+ serverVersion,
26
35
  });
27
36
  // 1. Behavior Pack
28
37
  const bpDir = path.join(targetDir, "behavior_pack");
@@ -40,24 +49,24 @@ export async function initCommand(targetDirArg, options) {
40
49
  fs.writeFileSync(path.join(textsDir, "en_US.lang"), `pack.name=${projectName}\npack.description=${projectDesc}\n`);
41
50
  }
42
51
  // 3. Scripts / Source code
43
- const starterCode = `import { world, system } from "@minecraft/server";
52
+ const starterCodeTs = `import { world, type Player } from "@minecraft/server";
44
53
 
45
- world.afterEvents.worldInitialize.subscribe(() => {
46
- world.sendMessage("Hello from ${projectName}!");
54
+ world.afterEvents.playerSpawn.subscribe((e) => {
55
+ const player: Player = e.player;
56
+ player.sendMessage("Welcome!");
47
57
  });
58
+ `;
59
+ const starterCodeJs = `import { world } from "@minecraft/server";
48
60
 
49
- let ticks = 0;
50
- system.runInterval(() => {
51
- ticks++;
52
- if (ticks % 100 === 0) {
53
- // Periodic tick logic
54
- }
55
- }, 20);
61
+ world.afterEvents.playerSpawn.subscribe((e) => {
62
+ const player = e.player;
63
+ player.sendMessage("Welcome!");
64
+ });
56
65
  `;
57
66
  if (isTs) {
58
67
  const srcDir = path.join(targetDir, "src");
59
68
  fs.mkdirSync(srcDir, { recursive: true });
60
- fs.writeFileSync(path.join(srcDir, "main.ts"), starterCode);
69
+ fs.writeFileSync(path.join(srcDir, "main.ts"), starterCodeTs);
61
70
  // tsconfig.json
62
71
  const tsconfig = {
63
72
  compilerOptions: {
@@ -75,7 +84,7 @@ system.runInterval(() => {
75
84
  else {
76
85
  const scriptsDir = path.join(bpDir, "scripts");
77
86
  fs.mkdirSync(scriptsDir, { recursive: true });
78
- fs.writeFileSync(path.join(scriptsDir, "main.js"), starterCode);
87
+ fs.writeFileSync(path.join(scriptsDir, "main.js"), starterCodeJs);
79
88
  }
80
89
  // 4. package.json
81
90
  const pkgJson = {
@@ -89,8 +98,8 @@ system.runInterval(() => {
89
98
  package: "bdev package",
90
99
  },
91
100
  dependencies: {
92
- "@minecraft/server": "1.16.0",
93
- "@minecraft/server-ui": "1.7.0",
101
+ "@minecraft/server": serverVersion,
102
+ "@minecraft/server-ui": serverUiVersion,
94
103
  },
95
104
  };
96
105
  if (isTs) {
@@ -100,7 +100,7 @@ export function generateManifests(opts) {
100
100
  if (opts.hasScript) {
101
101
  bpDependencies.push({
102
102
  module_name: "@minecraft/server",
103
- version: opts.serverVersion || "1.16.0",
103
+ version: opts.serverVersion || "2.11.0",
104
104
  });
105
105
  }
106
106
  if (opts.hasRp) {
@@ -28,19 +28,55 @@ export function findMojangPath(customPath, projectDir = process.cwd()) {
28
28
  }
29
29
  const platform = os.platform();
30
30
  if (platform === "win32") {
31
+ const appData = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
31
32
  const localAppData = process.env.LOCALAPPDATA ||
32
33
  path.join(os.homedir(), "AppData", "Local");
34
+ // Modern Windows GDK Bedrock (Shared folder contains dev packs)
35
+ const gdkShared = path.join(appData, "Minecraft Bedrock", "Users", "Shared", "games", "com.mojang");
36
+ if (fs.existsSync(gdkShared)) {
37
+ return makeLocations(gdkShared, "retail");
38
+ }
39
+ const gdkPreviewShared = path.join(appData, "Minecraft Bedrock Preview", "Users", "Shared", "games", "com.mojang");
40
+ if (fs.existsSync(gdkPreviewShared)) {
41
+ return makeLocations(gdkPreviewShared, "preview");
42
+ }
43
+ // Classic UWP Retail
33
44
  const retail = path.join(localAppData, "Packages", "Microsoft.MinecraftUWP_8wekyb3d8bbwe", "LocalState", "games", "com.mojang");
34
45
  if (fs.existsSync(retail)) {
35
46
  return makeLocations(retail, "retail");
36
47
  }
48
+ // Classic UWP Preview
37
49
  const preview = path.join(localAppData, "Packages", "Microsoft.MinecraftWindowsBeta_8wekyb3d8bbwe", "LocalState", "games", "com.mojang");
38
50
  if (fs.existsSync(preview)) {
39
51
  return makeLocations(preview, "preview");
40
52
  }
41
53
  }
42
- // Check WSL
54
+ // Check Linux / Bedrock-on-linux / Proton / WSL
43
55
  if (platform === "linux") {
56
+ // 1. Bedrock-on-Linux (Proton / Wine)
57
+ const bolBase = path.join(os.homedir(), ".local", "share", "bedrock-on-linux");
58
+ if (fs.existsSync(bolBase)) {
59
+ const profilesDir = path.join(bolBase, "profiles");
60
+ if (fs.existsSync(profilesDir)) {
61
+ try {
62
+ const profiles = fs.readdirSync(profilesDir);
63
+ for (const prof of profiles) {
64
+ const sharedPfx = path.join(profilesDir, prof, "compatdata", "pfx", "drive_c", "users", "steamuser", "AppData", "Roaming", "Minecraft Bedrock", "Users", "Shared", "games", "com.mojang");
65
+ if (fs.existsSync(sharedPfx)) {
66
+ return makeLocations(sharedPfx, "linux");
67
+ }
68
+ }
69
+ }
70
+ catch {
71
+ // ignore profile read errors
72
+ }
73
+ }
74
+ const defaultShared = path.join(bolBase, "compatdata", "pfx", "drive_c", "users", "steamuser", "AppData", "Roaming", "Minecraft Bedrock", "Users", "Shared", "games", "com.mojang");
75
+ if (fs.existsSync(defaultShared)) {
76
+ return makeLocations(defaultShared, "linux");
77
+ }
78
+ }
79
+ // 2. Check WSL
44
80
  try {
45
81
  const isWsl = Boolean(process.env.WSL_DISTRO_NAME) ||
46
82
  fs.readFileSync("/proc/version", "utf-8").toLowerCase().includes("microsoft");
@@ -49,14 +85,14 @@ export function findMojangPath(customPath, projectDir = process.cwd()) {
49
85
  if (fs.existsSync(mntCUsers)) {
50
86
  const users = fs.readdirSync(mntCUsers);
51
87
  for (const u of users) {
88
+ const gdk = path.join(mntCUsers, u, "AppData", "Roaming", "Minecraft Bedrock", "Users", "Shared", "games", "com.mojang");
89
+ if (fs.existsSync(gdk)) {
90
+ return makeLocations(gdk, "wsl");
91
+ }
52
92
  const retail = path.join(mntCUsers, u, "AppData", "Local", "Packages", "Microsoft.MinecraftUWP_8wekyb3d8bbwe", "LocalState", "games", "com.mojang");
53
93
  if (fs.existsSync(retail)) {
54
94
  return makeLocations(retail, "wsl");
55
95
  }
56
- const preview = path.join(mntCUsers, u, "AppData", "Local", "Packages", "Microsoft.MinecraftWindowsBeta_8wekyb3d8bbwe", "LocalState", "games", "com.mojang");
57
- if (fs.existsSync(preview)) {
58
- return makeLocations(preview, "wsl");
59
- }
60
96
  }
61
97
  }
62
98
  }
@@ -64,7 +100,7 @@ export function findMojangPath(customPath, projectDir = process.cwd()) {
64
100
  catch {
65
101
  // Ignore read errors
66
102
  }
67
- // Native Linux launcher locations
103
+ // 3. Native Linux mcpelauncher locations
68
104
  const linuxMcpelauncherPaths = [
69
105
  path.join(os.homedir(), ".var", "app", "io.mrarm.mcpelauncher", "data", "mcpelauncher", "games", "com.mojang"),
70
106
  path.join(os.homedir(), ".local", "share", "mcpelauncher", "games", "com.mojang"),
@@ -78,10 +114,22 @@ export function findMojangPath(customPath, projectDir = process.cwd()) {
78
114
  return null;
79
115
  }
80
116
  function makeLocations(root, type) {
117
+ // If pointing to a specific user XUID directory in Bedrock GDK (e.g. Users/<XUID>/games/com.mojang),
118
+ // Bedrock GDK only scans packs from Users/Shared/games/com.mojang.
119
+ let packsRoot = root;
120
+ try {
121
+ const sharedCandidate = path.resolve(root, "..", "..", "..", "Shared", "games", "com.mojang");
122
+ if (fs.existsSync(sharedCandidate)) {
123
+ packsRoot = sharedCandidate;
124
+ }
125
+ }
126
+ catch {
127
+ // Ignore resolution errors
128
+ }
81
129
  return {
82
- root,
83
- devBehaviorPacks: path.join(root, "development_behavior_packs"),
84
- devResourcePacks: path.join(root, "development_resource_packs"),
130
+ root: packsRoot,
131
+ devBehaviorPacks: path.join(packsRoot, "development_behavior_packs"),
132
+ devResourcePacks: path.join(packsRoot, "development_resource_packs"),
85
133
  type,
86
134
  };
87
135
  }
@@ -0,0 +1,2 @@
1
+ export declare function fetchLatestNpmVersion(pkgName: string, fallback?: string): Promise<string>;
2
+ export declare function resolveMinecraftDependencies(packages: string[]): Promise<Record<string, string>>;
@@ -0,0 +1,35 @@
1
+ const DEFAULT_FALLBACKS = {
2
+ "@minecraft/server": "2.11.0",
3
+ "@minecraft/server-ui": "2.3.0",
4
+ "@minecraft/server-admin": "1.0.0-beta",
5
+ "@minecraft/server-gametest": "1.0.0-beta",
6
+ "@minecraft/server-net": "1.0.0-beta",
7
+ };
8
+ export async function fetchLatestNpmVersion(pkgName, fallback) {
9
+ const defaultFallback = fallback || DEFAULT_FALLBACKS[pkgName] || "latest";
10
+ try {
11
+ const res = await fetch(`https://registry.npmjs.org/${pkgName}/latest`, {
12
+ headers: {
13
+ Accept: "application/json",
14
+ },
15
+ signal: AbortSignal.timeout(4000),
16
+ });
17
+ if (res.ok) {
18
+ const data = (await res.json());
19
+ if (data?.version) {
20
+ return data.version;
21
+ }
22
+ }
23
+ }
24
+ catch {
25
+ // Offline or network timeout, return fallback
26
+ }
27
+ return defaultFallback;
28
+ }
29
+ export async function resolveMinecraftDependencies(packages) {
30
+ const entries = await Promise.all(packages.map(async (pkg) => {
31
+ const ver = await fetchLatestNpmVersion(pkg);
32
+ return [pkg, ver];
33
+ }));
34
+ return Object.fromEntries(entries);
35
+ }
@@ -35,17 +35,29 @@ export class BedrockHotReloadServer {
35
35
  server.on("connection", (socket) => {
36
36
  this.clients.add(socket);
37
37
  logger.success(pc.green("Minecraft connected to WebSocket hot reload!"));
38
- // Delay welcome message 500ms so Bedrock completes internal handshake
39
- setTimeout(() => {
40
- if (socket.readyState === WebSocket.OPEN) {
41
- this.sendCommandToSocket(socket, 'tellraw @a {"rawtext":[{"text":"§a[bdev] Connected to hot reload server!"}]}');
42
- }
43
- }, 500);
38
+ // Bedrock expects an event subscription to establish connection cleanly
39
+ const subscribePayload = {
40
+ header: {
41
+ version: 1,
42
+ requestId: uuidv4(),
43
+ messageType: "commandRequest",
44
+ messagePurpose: "subscribe",
45
+ },
46
+ body: {
47
+ eventName: "PlayerMessage",
48
+ },
49
+ };
50
+ socket.send(JSON.stringify(subscribePayload));
44
51
  socket.on("message", (data) => {
45
52
  try {
46
53
  const res = JSON.parse(data.toString());
47
- if (res?.body?.statusCode && res.body.statusCode !== 0) {
48
- logger.warn(`Minecraft command response: ${res.body.statusMessage || "Error"}`);
54
+ if (res?.header?.messagePurpose === "commandResponse") {
55
+ if (res.body?.statusCode && res.body.statusCode !== 0) {
56
+ logger.warn(`Minecraft command error (${res.body.statusCode}): ${res.body.statusMessage || "Error"}`);
57
+ }
58
+ else if (res.body?.statusMessage) {
59
+ logger.info(`Minecraft: ${res.body.statusMessage}`);
60
+ }
49
61
  }
50
62
  }
51
63
  catch {
@@ -56,7 +68,8 @@ export class BedrockHotReloadServer {
56
68
  this.clients.delete(socket);
57
69
  logger.info("Minecraft disconnected from WebSocket.");
58
70
  });
59
- socket.on("error", () => {
71
+ socket.on("error", (err) => {
72
+ logger.warn(`WebSocket client error: ${err.message}`);
60
73
  this.clients.delete(socket);
61
74
  });
62
75
  });
@@ -69,7 +82,8 @@ export class BedrockHotReloadServer {
69
82
  }
70
83
  }
71
84
  sendCommandToSocket(socket, commandLine) {
72
- const formatted = commandLine.startsWith("/") ? commandLine : `/${commandLine}`;
85
+ // Bedrock commandLine must NOT have a leading slash
86
+ const cleanCmd = commandLine.startsWith("/") ? commandLine.slice(1) : commandLine;
73
87
  const payload = {
74
88
  header: {
75
89
  version: 1,
@@ -79,7 +93,7 @@ export class BedrockHotReloadServer {
79
93
  },
80
94
  body: {
81
95
  version: 1,
82
- commandLine: formatted,
96
+ commandLine: cleanCmd,
83
97
  origin: {
84
98
  type: "player",
85
99
  },
@@ -91,9 +105,7 @@ export class BedrockHotReloadServer {
91
105
  if (this.clients.size === 0) {
92
106
  return;
93
107
  }
94
- // Notify in game chat and execute reload command
95
- this.sendCommand('tellraw @a {"rawtext":[{"text":"§e[bdev] Reloading scripts..."}]}');
96
- this.sendCommand("/reload");
108
+ this.sendCommand("reload");
97
109
  }
98
110
  get clientCount() {
99
111
  return this.clients.size;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mafly/bdev-cli",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Modern CLI tool for Minecraft Bedrock Edition Addon development",
5
5
  "author": "Mafly",
6
6
  "license": "MIT",