build(server): compile with SWC instead of tsc so the build fits a small container

tsc needed about 3.4 GB of heap for the server build, all of it for the type graph, while the build never failed on type errors anyway. An install that builds from source on a 4 GB container (the Proxmox script gives Node 75% of its memory) ran out of heap with 5.2.2. SWC compiles the files tsconfig.build.json names, one at a time and with the options read from it, in about a second and 130 MB; the type check stays with npm run typecheck in CI. Built with both on the same commit, dist holds the same 2390 files, and the server boots with the same 859 routes and 226 modules and answers the same requests the same way.
This commit is contained in:
Maurice
2026-11-28 20:34:17 +01:00
parent c39f739b7f
commit 94163f76e0
5 changed files with 159 additions and 33 deletions
+61
View File
@@ -0,0 +1,61 @@
import ts from 'typescript';
/**
* The SWC options for `npm run build`, read from the tsconfig the build used to
* hand to tsc, so the compiler options stay written in one place. Only the
* settings the server is built with are translated; anything else stops the
* build instead of compiling differently from what the tsconfig says.
*
* @param {import('typescript').CompilerOptions} options
* @returns {import('@swc/core').Options}
*/
export function swcOptionsFrom(options) {
if (options.module !== ts.ModuleKind.CommonJS) {
throw new Error(
`[build] only CommonJS output is translated, the tsconfig asks for ${ts.ModuleKind[options.module]}`,
);
}
if (!options.esModuleInterop) {
throw new Error('[build] only esModuleInterop output is translated');
}
if (options.emitDecoratorMetadata && !options.experimentalDecorators) {
throw new Error('[build] emitDecoratorMetadata without experimentalDecorators is not translated');
}
const target = options.target ?? ts.ScriptTarget.ES5;
return {
swcrc: false,
configFile: false,
sourceMaps: Boolean(options.sourceMap),
jsc: {
parser: { syntax: 'typescript', decorators: Boolean(options.experimentalDecorators) },
target: ts.ScriptTarget[target].toLowerCase(),
transform: {
legacyDecorator: Boolean(options.experimentalDecorators),
decoratorMetadata: Boolean(options.emitDecoratorMetadata),
// tsc's own default: class fields are defined, not assigned, from ES2022 on.
useDefineForClassFields: options.useDefineForClassFields ?? target >= ts.ScriptTarget.ES2022,
},
},
module: { type: 'commonjs' },
};
}
/**
* A tsconfig file as tsc reads it: `extends` resolved, its options and the files it compiles.
*
* @param {string} tsconfigPath
* @returns {import('typescript').ParsedCommandLine}
*/
export function readTsconfig(tsconfigPath) {
const parsed = ts.getParsedCommandLineOfConfigFile(tsconfigPath, undefined, {
...ts.sys,
onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'));
},
});
if (!parsed) throw new Error(`[build] cannot read ${tsconfigPath}`);
if (parsed.errors.length > 0) {
throw new Error(parsed.errors.map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n')).join('\n'));
}
return parsed;
}
+33 -28
View File
@@ -1,40 +1,45 @@
import { execSync } from 'node:child_process';
import { existsSync, rmSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { readTsconfig, swcOptionsFrom } from './build-options.mjs';
import { transformFileSync } from '@swc/core';
import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
// Resolved from this file rather than cwd, so the directory that gets removed is
// always this package's own dist no matter where the script is invoked from.
const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
const distDir = join(packageRoot, 'dist');
// tsc only ever adds to dist, so a module deleted or renamed in src leaves its
// compiled twin behind. For most code that is merely stale, but the migrator
// globs dist/db/migrations at boot: an orphan there is a live migration with no
// source, and it runs. Same for dist/db/seeders. Nothing else writes into dist —
// the client bundle goes to server/public and the runtime assets the Dockerfile
// needs are copied in separately — so it is safe to drop wholesale.
rmSync(distDir, { recursive: true, force: true });
// SWC compiles each file on its own, the way the test suite runs the code, and
// never builds the type graph: tsc needed more than 3 GB of heap for that alone,
// more than an install building on a small container has. Type errors are the
// job of `npm run typecheck`, which CI runs; the build never failed on them. The
// files, the directories and the compiler options are the ones tsc would take
// from tsconfig.build.json.
const tsconfig = readTsconfig(join(packageRoot, 'tsconfig.build.json'));
const { rootDir, outDir } = tsconfig.options;
const swcOptions = swcOptionsFrom(tsconfig.options);
let tscExitedNonZero = false;
try {
execSync('tsc -p tsconfig.build.json', { stdio: 'inherit', cwd: packageRoot });
} catch {
tscExitedNonZero = true;
// A module deleted or renamed in src would otherwise leave its compiled twin
// behind. For most code that is merely stale, but the migrator globs
// dist/db/migrations at boot: an orphan there is a live migration with no
// source, and it runs. Same for dist/db/seeders. Nothing else writes into dist,
// since the client bundle goes to server/public and the runtime assets the
// Dockerfile needs are copied in separately, so it is safe to drop wholesale.
rmSync(outDir, { recursive: true, force: true });
let count = 0;
for (const file of tsconfig.fileNames) {
if (file.endsWith('.d.ts')) continue;
if (!file.endsWith('.ts')) throw new Error(`[build] ${file}: only .ts sources are compiled`);
const out = join(outDir, relative(rootDir, file)).replace(/\.ts$/, '.js');
mkdirSync(dirname(out), { recursive: true });
writeFileSync(out, transformFileSync(file, swcOptions).code);
count++;
}
// `noEmitOnError` is off, so tsc exits non-zero on type errors and still writes
// dist — that case is deliberate, and gated by `npm run typecheck`. A tsc that
// never ran at all (not on PATH, crashed) is indistinguishable from here, and
// now that dist is emptied first it would leave nothing behind while still
// reporting success. Checking for the entry point tells the two apart.
if (!existsSync(join(distDir, 'index.js'))) {
console.error('[build] tsc emitted nothing — dist is empty. Run via `npm run build` so tsc is on PATH.');
if (!existsSync(join(outDir, 'index.js'))) {
console.error(`[build] ${join(outDir, 'index.js')} is missing after compiling ${count} files.`);
process.exit(1);
}
if (tscExitedNonZero) {
console.warn('[build] tsc reported type errors — emitting anyway (gated by `npm run typecheck`).');
}
console.log('[build] dist ready.');
console.log(`[build] dist ready (${count} files).`);