mirror of
https://github.com/nexu-io/openmotion.git
synced 2026-12-01 23:59:50 +08:00
* feat(game-static-play): add 274-template R2 zip packaging, cookieless static play deploy, and verification pipeline * feat(game-skill): port 21-section OpenGame skill with dual-mode workflow and fast-play path * feat(onboarding): upgrade Cloud MCP install guide and add shared OpenGame prompt builders * feat(game-catalog): sync 274 official templates, 4 kits, downloads manifest, and game contract * feat(cloud-mcp): add read-only game catalog, free asset search, guest catalog API, redirects, and Docker packaging * feat(opengame): enable Stage 1 Game Studio routing, feature flags, and analytics * feat(opengame): add Stage 1 market, multi-client modal, Cursor HTTP fix, SuperAgent prompt, and i18n * fix(opengame): align nullable GameCardWithMeta fields and add opengame-catalog MCP capability * test(mcp-onboarding): update registered public tool count from 22 to 24 for Stage 1 game tools * chore(game-catalog): register 26 verified live R2 in-repo template bundles in game-downloads.json * fix(opengame): address Stage 1 review feedback and failing CI lanes - Send no play URL when GAME_PLAY_PUBLIC_ORIGIN is unset instead of a main-site path that no route serves; Studio falls back to bundled in-repo templates - Keep legacy-host 301 redirects on the configured origin for network-path inputs - Correct the BlenderKit page host in the asset search allowlist - Reuse the shared withdrawn list, TOP earning tag, curated order and comparator in Studio - Remove the unused shared prompt module; the shipped builders stay covered by Studio tests - Drop the blurred launch backdrop and the in-dialog copy notices in favour of Toasts - Describe the shipped read-only Game Studio boundary and 24-tool MCP contract in the architecture - Schedule the game skill and static play suites in CI and budget the three OpenGame events * fix(game-static-play): retry stalled template bundle downloads before failing the run * fix(game-asset-search): size the pagination cursor limit for every supported query A 200-unit query with non-ASCII, control or lone-surrogate characters produced a cursor longer than the 512-character limit, so nextCursor was rejected by both the decoder and the public schema. Share one limit derived from the worst-case JSON/base64url expansion and add a round-trip test for maximum-length queries. * fix(game-asset-search): accept BlenderKit pages on www.blendkit.com and guide licence checks www.blenderkit.com now redirects to www.blendkit.com and the upstream catalog returns that host, so requiring www.blenderkit.com dropped every BlenderKit result. Restore the live host, pin a real upstream row in tests, and tell Agents to confirm the licence on the source page when a source omits it. * fix(deploy): forward game play origin and legacy redirect hosts to the API deploy/.env.example and deploy/k8s/configmap.yaml declared GAME_PLAY_PUBLIC_ORIGIN and APP_REDIRECT_FROM_HOSTS, but neither the compose api service nor the reference api Deployment passed them to the process. Wire both and assert that every reference ConfigMap key is read by a workload. * Address review: keep legacy-host writes, enforce play-origin isolation, share catalog constants - Legacy-host redirects answer GET/HEAD with 301 and every other method with 308, so MCP and API writes keep their method and body. - parseConfig rejects a GAME_PLAY_PUBLIC_ORIGIN that is not https (loopback http excepted), carries a path, or shares or sits under the APP_PUBLIC_ORIGIN host. - The template id pattern, bundle key prefix, withdrawn set and TOP tag predicate live in shared/game-contract.ts; static play, deploy/verify scripts and the catalog service reuse them and the shared bundle URL builder. - Remove unused game-contract and model-catalog exports. - Update the MCP contract, AGENTS.md, README and docs to the 24-name phase-one surface and document the read-only OpenGame tools and guest catalog routes. * fix(game-static-play): make the full play-site upload resumable Upload through the S3 SDK instead of one aws CLI process per file, skip objects whose ETag already matches the local MD5, retry each request with backoff, and write assets before entry pages and the manifest. Give large bundle downloads time for a slow link. Record the provisioned bucket, domain and remaining header rule in the runbook. * feat(game-static-play): harden live play verification and add manual R2 publish workflow * fix(opengame): raise prompt/remix maxLength for >4k OG-13 test and reset notes on target change * fix(mcp): register resources/templates/list handler for Codex MCP compliance * chore(game-catalog): register uploaded tidebreaker bundle for 274/274 R2 CDN parity --------- Co-authored-by: heggria <bshengtao@gmail.com>
666 lines
24 KiB
TypeScript
666 lines
24 KiB
TypeScript
import assert from 'node:assert/strict';
|
|
import { createHash } from 'node:crypto';
|
|
import { access, lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import { ListObjectsV2Command, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
|
|
import { isMain } from '../shared/entry.ts';
|
|
import {
|
|
assertDistinctCookielessPlayOrigin,
|
|
auditStaticGameFiles,
|
|
buildGameBundleUrl,
|
|
buildStaticGameEntryPath,
|
|
buildStaticGamePlayUrl,
|
|
buildStaticPlayHeadersFile,
|
|
cacheControlForStaticGamePath,
|
|
contentTypeForStaticGamePath,
|
|
deflateZip,
|
|
GAME_PLAY_PATH_PREFIX,
|
|
includedGameBundlePath,
|
|
isValidGameTemplateId,
|
|
MAX_GAME_BUNDLE_BYTES,
|
|
prepareStaticPlayHtml,
|
|
resolveGameBundleOriginFromEnv,
|
|
resolveStaticPlayOriginFromEnv,
|
|
sha256Hex,
|
|
isTopEarningGameTags,
|
|
WITHDRAWN_GAME_TEMPLATE_IDS,
|
|
type GameBundleLock,
|
|
type StaticGameDeployManifest,
|
|
type StaticGameManifestEntry,
|
|
} from '../shared/game-static-play.ts';
|
|
import { readProjectZip } from '../shared/project-zip.ts';
|
|
import { boundedMediaBody } from '../shared/repository-media.ts';
|
|
import { collectInRepoTemplateFiles, readGameDownloadsManifest } from './package-in-repo-game-templates.ts';
|
|
|
|
export type PlannedStaticTemplate = {
|
|
id: string;
|
|
source: 'in-repo' | 'r2-hosted';
|
|
topEarning: boolean;
|
|
orientation: 'portrait' | 'landscape';
|
|
lock?: GameBundleLock;
|
|
entryPath: string;
|
|
playUrl: string | null;
|
|
};
|
|
|
|
export type DeployStaticGamePlayOptions = {
|
|
templatesDir: string;
|
|
downloadsIndexPath: string;
|
|
fallbackSourceDir?: string;
|
|
outputDir?: string;
|
|
cacheDir?: string;
|
|
playOrigin?: string | null;
|
|
appOrigin?: string | null;
|
|
bundleOrigin?: string;
|
|
pathPrefix?: string;
|
|
topOnly?: boolean;
|
|
ids?: string[];
|
|
concurrency?: number;
|
|
/** Parallel object writes; uploads are many small files, so this is higher than the unpack concurrency. */
|
|
uploadConcurrency?: number;
|
|
upload?: boolean;
|
|
/** Re-upload objects whose remote ETag already matches the local MD5. */
|
|
forceUpload?: boolean;
|
|
r2Endpoint?: string;
|
|
r2Bucket?: string;
|
|
fetcher?: typeof fetch;
|
|
uploadFile?: (params: StaticUploadParams) => Promise<void>;
|
|
/** Remote object key -> ETag (MD5 hex, unquoted) for the uploaded prefixes. */
|
|
listRemoteEtags?: (params: { endpoint: string; bucket: string; prefixes: string[] }) => Promise<Map<string, string>>;
|
|
};
|
|
|
|
type StaticUploadParams = {
|
|
key: string;
|
|
filePath: string;
|
|
contentType: string;
|
|
cacheControl: string;
|
|
endpoint: string;
|
|
bucket: string;
|
|
};
|
|
|
|
export type DeployStaticGamePlayResult = {
|
|
dryRun: boolean;
|
|
plannedTotal: number;
|
|
selectedTotal: number;
|
|
inRepoCount: number;
|
|
hostedCount: number;
|
|
topEarningCount: number;
|
|
withdrawnExcluded: string[];
|
|
stagedTemplates: number;
|
|
skippedUnchangedTemplates: number;
|
|
uploadedFiles: number;
|
|
skippedUnchangedFiles: number;
|
|
playOrigin: string | null;
|
|
manifest: StaticGameDeployManifest | null;
|
|
plan: PlannedStaticTemplate[];
|
|
};
|
|
|
|
async function pathExists(target: string): Promise<boolean> {
|
|
return access(target).then(() => true, error => {
|
|
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
|
|
throw error;
|
|
});
|
|
}
|
|
|
|
async function mapConcurrent<T>(
|
|
items: readonly T[],
|
|
concurrency: number,
|
|
worker: (item: T) => Promise<void>,
|
|
): Promise<void> {
|
|
let cursor = 0;
|
|
const count = Math.max(1, Math.min(concurrency, items.length));
|
|
await Promise.all(Array.from({ length: count }, async () => {
|
|
while (cursor < items.length) {
|
|
const index = cursor++;
|
|
await worker(items[index]);
|
|
}
|
|
}));
|
|
}
|
|
|
|
function assertValidStaticR2Config(
|
|
endpointRaw: string | undefined,
|
|
bucketRaw: string | undefined,
|
|
): { endpoint: string; bucket: string } {
|
|
const endpoint = new URL(endpointRaw ?? '');
|
|
assert(
|
|
endpoint.protocol === 'https:' && endpoint.hostname.endsWith('.r2.cloudflarestorage.com') && endpoint.href === `${endpoint.origin}/`,
|
|
'GAME_PLAY_R2_ENDPOINT must be a valid https://*.r2.cloudflarestorage.com origin',
|
|
);
|
|
const bucket = bucketRaw ?? '';
|
|
assert(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(bucket), `Invalid GAME_PLAY_R2_BUCKET name: ${bucket}`);
|
|
return { endpoint: endpoint.origin, bucket };
|
|
}
|
|
|
|
let staticS3Client: { endpoint: string; client: S3Client } | null = null;
|
|
|
|
// Credentials come from the standard AWS environment (AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY) or profile.
|
|
function staticS3ClientFor(endpoint: string): S3Client {
|
|
if (staticS3Client?.endpoint !== endpoint) {
|
|
staticS3Client = { endpoint, client: new S3Client({ region: 'auto', endpoint, maxAttempts: 5 }) };
|
|
}
|
|
return staticS3Client.client;
|
|
}
|
|
|
|
/** A 115k-object upload sees the odd connection reset; retry each request with backoff instead of failing the run. */
|
|
export async function withUploadRetries<T>(label: string, run: () => Promise<T>, attempts = 6, baseDelayMs = 500): Promise<T> {
|
|
let lastError: unknown;
|
|
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
try {
|
|
return await run();
|
|
} catch (error) {
|
|
lastError = error;
|
|
if (attempt < attempts) await new Promise(resolve => setTimeout(resolve, baseDelayMs * 2 ** (attempt - 1)));
|
|
}
|
|
}
|
|
throw new Error(`${label} failed after ${attempts} attempts`, { cause: lastError });
|
|
}
|
|
|
|
async function defaultUploadStaticFile(params: StaticUploadParams): Promise<void> {
|
|
const body = await readFile(params.filePath);
|
|
await withUploadRetries(`Upload ${params.key}`, () => staticS3ClientFor(params.endpoint).send(new PutObjectCommand({
|
|
Bucket: params.bucket,
|
|
Key: params.key,
|
|
Body: body,
|
|
ContentType: params.contentType,
|
|
CacheControl: params.cacheControl,
|
|
})));
|
|
}
|
|
|
|
async function defaultListRemoteEtags(params: { endpoint: string; bucket: string; prefixes: string[] }): Promise<Map<string, string>> {
|
|
const client = staticS3ClientFor(params.endpoint);
|
|
const etags = new Map<string, string>();
|
|
for (const prefix of params.prefixes) {
|
|
let token: string | undefined;
|
|
do {
|
|
const page = await withUploadRetries(`List ${prefix}`, () => client.send(new ListObjectsV2Command({
|
|
Bucket: params.bucket,
|
|
Prefix: prefix,
|
|
ContinuationToken: token,
|
|
})));
|
|
for (const object of page.Contents ?? []) {
|
|
if (object.Key && object.ETag) etags.set(object.Key, object.ETag.replace(/"/g, ''));
|
|
}
|
|
token = page.IsTruncated ? page.NextContinuationToken : undefined;
|
|
} while (token);
|
|
}
|
|
return etags;
|
|
}
|
|
|
|
/** Bundle downloads get a floor of two minutes plus time for a slow (64 KB/s) link, so large games do not time out. */
|
|
export function bundleDownloadTimeoutMs(bytes: number): number {
|
|
return 120_000 + Math.ceil(bytes / 64_000) * 1_000;
|
|
}
|
|
|
|
async function loadTemplateCardMeta(templateDir: string, id: string): Promise<{
|
|
topEarning: boolean;
|
|
orientation: 'portrait' | 'landscape';
|
|
}> {
|
|
const raw = await readFile(path.join(templateDir, 'game.json'), 'utf8');
|
|
const card = JSON.parse(raw) as { id?: unknown; tags?: unknown; orientation?: unknown };
|
|
assert.equal(card.id, id, `game.json id mismatch in ${templateDir}`);
|
|
const topEarning = isTopEarningGameTags(card.tags as readonly string[] | null | undefined);
|
|
const orientation = card.orientation === 'portrait' ? 'portrait' : 'landscape';
|
|
return { topEarning, orientation };
|
|
}
|
|
|
|
export async function planStaticGamePlay(options: {
|
|
templatesDir: string;
|
|
downloadsIndexPath: string;
|
|
playOrigin?: string | null;
|
|
appOrigin?: string | null;
|
|
pathPrefix?: string;
|
|
topOnly?: boolean;
|
|
ids?: string[];
|
|
}): Promise<{
|
|
plan: PlannedStaticTemplate[];
|
|
allListedCount: number;
|
|
withdrawnExcluded: string[];
|
|
playOrigin: string | null;
|
|
}> {
|
|
const pathPrefix = options.pathPrefix ?? GAME_PLAY_PATH_PREFIX;
|
|
const resolvedOrigin = options.playOrigin !== undefined ? options.playOrigin : resolveStaticPlayOriginFromEnv();
|
|
const normalizedPlayOrigin = resolvedOrigin
|
|
? assertDistinctCookielessPlayOrigin(resolvedOrigin, options.appOrigin ?? process.env.APP_PUBLIC_ORIGIN).origin
|
|
: null;
|
|
|
|
const hosted = await readGameDownloadsManifest(options.downloadsIndexPath);
|
|
const dirs = (await readdir(options.templatesDir))
|
|
.filter(name => !name.startsWith('.'))
|
|
.sort();
|
|
|
|
const withdrawnExcluded: string[] = [];
|
|
const allListed: PlannedStaticTemplate[] = [];
|
|
|
|
for (const id of dirs) {
|
|
assert(isValidGameTemplateId(id), `Invalid template directory name: ${id}`);
|
|
const dir = path.join(options.templatesDir, id);
|
|
assert((await lstat(dir)).isDirectory(), `Expected directory under templatesDir: ${id}`);
|
|
if (WITHDRAWN_GAME_TEMPLATE_IDS.has(id)) {
|
|
withdrawnExcluded.push(id);
|
|
continue;
|
|
}
|
|
const hasLocalIndex = await pathExists(path.join(dir, 'index.html'));
|
|
const lock = hosted[id];
|
|
const source: 'in-repo' | 'r2-hosted' = hasLocalIndex && !lock ? 'in-repo' : 'r2-hosted';
|
|
if (source === 'r2-hosted') {
|
|
assert(lock, `Card-only template ${id} is missing from ${options.downloadsIndexPath}`);
|
|
}
|
|
const meta = await loadTemplateCardMeta(dir, id);
|
|
const entryPath = buildStaticGameEntryPath(id, pathPrefix);
|
|
const playUrl = normalizedPlayOrigin
|
|
? buildStaticGamePlayUrl(normalizedPlayOrigin, id, { prefix: pathPrefix })
|
|
: null;
|
|
allListed.push({
|
|
id,
|
|
source,
|
|
topEarning: meta.topEarning,
|
|
orientation: meta.orientation,
|
|
lock,
|
|
entryPath,
|
|
playUrl,
|
|
});
|
|
}
|
|
|
|
let selected = allListed;
|
|
if (options.ids && options.ids.length > 0) {
|
|
const wanted = new Set(options.ids);
|
|
const missing = options.ids.filter(id => !allListed.some(item => item.id === id));
|
|
assert.equal(missing.length, 0, `Requested template id(s) not found or withdrawn: ${missing.join(', ')}`);
|
|
selected = selected.filter(item => wanted.has(item.id));
|
|
}
|
|
if (options.topOnly) {
|
|
selected = selected.filter(item => item.topEarning);
|
|
}
|
|
|
|
return {
|
|
plan: selected,
|
|
allListedCount: allListed.length,
|
|
withdrawnExcluded: withdrawnExcluded.sort(),
|
|
playOrigin: normalizedPlayOrigin,
|
|
};
|
|
}
|
|
|
|
async function fetchOrCacheBundleZip(
|
|
id: string,
|
|
lock: GameBundleLock,
|
|
bundleOrigin: string,
|
|
cacheDir: string | undefined,
|
|
fetcher: typeof fetch,
|
|
): Promise<Buffer> {
|
|
const url = buildGameBundleUrl(lock.sha256, bundleOrigin);
|
|
if (cacheDir) {
|
|
const cachedFile = path.join(cacheDir, `${lock.sha256}.zip`);
|
|
if (await pathExists(cachedFile)) {
|
|
const cached = await readFile(cachedFile);
|
|
if (cached.length === lock.bytes && sha256Hex(cached) === lock.sha256) {
|
|
return cached;
|
|
}
|
|
}
|
|
}
|
|
// A 274-bundle run should not abort on one stalled CDN response; integrity is still checked below.
|
|
let archive: Buffer | undefined;
|
|
let lastError: unknown;
|
|
for (let attempt = 1; attempt <= 3 && !archive; attempt += 1) {
|
|
try {
|
|
const response = await fetcher(url, { redirect: 'error', signal: AbortSignal.timeout(bundleDownloadTimeoutMs(lock.bytes)) });
|
|
archive = await boundedMediaBody(response, lock.bytes);
|
|
} catch (error) {
|
|
lastError = error;
|
|
}
|
|
}
|
|
if (!archive) throw new Error(`Failed to download R2 bundle for ${id} after 3 attempts: ${url}`, { cause: lastError });
|
|
assert(
|
|
archive.length === lock.bytes && sha256Hex(archive) === lock.sha256,
|
|
`Downloaded R2 bundle failed integrity check for ${id}: ${url}`,
|
|
);
|
|
if (cacheDir) {
|
|
await mkdir(cacheDir, { recursive: true });
|
|
const cachedFile = path.join(cacheDir, `${lock.sha256}.zip`);
|
|
const tempFile = `${cachedFile}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;
|
|
await writeFile(tempFile, archive);
|
|
await rename(tempFile, cachedFile);
|
|
}
|
|
return archive;
|
|
}
|
|
|
|
async function collectFilesRecursively(rootDir: string, prefix = ''): Promise<string[]> {
|
|
const results: string[] = [];
|
|
const entries = (await readdir(path.join(rootDir, prefix), { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
|
|
for (const entry of entries) {
|
|
if (entry.name.startsWith('.')) continue;
|
|
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
if (entry.isDirectory()) {
|
|
results.push(...await collectFilesRecursively(rootDir, relative));
|
|
} else if (entry.isFile()) {
|
|
results.push(relative);
|
|
}
|
|
}
|
|
return results;
|
|
}
|
|
|
|
export async function deployStaticGamePlay(options: DeployStaticGamePlayOptions): Promise<DeployStaticGamePlayResult> {
|
|
const upload = Boolean(options.upload);
|
|
const pathPrefix = options.pathPrefix ?? GAME_PLAY_PATH_PREFIX;
|
|
const bundleOrigin = options.bundleOrigin ?? resolveGameBundleOriginFromEnv();
|
|
const concurrency = Math.max(1, options.concurrency ?? 8);
|
|
const uploadConcurrency = Math.max(1, options.uploadConcurrency ?? 16);
|
|
const fetcher = options.fetcher ?? globalThis.fetch;
|
|
|
|
const { plan, allListedCount, withdrawnExcluded, playOrigin } = await planStaticGamePlay({
|
|
templatesDir: options.templatesDir,
|
|
downloadsIndexPath: options.downloadsIndexPath,
|
|
playOrigin: options.playOrigin,
|
|
appOrigin: options.appOrigin,
|
|
pathPrefix,
|
|
topOnly: options.topOnly,
|
|
ids: options.ids,
|
|
});
|
|
|
|
if (upload) {
|
|
assert(playOrigin, 'GAME_PLAY_PUBLIC_ORIGIN (or --play-origin) is required when --upload is enabled');
|
|
assert(options.outputDir, '--output staging directory is required when --upload is enabled');
|
|
}
|
|
|
|
let r2Config: { endpoint: string; bucket: string } | null = null;
|
|
if (upload) {
|
|
r2Config = assertValidStaticR2Config(
|
|
options.r2Endpoint ?? process.env.GAME_PLAY_R2_ENDPOINT,
|
|
options.r2Bucket ?? process.env.GAME_PLAY_R2_BUCKET,
|
|
);
|
|
}
|
|
|
|
const inRepoCount = plan.filter(item => item.source === 'in-repo').length;
|
|
const hostedCount = plan.filter(item => item.source === 'r2-hosted').length;
|
|
const topEarningCount = plan.filter(item => item.topEarning).length;
|
|
|
|
// Pure plan-only dry run when no --output staging directory was requested.
|
|
if (!options.outputDir) {
|
|
return {
|
|
dryRun: true,
|
|
plannedTotal: allListedCount,
|
|
selectedTotal: plan.length,
|
|
inRepoCount,
|
|
hostedCount,
|
|
topEarningCount,
|
|
withdrawnExcluded,
|
|
stagedTemplates: 0,
|
|
skippedUnchangedTemplates: 0,
|
|
uploadedFiles: 0,
|
|
skippedUnchangedFiles: 0,
|
|
playOrigin,
|
|
manifest: null,
|
|
plan,
|
|
};
|
|
}
|
|
|
|
const gamesRoot = path.join(options.outputDir, pathPrefix);
|
|
await mkdir(gamesRoot, { recursive: true });
|
|
|
|
const entriesById = new Map<string, StaticGameManifestEntry>();
|
|
let stagedTemplates = 0;
|
|
let skippedUnchangedTemplates = 0;
|
|
|
|
await mapConcurrent(plan, concurrency, async item => {
|
|
let fileMap: Map<string, Buffer>;
|
|
let bundleSha256: string;
|
|
let bundleBytes: number;
|
|
|
|
if (item.source === 'in-repo') {
|
|
const templateDir = path.join(options.templatesDir, item.id);
|
|
const fallbackDir = options.fallbackSourceDir ? path.join(options.fallbackSourceDir, item.id) : undefined;
|
|
const { entries } = await collectInRepoTemplateFiles(templateDir, item.id, fallbackDir);
|
|
const archive = deflateZip(entries, { deflate: true });
|
|
assert(archive.length <= MAX_GAME_BUNDLE_BYTES, `In-repo template zip exceeds limit: ${item.id}`);
|
|
bundleSha256 = sha256Hex(archive);
|
|
bundleBytes = archive.length;
|
|
fileMap = new Map(entries.map(entry => [entry.name, entry.data]));
|
|
} else {
|
|
assert(item.lock, `Missing lock for hosted template: ${item.id}`);
|
|
const archive = await fetchOrCacheBundleZip(item.id, item.lock, bundleOrigin, options.cacheDir, fetcher);
|
|
const unzipped = readProjectZip(archive);
|
|
fileMap = new Map();
|
|
for (const [relative, data] of unzipped) {
|
|
if (!includedGameBundlePath(relative)) continue;
|
|
fileMap.set(relative, data);
|
|
}
|
|
bundleSha256 = item.lock.sha256;
|
|
bundleBytes = item.lock.bytes;
|
|
}
|
|
|
|
const rawIndex = fileMap.get('index.html');
|
|
assert(rawIndex, `Template ${item.id} is missing index.html`);
|
|
const prepared = prepareStaticPlayHtml(rawIndex);
|
|
fileMap.set('index.html', prepared.html);
|
|
|
|
const audit = auditStaticGameFiles(item.id, fileMap, { checkCover: true, requireViewport: true });
|
|
assert(audit.ok, `Static play audit failed for ${item.id}: ${audit.errors.join('; ')}`);
|
|
|
|
const targetDir = path.join(gamesRoot, item.id);
|
|
const markerPath = path.join(targetDir, '.static-play-sha256');
|
|
const expectedMarker = `${bundleSha256}:${sha256Hex(prepared.html)}`;
|
|
|
|
let alreadyStaged = false;
|
|
if (await pathExists(markerPath)) {
|
|
const existingMarker = (await readFile(markerPath, 'utf8')).trim();
|
|
if (existingMarker === expectedMarker && await pathExists(path.join(targetDir, 'index.html'))) {
|
|
alreadyStaged = true;
|
|
}
|
|
}
|
|
|
|
if (alreadyStaged) {
|
|
skippedUnchangedTemplates += 1;
|
|
} else {
|
|
const tempDir = path.join(gamesRoot, `.staging-${item.id}-${process.pid}-${Math.random().toString(16).slice(2)}`);
|
|
try {
|
|
await mkdir(tempDir, { recursive: true });
|
|
for (const [relative, data] of fileMap) {
|
|
const dest = path.join(tempDir, relative);
|
|
await mkdir(path.dirname(dest), { recursive: true });
|
|
await writeFile(dest, data);
|
|
}
|
|
await writeFile(path.join(tempDir, '.static-play-sha256'), `${expectedMarker}\n`, 'utf8');
|
|
await rm(targetDir, { recursive: true, force: true });
|
|
await rename(tempDir, targetDir);
|
|
stagedTemplates += 1;
|
|
} finally {
|
|
await rm(tempDir, { recursive: true, force: true }).catch(() => undefined);
|
|
}
|
|
}
|
|
|
|
entriesById.set(item.id, {
|
|
id: item.id,
|
|
source: item.source,
|
|
sha256: bundleSha256,
|
|
bytes: bundleBytes,
|
|
fileCount: fileMap.size,
|
|
unpackedBytes: audit.stats.totalBytes,
|
|
topEarning: item.topEarning,
|
|
orientation: item.orientation,
|
|
entryPath: item.entryPath,
|
|
playUrl: item.playUrl,
|
|
bundleUrl: buildGameBundleUrl(bundleSha256, bundleOrigin),
|
|
injectedViewport: prepared.injectedViewport,
|
|
injectedCocosGuard: prepared.injectedCocosGuard,
|
|
injectedTouchGuard: prepared.injectedTouchGuard,
|
|
});
|
|
});
|
|
|
|
const sortedEntries = [...entriesById.values()].sort((a, b) => a.id.localeCompare(b.id));
|
|
const manifest: StaticGameDeployManifest = {
|
|
schemaVersion: 1,
|
|
generatedAt: new Date().toISOString(),
|
|
playOrigin,
|
|
playPathPrefix: pathPrefix,
|
|
bundleOrigin,
|
|
totalTemplates: sortedEntries.length,
|
|
inRepoCount,
|
|
hostedCount,
|
|
topEarningCount,
|
|
withdrawnExcluded,
|
|
games: sortedEntries,
|
|
};
|
|
|
|
const manifestPath = path.join(options.outputDir, 'manifest.json');
|
|
await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
|
|
await writeFile(path.join(options.outputDir, '_headers'), buildStaticPlayHeadersFile(), 'utf8');
|
|
|
|
let uploadedFiles = 0;
|
|
let skippedUnchangedFiles = 0;
|
|
if (upload && r2Config) {
|
|
const uploadFile = options.uploadFile ?? defaultUploadStaticFile;
|
|
// Injected uploaders (tests, custom sinks) start from an empty remote unless a lister is also injected.
|
|
const listRemoteEtags = options.listRemoteEtags
|
|
?? (options.uploadFile ? async () => new Map<string, string>() : defaultListRemoteEtags);
|
|
const uploadQueue: { key: string; filePath: string; contentType: string; cacheControl: string }[] = [];
|
|
|
|
for (const entry of sortedEntries) {
|
|
const templateDir = path.join(gamesRoot, entry.id);
|
|
const relFiles = await collectFilesRecursively(templateDir);
|
|
for (const rel of relFiles) {
|
|
const key = `${pathPrefix}/${entry.id}/${rel}`;
|
|
uploadQueue.push({
|
|
key,
|
|
filePath: path.join(templateDir, rel),
|
|
contentType: contentTypeForStaticGamePath(rel),
|
|
cacheControl: cacheControlForStaticGamePath(key),
|
|
});
|
|
}
|
|
}
|
|
|
|
const remoteEtags = options.forceUpload
|
|
? new Map<string, string>()
|
|
: await listRemoteEtags({
|
|
endpoint: r2Config.endpoint,
|
|
bucket: r2Config.bucket,
|
|
prefixes: sortedEntries.map(entry => `${pathPrefix}/${entry.id}/`),
|
|
});
|
|
const pending: typeof uploadQueue = [];
|
|
for (const task of uploadQueue) {
|
|
const remote = remoteEtags.get(task.key);
|
|
if (remote && remote === createHash('md5').update(await readFile(task.filePath)).digest('hex')) {
|
|
skippedUnchangedFiles += 1;
|
|
} else {
|
|
pending.push(task);
|
|
}
|
|
}
|
|
|
|
// Write assets before entry pages and the manifest so a live page never points at files that are not there yet.
|
|
const isEntry = (key: string) => key.endsWith('/index.html');
|
|
const put = async (task: (typeof uploadQueue)[number]) => {
|
|
await uploadFile({ ...task, endpoint: r2Config!.endpoint, bucket: r2Config!.bucket });
|
|
uploadedFiles += 1;
|
|
};
|
|
await mapConcurrent(pending.filter(task => !isEntry(task.key)), uploadConcurrency, put);
|
|
await mapConcurrent(pending.filter(task => isEntry(task.key)), uploadConcurrency, put);
|
|
await put({
|
|
key: 'manifest.json',
|
|
filePath: manifestPath,
|
|
contentType: 'application/json; charset=utf-8',
|
|
cacheControl: cacheControlForStaticGamePath('manifest.json'),
|
|
});
|
|
}
|
|
|
|
return {
|
|
dryRun: !upload,
|
|
plannedTotal: allListedCount,
|
|
selectedTotal: plan.length,
|
|
inRepoCount,
|
|
hostedCount,
|
|
topEarningCount,
|
|
withdrawnExcluded,
|
|
stagedTemplates,
|
|
skippedUnchangedTemplates,
|
|
uploadedFiles,
|
|
skippedUnchangedFiles,
|
|
playOrigin,
|
|
manifest,
|
|
plan,
|
|
};
|
|
}
|
|
|
|
function parseCliArgs(argv: string[]): DeployStaticGamePlayOptions & { json: boolean } {
|
|
let templatesDir = path.resolve('templates/games');
|
|
let downloadsIndexPath = path.resolve('templates/game-downloads.json');
|
|
let fallbackSourceDir: string | undefined;
|
|
let outputDir: string | undefined;
|
|
let cacheDir: string | undefined;
|
|
let playOrigin: string | null | undefined;
|
|
let appOrigin: string | null | undefined;
|
|
let bundleOrigin: string | undefined;
|
|
let pathPrefix: string | undefined;
|
|
let topOnly = false;
|
|
let ids: string[] | undefined;
|
|
let concurrency = 8;
|
|
let uploadConcurrency = 16;
|
|
let upload = false;
|
|
let forceUpload = false;
|
|
let json = false;
|
|
|
|
for (let i = 0; i < argv.length; i += 1) {
|
|
const arg = argv[i];
|
|
if (arg === '--templates-dir') templatesDir = path.resolve(argv[++i]);
|
|
else if (arg === '--downloads-index') downloadsIndexPath = path.resolve(argv[++i]);
|
|
else if (arg === '--fallback-source-dir') fallbackSourceDir = path.resolve(argv[++i]);
|
|
else if (arg === '--output') outputDir = path.resolve(argv[++i]);
|
|
else if (arg === '--cache-dir') cacheDir = path.resolve(argv[++i]);
|
|
else if (arg === '--play-origin') playOrigin = argv[++i];
|
|
else if (arg === '--app-origin') appOrigin = argv[++i];
|
|
else if (arg === '--bundle-origin') bundleOrigin = argv[++i];
|
|
else if (arg === '--path-prefix') pathPrefix = argv[++i];
|
|
else if (arg === '--top-only') topOnly = true;
|
|
else if (arg === '--ids') ids = argv[++i].split(',').map(s => s.trim()).filter(Boolean);
|
|
else if (arg === '--concurrency') concurrency = Number(argv[++i]);
|
|
else if (arg === '--upload-concurrency') uploadConcurrency = Number(argv[++i]);
|
|
else if (arg === '--upload') upload = true;
|
|
else if (arg === '--force-upload') forceUpload = true;
|
|
else if (arg === '--dry-run') upload = false;
|
|
else if (arg === '--json') json = true;
|
|
else throw new Error(`Unknown option: ${arg}`);
|
|
}
|
|
|
|
return {
|
|
templatesDir,
|
|
downloadsIndexPath,
|
|
fallbackSourceDir,
|
|
outputDir,
|
|
cacheDir,
|
|
playOrigin,
|
|
appOrigin,
|
|
bundleOrigin,
|
|
pathPrefix,
|
|
topOnly,
|
|
ids,
|
|
concurrency,
|
|
uploadConcurrency,
|
|
upload,
|
|
forceUpload,
|
|
json,
|
|
};
|
|
}
|
|
|
|
if (isMain(import.meta.url)) {
|
|
const cli = parseCliArgs(process.argv.slice(2));
|
|
const result = await deployStaticGamePlay(cli);
|
|
if (cli.json) {
|
|
console.log(JSON.stringify({ ...result, plan: undefined, manifest: result.manifest ? { ...result.manifest, games: undefined } : null }, null, 2));
|
|
} else {
|
|
const mode = result.dryRun ? 'DRY-RUN' : 'UPLOAD';
|
|
console.log(
|
|
`[${mode}] Selected ${result.selectedTotal}/${result.plannedTotal} official templates ` +
|
|
`(${result.inRepoCount} in-repo, ${result.hostedCount} R2-hosted, ${result.topEarningCount} TOP赚钱; ` +
|
|
`excluded ${result.withdrawnExcluded.length} withdrawn: ${result.withdrawnExcluded.join(', ') || 'none'})`,
|
|
);
|
|
if (result.playOrigin) {
|
|
console.log(`Target cookieless static play origin: ${result.playOrigin}`);
|
|
}
|
|
if (cli.outputDir) {
|
|
console.log(`Staged ${result.stagedTemplates} template(s), skipped ${result.skippedUnchangedTemplates} unchanged in ${cli.outputDir}`);
|
|
}
|
|
if (!result.dryRun) {
|
|
console.log(
|
|
`Uploaded ${result.uploadedFiles} static file(s) to cookieless static playable bucket, ` +
|
|
`skipped ${result.skippedUnchangedFiles} unchanged`,
|
|
);
|
|
}
|
|
}
|
|
}
|