Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

5.7 KB
Raw Blame
#!/usr/bin/env node
// Generate the runtime-extension vendor shims from one source of truth.
//
// A shim hands a runtime-loaded extension the HOST's instance of a module
// (captured in globalThis.__SK_VENDOR__ by vendorShare.js) instead of letting
// the extension bundle its own — two copies of React means "Invalid hook
// call", and two copies of i18next means an extension whose translations
// silently never load.
//
// Every shim is the same six lines around a list of export names, so the lists
// are DERIVED, never typed: from the real package's namespace for vendored
// modules, and from the SDK entry's own export statements for the SDK. Three
// hand-maintained copies of those lists is what produced the two bugs this
// replaces (see src/plugins/runtime/vendorManifest.js).
//
// Usage (from frontend/):
//   node scripts/generate-vendor-shims.mjs           # write the shims
//   node scripts/generate-vendor-shims.mjs --check   # fail if they drift

import { readFileSync, readdirSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parse } from 'espree';
import { VENDOR_MODULES } from '../src/plugins/runtime/vendorManifest.js';

const here = dirname(fileURLToPath(import.meta.url));
const root = resolve(here, '..');
const outDir = resolve(root, 'public', 'serverkit-vendor');
const sdkEntry = resolve(root, 'src', 'plugins', 'sdk', 'index.js');
const vendorShare = resolve(root, 'src', 'plugins', 'runtime', 'vendorShare.js');

/** Export names of the SDK entry, read from its own export statements. */
function sdkExportNames() {
    const ast = parse(readFileSync(sdkEntry, 'utf8'), {
        ecmaVersion: 'latest',
        sourceType: 'module',
    });
    const names = [];
    for (const node of ast.body) {
        if (node.type === 'ExportNamedDeclaration') {
            for (const specifier of node.specifiers || []) {
                names.push(specifier.exported.name);
            }
            const declaration = node.declaration;
            if (declaration?.type === 'VariableDeclaration') {
                for (const d of declaration.declarations) names.push(d.id.name);
            } else if (declaration?.id) {
                names.push(declaration.id.name);
            }
        }
    }
    // `default` cannot be re-exported as a const; the SDK has no default anyway.
    return [...new Set(names)].filter((name) => name !== 'default');
}

/** Export names of a real package, read from its namespace object. */
async function moduleExportNames(specifier) {
    const namespace = await import(specifier);
    return Object.keys(namespace)
        .filter((name) => name !== 'default')
        // Valid identifiers only — a namespace can carry exotic keys that
        // cannot appear on the left of `export const`.
        .filter((name) => /^[A-Za-z_$][\w$]*$/.test(name))
        .sort();
}

function render(specifier, names, hasDefault) {
    const lines = [
        '// GENERATED by scripts/generate-vendor-shims.mjs — do not edit.',
        `// Runtime-extension shim for \`${specifier}\`: re-exports the HOST instance so`,
        '// the extension and the panel share one copy (see vendorManifest.js).',
        `const m = (globalThis.__SK_VENDOR__ || {})['${specifier}'];`,
        'if (!m) {',
        `    throw new Error('[serverkit] host ${specifier} unavailable — vendorShare did not run');`,
        '}',
    ];
    if (hasDefault) lines.push('export default m.default ?? m;');
    for (const name of names) lines.push(`export const ${name} = m.${name};`);
    return `${lines.join('\n')}\n`;
}

const generated = new Map();
for (const entry of VENDOR_MODULES) {
    let names;
    let hasDefault = false;
    if (entry.exportsFrom === 'sdk') {
        names = sdkExportNames();
    } else {
        const namespace = await import(entry.specifier);
        hasDefault = 'default' in namespace;
        names = await moduleExportNames(entry.specifier);
    }
    generated.set(entry.file, render(entry.specifier, names, hasDefault));
}

// vendorShare.js must capture exactly these specifiers, or a shim resolves to
// undefined at runtime with a misleading "did not run" message.
const shareSource = readFileSync(vendorShare, 'utf8');
const missingShare = VENDOR_MODULES
    .map((entry) => entry.specifier)
    .filter((specifier) => !shareSource.includes(`'${specifier}':`));

const problems = [];
if (missingShare.length) {
    problems.push(`vendorShare.js does not capture: ${missingShare.join(', ')}`);
}

if (process.argv.includes('--check')) {
    const onDisk = new Set(readdirSync(outDir).filter((name) => name.endsWith('.mjs')));
    for (const [file, contents] of generated) {
        if (!onDisk.has(file)) {
            problems.push(`missing shim: ${file}`);
            continue;
        }
        onDisk.delete(file);
        if (readFileSync(join(outDir, file), 'utf8') !== contents) {
            problems.push(`stale shim: ${file}`);
        }
    }
    for (const orphan of onDisk) problems.push(`orphan shim (not in the manifest): ${orphan}`);

    if (problems.length) {
        console.error('\nvendor shim check failed:\n');
        for (const problem of problems) console.error(`  ${problem}`);
        console.error('\n  node scripts/generate-vendor-shims.mjs\n');
        process.exit(1);
    }
    console.log(`✓ vendor shims: ${generated.size} shims match the manifest.`);
    process.exit(0);
}

if (problems.length) {
    console.error('\nvendor shim generation failed:\n');
    for (const problem of problems) console.error(`  ${problem}`);
    console.error('');
    process.exit(1);
}

for (const [file, contents] of generated) {
    writeFileSync(join(outDir, file), contents);
}
console.log(`✓ wrote ${generated.size} vendor shims to public/serverkit-vendor/.`);