@replaystage/cli 0.5.0 → 2.0.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,81 @@
1
+ export type GameGenre = 'arcade' | 'puzzle' | 'mystery' | 'strategy';
2
+ export type GameVisibility = 'featured' | 'live' | 'beta' | 'unlisted' | 'hidden' | 'suspended';
3
+ export type GameTier = 0 | 1 | 2;
4
+ export type SupportedLocale = 'en' | 'zh-Hans';
5
+ export interface GameLocaleCopy {
6
+ title: string;
7
+ tagline: string;
8
+ description: string;
9
+ howToPlay: string[];
10
+ tags: string[];
11
+ }
12
+ export interface ReplayStageManifest {
13
+ schemaVersion?: number;
14
+ slug: string;
15
+ version: string;
16
+ tier: GameTier;
17
+ genre: GameGenre;
18
+ accentColor: string;
19
+ aspectRatio: string;
20
+ sessionMinutes: string;
21
+ ageRating: string;
22
+ gameLanguages?: SupportedLocale[];
23
+ locales: {
24
+ en: GameLocaleCopy;
25
+ 'zh-Hans': GameLocaleCopy;
26
+ };
27
+ runtime: {
28
+ originSlug: string;
29
+ entryPath: string;
30
+ supportsPause?: boolean;
31
+ supportsMute?: boolean;
32
+ supportsChallengeSeed?: boolean;
33
+ };
34
+ artwork: {
35
+ icon: string;
36
+ cover: string;
37
+ };
38
+ platforms: {
39
+ web: boolean;
40
+ wechat?: {
41
+ available: boolean;
42
+ appId?: string;
43
+ };
44
+ douyin?: {
45
+ available: boolean;
46
+ appId?: string;
47
+ };
48
+ ios?: {
49
+ available: boolean;
50
+ storeUrl?: string;
51
+ };
52
+ android?: {
53
+ available: boolean;
54
+ storeUrl?: string;
55
+ };
56
+ };
57
+ }
58
+ export declare const SLUG_RE: RegExp;
59
+ export declare const HEX_COLOR_RE: RegExp;
60
+ export declare const ASPECT_RATIO_RE: RegExp;
61
+ export declare const VALID_GENRES: readonly GameGenre[];
62
+ export declare const VALID_CREATOR_VISIBILITIES: readonly ["live", "beta", "unlisted", "hidden"];
63
+ export declare const VALID_ADMIN_VISIBILITIES: readonly GameVisibility[];
64
+ export declare function slugToTitle(slug: string): string;
65
+ export declare function validateManifestObject(raw: unknown): {
66
+ valid: boolean;
67
+ errors: string[];
68
+ manifest?: ReplayStageManifest;
69
+ };
70
+ export declare function loadAndValidateManifest(manifestPath: string): Promise<{
71
+ manifest: ReplayStageManifest;
72
+ manifestPath: string;
73
+ }>;
74
+ export declare function buildStarterManifest(options: {
75
+ slug: string;
76
+ titleEn?: string;
77
+ titleZh?: string;
78
+ genre?: GameGenre;
79
+ accentColor?: string;
80
+ }): ReplayStageManifest;
81
+ export declare function writeStarterManifest(targetPath: string, manifest: ReplayStageManifest, force?: boolean): Promise<string>;
@@ -0,0 +1,198 @@
1
+ import { readFile, stat, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { CliError } from './output.js';
4
+ export const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
5
+ export const HEX_COLOR_RE = /^#[0-9a-fA-F]{6}$/;
6
+ export const ASPECT_RATIO_RE = /^\d+:\d+$/;
7
+ export const VALID_GENRES = ['arcade', 'puzzle', 'mystery', 'strategy'];
8
+ export const VALID_CREATOR_VISIBILITIES = ['live', 'beta', 'unlisted', 'hidden'];
9
+ export const VALID_ADMIN_VISIBILITIES = [
10
+ 'featured',
11
+ 'live',
12
+ 'beta',
13
+ 'unlisted',
14
+ 'hidden',
15
+ 'suspended',
16
+ ];
17
+ export function slugToTitle(slug) {
18
+ return slug
19
+ .split('-')
20
+ .filter(Boolean)
21
+ .map(part => (part[0] ? part[0].toUpperCase() + part.slice(1) : part))
22
+ .join(' ');
23
+ }
24
+ function isNonEmptyString(val) {
25
+ return typeof val === 'string' && val.trim().length > 0;
26
+ }
27
+ export function validateManifestObject(raw) {
28
+ const errors = [];
29
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
30
+ return { valid: false, errors: ['Manifest must be a JSON object'] };
31
+ }
32
+ const m = raw;
33
+ if (!isNonEmptyString(m.slug) || !SLUG_RE.test(m.slug) || m.slug.length < 3 || m.slug.length > 48) {
34
+ errors.push('slug must be 3-48 chars lowercase kebab-case (e.g. "neon-stack")');
35
+ }
36
+ if (!isNonEmptyString(m.version) || m.version.length > 64) {
37
+ errors.push('version must be a non-empty string (e.g. "1.0.0")');
38
+ }
39
+ if (m.tier !== 0 && m.tier !== 1 && m.tier !== 2) {
40
+ errors.push('tier must be 0, 1, or 2');
41
+ }
42
+ if (!isNonEmptyString(m.genre) || !VALID_GENRES.includes(m.genre)) {
43
+ errors.push(`genre must be one of: ${VALID_GENRES.join(', ')}`);
44
+ }
45
+ if (!isNonEmptyString(m.accentColor) || !HEX_COLOR_RE.test(m.accentColor)) {
46
+ errors.push('accentColor must be a 6-digit hex color (e.g. "#E5482E")');
47
+ }
48
+ if (!isNonEmptyString(m.aspectRatio) || !ASPECT_RATIO_RE.test(m.aspectRatio)) {
49
+ errors.push('aspectRatio must match "<w>:<h>" (e.g. "9:16")');
50
+ }
51
+ if (!isNonEmptyString(m.sessionMinutes)) {
52
+ errors.push('sessionMinutes must be a non-empty string (e.g. "1–3 min")');
53
+ }
54
+ if (!isNonEmptyString(m.ageRating)) {
55
+ errors.push('ageRating must be a non-empty string (e.g. "6+")');
56
+ }
57
+ const locales = m.locales;
58
+ for (const loc of ['en', 'zh-Hans']) {
59
+ const copy = locales?.[loc];
60
+ if (!copy || typeof copy !== 'object') {
61
+ errors.push(`locales.${loc} is required`);
62
+ continue;
63
+ }
64
+ if (!isNonEmptyString(copy.title))
65
+ errors.push(`locales.${loc}.title is required`);
66
+ if (!isNonEmptyString(copy.tagline))
67
+ errors.push(`locales.${loc}.tagline is required`);
68
+ if (!isNonEmptyString(copy.description))
69
+ errors.push(`locales.${loc}.description is required`);
70
+ if (!Array.isArray(copy.howToPlay) || copy.howToPlay.length === 0 || !copy.howToPlay.every(isNonEmptyString)) {
71
+ errors.push(`locales.${loc}.howToPlay must be a non-empty string array`);
72
+ }
73
+ if (!Array.isArray(copy.tags) || !copy.tags.every(isNonEmptyString)) {
74
+ errors.push(`locales.${loc}.tags must be an array of strings`);
75
+ }
76
+ }
77
+ const runtime = m.runtime;
78
+ if (!runtime || typeof runtime !== 'object') {
79
+ errors.push('runtime is required');
80
+ }
81
+ else {
82
+ if (!isNonEmptyString(runtime.originSlug) || !SLUG_RE.test(runtime.originSlug)) {
83
+ errors.push('runtime.originSlug must be lowercase kebab-case');
84
+ }
85
+ if (!isNonEmptyString(runtime.entryPath) || !runtime.entryPath.startsWith('/')) {
86
+ errors.push('runtime.entryPath must start with "/" (e.g. "/index.html")');
87
+ }
88
+ }
89
+ const artwork = m.artwork;
90
+ if (!artwork || typeof artwork !== 'object') {
91
+ errors.push('artwork is required');
92
+ }
93
+ else {
94
+ if (!isNonEmptyString(artwork.icon))
95
+ errors.push('artwork.icon is required');
96
+ if (!isNonEmptyString(artwork.cover))
97
+ errors.push('artwork.cover is required');
98
+ }
99
+ const platforms = m.platforms;
100
+ if (!platforms || typeof platforms.web !== 'boolean') {
101
+ errors.push('platforms.web must be a boolean');
102
+ }
103
+ if (errors.length > 0) {
104
+ return { valid: false, errors };
105
+ }
106
+ return { valid: true, errors: [], manifest: raw };
107
+ }
108
+ export async function loadAndValidateManifest(manifestPath) {
109
+ const resolved = path.resolve(manifestPath);
110
+ try {
111
+ await stat(resolved);
112
+ }
113
+ catch {
114
+ throw new CliError('MANIFEST_MISSING', `Missing replaystage.manifest.json at ${resolved}. Run \`npx -y replaystage init <slug>\` and fill bilingual (en + zh-Hans) metadata before validating or publishing.`, { details: { manifestPath: resolved } });
115
+ }
116
+ let parsed;
117
+ try {
118
+ const raw = await readFile(resolved, 'utf8');
119
+ parsed = JSON.parse(raw);
120
+ }
121
+ catch (err) {
122
+ throw new CliError('INVALID_MANIFEST', `Failed to parse JSON in ${resolved}: ${err instanceof Error ? err.message : String(err)}`, { details: { manifestPath: resolved, errors: ['Invalid JSON syntax'] } });
123
+ }
124
+ const check = validateManifestObject(parsed);
125
+ if (!check.valid || !check.manifest) {
126
+ throw new CliError('INVALID_MANIFEST', `Invalid replaystage.manifest.json (${check.errors.length} error${check.errors.length === 1 ? '' : 's'}). Fix the listed fields and retry.`, { details: { manifestPath: resolved, errors: check.errors } });
127
+ }
128
+ return { manifest: check.manifest, manifestPath: resolved };
129
+ }
130
+ export function buildStarterManifest(options) {
131
+ const titleEn = options.titleEn?.trim() || slugToTitle(options.slug);
132
+ const titleZh = options.titleZh?.trim() || titleEn;
133
+ const genre = options.genre ?? 'arcade';
134
+ const accentColor = options.accentColor ?? '#E5482E';
135
+ return {
136
+ schemaVersion: 1,
137
+ slug: options.slug,
138
+ version: '1.0.0',
139
+ tier: 2,
140
+ genre,
141
+ accentColor,
142
+ aspectRatio: '9:16',
143
+ sessionMinutes: '1–3 min',
144
+ ageRating: '6+',
145
+ gameLanguages: ['en', 'zh-Hans'],
146
+ locales: {
147
+ en: {
148
+ title: titleEn,
149
+ tagline: `Play ${titleEn} in an instant portrait stage.`,
150
+ description: `${titleEn} is an instant-play portrait casual game built for ReplayStage.`,
151
+ howToPlay: [
152
+ 'Tap or swipe inside the portrait stage to play.',
153
+ 'Chase a new personal best and share a replay.st challenge card.',
154
+ ],
155
+ tags: ['Portrait', 'Instant'],
156
+ },
157
+ 'zh-Hans': {
158
+ title: titleZh,
159
+ tagline: `在竖屏舞台点开即玩《${titleZh}》。`,
160
+ description: `《${titleZh}》是一款专为 ReplayStage 打造的竖屏休闲即玩小游戏。`,
161
+ howToPlay: [
162
+ '在竖屏舞台中点击或滑动即可轻松上手。',
163
+ '刷新个人最佳战绩,并生成 replay.st 挑战卡分享好友。',
164
+ ],
165
+ tags: ['竖屏', '即玩'],
166
+ },
167
+ },
168
+ runtime: {
169
+ originSlug: options.slug,
170
+ entryPath: '/index.html',
171
+ supportsPause: true,
172
+ supportsMute: true,
173
+ supportsChallengeSeed: true,
174
+ },
175
+ artwork: {
176
+ icon: `/media/${options.slug}/icon.png`,
177
+ cover: `/media/${options.slug}/cover.png`,
178
+ },
179
+ platforms: {
180
+ web: true,
181
+ },
182
+ };
183
+ }
184
+ export async function writeStarterManifest(targetPath, manifest, force = false) {
185
+ const resolved = path.resolve(targetPath);
186
+ if (!force) {
187
+ try {
188
+ await stat(resolved);
189
+ throw new CliError('MANIFEST_EXISTS', `Manifest already exists at ${resolved}. Pass --force to overwrite.`, { details: { manifestPath: resolved } });
190
+ }
191
+ catch (err) {
192
+ if (err instanceof CliError)
193
+ throw err;
194
+ }
195
+ }
196
+ await writeFile(resolved, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
197
+ return resolved;
198
+ }
@@ -0,0 +1,35 @@
1
+ export declare class CliError extends Error {
2
+ readonly code: string;
3
+ readonly exitCode: number;
4
+ readonly status?: number;
5
+ readonly details?: Record<string, unknown>;
6
+ constructor(code: string, message: string, options?: {
7
+ exitCode?: number;
8
+ status?: number;
9
+ details?: Record<string, unknown>;
10
+ });
11
+ }
12
+ export interface OutputStreams {
13
+ stdout: (line: string) => void;
14
+ stderr: (line: string) => void;
15
+ }
16
+ export declare const DEFAULT_STREAMS: OutputStreams;
17
+ export interface GlobalOptions {
18
+ json: boolean;
19
+ apiBase?: string;
20
+ token?: string;
21
+ streams: OutputStreams;
22
+ cwd: string;
23
+ }
24
+ export declare function emitJson(streams: OutputStreams, payload: Record<string, unknown>): void;
25
+ export declare function emitSuccess(opts: GlobalOptions, data: Record<string, unknown>, renderHuman: () => string[]): void;
26
+ export declare function emitError(opts: GlobalOptions, error: unknown): number;
27
+ export declare function extractFlag(args: readonly string[], names: readonly string[]): {
28
+ value: string | undefined;
29
+ rest: string[];
30
+ };
31
+ export declare function extractBoolFlag(args: readonly string[], names: readonly string[]): {
32
+ present: boolean;
33
+ rest: string[];
34
+ };
35
+ export declare function assertNoUnknownFlags(args: readonly string[]): void;
package/dist/output.js ADDED
@@ -0,0 +1,105 @@
1
+ export class CliError extends Error {
2
+ code;
3
+ exitCode;
4
+ status;
5
+ details;
6
+ constructor(code, message, options = {}) {
7
+ super(message);
8
+ this.name = 'CliError';
9
+ this.code = code;
10
+ this.exitCode = options.exitCode ?? 1;
11
+ this.status = options.status;
12
+ this.details = options.details;
13
+ }
14
+ }
15
+ export const DEFAULT_STREAMS = {
16
+ stdout: line => process.stdout.write(`${line}\n`),
17
+ stderr: line => process.stderr.write(`${line}\n`),
18
+ };
19
+ export function emitJson(streams, payload) {
20
+ streams.stdout(JSON.stringify(payload, null, 2));
21
+ }
22
+ export function emitSuccess(opts, data, renderHuman) {
23
+ if (opts.json) {
24
+ emitJson(opts.streams, { ok: true, ...data });
25
+ return;
26
+ }
27
+ for (const line of renderHuman()) {
28
+ opts.streams.stdout(line);
29
+ }
30
+ }
31
+ export function emitError(opts, error) {
32
+ const cliErr = error instanceof CliError
33
+ ? error
34
+ : new CliError('UNEXPECTED_ERROR', error instanceof Error ? error.message : String(error));
35
+ if (opts.json) {
36
+ const payload = {
37
+ ok: false,
38
+ code: cliErr.code,
39
+ message: cliErr.message,
40
+ };
41
+ if (cliErr.status !== undefined)
42
+ payload.status = cliErr.status;
43
+ if (cliErr.details !== undefined)
44
+ payload.details = cliErr.details;
45
+ emitJson(opts.streams, payload);
46
+ }
47
+ else {
48
+ opts.streams.stderr(`[replaystage] Error (${cliErr.code}): ${cliErr.message}`);
49
+ if (cliErr.details && Array.isArray(cliErr.details.errors)) {
50
+ for (const item of cliErr.details.errors) {
51
+ opts.streams.stderr(` - ${String(item)}`);
52
+ }
53
+ }
54
+ }
55
+ return cliErr.exitCode;
56
+ }
57
+ export function extractFlag(args, names) {
58
+ const rest = [];
59
+ let value;
60
+ for (let i = 0; i < args.length; i += 1) {
61
+ const arg = args[i] ?? '';
62
+ let matched = false;
63
+ for (const name of names) {
64
+ if (arg === name) {
65
+ const next = args[i + 1];
66
+ if (next === undefined || next.startsWith('-')) {
67
+ throw new CliError('INVALID_ARGUMENTS', `Flag "${name}" requires a value.`);
68
+ }
69
+ value = next;
70
+ i += 1;
71
+ matched = true;
72
+ break;
73
+ }
74
+ if (arg.startsWith(`${name}=`)) {
75
+ value = arg.slice(name.length + 1);
76
+ matched = true;
77
+ break;
78
+ }
79
+ }
80
+ if (!matched) {
81
+ rest.push(arg);
82
+ }
83
+ }
84
+ return { value, rest };
85
+ }
86
+ export function extractBoolFlag(args, names) {
87
+ const nameSet = new Set(names);
88
+ const rest = [];
89
+ let present = false;
90
+ for (const arg of args) {
91
+ if (nameSet.has(arg)) {
92
+ present = true;
93
+ }
94
+ else {
95
+ rest.push(arg);
96
+ }
97
+ }
98
+ return { present, rest };
99
+ }
100
+ export function assertNoUnknownFlags(args) {
101
+ const unknown = args.filter(a => a.startsWith('-'));
102
+ if (unknown.length > 0) {
103
+ throw new CliError('UNKNOWN_FLAG', `Unknown flag(s): ${unknown.join(', ')}. Run with --help to see supported options.`, { details: { unknownFlags: unknown } });
104
+ }
105
+ }
@@ -0,0 +1,38 @@
1
+ import { type ReplayStageManifest } from './manifest.js';
2
+ export declare const MAX_FILE_BYTES: number;
3
+ export declare const MAX_TOTAL_BYTES: number;
4
+ export declare const MAX_FILE_COUNT = 1000;
5
+ export declare const MAX_MEDIA_BYTES: number;
6
+ export declare function guessContentType(filePath: string): string;
7
+ export interface BundleFileItem {
8
+ relPath: string;
9
+ absPath: string;
10
+ bytes: number;
11
+ contentType: string;
12
+ }
13
+ export interface DiscoveredMediaItem {
14
+ slot: 'icon' | 'cover';
15
+ filename: string;
16
+ absPath: string;
17
+ bytes: number;
18
+ contentType: string;
19
+ }
20
+ export interface ValidationReport {
21
+ slug: string;
22
+ version: string;
23
+ manifestPath: string;
24
+ distDir: string;
25
+ entryPath: string;
26
+ fileCount: number;
27
+ totalBytes: number;
28
+ files: BundleFileItem[];
29
+ media: DiscoveredMediaItem[];
30
+ warnings: string[];
31
+ manifest: ReplayStageManifest;
32
+ }
33
+ export declare function validateProjectBundle(options: {
34
+ cwd: string;
35
+ distDir?: string;
36
+ manifestPath?: string;
37
+ versionOverride?: string;
38
+ }): Promise<ValidationReport>;
@@ -0,0 +1,196 @@
1
+ import { readdir, stat } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { loadAndValidateManifest } from './manifest.js';
4
+ import { CliError } from './output.js';
5
+ export const MAX_FILE_BYTES = 25 * 1024 * 1024; // 25 MB
6
+ export const MAX_TOTAL_BYTES = 50 * 1024 * 1024; // 50 MB
7
+ export const MAX_FILE_COUNT = 1000;
8
+ export const MAX_MEDIA_BYTES = 2 * 1024 * 1024; // 2 MB
9
+ const AUTO_SKIP_DIRS = new Set(['.git', 'node_modules', '__MACOSX']);
10
+ const AUTO_SKIP_FILES = new Set(['.DS_Store', 'Thumbs.db']);
11
+ const PROHIBITED_EXTENSIONS = new Set(['.exe', '.dll', '.sh', '.bat', '.cmd', '.msi', '.com', '.scr']);
12
+ const MIME_BY_EXT = {
13
+ '.html': 'text/html; charset=utf-8',
14
+ '.htm': 'text/html; charset=utf-8',
15
+ '.js': 'application/javascript; charset=utf-8',
16
+ '.mjs': 'application/javascript; charset=utf-8',
17
+ '.cjs': 'application/javascript; charset=utf-8',
18
+ '.css': 'text/css; charset=utf-8',
19
+ '.json': 'application/json; charset=utf-8',
20
+ '.svg': 'image/svg+xml',
21
+ '.png': 'image/png',
22
+ '.jpg': 'image/jpeg',
23
+ '.jpeg': 'image/jpeg',
24
+ '.webp': 'image/webp',
25
+ '.gif': 'image/gif',
26
+ '.ico': 'image/x-icon',
27
+ '.wasm': 'application/wasm',
28
+ '.mp3': 'audio/mpeg',
29
+ '.ogg': 'audio/ogg',
30
+ '.wav': 'audio/wav',
31
+ '.m4a': 'audio/mp4',
32
+ '.mp4': 'video/mp4',
33
+ '.webm': 'video/webm',
34
+ '.woff': 'font/woff',
35
+ '.woff2': 'font/woff2',
36
+ '.ttf': 'font/ttf',
37
+ '.otf': 'font/otf',
38
+ '.txt': 'text/plain; charset=utf-8',
39
+ '.xml': 'application/xml; charset=utf-8',
40
+ '.glsl': 'text/plain; charset=utf-8',
41
+ '.map': 'application/json; charset=utf-8',
42
+ };
43
+ export function guessContentType(filePath) {
44
+ const ext = path.extname(filePath).toLowerCase();
45
+ return MIME_BY_EXT[ext] ?? 'application/octet-stream';
46
+ }
47
+ function isEnvFile(name) {
48
+ return name === '.env' || name.startsWith('.env.');
49
+ }
50
+ async function fileExists(target) {
51
+ try {
52
+ const info = await stat(target);
53
+ return info.isFile();
54
+ }
55
+ catch {
56
+ return false;
57
+ }
58
+ }
59
+ async function discoverMediaFile(slot, artworkUrl, slug, repoDir, distDir) {
60
+ // Expected format: `/media/<slug>/<filename>` (or direct local path)
61
+ const expectedPrefix = `/media/${slug}/`;
62
+ let filename = '';
63
+ if (artworkUrl.startsWith(expectedPrefix)) {
64
+ filename = artworkUrl.slice(expectedPrefix.length);
65
+ }
66
+ else if (artworkUrl.startsWith('/')) {
67
+ filename = path.basename(artworkUrl);
68
+ }
69
+ else if (!artworkUrl.startsWith('http://') && !artworkUrl.startsWith('https://')) {
70
+ filename = path.basename(artworkUrl);
71
+ }
72
+ else {
73
+ return null;
74
+ }
75
+ if (!filename || filename.includes('..') || filename.includes('/')) {
76
+ return null;
77
+ }
78
+ const candidates = [
79
+ path.join(repoDir, 'public', 'media', slug, filename),
80
+ path.join(repoDir, 'media', slug, filename),
81
+ path.join(repoDir, 'media', filename),
82
+ path.join(repoDir, 'public', filename),
83
+ path.join(repoDir, filename),
84
+ path.join(distDir, 'media', slug, filename),
85
+ path.join(distDir, filename),
86
+ ];
87
+ for (const candidate of candidates) {
88
+ if (await fileExists(candidate)) {
89
+ const info = await stat(candidate);
90
+ if (info.size > MAX_MEDIA_BYTES) {
91
+ throw new CliError('MEDIA_TOO_LARGE', `Artwork file "${filename}" (${info.size} bytes) exceeds the 2 MB media limit.`, { details: { slot, filename, bytes: info.size, maxBytes: MAX_MEDIA_BYTES } });
92
+ }
93
+ return {
94
+ slot,
95
+ filename,
96
+ absPath: candidate,
97
+ bytes: info.size,
98
+ contentType: guessContentType(candidate),
99
+ };
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+ export async function validateProjectBundle(options) {
105
+ const manifestPath = options.manifestPath
106
+ ? path.resolve(options.cwd, options.manifestPath)
107
+ : path.resolve(options.cwd, 'replaystage.manifest.json');
108
+ const { manifest, manifestPath: resolvedManifestPath } = await loadAndValidateManifest(manifestPath);
109
+ const repoDir = path.dirname(resolvedManifestPath);
110
+ const resolvedDistDir = path.resolve(options.cwd, options.distDir || 'dist');
111
+ try {
112
+ const distInfo = await stat(resolvedDistDir);
113
+ if (!distInfo.isDirectory()) {
114
+ throw new CliError('DIST_NOT_FOUND', `Bundle path is not a directory: ${resolvedDistDir}`, { details: { distDir: resolvedDistDir } });
115
+ }
116
+ }
117
+ catch (err) {
118
+ if (err instanceof CliError)
119
+ throw err;
120
+ throw new CliError('DIST_NOT_FOUND', `Build output directory not found: ${resolvedDistDir}. Build your game first or pass the dist directory path.`, { details: { distDir: resolvedDistDir } });
121
+ }
122
+ const files = [];
123
+ const warnings = [];
124
+ let totalBytes = 0;
125
+ async function walk(currentDir, relPrefix) {
126
+ const entries = await readdir(currentDir, { withFileTypes: true });
127
+ for (const entry of entries) {
128
+ const rel = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
129
+ const abs = path.join(currentDir, entry.name);
130
+ if (entry.isDirectory()) {
131
+ if (AUTO_SKIP_DIRS.has(entry.name)) {
132
+ warnings.push(`Skipped directory "${rel}/" during bundle scan (left untouched on disk).`);
133
+ continue;
134
+ }
135
+ await walk(abs, rel);
136
+ continue;
137
+ }
138
+ if (!entry.isFile()) {
139
+ warnings.push(`Skipped non-regular entry "${rel}".`);
140
+ continue;
141
+ }
142
+ if (AUTO_SKIP_FILES.has(entry.name) || isEnvFile(entry.name)) {
143
+ warnings.push(`Skipped sensitive/system file "${rel}" during bundle scan (left untouched on disk).`);
144
+ continue;
145
+ }
146
+ const ext = path.extname(entry.name).toLowerCase();
147
+ if (PROHIBITED_EXTENSIONS.has(ext)) {
148
+ throw new CliError('PROHIBITED_FILE', `Prohibited executable/script file in bundle: "${rel}". Remove build scripts from the dist directory before publishing.`, { details: { file: rel, extension: ext } });
149
+ }
150
+ const info = await stat(abs);
151
+ if (info.size > MAX_FILE_BYTES) {
152
+ throw new CliError('FILE_TOO_LARGE', `File "${rel}" (${info.size} bytes) exceeds the 25 MB per-file limit.`, { details: { file: rel, bytes: info.size, maxBytes: MAX_FILE_BYTES } });
153
+ }
154
+ totalBytes += info.size;
155
+ if (files.length + 1 > MAX_FILE_COUNT) {
156
+ throw new CliError('TOO_MANY_FILES', `Bundle contains more than ${MAX_FILE_COUNT} files.`, { details: { maxFiles: MAX_FILE_COUNT } });
157
+ }
158
+ if (totalBytes > MAX_TOTAL_BYTES) {
159
+ throw new CliError('BUNDLE_TOO_LARGE', `Total bundle size (${totalBytes} bytes) exceeds the 50 MB limit.`, { details: { totalBytes, maxTotalBytes: MAX_TOTAL_BYTES } });
160
+ }
161
+ files.push({
162
+ relPath: rel,
163
+ absPath: abs,
164
+ bytes: info.size,
165
+ contentType: guessContentType(abs),
166
+ });
167
+ }
168
+ }
169
+ await walk(resolvedDistDir, '');
170
+ const normalizedEntry = manifest.runtime.entryPath.replace(/^\/+/, '') || 'index.html';
171
+ const hasEntry = files.some(f => f.relPath === normalizedEntry);
172
+ if (!hasEntry) {
173
+ throw new CliError('ENTRY_MISSING', `Entry file "${normalizedEntry}" (from runtime.entryPath) was not found inside ${resolvedDistDir}.`, { details: { entryPath: normalizedEntry, distDir: resolvedDistDir } });
174
+ }
175
+ const media = [];
176
+ const iconMedia = await discoverMediaFile('icon', manifest.artwork.icon, manifest.slug, repoDir, resolvedDistDir);
177
+ if (iconMedia)
178
+ media.push(iconMedia);
179
+ const coverMedia = await discoverMediaFile('cover', manifest.artwork.cover, manifest.slug, repoDir, resolvedDistDir);
180
+ if (coverMedia)
181
+ media.push(coverMedia);
182
+ const version = options.versionOverride?.trim() || manifest.version;
183
+ return {
184
+ slug: manifest.slug,
185
+ version,
186
+ manifestPath: resolvedManifestPath,
187
+ distDir: resolvedDistDir,
188
+ entryPath: `/${normalizedEntry}`,
189
+ fileCount: files.length,
190
+ totalBytes,
191
+ files: files.sort((a, b) => a.relPath.localeCompare(b.relPath)),
192
+ media,
193
+ warnings,
194
+ manifest: { ...manifest, version },
195
+ };
196
+ }