@monlabs/cli 0.0.0-stage → 0.1.0

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 (3) hide show
  1. package/README.md +31 -2
  2. package/bin/monlabs.mjs +268 -0
  3. package/package.json +12 -4
package/README.md CHANGED
@@ -1,3 +1,32 @@
1
- # Temporary Holding Version
1
+ # @monlabs/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Đẩy bản build game lên [Monlabs Game Hub](https://play.monlabs.fun) từ terminal hoặc CI – không cần upload qua web.
4
+
5
+ ```bash
6
+ # 1. Studio → Token cho CLI / CI → Tạo token
7
+ npx @monlabs/cli login
8
+ # 2. Build game rồi đẩy lên (version mặc định lấy từ package.json)
9
+ npm run build
10
+ npx @monlabs/cli deploy ./dist --game my-game --notes "Sửa lỗi nhảy"
11
+ ```
12
+
13
+ | Lệnh | |
14
+ |---|---|
15
+ | `monlabs login` | Lưu token vào `~/.monlabs/config.json` (quyền 600) |
16
+ | `monlabs games` | Game của studio |
17
+ | `monlabs deploy [dir] --game <slug> [--version] [--notes] [--dry-run]` | Nén thư mục build (bỏ `node_modules`, `.git`, `.env*`, `*.map`), tải lên, tạo phiên bản chờ duyệt, in kết quả quét |
18
+ | `monlabs sandbox [url]` | Link thử game local với hub giả lập |
19
+
20
+ `monlabs.json` trong project: `{ "game": "my-game", "dir": "dist" }`.
21
+
22
+ ## GitHub Actions
23
+
24
+ ```yaml
25
+ - run: npm ci && npm run build
26
+ - run: npx @monlabs/cli deploy ./dist --game my-game --version ${{ github.ref_name }}
27
+ env:
28
+ MONLABS_TOKEN: ${{ secrets.MONLABS_TOKEN }}
29
+ ```
30
+
31
+ **Đừng commit token.** Để trong `MONLABS_TOKEN` / GitHub Secrets. Lộ token → thu hồi ngay trong Studio. Token chỉ dùng được cho API Studio.
32
+ Mã thoát: `0` ok · `1` lỗi · `2` sai cách dùng / thiếu token · `3` upload xong nhưng bản build bị quét ra mức nguy hiểm.
@@ -0,0 +1,268 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @monlabs/cli – đẩy bản build game lên Monlabs Game Hub từ terminal / CI.
4
+ *
5
+ * npx @monlabs/cli login # dán token tạo ở Studio → Token cho CLI / CI
6
+ * npx @monlabs/cli games # game của studio
7
+ * npx @monlabs/cli deploy ./dist --game my-game --version 1.0.1 --notes "Sửa lỗi"
8
+ * npx @monlabs/cli sandbox http://localhost:5173
9
+ *
10
+ * Token: biến môi trường MONLABS_TOKEN (khuyên dùng trong CI) hoặc file ~/.monlabs/config.json (quyền 600).
11
+ * Không bao giờ in token ra màn hình.
12
+ */
13
+ import fs from "node:fs";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import readline from "node:readline";
17
+
18
+ const DEFAULT_HUB = "https://play.monlabs.fun";
19
+ const CONFIG_DIR = path.join(os.homedir(), ".monlabs");
20
+ const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
21
+ const MAX_ZIP = 50 * 1024 * 1024;
22
+ const SKIP = /(^|\/)(node_modules|\.git|\.svn|\.idea|\.vscode)(\/|$)|(^|\/)(\.DS_Store|Thumbs\.db)$|(^|\/)\.env(\..*)?$|\.map$/;
23
+
24
+ // ───────── tiện ích ─────────
25
+ const color = !process.env.NO_COLOR && process.stdout.isTTY;
26
+ const paint = (code) => (s) => (color ? `\x1b[${code}m${s}\x1b[0m` : String(s));
27
+ const c = { green: paint(32), red: paint(31), yellow: paint(33), dim: paint(2), bold: paint(1) };
28
+
29
+ export function parseArgs(argv) {
30
+ const out = { _: [] };
31
+ for (let i = 0; i < argv.length; i++) {
32
+ const a = argv[i];
33
+ if (a.startsWith("--")) {
34
+ const [k, v] = a.slice(2).split("=", 2);
35
+ if (v !== undefined) out[k] = v;
36
+ else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith("--")) out[k] = argv[++i];
37
+ else out[k] = true;
38
+ } else out._.push(a);
39
+ }
40
+ return out;
41
+ }
42
+
43
+ function readConfig() {
44
+ try {
45
+ return JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8"));
46
+ } catch {
47
+ return {};
48
+ }
49
+ }
50
+
51
+ function writeConfig(cfg) {
52
+ fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
53
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2), { mode: 0o600 });
54
+ try {
55
+ fs.chmodSync(CONFIG_FILE, 0o600);
56
+ } catch {
57
+ // Windows: bỏ qua
58
+ }
59
+ }
60
+
61
+ /** Cấu hình dự án (monlabs.json ở thư mục hiện tại): { "game": "my-game", "dir": "dist" } */
62
+ function readProject() {
63
+ try {
64
+ return JSON.parse(fs.readFileSync(path.resolve("monlabs.json"), "utf8"));
65
+ } catch {
66
+ return {};
67
+ }
68
+ }
69
+
70
+ function hubUrl(args) {
71
+ return String(args.hub || process.env.MONLABS_HUB || readConfig().hub || DEFAULT_HUB).replace(/\/+$/, "");
72
+ }
73
+
74
+ function token() {
75
+ const t = process.env.MONLABS_TOKEN || readConfig().token;
76
+ if (!t) {
77
+ console.error(c.red("✗ Chưa có token.") + " Chạy `monlabs login` hoặc đặt biến môi trường MONLABS_TOKEN.");
78
+ process.exit(2);
79
+ }
80
+ return t;
81
+ }
82
+
83
+ async function api(args, method, p, body) {
84
+ const res = await fetch(`${hubUrl(args)}/api/v1${p}`, {
85
+ method,
86
+ headers: { authorization: `Bearer ${token()}`, ...(body ? { "content-type": "application/json" } : {}), "user-agent": "monlabs-cli/1" },
87
+ body: body ? JSON.stringify(body) : undefined,
88
+ });
89
+ const text = await res.text();
90
+ let json = null;
91
+ try {
92
+ json = text ? JSON.parse(text) : null;
93
+ } catch {
94
+ // không phải JSON
95
+ }
96
+ if (!res.ok) {
97
+ const err = new Error(json?.error?.message || `HTTP ${res.status}`);
98
+ err.code = json?.error?.code || `HTTP_${res.status}`;
99
+ err.status = res.status;
100
+ throw err;
101
+ }
102
+ return json;
103
+ }
104
+
105
+ function ask(question, { hidden = false } = {}) {
106
+ return new Promise((resolve) => {
107
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
108
+ if (hidden) {
109
+ rl._writeToOutput = (s) => {
110
+ if (s.includes(question)) process.stdout.write(s);
111
+ };
112
+ }
113
+ rl.question(question, (answer) => {
114
+ rl.close();
115
+ if (hidden) process.stdout.write("\n");
116
+ resolve(answer.trim());
117
+ });
118
+ });
119
+ }
120
+
121
+ /** Gom các file của thư mục build (bỏ node_modules, .git, .env, *.map) */
122
+ export function collectFiles(dir) {
123
+ const files = {};
124
+ let count = 0;
125
+ const walk = (abs, rel) => {
126
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
127
+ const r = rel ? `${rel}/${entry.name}` : entry.name;
128
+ if (SKIP.test(r)) continue;
129
+ const a = path.join(abs, entry.name);
130
+ if (entry.isDirectory()) walk(a, r);
131
+ else if (entry.isFile()) {
132
+ files[r] = new Uint8Array(fs.readFileSync(a));
133
+ count++;
134
+ }
135
+ }
136
+ };
137
+ walk(dir, "");
138
+ return { files, count };
139
+ }
140
+
141
+ function formatBytes(n) {
142
+ return n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.ceil(n / 1024)} KB`;
143
+ }
144
+
145
+ // ───────── lệnh ─────────
146
+ async function cmdLogin(args) {
147
+ const t = process.env.MONLABS_TOKEN || (await ask("Token (Studio → Token cho CLI / CI): ", { hidden: true }));
148
+ if (!/^mlb_[A-Za-z0-9_-]{32,64}$/.test(t)) {
149
+ console.error(c.red("✗ Token không đúng định dạng (mlb_…)."));
150
+ process.exit(2);
151
+ }
152
+ process.env.MONLABS_TOKEN = t;
153
+ const r = await api(args, "GET", "/developer/games");
154
+ writeConfig({ ...readConfig(), token: t, hub: hubUrl(args) });
155
+ console.log(`${c.green("✓")} Đã đăng nhập studio ${c.bold(r.studio.name)} (${r.games.length} game). Token lưu ở ${CONFIG_FILE}`);
156
+ }
157
+
158
+ function cmdLogout() {
159
+ const cfg = readConfig();
160
+ delete cfg.token;
161
+ writeConfig(cfg);
162
+ console.log(`${c.green("✓")} Đã xóa token khỏi máy (token vẫn còn hiệu lực – thu hồi trong Studio nếu bị lộ).`);
163
+ }
164
+
165
+ async function cmdGames(args) {
166
+ const r = await api(args, "GET", "/developer/games");
167
+ console.log(c.bold(`Studio: ${r.studio.name}`));
168
+ for (const g of r.games) {
169
+ const live = g.versions?.find((v) => v.isCurrent)?.version;
170
+ console.log(` ${g.slug.padEnd(28)} ${String(g.status).padEnd(15)} ${live ? `v${live}` : c.dim("chưa có bản chạy")}`);
171
+ }
172
+ if (args.json) console.log(JSON.stringify(r.games.map((g) => ({ id: g.id, slug: g.slug, status: g.status }))));
173
+ }
174
+
175
+ export async function cmdDeploy(args) {
176
+ const project = readProject();
177
+ const dir = path.resolve(args._[1] || project.dir || "dist");
178
+ const slug = args.game || project.game;
179
+ let version = args.version;
180
+ if (!version) {
181
+ try {
182
+ version = JSON.parse(fs.readFileSync(path.resolve("package.json"), "utf8")).version;
183
+ } catch {
184
+ // không có package.json
185
+ }
186
+ }
187
+ if (!slug) throw Object.assign(new Error("Thiếu --game <slug> (hoặc \"game\" trong monlabs.json)"), { code: "USAGE" });
188
+ if (!version) throw Object.assign(new Error("Thiếu --version (hoặc \"version\" trong package.json)"), { code: "USAGE" });
189
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw Object.assign(new Error(`Không thấy thư mục ${dir} – build game trước`), { code: "USAGE" });
190
+
191
+ const { files, count } = collectFiles(dir);
192
+ if (!files["index.html"]) throw Object.assign(new Error(`Thiếu index.html ở gốc ${dir}`), { code: "NO_INDEX" });
193
+ const { zipSync } = await import("fflate");
194
+ const zip = zipSync(files, { level: 6 });
195
+ console.log(`${c.dim("•")} ${count} file → zip ${formatBytes(zip.byteLength)}`);
196
+ if (zip.byteLength > MAX_ZIP) throw Object.assign(new Error("Bản build quá 50MB sau khi nén"), { code: "TOO_LARGE" });
197
+
198
+ const { games } = await api(args, "GET", "/developer/games");
199
+ const game = games.find((g) => g.slug === slug || g.id === slug);
200
+ if (!game) throw Object.assign(new Error(`Studio không có game "${slug}" – xem \`monlabs games\``), { code: "GAME_NOT_FOUND" });
201
+
202
+ if (args["dry-run"]) {
203
+ console.log(`${c.yellow("○")} --dry-run: dừng trước khi upload (${game.slug} v${version})`);
204
+ return { dryRun: true };
205
+ }
206
+
207
+ const { upload } = await api(args, "POST", "/developer/uploads", { kind: "build", contentType: "application/zip", size: zip.byteLength });
208
+ // Kho lưu trữ R2 trả URL đầy đủ; máy chủ tự host (lưu trên đĩa) trả đường dẫn tương đối của hub
209
+ const put = await fetch(new URL(upload.url, `${hubUrl(args)}/`), { method: "PUT", headers: upload.headers, body: zip });
210
+ if (!put.ok) throw Object.assign(new Error(`Tải file lên thất bại (HTTP ${put.status})`), { code: "UPLOAD_FAILED" });
211
+ console.log(`${c.dim("•")} đã tải lên, đang giải nén + quét…`);
212
+
213
+ const notes = typeof args.notes === "string" ? args.notes : undefined;
214
+ const { version: v } = await api(args, "POST", `/developer/games/${game.id}/versions`, { version, uploadKey: upload.key, releaseNotes: notes });
215
+ console.log(`${c.green("✓")} ${c.bold(`${game.slug} v${v.version}`)} – ${v.files} file, trạng thái ${v.status}`);
216
+ if (v.scan) {
217
+ const tone = v.scan.level === "critical" ? c.red : v.scan.level === "warning" ? c.yellow : c.green;
218
+ console.log(` quét: ${tone(v.scan.level)}`);
219
+ for (const f of v.scan.findings?.slice(0, 10) ?? []) console.log(` ${f.severity === "critical" ? c.red("!") : "-"} ${f.rule} ${c.dim(f.path)}`);
220
+ }
221
+ if (v.autoCover) console.log(` ảnh bìa: lấy từ ${v.autoCover.path}`);
222
+ console.log(c.dim(` Studio: ${hubUrl(args)}/developer/games/${game.id}`));
223
+ if (v.scan?.level === "critical") process.exitCode = 3;
224
+ return v;
225
+ }
226
+
227
+ function cmdSandbox(args) {
228
+ const url = args._[1] || "http://localhost:5173";
229
+ const link = `${hubUrl(args)}/developer/sandbox?url=${encodeURIComponent(url)}`;
230
+ console.log(`Mở trong trình duyệt:\n ${link}`);
231
+ }
232
+
233
+ function help() {
234
+ console.log(`monlabs – CLI cho Monlabs Game Hub
235
+
236
+ monlabs login lưu token (tạo ở Studio → Token cho CLI / CI)
237
+ monlabs logout xóa token khỏi máy
238
+ monlabs games game của studio
239
+ monlabs deploy [dir] --game <slug> [--version 1.0.1] [--notes "…"] [--dry-run]
240
+ monlabs sandbox [url] link thử game local với hub giả lập
241
+
242
+ Tùy chọn: --hub <url> (mặc định ${DEFAULT_HUB}) · biến môi trường MONLABS_TOKEN, MONLABS_HUB
243
+ monlabs.json: { "game": "my-game", "dir": "dist" } · version mặc định lấy từ package.json`);
244
+ }
245
+
246
+ export async function main(argv) {
247
+ const args = parseArgs(argv);
248
+ const cmd = args._[0];
249
+ try {
250
+ if (!cmd || cmd === "help" || args.help) return help();
251
+ if (cmd === "login") return await cmdLogin(args);
252
+ if (cmd === "logout") return cmdLogout();
253
+ if (cmd === "games") return await cmdGames(args);
254
+ if (cmd === "deploy") return await cmdDeploy(args);
255
+ if (cmd === "sandbox") return cmdSandbox(args);
256
+ console.error(c.red(`✗ Không có lệnh "${cmd}"`));
257
+ help();
258
+ process.exitCode = 2;
259
+ } catch (err) {
260
+ console.error(`${c.red("✗")} ${err.message}${err.code ? c.dim(` (${err.code})`) : ""}`);
261
+ if (err.status === 401) console.error(" Token sai, đã bị thu hồi hoặc hết hạn – tạo token mới trong Studio.");
262
+ process.exitCode = err.code === "USAGE" ? 2 : 1;
263
+ }
264
+ }
265
+
266
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(new URL(import.meta.url).pathname)) {
267
+ await main(process.argv.slice(2));
268
+ }
package/package.json CHANGED
@@ -1,6 +1,14 @@
1
1
  {
2
2
  "name": "@monlabs/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Deploy HTML5 game builds to Monlabs Game Hub from the terminal or CI",
5
+ "type": "module",
6
+ "bin": { "monlabs": "bin/monlabs.mjs" },
7
+ "files": ["bin", "README.md"],
8
+ "dependencies": { "fflate": "^0.8.2" },
9
+ "engines": { "node": ">=18" },
10
+ "keywords": ["monlabs", "game-hub", "deploy", "cli", "html5-games"],
11
+ "homepage": "https://docs.monlabs.fun/cli",
12
+ "repository": { "type": "git", "url": "git+https://github.com/phh0302/game-hub.git", "directory": "packages/cli" },
13
+ "license": "MIT"
14
+ }