@replaystage/cli 0.8.1 → 2.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.
@@ -0,0 +1,886 @@
1
+ import { cp, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { DEFAULT_PORTAL_ORIGIN, DEFAULT_STUDIO_ORIGIN, findPlatformWorkspaceRoot, requireAuthToken, resolveApiBase, } from '../config.js';
4
+ import { apiRequestJson } from '../http.js';
5
+ import { HEX_COLOR_RE, SLUG_RE, VALID_CREATOR_VISIBILITIES, VALID_GENRES, buildStarterManifest, loadAndValidateManifest, slugToTitle, writeStarterManifest, } from '../manifest.js';
6
+ import { CliError, assertNoUnknownFlags, emitSuccess, extractBoolFlag, extractFlag, } from '../output.js';
7
+ import { discoverMediaFile, validateProjectBundle } from '../validate.js';
8
+ async function exists(targetPath) {
9
+ try {
10
+ await stat(targetPath);
11
+ return true;
12
+ }
13
+ catch {
14
+ return false;
15
+ }
16
+ }
17
+ function formatBytes(bytes) {
18
+ if (bytes < 1024)
19
+ return `${bytes} B`;
20
+ if (bytes < 1024 * 1024)
21
+ return `${(bytes / 1024).toFixed(1)} KB`;
22
+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
23
+ }
24
+ async function runPool(items, concurrency, worker) {
25
+ let cursor = 0;
26
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
27
+ while (cursor < items.length) {
28
+ const idx = cursor;
29
+ cursor += 1;
30
+ const item = items[idx];
31
+ if (item !== undefined) {
32
+ await worker(item);
33
+ }
34
+ }
35
+ });
36
+ await Promise.all(workers);
37
+ }
38
+ export async function cmdInit(args, opts) {
39
+ let rest = args;
40
+ const dirFlag = extractFlag(rest, ['--dir']);
41
+ rest = dirFlag.rest;
42
+ const titleFlag = extractFlag(rest, ['--title']);
43
+ rest = titleFlag.rest;
44
+ const zhFlag = extractFlag(rest, ['--zh']);
45
+ rest = zhFlag.rest;
46
+ const genreFlag = extractFlag(rest, ['--genre']);
47
+ rest = genreFlag.rest;
48
+ const accentFlag = extractFlag(rest, ['--accent']);
49
+ rest = accentFlag.rest;
50
+ const forceFlag = extractBoolFlag(rest, ['--force', '-f']);
51
+ rest = forceFlag.rest;
52
+ assertNoUnknownFlags(rest);
53
+ const slug = rest[0]?.trim().toLowerCase();
54
+ if (!slug || !SLUG_RE.test(slug) || slug.length < 3 || slug.length > 48) {
55
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage init <slug> [--dir <path>] [--title "<English>"] [--zh "<中文>"] [--genre arcade|puzzle|mystery|strategy] [--accent "#0F62FE"] [--force]');
56
+ }
57
+ const genre = (genreFlag.value || 'arcade');
58
+ if (!VALID_GENRES.includes(genre)) {
59
+ throw new CliError('INVALID_ARGUMENTS', `Invalid --genre "${genre}". Expected one of: ${VALID_GENRES.join(', ')}`);
60
+ }
61
+ const accentColor = accentFlag.value || '#0F62FE';
62
+ if (!HEX_COLOR_RE.test(accentColor)) {
63
+ throw new CliError('INVALID_ARGUMENTS', `Invalid --accent "${accentColor}". Expected 6-digit hex like "#0F62FE".`);
64
+ }
65
+ const targetDir = path.resolve(opts.cwd, dirFlag.value || '.');
66
+ await mkdir(targetDir, { recursive: true });
67
+ const manifest = buildStarterManifest({
68
+ slug,
69
+ titleEn: titleFlag.value,
70
+ titleZh: zhFlag.value,
71
+ genre,
72
+ accentColor,
73
+ });
74
+ const writtenPath = await writeStarterManifest(path.join(targetDir, 'replaystage.manifest.json'), manifest, forceFlag.present);
75
+ emitSuccess(opts, { slug, manifestPath: writtenPath, manifest }, () => [
76
+ `Created ${writtenPath}`,
77
+ 'Next steps:',
78
+ ' 1. Replace the placeholder tagline/description/howToPlay with real bilingual (en + zh-Hans) copy.',
79
+ ` 2. Add icon.png and cover.png under public/media/${slug}/ (<= 2 MB each).`,
80
+ ' 3. Build your game and run `npx -y replaystage validate ./dist --json`.',
81
+ ' 4. Publish an unlisted preview with `npx -y replaystage publish ./dist --json`.',
82
+ ]);
83
+ }
84
+ export async function cmdCreateGame(args, opts) {
85
+ let rest = args;
86
+ const dirFlag = extractFlag(rest, ['--dir']);
87
+ rest = dirFlag.rest;
88
+ const titleFlag = extractFlag(rest, ['--title']);
89
+ rest = titleFlag.rest;
90
+ const zhFlag = extractFlag(rest, ['--zh']);
91
+ rest = zhFlag.rest;
92
+ const genreFlag = extractFlag(rest, ['--genre']);
93
+ rest = genreFlag.rest;
94
+ assertNoUnknownFlags(rest);
95
+ const slug = rest[0]?.trim().toLowerCase();
96
+ if (!slug || !SLUG_RE.test(slug) || slug.length < 3 || slug.length > 48) {
97
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage create-game <slug> [--dir <path>] [--title "<English>"] [--zh "<中文>"] [--genre arcade|puzzle|mystery|strategy]');
98
+ }
99
+ const titleEn = titleFlag.value?.trim() || slugToTitle(slug);
100
+ const titleZh = zhFlag.value?.trim() || titleEn;
101
+ const genre = (genreFlag.value || 'arcade');
102
+ if (!VALID_GENRES.includes(genre)) {
103
+ throw new CliError('INVALID_ARGUMENTS', `Invalid --genre "${genre}".`);
104
+ }
105
+ const workspaceRoot = await findPlatformWorkspaceRoot(opts.cwd);
106
+ const targetDir = dirFlag.value
107
+ ? path.resolve(opts.cwd, dirFlag.value)
108
+ : workspaceRoot
109
+ ? path.resolve(workspaceRoot, '..', slug)
110
+ : path.resolve(opts.cwd, slug);
111
+ if (await exists(targetDir)) {
112
+ const existing = await readdir(targetDir);
113
+ if (existing.length > 0) {
114
+ throw new CliError('TARGET_NOT_EMPTY', `Target directory is not empty: ${targetDir}`, {
115
+ details: { targetDir },
116
+ });
117
+ }
118
+ }
119
+ await mkdir(targetDir, { recursive: true });
120
+ let mode = 'standalone-starter';
121
+ if (workspaceRoot && (await exists(path.join(workspaceRoot, 'templates', 'starter-web-game')))) {
122
+ mode = 'workspace-template';
123
+ const templateDir = path.join(workspaceRoot, 'templates', 'starter-web-game');
124
+ await cp(templateDir, targetDir, { recursive: true });
125
+ const replacements = [
126
+ ['package.json', [['"name": "replaystage-starter-game"', `"name": "${slug}"`]]],
127
+ ['index.html', [['<title>ReplayStage Starter Game</title>', `<title>${titleEn}</title>`]]],
128
+ ['.github/workflows/publish-replaystage.yml', [['slug: starter-game', `slug: ${slug}`]]],
129
+ [
130
+ 'replaystage.manifest.json',
131
+ [
132
+ ['"slug": "starter-game"', `"slug": "${slug}"`],
133
+ ['"originSlug": "starter-game"', `"originSlug": "${slug}"`],
134
+ ['"genre": "arcade"', `"genre": "${genre}"`],
135
+ ['"title": "Pulse Tap"', `"title": ${JSON.stringify(titleEn)}`],
136
+ ['"title": "节拍点按"', `"title": ${JSON.stringify(titleZh)}`],
137
+ ],
138
+ ],
139
+ [
140
+ 'src/main.ts',
141
+ [
142
+ [
143
+ "const STORAGE_KEY = 'rs_starter_save_v1';",
144
+ `const STORAGE_KEY = 'rs_${slug.replace(/-/g, '_')}_save_v1';`,
145
+ ],
146
+ ["title: 'PULSE TAP'", `title: ${JSON.stringify(titleEn.toUpperCase())}`],
147
+ ["title: '节拍点按'", `title: ${JSON.stringify(titleZh)}`],
148
+ ],
149
+ ],
150
+ ['public/cover.svg', [['PULSE TAP', titleEn.toUpperCase()]]],
151
+ ];
152
+ for (const [relFile, pairs] of replacements) {
153
+ const full = path.join(targetDir, relFile);
154
+ if (!(await exists(full)))
155
+ continue;
156
+ let content = await readFile(full, 'utf8');
157
+ for (const [from, to] of pairs) {
158
+ content = content.replace(from, to);
159
+ }
160
+ await writeFile(full, content, 'utf8');
161
+ }
162
+ }
163
+ else {
164
+ // Standalone zero-install Tier 2 starter using ReplayStage hosted CDN SDK
165
+ const manifest = buildStarterManifest({ slug, titleEn, titleZh, genre });
166
+ await writeFile(path.join(targetDir, 'replaystage.manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
167
+ await mkdir(path.join(targetDir, 'dist'), { recursive: true });
168
+ await mkdir(path.join(targetDir, '.github', 'workflows'), { recursive: true });
169
+ await writeFile(path.join(targetDir, 'dist', 'index.html'), `<!doctype html>
170
+ <html lang="en">
171
+ <head>
172
+ <meta charset="utf-8" />
173
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
174
+ <title>${titleEn}</title>
175
+ <style>
176
+ :root { color-scheme: light dark; --bg: #f4f7fb; --card: #ffffff; --ink: #0f172a; --muted: #475569; --accent: #0f62fe; --accent-ink: #ffffff; }
177
+ :root[data-theme='dark'] { --bg: #0b111b; --card: #111a29; --ink: #f1f5f9; --muted: #94a3b8; --accent: #38bdf8; --accent-ink: #061826; }
178
+ html, body { margin: 0; height: 100dvh; overflow: hidden; touch-action: manipulation; background: var(--bg); color: var(--ink); font-family: system-ui, -apple-system, sans-serif; display: grid; place-items: center; }
179
+ main { text-align: center; padding: 24px; width: min(320px, 90vw); background: var(--card); border-radius: 20px; box-shadow: 0 12px 32px rgba(15, 23, 42, 0.12); display: grid; gap: 12px; }
180
+ h1 { margin: 0; font-size: 1.5rem; }
181
+ p { margin: 0; color: var(--muted); }
182
+ .row { display: flex; gap: 8px; justify-content: center; flex-wrap: wrap; }
183
+ button { padding: 12px 20px; border-radius: 11px; border: 0; background: var(--accent); color: var(--accent-ink); font-size: 15px; font-weight: 700; cursor: pointer; }
184
+ button.ghost { background: transparent; color: var(--muted); border: 1px solid color-mix(in oklab, var(--muted) 30%, transparent); }
185
+ [hidden] { display: none !important; }
186
+ </style>
187
+ </head>
188
+ <body>
189
+ <main>
190
+ <h1 id="title">${titleEn}</h1>
191
+ <p id="score">Score: 0</p>
192
+ <div class="row">
193
+ <button id="start" type="button">Start</button>
194
+ <button id="tap" type="button" hidden>Tap +1</button>
195
+ <button id="pause" type="button" class="ghost" hidden>Pause</button>
196
+ <button id="resume" type="button" hidden>Resume</button>
197
+ <button id="finish" type="button" class="ghost" hidden>Finish</button>
198
+ <button id="share" type="button" class="ghost" hidden>Share</button>
199
+ </div>
200
+ </main>
201
+ <script type="module">
202
+ import { initReplayStageGame } from 'https://replaystage.com/sdk/v1/replaystage.esm.js';
203
+ const titleMap = { en: ${JSON.stringify(titleEn)}, 'zh-Hans': ${JSON.stringify(titleZh)} };
204
+ let score = 0;
205
+ let playing = false;
206
+
207
+ const elTitle = document.getElementById('title');
208
+ const elScore = document.getElementById('score');
209
+ const btnStart = document.getElementById('start');
210
+ const btnTap = document.getElementById('tap');
211
+ const btnPause = document.getElementById('pause');
212
+ const btnResume = document.getElementById('resume');
213
+ const btnFinish = document.getElementById('finish');
214
+ const btnShare = document.getElementById('share');
215
+
216
+ const rs = initReplayStageGame({
217
+ gameVersion: '1.0.0',
218
+ onLocaleChange: render,
219
+ onThemeChange: theme => { document.documentElement.dataset.theme = theme; },
220
+ onPauseChange: render,
221
+ });
222
+ document.documentElement.dataset.theme = rs.theme;
223
+
224
+ function render() {
225
+ const zh = rs.locale === 'zh-Hans';
226
+ elTitle.textContent = zh ? titleMap['zh-Hans'] : titleMap.en;
227
+ elScore.textContent = (zh ? '得分:' : 'Score: ') + score + (rs.paused ? (zh ? '(已暂停)' : ' (Paused)') : '');
228
+ btnStart.textContent = zh ? '开始游戏' : 'Start';
229
+ btnTap.textContent = zh ? '点按 +1' : 'Tap +1';
230
+ btnPause.textContent = zh ? '暂停' : 'Pause';
231
+ btnResume.textContent = zh ? '继续' : 'Resume';
232
+ btnFinish.textContent = zh ? '结算' : 'Finish';
233
+ btnShare.textContent = zh ? '分享挑战' : 'Share';
234
+ btnStart.hidden = playing;
235
+ btnTap.hidden = !playing || rs.paused;
236
+ btnPause.hidden = !playing || rs.paused;
237
+ btnResume.hidden = !playing || !rs.paused;
238
+ btnFinish.hidden = !playing;
239
+ btnShare.hidden = playing || score <= 0;
240
+ }
241
+
242
+ btnStart.addEventListener('click', () => {
243
+ score = 0;
244
+ playing = true;
245
+ rs.gameplayStart();
246
+ render();
247
+ });
248
+ btnTap.addEventListener('click', () => {
249
+ score += 1;
250
+ rs.haptics.tap();
251
+ render();
252
+ });
253
+ btnPause.addEventListener('click', () => { rs.pause(); render(); });
254
+ btnResume.addEventListener('click', () => { rs.resume(); render(); });
255
+ btnFinish.addEventListener('click', () => {
256
+ playing = false;
257
+ rs.gameplayStop();
258
+ rs.reportResult({ score, scoreUnit: 'pts', completed: true });
259
+ render();
260
+ });
261
+ btnShare.addEventListener('click', () => {
262
+ rs.shareChallenge({ title: elTitle.textContent + ' — ' + score, score, scoreUnit: 'pts' });
263
+ });
264
+ render();
265
+ </script>
266
+ </body>
267
+ </html>
268
+ `, 'utf8');
269
+ await writeFile(path.join(targetDir, '.github', 'workflows', 'publish-replaystage.yml'), `name: Publish to ReplayStage
270
+
271
+ on:
272
+ push:
273
+ branches:
274
+ - main
275
+ workflow_dispatch:
276
+
277
+ jobs:
278
+ publish:
279
+ uses: replaystage/platform/.github/workflows/publish-game-reusable.yml@main
280
+ with:
281
+ slug: ${slug}
282
+ manifest_path: replaystage.manifest.json
283
+ dist_dir: dist
284
+ build_command: "true"
285
+ package_manager: npm
286
+ secrets:
287
+ REPLAYSTAGE_PUBLISH_TOKEN: \${{ secrets.REPLAYSTAGE_PUBLISH_TOKEN }}
288
+ `, 'utf8');
289
+ }
290
+ emitSuccess(opts, { slug, targetDir, mode, titleEn, titleZh, genre }, () => [
291
+ `Created Tier 2 starter project "${slug}" at ${targetDir} (${mode})`,
292
+ 'Next steps:',
293
+ ` 1. cd ${targetDir}`,
294
+ ' 2. Build your game and run `npx -y replaystage validate ./dist --json`',
295
+ ' 3. Publish an unlisted preview with `npx -y replaystage publish ./dist --json`',
296
+ ]);
297
+ }
298
+ export async function cmdValidate(args, opts) {
299
+ let rest = args;
300
+ const manifestFlag = extractFlag(rest, ['--manifest', '-m']);
301
+ rest = manifestFlag.rest;
302
+ const versionFlag = extractFlag(rest, ['--version']);
303
+ rest = versionFlag.rest;
304
+ const strictFlag = extractBoolFlag(rest, ['--strict']);
305
+ rest = strictFlag.rest;
306
+ assertNoUnknownFlags(rest);
307
+ const distDir = rest[0] || 'dist';
308
+ const report = await validateProjectBundle({
309
+ cwd: opts.cwd,
310
+ distDir,
311
+ manifestPath: manifestFlag.value,
312
+ versionOverride: versionFlag.value,
313
+ });
314
+ if (strictFlag.present && report.warnings.length > 0) {
315
+ throw new CliError('VALIDATION_WARNINGS', `Strict validation failed with ${report.warnings.length} warning(s). Resolve all warnings or omit --strict.`, {
316
+ details: {
317
+ slug: report.slug,
318
+ version: report.version,
319
+ warnings: report.warnings,
320
+ errors: report.warnings,
321
+ },
322
+ });
323
+ }
324
+ emitSuccess(opts, {
325
+ slug: report.slug,
326
+ version: report.version,
327
+ manifestPath: report.manifestPath,
328
+ distDir: report.distDir,
329
+ entryPath: report.entryPath,
330
+ fileCount: report.fileCount,
331
+ totalBytes: report.totalBytes,
332
+ media: report.media.map(m => ({ slot: m.slot, filename: m.filename, bytes: m.bytes })),
333
+ warnings: report.warnings,
334
+ }, () => {
335
+ const lines = [
336
+ `Valid ReplayStage bundle: ${report.slug} v${report.version}`,
337
+ ` Manifest: ${report.manifestPath}`,
338
+ ` Dist: ${report.distDir} (${report.fileCount} files, ${formatBytes(report.totalBytes)}, entry ${report.entryPath})`,
339
+ ];
340
+ if (report.media.length > 0) {
341
+ lines.push(` Media: ${report.media.map(m => `${m.slot}=${m.filename}`).join(', ')}`);
342
+ }
343
+ for (const w of report.warnings) {
344
+ lines.push(` [WARN] ${w}`);
345
+ }
346
+ return lines;
347
+ });
348
+ }
349
+ export async function cmdPublish(args, opts) {
350
+ let rest = args;
351
+ const manifestFlag = extractFlag(rest, ['--manifest', '-m']);
352
+ rest = manifestFlag.rest;
353
+ const versionFlag = extractFlag(rest, ['--version']);
354
+ rest = versionFlag.rest;
355
+ const visFlag = extractFlag(rest, ['--visibility']);
356
+ rest = visFlag.rest;
357
+ const unlistedFlag = extractBoolFlag(rest, ['--unlisted']);
358
+ rest = unlistedFlag.rest;
359
+ const liveFlag = extractBoolFlag(rest, ['--live']);
360
+ rest = liveFlag.rest;
361
+ const betaFlag = extractBoolFlag(rest, ['--beta']);
362
+ rest = betaFlag.rest;
363
+ const hiddenFlag = extractBoolFlag(rest, ['--hidden']);
364
+ rest = hiddenFlag.rest;
365
+ const skipHealthFlag = extractBoolFlag(rest, ['--skip-health']);
366
+ rest = skipHealthFlag.rest;
367
+ const dryRunFlag = extractBoolFlag(rest, ['--dry-run']);
368
+ rest = dryRunFlag.rest;
369
+ assertNoUnknownFlags(rest);
370
+ const selectedVisFlags = [
371
+ visFlag.value,
372
+ unlistedFlag.present ? 'unlisted' : undefined,
373
+ liveFlag.present ? 'live' : undefined,
374
+ betaFlag.present ? 'beta' : undefined,
375
+ hiddenFlag.present ? 'hidden' : undefined,
376
+ ].filter((v) => Boolean(v));
377
+ if (selectedVisFlags.length > 1) {
378
+ throw new CliError('INVALID_ARGUMENTS', 'Specify at most one visibility flag (--unlisted, --live, --beta, --hidden, or --visibility).');
379
+ }
380
+ const explicitVisibility = selectedVisFlags[0];
381
+ if (explicitVisibility &&
382
+ !VALID_CREATOR_VISIBILITIES.includes(explicitVisibility)) {
383
+ throw new CliError('INVALID_ARGUMENTS', `Invalid visibility "${explicitVisibility}". Allowed: ${VALID_CREATOR_VISIBILITIES.join(', ')}.`);
384
+ }
385
+ const distDir = rest[0] || 'dist';
386
+ // 1. Offline preflight validation (fail fast before touching network!)
387
+ const report = await validateProjectBundle({
388
+ cwd: opts.cwd,
389
+ distDir,
390
+ manifestPath: manifestFlag.value,
391
+ versionOverride: versionFlag.value,
392
+ });
393
+ if (dryRunFlag.present) {
394
+ emitSuccess(opts, {
395
+ dryRun: true,
396
+ slug: report.slug,
397
+ version: report.version,
398
+ visibility: explicitVisibility ?? 'unlisted (new) / preserve (existing)',
399
+ entryPath: report.entryPath,
400
+ bundle: { fileCount: report.fileCount, totalBytes: report.totalBytes },
401
+ media: report.media.map(m => ({ slot: m.slot, filename: m.filename, bytes: m.bytes })),
402
+ warnings: report.warnings,
403
+ }, () => {
404
+ const lines = [
405
+ `[DRY RUN] Would publish ${report.slug} v${report.version}`,
406
+ ` Dist: ${report.distDir} (${report.fileCount} files, ${formatBytes(report.totalBytes)}, entry ${report.entryPath})`,
407
+ ` Media: ${report.media.length > 0 ? report.media.map(m => `${m.slot}=${m.filename}`).join(', ') : '(none discovered)'}`,
408
+ ` Visibility: ${explicitVisibility ?? 'unlisted (new) / preserve (existing)'}`,
409
+ ];
410
+ for (const w of report.warnings) {
411
+ lines.push(` [WARN] ${w}`);
412
+ }
413
+ return lines;
414
+ });
415
+ return;
416
+ }
417
+ const apiBase = await resolveApiBase(opts.apiBase);
418
+ const token = await requireAuthToken({
419
+ flagToken: opts.token,
420
+ allowPublishEnvFallback: true,
421
+ cwd: opts.cwd,
422
+ });
423
+ const slug = report.slug;
424
+ const version = report.version;
425
+ let createdSlot = false;
426
+ // 2. If using an account key (RSKEY_ / RSSESS_), auto-register the game slot when new
427
+ if (token.startsWith('RSKEY_') || token.startsWith('RSSESS_')) {
428
+ const owned = await apiRequestJson({
429
+ apiBase,
430
+ method: 'GET',
431
+ path: '/v1/creator/games',
432
+ token,
433
+ });
434
+ const existsInAccount = (owned.games ?? []).some(g => g.slug === slug);
435
+ if (!existsInAccount) {
436
+ await apiRequestJson({
437
+ apiBase,
438
+ method: 'POST',
439
+ path: '/v1/creator/games',
440
+ token,
441
+ body: {
442
+ slug,
443
+ titleEn: report.manifest.locales.en.title,
444
+ titleZh: report.manifest.locales['zh-Hans'].title,
445
+ genre: report.manifest.genre,
446
+ accentColor: report.manifest.accentColor,
447
+ },
448
+ });
449
+ createdSlot = true;
450
+ }
451
+ }
452
+ // 3. Upload immutable bundle files concurrently
453
+ await runPool(report.files, 8, async (file) => {
454
+ const bytes = await readFile(file.absPath);
455
+ const encodedRel = file.relPath.split('/').map(encodeURIComponent).join('/');
456
+ await apiRequestJson({
457
+ apiBase,
458
+ method: 'PUT',
459
+ path: `/v1/publish/${encodeURIComponent(slug)}/files/${encodeURIComponent(version)}/${encodedRel}`,
460
+ token,
461
+ rawBody: bytes,
462
+ contentType: file.contentType,
463
+ });
464
+ });
465
+ // 4. Upload discovered local artwork (<= 2 MB each)
466
+ const mediaUploaded = [];
467
+ for (const media of report.media) {
468
+ const bytes = await readFile(media.absPath);
469
+ await apiRequestJson({
470
+ apiBase,
471
+ method: 'PUT',
472
+ path: `/v1/publish/${encodeURIComponent(slug)}/media/${encodeURIComponent(media.filename)}`,
473
+ token,
474
+ rawBody: bytes,
475
+ contentType: media.contentType,
476
+ });
477
+ mediaUploaded.push(`/media/${slug}/${media.filename}`);
478
+ }
479
+ // 5. Finalize atomic pointer release
480
+ const releaseRes = await apiRequestJson({
481
+ apiBase,
482
+ method: 'POST',
483
+ path: `/v1/publish/${encodeURIComponent(slug)}/release`,
484
+ token,
485
+ body: {
486
+ version,
487
+ manifest: report.manifest,
488
+ fileCount: report.fileCount,
489
+ totalBytes: report.totalBytes,
490
+ ...(explicitVisibility ? { visibility: explicitVisibility } : {}),
491
+ },
492
+ });
493
+ // 6. Verify live edge health unless skipped
494
+ let health = null;
495
+ if (!skipHealthFlag.present && releaseRes.origin) {
496
+ const controller = new AbortController();
497
+ const timer = setTimeout(() => controller.abort(), 10_000);
498
+ try {
499
+ const probe = await fetch(`${releaseRes.origin}/_rs/health`, { signal: controller.signal });
500
+ health = { ok: probe.ok, status: probe.status };
501
+ }
502
+ catch {
503
+ health = { ok: false, status: 0 };
504
+ }
505
+ finally {
506
+ clearTimeout(timer);
507
+ }
508
+ }
509
+ const playUrl = releaseRes.playUrl || `${DEFAULT_PORTAL_ORIGIN}/play/${slug}`;
510
+ const studioUrl = `${DEFAULT_STUDIO_ORIGIN}/games/${slug}`;
511
+ const emulatorUrl = `${DEFAULT_STUDIO_ORIGIN}/emulator?game=${encodeURIComponent(slug)}`;
512
+ emitSuccess(opts, {
513
+ slug,
514
+ version,
515
+ releaseId: releaseRes.releaseId,
516
+ visibility: releaseRes.visibility,
517
+ createdSlot,
518
+ playUrl,
519
+ origin: releaseRes.origin,
520
+ studioUrl,
521
+ emulatorUrl,
522
+ bundle: releaseRes.bundle ?? { fileCount: report.fileCount, totalBytes: report.totalBytes },
523
+ mediaUploaded,
524
+ health,
525
+ warnings: report.warnings,
526
+ }, () => {
527
+ const lines = [
528
+ `Published ${slug} v${version} (${releaseRes.visibility})`,
529
+ ` Play URL: ${playUrl}`,
530
+ ` Game Origin: ${releaseRes.origin}`,
531
+ ` Emulator: ${emulatorUrl}`,
532
+ ` Bundle: ${report.fileCount} files (${formatBytes(report.totalBytes)})`,
533
+ ` Media: ${mediaUploaded.length > 0 ? mediaUploaded.join(', ') : '(none uploaded)'}`,
534
+ ];
535
+ if (releaseRes.visibility === 'unlisted') {
536
+ lines.push(` Preview: Unlisted (noindex, direct-link playable). Promote when ready with: replaystage visibility ${slug} live`);
537
+ }
538
+ for (const w of report.warnings) {
539
+ lines.push(` [WARN] ${w}`);
540
+ }
541
+ return lines;
542
+ });
543
+ }
544
+ export async function cmdUpdate(args, opts) {
545
+ let rest = args;
546
+ const manifestFlag = extractFlag(rest, ['--manifest', '-m']);
547
+ rest = manifestFlag.rest;
548
+ const visFlag = extractFlag(rest, ['--visibility']);
549
+ rest = visFlag.rest;
550
+ assertNoUnknownFlags(rest);
551
+ const manifestPath = manifestFlag.value
552
+ ? path.resolve(opts.cwd, manifestFlag.value)
553
+ : path.resolve(opts.cwd, 'replaystage.manifest.json');
554
+ const { manifest, manifestPath: resolvedManifestPath } = await loadAndValidateManifest(manifestPath);
555
+ const slug = rest[0]?.trim().toLowerCase() || manifest.slug;
556
+ if (!SLUG_RE.test(slug)) {
557
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage update [slug] [--manifest <path>] [--visibility live|beta|unlisted|hidden] [--json]');
558
+ }
559
+ if (manifest.slug !== slug) {
560
+ throw new CliError('SLUG_MISMATCH', `Manifest slug "${manifest.slug}" does not match target slug "${slug}".`);
561
+ }
562
+ if (visFlag.value && !VALID_CREATOR_VISIBILITIES.includes(visFlag.value)) {
563
+ throw new CliError('INVALID_ARGUMENTS', `Invalid visibility "${visFlag.value}". Allowed: ${VALID_CREATOR_VISIBILITIES.join(', ')}.`);
564
+ }
565
+ const apiBase = await resolveApiBase(opts.apiBase);
566
+ const token = await requireAuthToken({ flagToken: opts.token, cwd: opts.cwd });
567
+ const repoDir = path.dirname(resolvedManifestPath);
568
+ const mediaUploaded = [];
569
+ for (const slot of ['icon', 'cover']) {
570
+ const discovered = await discoverMediaFile(slot, manifest.artwork[slot], slug, repoDir);
571
+ if (discovered) {
572
+ const bytes = await readFile(discovered.absPath);
573
+ await apiRequestJson({
574
+ apiBase,
575
+ method: 'PUT',
576
+ path: `/v1/publish/${encodeURIComponent(slug)}/media/${encodeURIComponent(discovered.filename)}`,
577
+ token,
578
+ rawBody: bytes,
579
+ contentType: discovered.contentType,
580
+ });
581
+ mediaUploaded.push(`/media/${slug}/${discovered.filename}`);
582
+ }
583
+ }
584
+ const res = await apiRequestJson({
585
+ apiBase,
586
+ method: 'PUT',
587
+ path: `/v1/creator/games/${encodeURIComponent(slug)}`,
588
+ token,
589
+ body: {
590
+ manifest,
591
+ ...(visFlag.value ? { visibility: visFlag.value } : {}),
592
+ },
593
+ });
594
+ emitSuccess(opts, {
595
+ slug,
596
+ manifestPath: resolvedManifestPath,
597
+ mediaUploaded,
598
+ game: res.game,
599
+ }, () => [
600
+ `Updated metadata for "${slug}" from ${resolvedManifestPath}`,
601
+ ...(mediaUploaded.length > 0 ? [` Media synced: ${mediaUploaded.join(', ')}`] : []),
602
+ ]);
603
+ }
604
+ export async function cmdDelete(args, opts) {
605
+ const yesFlag = extractBoolFlag(args, ['--yes', '-y']);
606
+ assertNoUnknownFlags(yesFlag.rest);
607
+ const slug = yesFlag.rest[0]?.trim().toLowerCase();
608
+ if (!slug || !SLUG_RE.test(slug)) {
609
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage delete <slug> --yes [--json]');
610
+ }
611
+ if (!yesFlag.present) {
612
+ throw new CliError('CONFIRMATION_REQUIRED', `Deleting "${slug}" removes its catalog entry and revokes its CI tokens. Re-run with --yes to confirm.`);
613
+ }
614
+ const apiBase = await resolveApiBase(opts.apiBase);
615
+ const token = await requireAuthToken({ flagToken: opts.token, cwd: opts.cwd });
616
+ const res = await apiRequestJson({
617
+ apiBase,
618
+ method: 'DELETE',
619
+ path: `/v1/creator/games/${encodeURIComponent(slug)}`,
620
+ token,
621
+ });
622
+ emitSuccess(opts, { slug, deleted: res.deleted ?? true }, () => [
623
+ `Deleted "${slug}" and revoked its scoped CI tokens.`,
624
+ ]);
625
+ }
626
+ export async function cmdSdk(args, opts) {
627
+ const [sub, ...restArgs] = args;
628
+ if (sub !== 'sync') {
629
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage sdk sync [targetDir] [--url <sdkBaseUrl>] [--json]');
630
+ }
631
+ const urlFlag = extractFlag(restArgs, ['--url']);
632
+ assertNoUnknownFlags(urlFlag.rest);
633
+ const targetDir = path.resolve(opts.cwd, urlFlag.rest[0] || 'src/sdk');
634
+ await mkdir(targetDir, { recursive: true });
635
+ const workspaceRoot = await findPlatformWorkspaceRoot(opts.cwd);
636
+ let version = 'unknown';
637
+ let source = '';
638
+ let esmContent;
639
+ let dtsContent;
640
+ if (!urlFlag.value && workspaceRoot && (await exists(path.join(workspaceRoot, 'apps', 'portal', 'public', 'sdk', 'v1', 'replaystage.esm.js')))) {
641
+ const localSdkDir = path.join(workspaceRoot, 'apps', 'portal', 'public', 'sdk', 'v1');
642
+ source = localSdkDir;
643
+ const manifestJson = JSON.parse(await readFile(path.join(localSdkDir, 'manifest.json'), 'utf8'));
644
+ version = manifestJson.version ?? 'unknown';
645
+ esmContent = await readFile(path.join(localSdkDir, 'replaystage.esm.js'), 'utf8');
646
+ dtsContent = await readFile(path.join(localSdkDir, 'replaystage.d.ts'), 'utf8');
647
+ }
648
+ else {
649
+ const base = (urlFlag.value || `${DEFAULT_PORTAL_ORIGIN}/sdk/v1`).replace(/\/+$/, '');
650
+ source = base;
651
+ const fetchText = async (url) => {
652
+ const controller = new AbortController();
653
+ const timer = setTimeout(() => controller.abort(), 20_000);
654
+ try {
655
+ const res = await fetch(url, { signal: controller.signal });
656
+ if (!res.ok) {
657
+ throw new CliError('SDK_FETCH_FAILED', `Failed to fetch ${url}: HTTP ${res.status}`, {
658
+ status: res.status,
659
+ });
660
+ }
661
+ return await res.text();
662
+ }
663
+ catch (err) {
664
+ if (err instanceof CliError)
665
+ throw err;
666
+ throw new CliError('NETWORK_ERROR', `Failed to fetch ${url}: ${err instanceof Error ? err.message : String(err)}`);
667
+ }
668
+ finally {
669
+ clearTimeout(timer);
670
+ }
671
+ };
672
+ const [manifestRaw, esmRaw, dtsRaw] = await Promise.all([
673
+ fetchText(`${base}/manifest.json`),
674
+ fetchText(`${base}/replaystage.esm.js`),
675
+ fetchText(`${base}/replaystage.d.ts`),
676
+ ]);
677
+ const manifestJson = JSON.parse(manifestRaw);
678
+ version = manifestJson.version ?? 'unknown';
679
+ if (manifestJson.sizes?.esmBytes !== undefined &&
680
+ Buffer.byteLength(esmRaw, 'utf8') !== manifestJson.sizes.esmBytes) {
681
+ throw new CliError('SDK_INTEGRITY_MISMATCH', `Downloaded replaystage.esm.js size (${Buffer.byteLength(esmRaw, 'utf8')} B) does not match manifest (${manifestJson.sizes.esmBytes} B).`);
682
+ }
683
+ esmContent = esmRaw;
684
+ dtsContent = dtsRaw;
685
+ }
686
+ const esmPath = path.join(targetDir, 'replaystage.esm.js');
687
+ const dtsPath = path.join(targetDir, 'replaystage.esm.d.ts');
688
+ await Promise.all([
689
+ writeFile(esmPath, esmContent, 'utf8'),
690
+ writeFile(dtsPath, dtsContent, 'utf8'),
691
+ ]);
692
+ const esmBytes = Buffer.byteLength(esmContent, 'utf8');
693
+ emitSuccess(opts, {
694
+ version,
695
+ source,
696
+ targetDir,
697
+ files: [esmPath, dtsPath],
698
+ esmBytes,
699
+ }, () => [
700
+ `Synced @replaystage/sdk v${version} (${formatBytes(esmBytes)}) -> ${targetDir}`,
701
+ ` ${esmPath}`,
702
+ ` ${dtsPath}`,
703
+ ]);
704
+ }
705
+ export async function cmdGames(args, opts) {
706
+ assertNoUnknownFlags(args);
707
+ const apiBase = await resolveApiBase(opts.apiBase);
708
+ const token = await requireAuthToken({ flagToken: opts.token, cwd: opts.cwd });
709
+ const data = await apiRequestJson({
710
+ apiBase,
711
+ method: 'GET',
712
+ path: '/v1/creator/games',
713
+ token,
714
+ });
715
+ emitSuccess(opts, { games: data.games }, () => {
716
+ if (data.games.length === 0) {
717
+ return ['No games registered under your account yet. Run `replaystage init <slug>` to get started.'];
718
+ }
719
+ return [
720
+ 'Your ReplayStage Games:',
721
+ ...data.games.map(g => ` ${g.slug.padEnd(20)} ${g.status.padEnd(11)} v${String(g.version).padEnd(12)} T${g.tier} ${g.locales?.en?.title ?? ''}`),
722
+ ];
723
+ });
724
+ }
725
+ export async function cmdReleases(args, opts) {
726
+ assertNoUnknownFlags(args);
727
+ const slug = args[0]?.trim().toLowerCase();
728
+ if (!slug || !SLUG_RE.test(slug)) {
729
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage releases <slug> [--json]');
730
+ }
731
+ const apiBase = await resolveApiBase(opts.apiBase);
732
+ const token = await requireAuthToken({ flagToken: opts.token, cwd: opts.cwd });
733
+ const data = await apiRequestJson({
734
+ apiBase,
735
+ method: 'GET',
736
+ path: `/v1/creator/games/${encodeURIComponent(slug)}/releases`,
737
+ token,
738
+ });
739
+ emitSuccess(opts, { slug, releases: data.releases }, () => [
740
+ `Releases for ${slug}:`,
741
+ ...(data.releases.length === 0
742
+ ? [' (no releases published yet)']
743
+ : data.releases.map(r => ` v${r.version.padEnd(14)} ${r.status.padEnd(10)} ${String(r.fileCount).padStart(4)} files ${formatBytes(r.totalBytes).padEnd(10)} ${r.createdAt}`)),
744
+ ]);
745
+ }
746
+ export async function cmdRollback(args, opts) {
747
+ assertNoUnknownFlags(args);
748
+ const [slugRaw, versionRaw] = args;
749
+ const slug = slugRaw?.trim().toLowerCase();
750
+ const version = versionRaw?.trim();
751
+ if (!slug || !SLUG_RE.test(slug) || !version) {
752
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage rollback <slug> <version> [--json]');
753
+ }
754
+ const apiBase = await resolveApiBase(opts.apiBase);
755
+ const token = await requireAuthToken({ flagToken: opts.token, cwd: opts.cwd });
756
+ const res = await apiRequestJson({
757
+ apiBase,
758
+ method: 'POST',
759
+ path: `/v1/creator/games/${encodeURIComponent(slug)}/rollback`,
760
+ token,
761
+ body: { version },
762
+ });
763
+ emitSuccess(opts, { slug, version, ...res }, () => [
764
+ `Rolled back ${slug} to v${version}.`,
765
+ ]);
766
+ }
767
+ export async function cmdVisibility(args, opts) {
768
+ assertNoUnknownFlags(args);
769
+ const [slugRaw, visibilityRaw] = args;
770
+ const slug = slugRaw?.trim().toLowerCase();
771
+ const visibility = visibilityRaw?.trim().toLowerCase();
772
+ if (!slug ||
773
+ !SLUG_RE.test(slug) ||
774
+ !visibility ||
775
+ !VALID_CREATOR_VISIBILITIES.includes(visibility)) {
776
+ throw new CliError('INVALID_ARGUMENTS', `Usage: replaystage visibility <slug> <${VALID_CREATOR_VISIBILITIES.join('|')}> [--json]`);
777
+ }
778
+ const apiBase = await resolveApiBase(opts.apiBase);
779
+ const token = await requireAuthToken({ flagToken: opts.token, cwd: opts.cwd });
780
+ const res = await apiRequestJson({
781
+ apiBase,
782
+ method: 'PUT',
783
+ path: `/v1/creator/games/${encodeURIComponent(slug)}`,
784
+ token,
785
+ body: { visibility },
786
+ });
787
+ emitSuccess(opts, {
788
+ slug,
789
+ visibility,
790
+ playUrl: `${DEFAULT_PORTAL_ORIGIN}/play/${slug}`,
791
+ game: res.game,
792
+ }, () => [
793
+ `Updated "${slug}" visibility -> ${visibility}`,
794
+ `Play URL: ${DEFAULT_PORTAL_ORIGIN}/play/${slug}`,
795
+ ]);
796
+ }
797
+ export async function cmdTokens(args, opts) {
798
+ const [action, ...restArgs] = args;
799
+ const apiBase = await resolveApiBase(opts.apiBase);
800
+ const token = await requireAuthToken({ flagToken: opts.token, cwd: opts.cwd });
801
+ if (action === 'list') {
802
+ assertNoUnknownFlags(restArgs);
803
+ const slug = restArgs[0]?.trim().toLowerCase();
804
+ if (!slug || !SLUG_RE.test(slug)) {
805
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage tokens list <slug> [--json]');
806
+ }
807
+ const res = await apiRequestJson({
808
+ apiBase,
809
+ method: 'GET',
810
+ path: `/v1/creator/games/${encodeURIComponent(slug)}/tokens`,
811
+ token,
812
+ });
813
+ emitSuccess(opts, { slug, tokens: res.tokens }, () => [
814
+ `CI publish tokens for ${slug}:`,
815
+ ...(res.tokens.length === 0
816
+ ? [' (none)']
817
+ : res.tokens.map(t => ` ${t.id.padEnd(22)} ${(t.tokenPrefix + '…').padEnd(16)} ${(t.revokedAt ? 'REVOKED' : 'ACTIVE').padEnd(9)} ${t.label}`)),
818
+ ]);
819
+ return;
820
+ }
821
+ if (action === 'create') {
822
+ const labelFlag = extractFlag(restArgs, ['--label']);
823
+ assertNoUnknownFlags(labelFlag.rest);
824
+ const slug = labelFlag.rest[0]?.trim().toLowerCase();
825
+ if (!slug || !SLUG_RE.test(slug)) {
826
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage tokens create <slug> [--label "..."] [--json]');
827
+ }
828
+ const res = await apiRequestJson({
829
+ apiBase,
830
+ method: 'POST',
831
+ path: `/v1/creator/games/${encodeURIComponent(slug)}/tokens`,
832
+ token,
833
+ body: { label: labelFlag.value || 'GitHub Actions CI' },
834
+ });
835
+ emitSuccess(opts, { slug, ...res }, () => [
836
+ `Minted CI publish token for ${slug} (shown once):`,
837
+ ` ${res.publishToken}`,
838
+ ` Token ID: ${res.token.id}`,
839
+ ]);
840
+ return;
841
+ }
842
+ if (action === 'revoke') {
843
+ assertNoUnknownFlags(restArgs);
844
+ const [slugRaw, tokenId] = restArgs;
845
+ const slug = slugRaw?.trim().toLowerCase();
846
+ if (!slug || !SLUG_RE.test(slug) || !tokenId) {
847
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage tokens revoke <slug> <tokenId> [--json]');
848
+ }
849
+ const res = await apiRequestJson({
850
+ apiBase,
851
+ method: 'DELETE',
852
+ path: `/v1/creator/games/${encodeURIComponent(slug)}/tokens/${encodeURIComponent(tokenId)}`,
853
+ token,
854
+ });
855
+ emitSuccess(opts, { slug, tokenId, ...res }, () => [
856
+ `Revoked CI publish token ${tokenId} on ${slug}.`,
857
+ ]);
858
+ return;
859
+ }
860
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage tokens <list|create|revoke> <slug> [args] [--json]');
861
+ }
862
+ export async function cmdStats(args, opts) {
863
+ const daysFlag = extractFlag(args, ['--days']);
864
+ assertNoUnknownFlags(daysFlag.rest);
865
+ const slug = daysFlag.rest[0]?.trim().toLowerCase();
866
+ if (!slug || !SLUG_RE.test(slug)) {
867
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage stats <slug> [--days 7] [--json]');
868
+ }
869
+ const days = Math.min(90, Math.max(1, Number(daysFlag.value || '7') || 7));
870
+ const apiBase = await resolveApiBase(opts.apiBase);
871
+ const token = await requireAuthToken({ flagToken: opts.token, cwd: opts.cwd });
872
+ const data = await apiRequestJson({
873
+ apiBase,
874
+ method: 'GET',
875
+ path: `/v1/creator/games/${encodeURIComponent(slug)}/stats?days=${days}`,
876
+ token,
877
+ });
878
+ emitSuccess(opts, data, () => [
879
+ `Stats for ${data.gameSlug} (${data.sinceDate} .. ${data.untilDate}, ${data.windowDays}d):`,
880
+ ` stage_launch: ${data.totals.stage_launch ?? 0}`,
881
+ ` daily_launch: ${data.totals.daily_launch ?? 0}`,
882
+ ` result_reported: ${data.totals.result_reported ?? 0}`,
883
+ ` save_synced: ${data.totals.save_synced ?? 0}`,
884
+ ` challenge_shared:${data.totals.challenge_shared ?? 0}`,
885
+ ]);
886
+ }