Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

5.7 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    check-examples.js
 * @brief   Type-check all example projects against current SDK/editor types
 */

import { existsSync, readdirSync, statSync, mkdirSync, symlinkSync, rmSync, lstatSync, unlinkSync } from 'fs';
import path from 'path';
import { execSync } from 'child_process';
import { fileURLToPath } from 'url';
import * as logger from '../utils/logger.js';
import { exampleFailureLines } from '../utils/exampleDiagnostics.js';

// Every project directory that ships to users: the examples plus the editor's
// bundled new-project templates (templates/).
const PROJECT_ROOTS = ['examples', 'templates'];

function discoverExamples(rootDir) {
    const out = [];
    for (const rel of PROJECT_ROOTS) {
        const rootPath = path.join(rootDir, rel);
        if (!existsSync(rootPath)) continue;
        for (const entry of readdirSync(rootPath)) {
            const fullPath = path.join(rootPath, entry);
            if (statSync(fullPath).isDirectory() &&
                existsSync(path.join(fullPath, 'tsconfig.json')) &&
                existsSync(path.join(fullPath, 'src'))) {
                out.push({ name: entry, dir: fullPath });
            }
        }
    }
    return out;
}

// A directory SYMLINK needs a privilege Windows grants only under Developer Mode
// or elevation, so the gate reported all 53 examples broken on a plain checkout.
// A junction resolves the same and needs none.
const LINK_TYPE = process.platform === 'win32' ? 'junction' : 'dir';

function setupTypeLinks(exampleDir, rootDir) {
    const sdkDist = path.join(rootDir, 'sdk', 'dist');
    const editorDist = path.join(rootDir, 'editor', 'dist');

    if (!existsSync(sdkDist)) {
        throw new Error(`SDK dist not found at ${sdkDist}. Run "pnpm --filter ./sdk build" first.`);
    }

    const esengineDir = path.join(exampleDir, '.esengine');
    const sdkLink = path.join(esengineDir, 'sdk');
    const editorLink = path.join(esengineDir, 'editor');
    const packagesLink = path.join(esengineDir, 'packages');

    mkdirSync(esengineDir, { recursive: true });

    // Always relink to the LIVE dist: the editor stages a real-directory type
    // mirror at the same path when a project is opened, and a stale mirror
    // would silently shadow current SDK types (checks would fail — or pass —
    // against an old API). The mirror is a disposable cache; the editor
    // re-stages it on the next open.
    rmSync(sdkLink, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
    symlinkSync(sdkDist, sdkLink, LINK_TYPE);

    // What the editor mirrors on open: the official packages, which a project's
    // tsconfig maps as `estella-plugin-*` → ./.esengine/packages/*.
    rmSync(packagesLink, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
    symlinkSync(path.join(rootDir, 'plugins'), packagesLink, LINK_TYPE);

    if (existsSync(editorDist)) {
        rmSync(editorLink, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
        symlinkSync(editorDist, editorLink, LINK_TYPE);
    }
}

function isSymlinkOrExists(p) {
    try { lstatSync(p); return true; } catch { return false; }
}

function cleanTypeLinks(exampleDir) {
    const sdkLink = path.join(exampleDir, '.esengine', 'sdk');
    const editorLink = path.join(exampleDir, '.esengine', 'editor');
    const packagesLink = path.join(exampleDir, '.esengine', 'packages');

    try { if (isSymlinkOrExists(sdkLink)) unlinkSync(sdkLink); } catch {}
    try { if (isSymlinkOrExists(packagesLink)) unlinkSync(packagesLink); } catch {}
    try { if (isSymlinkOrExists(editorLink)) unlinkSync(editorLink); } catch {}
}

export async function checkExamples(rootDir) {
    logger.step('Type-checking example projects...');

    const examples = discoverExamples(rootDir);
    if (examples.length === 0) {
        logger.warn('No example projects found');
        return { passed: 0, failed: 0, errors: [] };
    }

    const sdkDist = path.join(rootDir, 'sdk', 'dist');
    if (!existsSync(sdkDist)) {
        logger.error('SDK dist not found. Build SDK first: pnpm --filter ./sdk build');
        process.exit(1);
    }

    const tscCandidates = [
        path.join(rootDir, 'node_modules', 'typescript', 'bin', 'tsc'),
        path.join(rootDir, 'sdk', 'node_modules', 'typescript', 'bin', 'tsc'),
        path.join(rootDir, 'editor', 'node_modules', 'typescript', 'bin', 'tsc'),
    ];
    const tscBin = tscCandidates.find(p => existsSync(p));
    if (!tscBin) {
        logger.error('TypeScript not found. Run "pnpm install" first.');
        process.exit(1);
    }

    const results = { passed: 0, failed: 0, errors: [] };

    for (const example of examples) {
        try {
            setupTypeLinks(example.dir, rootDir);
            execSync(`node ${tscBin} --noEmit`, {
                cwd: example.dir,
                stdio: 'pipe',
                timeout: 30000,
            });
            logger.success(example.name);
            results.passed++;
        } catch (err) {
            logger.error(`${example.name}`);
            const lines = exampleFailureLines(err);
            for (const line of lines.slice(0, 10)) {
                logger.error(`  ${line.trim()}`);
            }
            if (lines.length > 10) {
                logger.error(`  ... and ${lines.length - 10} more errors`);
            }
            results.failed++;
            results.errors.push({ name: example.name, errors: lines });
        } finally {
            cleanTypeLinks(example.dir);
        }
    }

    logger.step(`Results: ${results.passed} passed, ${results.failed} failed out of ${examples.length} examples`);

    if (results.failed > 0) {
        process.exitCode = 1;
    }

    return results;
}