@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.
package/README.md CHANGED
@@ -1,59 +1,27 @@
1
- # @replaystage/cli (`replaystage`)
1
+ # @replaystage/cli
2
2
 
3
- Deploy, validate, and iterate playable web games on **ReplayStage** (`replaystage.com` & `replay.st`) directly from your terminal or autonomous AI coding agents (Antigravity, Claude Code, Cursor, Codex, Windsurf, Gemini CLI).
3
+ Unified, zero-dependency agent-native CLI for **ReplayStage** ([replaystage.com](https://replaystage.com)).
4
4
 
5
5
  ## Quick Start
6
6
 
7
7
  ```bash
8
- # Zero-config public launch (auto-detects title & defaults --category to arcade)
9
- npx -y replaystage publish . --public
10
-
11
- # 1. Pre-flight offline validation (checks index.html, bundle size <= 25MB, and prohibited files)
12
- npx -y replaystage validate ./dist --json
13
-
14
- # 2. Publish with full AI model & genre attribution (zero login required)
15
- npx -y replaystage publish ./dist \
16
- --title "Neon Drift '86" \
17
- --tagline "Synthwave endless drift arcade" \
18
- --model "Claude Fable 5.2" \
19
- --tool codex \
20
- --category arcade \
21
- --tags "retro,synth-audio" \
22
- --aspect-ratio 16:9 \
23
- --draft \
24
- --json
25
-
26
- # 3. Push an incremental update to the same 8-char stage ID (.replaystage.json)
27
- npx -y replaystage publish ./dist --changelog "Tuned drift physics" --json
28
-
29
- # 4. Promote draft to the public arcade leaderboard
30
- npx -y replaystage publish ./dist --public --changelog "v1.0 Launch" --json
31
- ```
32
-
33
- ### Primary Categories (`--category`)
34
-
35
- ReplayStage supports 8 pure gameplay genres (defaults to `arcade` when omitted):
36
- `arcade`, `action`, `puzzle`, `strategy`, `simulation`, `racing` (Racing & Sports), `rpg`, `casual`.
8
+ # 1. Mint a personal API Key (RSKEY_...) at https://studio.replaystage.com/account
9
+ echo "RSKEY_..." | npx -y replaystage login --token-stdin --json
37
10
 
38
- ## Responsive Aspect Ratio & Screen Formats
11
+ # 2. Initialize manifest or sync latest @replaystage/sdk into your portrait game repo
12
+ npx -y replaystage init my-game --title "My Game" --zh "我的游戏" --genre arcade --json
13
+ npx -y replaystage sdk sync
39
14
 
40
- ReplayStage automatically conforms game stages to specified aspect ratios:
15
+ # 3. Validate your build output offline (--strict fails on warnings)
16
+ npx -y replaystage validate ./dist --strict --json
41
17
 
42
- - **Presets**: `auto` (fluid responsive), `16:9`, `9:16` (vertical/mobile), `4:3`, `3:4`, `1:1`.
43
- - **Custom Ratio**: `W:H` or `W/H` (e.g. `21:9`, `5:3`, `800:600`), bounded between `1:4` (0.25) and `4:1` (4.0).
44
- - **HTML Meta Tag**: Declare in your entry `index.html` `<head>` for automatic detection:
45
- ```html
46
- <meta name="replaystage:aspect-ratio" content="9:16">
47
- ```
48
- - **CLI Flag Priority**: Explicit `--aspect-ratio <ratio>` overrides the HTML `<meta>` tag, which overrides the default `auto`. Persisted in `.replaystage.json`.
18
+ # 4. Dry-run or publish (new games default to unlisted preview; pass --live to publish publicly)
19
+ npx -y replaystage publish ./dist --dry-run --json
20
+ npx -y replaystage publish ./dist --json
49
21
 
50
- ## Creator Authentication (`rps_...` API Tokens)
51
-
52
- Generate a Personal API Token in `https://replaystage.com/settings#tokens` to bind all CLI & AI agent deployments directly to your `@handle`:
53
-
54
- ```bash
55
- npx -y replaystage login --token rps_<your_token>
56
- npx -y replaystage whoami
22
+ # 5. Update metadata/artwork without re-uploading the bundle, or promote to public Lobby
23
+ npx -y replaystage update my-game --json
24
+ npx -y replaystage visibility my-game live --json
57
25
  ```
58
26
 
59
- Or pass `REPLAYSTAGE_TOKEN=rps_<your_token>` in CI / agent environments.
27
+ Full machine-readable agent protocol: **https://replaystage.com/skill.md**
@@ -1,23 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { execFileSync } from "node:child_process";
3
- import fs from "node:fs";
4
- import path from "node:path";
5
- import { fileURLToPath, pathToFileURL } from "node:url";
2
+ import { runCli } from '../dist/index.js';
6
3
 
7
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
8
- const distPath = path.resolve(__dirname, "../dist/index.js");
9
-
10
- // If dist artifact does not exist (e.g. dev testing before pnpm build), auto-build on-the-fly
11
- if (!fs.existsSync(distPath)) {
12
- const cliRoot = path.resolve(__dirname, "..");
13
- try {
14
- execFileSync("npx", ["tsup"], { cwd: cliRoot, stdio: "ignore" });
15
- } catch {
16
- // If auto-build fails, continue to let import report error
17
- }
18
- }
19
-
20
- const cliModule = await import(pathToFileURL(distPath).href);
21
- if (typeof cliModule.runCli === "function") {
22
- await cliModule.runCli(process.argv);
23
- }
4
+ const exitCode = await runCli(process.argv.slice(2));
5
+ process.exitCode = exitCode;
@@ -0,0 +1,5 @@
1
+ import { type GlobalOptions } from '../output.js';
2
+ export declare function cmdCatalog(args: string[], opts: GlobalOptions): Promise<void>;
3
+ export declare function cmdDaily(args: string[], opts: GlobalOptions): Promise<void>;
4
+ export declare function cmdAdmin(args: string[], opts: GlobalOptions): Promise<void>;
5
+ export declare function cmdAudit(args: string[], opts: GlobalOptions): Promise<void>;
@@ -0,0 +1,448 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { DEFAULT_PORTAL_ORIGIN, findPlatformWorkspaceRoot, requireAuthToken, resolveApiBase, } from '../config.js';
4
+ import { apiRequestJson } from '../http.js';
5
+ import { SLUG_RE, VALID_ADMIN_VISIBILITIES } from '../manifest.js';
6
+ import { CliError, assertNoUnknownFlags, emitSuccess, extractBoolFlag, extractFlag, } from '../output.js';
7
+ const DATE_KEY_RE = /^\d{4}-\d{2}-\d{2}$/;
8
+ async function exists(targetPath) {
9
+ try {
10
+ await stat(targetPath);
11
+ return true;
12
+ }
13
+ catch {
14
+ return false;
15
+ }
16
+ }
17
+ async function adminApi(opts, method, apiPath, body) {
18
+ const apiBase = await resolveApiBase(opts.apiBase);
19
+ const token = await requireAuthToken({
20
+ flagToken: opts.token,
21
+ allowAdminEnvFallback: true,
22
+ cwd: opts.cwd,
23
+ });
24
+ return apiRequestJson({ apiBase, method, path: apiPath, token, body });
25
+ }
26
+ export async function cmdCatalog(args, opts) {
27
+ const [sub, ...rest] = args;
28
+ if (sub === 'list' || !sub) {
29
+ assertNoUnknownFlags(rest);
30
+ const data = await adminApi(opts, 'GET', '/v1/admin/games');
31
+ emitSuccess(opts, { games: data.games }, () => [
32
+ 'ReplayStage Live D1 Catalog',
33
+ 'SLUG VISIBILITY ORDER DAILY TIER VERSION TITLE',
34
+ '-'.repeat(92),
35
+ ...data.games.map(g => String(g.slug).padEnd(18) +
36
+ String(g.status).padEnd(12) +
37
+ String(g.featuredOrder ?? 100).padEnd(7) +
38
+ (g.dailyEligible ? 'yes' : 'no').padEnd(7) +
39
+ `T${g.tier}`.padEnd(6) +
40
+ String(g.version).slice(0, 14).padEnd(16) +
41
+ (g.locales?.en?.title ?? '')),
42
+ ]);
43
+ return;
44
+ }
45
+ if (sub === 'register' || sub === 'set') {
46
+ let rem = rest;
47
+ const visFlag = extractFlag(rem, ['--visibility']);
48
+ rem = visFlag.rest;
49
+ const orderFlag = extractFlag(rem, ['--order']);
50
+ rem = orderFlag.rest;
51
+ const dailyFlag = extractFlag(rem, ['--daily']);
52
+ rem = dailyFlag.rest;
53
+ const noteFlag = extractFlag(rem, ['--note']);
54
+ rem = noteFlag.rest;
55
+ const manifestFlag = extractFlag(rem, ['--manifest']);
56
+ rem = manifestFlag.rest;
57
+ assertNoUnknownFlags(rem);
58
+ const slug = rem[0]?.trim().toLowerCase();
59
+ if (!slug || !SLUG_RE.test(slug)) {
60
+ throw new CliError('INVALID_ARGUMENTS', `Usage: replaystage admin catalog ${sub} <slug> [--visibility featured|live|beta|unlisted|hidden|suspended] [--order N] [--daily true|false] [--note "..."] [--manifest <file.json>]`);
61
+ }
62
+ const body = {};
63
+ if (visFlag.value) {
64
+ if (!VALID_ADMIN_VISIBILITIES.includes(visFlag.value)) {
65
+ throw new CliError('INVALID_ARGUMENTS', `Invalid visibility "${visFlag.value}". Allowed: ${VALID_ADMIN_VISIBILITIES.join(', ')}.`);
66
+ }
67
+ body.visibility = visFlag.value;
68
+ }
69
+ if (orderFlag.value !== undefined)
70
+ body.featuredOrder = Number(orderFlag.value);
71
+ if (dailyFlag.value !== undefined)
72
+ body.dailyEligible = dailyFlag.value === 'true' || dailyFlag.value === '1';
73
+ if (noteFlag.value !== undefined)
74
+ body.moderationNote = noteFlag.value;
75
+ if (manifestFlag.value) {
76
+ body.manifest = JSON.parse(await readFile(path.resolve(opts.cwd, manifestFlag.value), 'utf8'));
77
+ }
78
+ const res = await adminApi(opts, 'PUT', `/v1/admin/games/${encodeURIComponent(slug)}`, body);
79
+ emitSuccess(opts, { slug, ...res }, () => {
80
+ const lines = [
81
+ `Saved "${slug}" (visibility=${String(res.game?.status)}, order=${String(res.game?.featuredOrder)}, daily=${String(res.game?.dailyEligible)})`,
82
+ ];
83
+ if (res.publishToken) {
84
+ lines.push('One-time REPLAYSTAGE_PUBLISH_TOKEN:', ` ${res.publishToken}`);
85
+ }
86
+ return lines;
87
+ });
88
+ return;
89
+ }
90
+ if (sub === 'rotate-token') {
91
+ assertNoUnknownFlags(rest);
92
+ const slug = rest[0]?.trim().toLowerCase();
93
+ if (!slug || !SLUG_RE.test(slug)) {
94
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage admin catalog rotate-token <slug> [--json]');
95
+ }
96
+ const res = await adminApi(opts, 'POST', `/v1/admin/games/${encodeURIComponent(slug)}/rotate-token`);
97
+ emitSuccess(opts, { slug, ...res }, () => [
98
+ `Rotated publish token for "${slug}":`,
99
+ ` ${res.publishToken}`,
100
+ ]);
101
+ return;
102
+ }
103
+ if (sub === 'delete') {
104
+ assertNoUnknownFlags(rest);
105
+ const slug = rest[0]?.trim().toLowerCase();
106
+ if (!slug || !SLUG_RE.test(slug)) {
107
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage admin catalog delete <slug> [--json]');
108
+ }
109
+ const res = await adminApi(opts, 'DELETE', `/v1/admin/games/${encodeURIComponent(slug)}`);
110
+ emitSuccess(opts, { slug, ...res }, () => [`Deleted "${slug}" from D1 catalog.`]);
111
+ return;
112
+ }
113
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage admin catalog <list|register|set|rotate-token|delete> ...');
114
+ }
115
+ export async function cmdDaily(args, opts) {
116
+ const [sub, ...rest] = args;
117
+ if (sub === 'show' || !sub) {
118
+ assertNoUnknownFlags(rest);
119
+ const apiBase = await resolveApiBase(opts.apiBase);
120
+ const data = await apiRequestJson({ apiBase, method: 'GET', path: '/v1/catalog' });
121
+ emitSuccess(opts, data, () => [
122
+ `ReplayStage Daily Stage Schedule (UTC today: ${data.utcDate})`,
123
+ ...(data.upcoming ?? []).map(entry => {
124
+ const marker = entry.dateKey === data.utcDate ? 'TODAY' : ' ';
125
+ const src = entry.source === 'manual' ? '[PIN]' : '[AUTO]';
126
+ return ` ${marker} ${entry.dateKey} ${src.padEnd(6)} ${entry.game.slug.padEnd(18)} ${entry.game.locales?.en?.title ?? ''}`;
127
+ }),
128
+ ]);
129
+ return;
130
+ }
131
+ if (sub === 'pin') {
132
+ assertNoUnknownFlags(rest);
133
+ const [dateKey, gameSlug] = rest;
134
+ if (!dateKey || !DATE_KEY_RE.test(dateKey) || !gameSlug || !SLUG_RE.test(gameSlug)) {
135
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage admin daily pin <YYYY-MM-DD> <slug> [--json]');
136
+ }
137
+ const res = await adminApi(opts, 'PUT', `/v1/admin/daily/${encodeURIComponent(dateKey)}`, { gameSlug });
138
+ emitSuccess(opts, { dateKey, gameSlug, ...res }, () => [`Pinned ${dateKey} -> ${gameSlug}`]);
139
+ return;
140
+ }
141
+ if (sub === 'unpin') {
142
+ assertNoUnknownFlags(rest);
143
+ const [dateKey] = rest;
144
+ if (!dateKey || !DATE_KEY_RE.test(dateKey)) {
145
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage admin daily unpin <YYYY-MM-DD> [--json]');
146
+ }
147
+ const res = await adminApi(opts, 'DELETE', `/v1/admin/daily/${encodeURIComponent(dateKey)}`);
148
+ emitSuccess(opts, { dateKey, ...res }, () => [`Unpinned ${dateKey}`]);
149
+ return;
150
+ }
151
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage admin daily <show|pin|unpin> ...');
152
+ }
153
+ export async function cmdAdmin(args, opts) {
154
+ const [sub, ...rest] = args;
155
+ if (sub === 'catalog') {
156
+ return cmdCatalog(rest, opts);
157
+ }
158
+ if (sub === 'daily') {
159
+ return cmdDaily(rest, opts);
160
+ }
161
+ if (sub === 'reg-mode') {
162
+ assertNoUnknownFlags(rest);
163
+ const mode = rest[0];
164
+ if (!mode) {
165
+ const data = await adminApi(opts, 'GET', '/v1/admin/settings');
166
+ emitSuccess(opts, data, () => [
167
+ `Registration mode: ${data.registrationMode}`,
168
+ `Email delivery configured: ${data.emailDeliveryConfigured ? 'yes' : 'no'}`,
169
+ ]);
170
+ return;
171
+ }
172
+ if (!['closed', 'invite_code', 'open'].includes(mode)) {
173
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage admin reg-mode [closed|invite_code|open]');
174
+ }
175
+ const res = await adminApi(opts, 'PUT', '/v1/admin/settings', { registrationMode: mode });
176
+ emitSuccess(opts, res, () => [`Registration mode set to "${res.registrationMode}"`]);
177
+ return;
178
+ }
179
+ if (sub === 'invite') {
180
+ const [action, ...invRest] = rest;
181
+ if (action === 'list' || !action) {
182
+ assertNoUnknownFlags(invRest);
183
+ const data = await adminApi(opts, 'GET', '/v1/admin/invites');
184
+ emitSuccess(opts, data, () => [
185
+ 'ReplayStage Creator Invite Codes',
186
+ ...(data.invites ?? []).map(inv => {
187
+ const status = inv.revokedAt ? 'REVOKED' : inv.usedCount >= inv.maxUses ? 'EXHAUSTED' : 'ACTIVE';
188
+ return ` ${inv.id.padEnd(22)} ${inv.code.padEnd(18)} ${`${inv.usedCount}/${inv.maxUses}`.padEnd(8)} ${status.padEnd(10)} ${inv.note || ''}`;
189
+ }),
190
+ ]);
191
+ return;
192
+ }
193
+ if (action === 'create') {
194
+ let rem = invRest;
195
+ const noteFlag = extractFlag(rem, ['--note']);
196
+ rem = noteFlag.rest;
197
+ const usesFlag = extractFlag(rem, ['--max-uses', '--uses']);
198
+ rem = usesFlag.rest;
199
+ const daysFlag = extractFlag(rem, ['--days']);
200
+ rem = daysFlag.rest;
201
+ assertNoUnknownFlags(rem);
202
+ const res = await adminApi(opts, 'POST', '/v1/admin/invites', {
203
+ note: noteFlag.value || '',
204
+ maxUses: usesFlag.value ? Number(usesFlag.value) : 1,
205
+ expiresInDays: daysFlag.value ? Number(daysFlag.value) : 30,
206
+ });
207
+ emitSuccess(opts, res, () => [
208
+ `Created invite code: ${res.invite.code} (id=${res.invite.id}, uses=${res.invite.maxUses})`,
209
+ ]);
210
+ return;
211
+ }
212
+ if (action === 'revoke') {
213
+ assertNoUnknownFlags(invRest);
214
+ const id = invRest[0];
215
+ if (!id) {
216
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage admin invite revoke <invite-id>');
217
+ }
218
+ const res = await adminApi(opts, 'DELETE', `/v1/admin/invites/${encodeURIComponent(id)}`);
219
+ emitSuccess(opts, { id, ...res }, () => [`Revoked invite ${id}`]);
220
+ return;
221
+ }
222
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage admin invite <list|create|revoke> ...');
223
+ }
224
+ if (sub === 'creators') {
225
+ if (rest[0] === 'set') {
226
+ let rem = rest.slice(1);
227
+ const roleFlag = extractFlag(rem, ['--role']);
228
+ rem = roleFlag.rest;
229
+ const statusFlag = extractFlag(rem, ['--status']);
230
+ rem = statusFlag.rest;
231
+ assertNoUnknownFlags(rem);
232
+ const id = rem[0];
233
+ if (!id || (!roleFlag.value && !statusFlag.value)) {
234
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage admin creators set <creatorId> [--role creator|verified|admin] [--status active|suspended]');
235
+ }
236
+ const body = {};
237
+ if (roleFlag.value)
238
+ body.role = roleFlag.value;
239
+ if (statusFlag.value)
240
+ body.status = statusFlag.value;
241
+ const res = await adminApi(opts, 'PUT', `/v1/admin/creators/${encodeURIComponent(id)}`, body);
242
+ emitSuccess(opts, res, () => [`Updated creator ${id}`]);
243
+ return;
244
+ }
245
+ assertNoUnknownFlags(rest);
246
+ const data = await adminApi(opts, 'GET', '/v1/admin/creators');
247
+ emitSuccess(opts, data, () => [
248
+ 'ReplayStage Creators',
249
+ ...(data.creators ?? []).map(c => ` ${c.id.padEnd(20)} @${String(c.handle).padEnd(16)} ${String(c.role).padEnd(10)} ${String(c.status).padEnd(10)} ${String(c.gameCount).padEnd(4)} ${c.email}`),
250
+ ]);
251
+ return;
252
+ }
253
+ if (sub === 'login-link') {
254
+ assertNoUnknownFlags(rest);
255
+ const email = rest[0]?.trim();
256
+ if (!email || !email.includes('@')) {
257
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage admin login-link <creator-email>');
258
+ }
259
+ const res = await adminApi(opts, 'POST', '/v1/admin/creators/login-link', { email });
260
+ emitSuccess(opts, res, () => [
261
+ `One-time Studio Magic Login Link for @${res.handle} (${res.email}):`,
262
+ ` ${res.magicUrl}`,
263
+ ` Expires: ${res.expiresAt}`,
264
+ ]);
265
+ return;
266
+ }
267
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage admin <reg-mode|invite|creators|login-link|catalog|daily> ...');
268
+ }
269
+ async function probeUrl(label, url) {
270
+ const started = Date.now();
271
+ const controller = new AbortController();
272
+ const timer = setTimeout(() => controller.abort(), 12_000);
273
+ try {
274
+ const res = await fetch(url, { redirect: 'manual', signal: controller.signal });
275
+ const ms = Date.now() - started;
276
+ const ok = res.status >= 200 && res.status < 400;
277
+ let extra = '';
278
+ if (ok && url.endsWith('/_rs/health')) {
279
+ try {
280
+ const body = (await res.json());
281
+ extra = body.version ? ` v${body.version}` : '';
282
+ }
283
+ catch {
284
+ // ignore
285
+ }
286
+ }
287
+ return { ok, label, url, status: res.status, ms, extra };
288
+ }
289
+ catch (err) {
290
+ return {
291
+ ok: false,
292
+ label,
293
+ url,
294
+ status: 0,
295
+ ms: Date.now() - started,
296
+ extra: err instanceof Error ? err.message : String(err),
297
+ };
298
+ }
299
+ finally {
300
+ clearTimeout(timer);
301
+ }
302
+ }
303
+ export async function cmdAudit(args, opts) {
304
+ const liveFlag = extractBoolFlag(args, ['--live']);
305
+ assertNoUnknownFlags(liveFlag.rest);
306
+ const apiBase = await resolveApiBase(opts.apiBase);
307
+ const workspaceRoot = await findPlatformWorkspaceRoot(opts.cwd);
308
+ const checks = [];
309
+ if (workspaceRoot) {
310
+ // 1. Hosted SDK CDN artifacts & starter template single-source sync check
311
+ const sdkPublicDir = path.join(workspaceRoot, 'apps', 'portal', 'public', 'sdk', 'v1');
312
+ const starterSdkDir = path.join(workspaceRoot, 'templates', 'starter-web-game', 'src', 'sdk');
313
+ const requiredSdkFiles = ['replaystage.js', 'replaystage.esm.js', 'replaystage.d.ts', 'manifest.json'];
314
+ let sdkMissing = false;
315
+ for (const file of requiredSdkFiles) {
316
+ if (!(await exists(path.join(sdkPublicDir, file)))) {
317
+ sdkMissing = true;
318
+ checks.push({ ok: false, name: 'sdk_cdn', detail: `Missing apps/portal/public/sdk/v1/${file}` });
319
+ }
320
+ }
321
+ if (!sdkMissing) {
322
+ const sdkManifest = JSON.parse(await readFile(path.join(sdkPublicDir, 'manifest.json'), 'utf8'));
323
+ const iifeSize = (await stat(path.join(sdkPublicDir, 'replaystage.js'))).size;
324
+ const esmBuf = await readFile(path.join(sdkPublicDir, 'replaystage.esm.js'));
325
+ const starterEsmPath = path.join(starterSdkDir, 'replaystage.esm.js');
326
+ const starterMatches = (await exists(starterEsmPath)) && Buffer.compare(esmBuf, await readFile(starterEsmPath)) === 0;
327
+ if (sdkManifest.sizes?.iifeBytes !== iifeSize || sdkManifest.sizes?.esmBytes !== esmBuf.byteLength) {
328
+ checks.push({
329
+ ok: false,
330
+ name: 'sdk_cdn',
331
+ detail: 'SDK manifest.json size mismatch — run `pnpm --filter @replaystage/sdk build`',
332
+ });
333
+ }
334
+ else if (!starterMatches) {
335
+ checks.push({
336
+ ok: false,
337
+ name: 'sdk_cdn',
338
+ detail: 'Starter template SDK is out of sync — run `pnpm --filter @replaystage/sdk build`',
339
+ });
340
+ }
341
+ else {
342
+ checks.push({
343
+ ok: true,
344
+ name: 'sdk_cdn',
345
+ detail: `Single-source SDK v${sdkManifest.version} verified across CDN & starter template (iife=${iifeSize} B, esm=${esmBuf.byteLength} B)`,
346
+ });
347
+ }
348
+ }
349
+ // 2. Verify zero legacy coupled files exist (including removed tools/rs.mjs!)
350
+ const forbiddenLegacyPaths = [
351
+ 'tools/rs.mjs',
352
+ 'catalog/local-sources.json',
353
+ 'tools/sync-routes.mjs',
354
+ 'tools/sync-media.mjs',
355
+ 'apps/portal/worker/game-meta.generated.ts',
356
+ 'workers/challenge-hub/src/game-meta.generated.ts',
357
+ 'apps/portal/src/components/studio.ts',
358
+ ];
359
+ const foundLegacy = [];
360
+ for (const rel of forbiddenLegacyPaths) {
361
+ if (await exists(path.join(workspaceRoot, rel))) {
362
+ foundLegacy.push(rel);
363
+ }
364
+ }
365
+ checks.push(foundLegacy.length === 0
366
+ ? { ok: true, name: 'clean_architecture', detail: 'Zero legacy coupled files or duplicate CLI scripts' }
367
+ : { ok: false, name: 'clean_architecture', detail: `Legacy files present: ${foundLegacy.join(', ')}` });
368
+ // 3. Required platform contracts & docs
369
+ const requiredPlatformFiles = [
370
+ 'AGENTS.md',
371
+ 'packages/catalog/schema.json',
372
+ 'docs/GAME_INTEGRATION_GUIDE.md',
373
+ 'docs/PUBLISHING_GUIDE.md',
374
+ 'skills/replaystage-game-integration/SKILL.md',
375
+ '.github/workflows/publish-game-reusable.yml',
376
+ ];
377
+ const missingDocs = [];
378
+ for (const rel of requiredPlatformFiles) {
379
+ if (!(await exists(path.join(workspaceRoot, rel)))) {
380
+ missingDocs.push(rel);
381
+ }
382
+ }
383
+ checks.push(missingDocs.length === 0
384
+ ? { ok: true, name: 'platform_assets', detail: 'AGENTS.md, schema, guides, agent skill & reusable CI workflow present' }
385
+ : { ok: false, name: 'platform_assets', detail: `Missing platform asset(s): ${missingDocs.join(', ')}` });
386
+ }
387
+ else if (!liveFlag.present) {
388
+ throw new CliError('WORKSPACE_NOT_FOUND', 'Not inside the ReplayStage platform repository. Pass `--live` to audit live production endpoints.');
389
+ }
390
+ const probes = [];
391
+ if (liveFlag.present) {
392
+ let liveGames = [];
393
+ try {
394
+ const catRes = await fetch(`${apiBase}/v1/catalog`);
395
+ if (catRes.ok) {
396
+ const catData = (await catRes.json());
397
+ liveGames = catData.games ?? [];
398
+ }
399
+ }
400
+ catch {
401
+ // captured by api catalog probe
402
+ }
403
+ const targets = [
404
+ ['portal /', `${DEFAULT_PORTAL_ORIGIN}/`],
405
+ ['portal /skill.md', `${DEFAULT_PORTAL_ORIGIN}/skill.md`],
406
+ ['portal /@linmo', `${DEFAULT_PORTAL_ORIGIN}/@linmo`],
407
+ ['portal /studio 301', `${DEFAULT_PORTAL_ORIGIN}/studio`],
408
+ ['studio /', 'https://studio.replaystage.com/'],
409
+ ['studio /emulator', 'https://studio.replaystage.com/emulator'],
410
+ ['sdk iife', `${DEFAULT_PORTAL_ORIGIN}/sdk/v1/replaystage.js`],
411
+ ['sdk esm', `${DEFAULT_PORTAL_ORIGIN}/sdk/v1/replaystage.esm.js`],
412
+ ['robots.txt', `${DEFAULT_PORTAL_ORIGIN}/robots.txt`],
413
+ ['sitemap.xml', `${DEFAULT_PORTAL_ORIGIN}/sitemap.xml`],
414
+ ['api health', `${apiBase}/v1/health`],
415
+ ['api auth/config', `${apiBase}/v1/auth/config`],
416
+ ['api catalog', `${apiBase}/v1/catalog`],
417
+ ['api creator', `${apiBase}/v1/creators/linmo`],
418
+ ['api stats', `${apiBase}/v1/stats?days=7`],
419
+ ['challenge hub', 'https://replay.st/'],
420
+ ...liveGames
421
+ .filter(g => Boolean(g.runtime?.originSlug))
422
+ .map(g => [
423
+ `play-${g.runtime.originSlug}`,
424
+ `https://play-${g.runtime.originSlug}.replaystage.com/_rs/health`,
425
+ ]),
426
+ ];
427
+ const probed = await Promise.all(targets.map(([label, url]) => probeUrl(label, url)));
428
+ probes.push(...probed);
429
+ const unknownProbe = await probeUrl('wildcard 404 guard', 'https://play-nonexistent-audit-probe.replaystage.com/_rs/health');
430
+ probes.push({
431
+ ...unknownProbe,
432
+ ok: unknownProbe.status === 404,
433
+ extra: unknownProbe.status === 404 ? '' : `expected HTTP 404, got ${unknownProbe.status}`,
434
+ });
435
+ }
436
+ const failures = checks.filter(c => !c.ok).length + probes.filter(p => !p.ok).length;
437
+ if (failures > 0) {
438
+ throw new CliError('AUDIT_FAILED', `ReplayStage audit failed with ${failures} issue(s).`, { details: { checks, probes, failures } });
439
+ }
440
+ emitSuccess(opts, { checks, probes, failures: 0 }, () => [
441
+ 'ReplayStage Platform Audit',
442
+ ...checks.map(c => ` [PASS] ${c.detail}`),
443
+ ...(probes.length > 0 ? ['', 'Live production probes:'] : []),
444
+ ...probes.map(p => ` [PASS] ${p.label.padEnd(20)} HTTP ${p.status} (${p.ms}ms)${p.extra}`),
445
+ '',
446
+ 'ReplayStage platform audit passed.',
447
+ ]);
448
+ }
@@ -0,0 +1,4 @@
1
+ import { type GlobalOptions } from '../output.js';
2
+ export declare function cmdLogin(args: string[], opts: GlobalOptions): Promise<void>;
3
+ export declare function cmdWhoami(args: string[], opts: GlobalOptions): Promise<void>;
4
+ export declare function cmdLogout(args: string[], opts: GlobalOptions): Promise<void>;
@@ -0,0 +1,75 @@
1
+ import { clearStoredToken, getConfigFilePath, readStoredConfig, requireAuthToken, resolveApiBase, writeStoredConfig, } from '../config.js';
2
+ import { apiRequestJson } from '../http.js';
3
+ import { CliError, assertNoUnknownFlags, emitSuccess, extractBoolFlag, extractFlag, } from '../output.js';
4
+ async function readTokenFromStdin() {
5
+ const chunks = [];
6
+ for await (const chunk of process.stdin) {
7
+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
8
+ }
9
+ return Buffer.concat(chunks).toString('utf8').trim();
10
+ }
11
+ export async function cmdLogin(args, opts) {
12
+ const stdinFlag = extractBoolFlag(args, ['--token-stdin']);
13
+ const { value: flagToken, rest } = extractFlag(stdinFlag.rest, ['--token', '-t']);
14
+ assertNoUnknownFlags(rest);
15
+ const token = stdinFlag.present
16
+ ? await readTokenFromStdin()
17
+ : (flagToken || opts.token || rest[0] || '').trim();
18
+ if (!token) {
19
+ throw new CliError('INVALID_ARGUMENTS', 'Usage: replaystage login --token <RSKEY_...> | --token-stdin [--api <url>] [--json]');
20
+ }
21
+ if (!token.startsWith('RSKEY_') && !token.startsWith('RSSESS_')) {
22
+ throw new CliError('INVALID_TOKEN_FORMAT', 'Expected an account API key starting with "RSKEY_" (mint one at https://studio.replaystage.com/account).');
23
+ }
24
+ const apiBase = await resolveApiBase(opts.apiBase);
25
+ const me = await apiRequestJson({
26
+ apiBase,
27
+ method: 'GET',
28
+ path: '/v1/auth/me',
29
+ token,
30
+ });
31
+ const existing = await readStoredConfig();
32
+ const configPath = await writeStoredConfig({
33
+ ...existing,
34
+ token,
35
+ ...(opts.apiBase ? { apiBase } : {}),
36
+ });
37
+ emitSuccess(opts, {
38
+ creator: me.creator,
39
+ authMethod: me.authMethod,
40
+ scopes: me.scopes,
41
+ apiBase,
42
+ configPath,
43
+ }, () => [
44
+ `Signed in as @${me.creator.handle} (${me.creator.email})`,
45
+ `Role: ${me.creator.role} · Scopes: ${me.scopes.join(', ')}`,
46
+ `Saved credentials to ${configPath} (0600)`,
47
+ ]);
48
+ }
49
+ export async function cmdWhoami(args, opts) {
50
+ assertNoUnknownFlags(args);
51
+ const apiBase = await resolveApiBase(opts.apiBase);
52
+ const token = await requireAuthToken({ flagToken: opts.token, cwd: opts.cwd });
53
+ const me = await apiRequestJson({
54
+ apiBase,
55
+ method: 'GET',
56
+ path: '/v1/auth/me',
57
+ token,
58
+ });
59
+ emitSuccess(opts, {
60
+ creator: me.creator,
61
+ authMethod: me.authMethod,
62
+ scopes: me.scopes,
63
+ apiBase,
64
+ configPath: getConfigFilePath(),
65
+ }, () => [
66
+ `@${me.creator.handle} — ${me.creator.displayName} <${me.creator.email}>`,
67
+ `Role: ${me.creator.role} · Status: ${me.creator.status} · Auth: ${me.authMethod} · Scopes: ${me.scopes.join(', ')}`,
68
+ `API: ${apiBase}`,
69
+ ]);
70
+ }
71
+ export async function cmdLogout(args, opts) {
72
+ assertNoUnknownFlags(args);
73
+ const configPath = await clearStoredToken();
74
+ emitSuccess(opts, { loggedOut: true, configPath }, () => [`Cleared stored ReplayStage credentials from ${configPath}.`]);
75
+ }
@@ -0,0 +1,14 @@
1
+ import { type GlobalOptions } from '../output.js';
2
+ export declare function cmdInit(args: string[], opts: GlobalOptions): Promise<void>;
3
+ export declare function cmdCreateGame(args: string[], opts: GlobalOptions): Promise<void>;
4
+ export declare function cmdValidate(args: string[], opts: GlobalOptions): Promise<void>;
5
+ export declare function cmdPublish(args: string[], opts: GlobalOptions): Promise<void>;
6
+ export declare function cmdUpdate(args: string[], opts: GlobalOptions): Promise<void>;
7
+ export declare function cmdDelete(args: string[], opts: GlobalOptions): Promise<void>;
8
+ export declare function cmdSdk(args: string[], opts: GlobalOptions): Promise<void>;
9
+ export declare function cmdGames(args: string[], opts: GlobalOptions): Promise<void>;
10
+ export declare function cmdReleases(args: string[], opts: GlobalOptions): Promise<void>;
11
+ export declare function cmdRollback(args: string[], opts: GlobalOptions): Promise<void>;
12
+ export declare function cmdVisibility(args: string[], opts: GlobalOptions): Promise<void>;
13
+ export declare function cmdTokens(args: string[], opts: GlobalOptions): Promise<void>;
14
+ export declare function cmdStats(args: string[], opts: GlobalOptions): Promise<void>;