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
+1 -3
View File
@@ -41,9 +41,7 @@ COPY server/package.json ./server/
RUN npm ci --workspace=server --ignore-scripts
COPY --from=shared-builder /app/shared/dist ./shared/dist
COPY server/ ./server/
# tsc needs more than the 2 GB heap Node picks on a host with about 12 GB of RAM;
# on a bigger build machine the default is larger, so only small hosts failed.
RUN NODE_OPTIONS=--max-old-space-size=4096 npm run build --workspace=server
RUN npm run build --workspace=server
# ── Stage 4: production runtime ──────────────────────────────────────────────
FROM node:24-trixie-slim
+2 -2
View File
@@ -6,7 +6,7 @@ Scope: the **`@trek/server`** workspace. See the repo-root `CLAUDE.md` for the m
```bash
npm run dev # scripts/dev.mjs: tsc -w then node --watch dist/index.js (server on :3001)
npm run build # scripts/build.mjs — emits even on type errors (see below)
npm run build # scripts/build.mjs: SWC, no type check (see below)
npm run typecheck # tsc --noEmit — the real type gate
npm run typecheck:tests # tsc over tests/ — CI runs this too; vitest green does NOT mean typed mocks compile
npm run lint # eslint, no fix
@@ -65,7 +65,7 @@ npm run contracts:dto-open # open shapes in the createZodDto schemas may only sh
Single test: `npx vitest run tests/unit/nest/weather.controller.test.ts`, or `npx vitest run -t "returns 401 without cookie"`.
**Build emits even with type errors** (`scripts/build.mjs` catches `tsc` failures and warns). `npm run build` succeeding does **not** mean the code typechecks — run `npm run typecheck`.
**The build does not typecheck.** `scripts/build.mjs` compiles every file of `tsconfig.build.json` with SWC, one file at a time and with the options `scripts/build-options.mjs` reads from that tsconfig (an option it does not translate stops the build), the way vitest runs the code; it takes about a second and little memory, where tsc needed more than 3 GB of heap for the type graph. `npm run build` succeeding does **not** mean the code typechecks: run `npm run typecheck`, which CI does.
**`lint:dialect`** (`scripts/dialect-lint.mjs`) reads every string and template literal under `src/` (comments do not count), every `.insertId` read and every MikroORM `$like`, and counts the SQLite-only spellings per file and rule: `INSERT OR IGNORE`/`REPLACE`, `datetime()`/`julianday()`/`unixepoch()` (also as the bare name handed to `eb.fn`), `strftime`, `json_extract` and its siblings (`json_object()`, `json_array()`, `json_valid()`, `json_type()`, `json_quote()` as calls), the SQLite-only functions `group_concat`, `ifnull`, `instr`, `iif`, `printf`, `typeof` (as calls or as the bare name handed to `eb.fn`) and `total(`/`changes(`, `GLOB`, `last_insert_rowid`, `AUTOINCREMENT`, a `PRAGMA` statement outside the `src/db/*.ts` lifecycle files and the migrations, `||` concatenation in SQL, and `like`: LIKE in SQL text, Kysely's `'like'`/`'not like'` operator and `$like`, which ignore case on SQLite only. A LIKE that is exact on purpose (a settings key, a storage path) carries a `// like-exact: <reason>` comment on its line or the line above; a case-insensitive search uses `ilike()`. The counts are held to `scripts/dialect-baseline.json`; a new hit fails, and so does an entry above what its file holds now, so the change that removes one runs `npm run lint:dialect -- --update` (it never raises or adds an entry). The dialect layer `src/db/dialect/` and the SQLite engine's own code `src/db/engine/sqlite/` are not scanned, and neither are the migrations up to `FROZEN_MIGRATIONS_THROUGH` in the script; a newer migration is held to the DML rules (`like` only after the cut). A migration after the Postgres baseline's cut (`through` in `assets/postgres/baseline.json`, read on every run, or `POSTGRES_FIRST_CUT` in the script when that comes first, so regenerating the baseline over a migration never takes it off these rules) is also held to rules no baseline entry can excuse: `ddl` (a CREATE/ALTER/DROP of a table, index, trigger or view, or a RENAME, outside `engineDdl`; a plain string as `addColumnIfMissing`'s column; a call to the SQLite-only `tableSql` or `createPlaceRegionsFollowPlaceTrigger`), `sqlite-ddl` (DATETIME, AUTOINCREMENT, INTEGER PRIMARY KEY, WITHOUT ROWID, PRAGMA or a SQLite-only function in an `engineDdl` postgres member), `sqlite-member` (an `engineDdl` sqlite member holding anything but inline schema statements: CREATE/DROP of a table, index or view, ALTER TABLE, PRAGMA, and for a rebuild the `INSERT INTO <new table> ... SELECT` and the `sqlite_sequence` statements; a trigger or a data change there would never reach Postgres), `empty-postgres` (SQLite statements with an empty postgres member and no `// sqlite-only: <reason>` comment above it) and `best-effort` (`execBestEffort`, `bestEffort`, `execUnlessTableMissing`, whose swallowed failure aborts the transaction every pending migration runs in on Postgres). The routine under SQL dialect, Migrations, is what satisfies them.
+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).`);
@@ -0,0 +1,62 @@
import { readTsconfig, swcOptionsFrom } from '../../../scripts/build-options.mjs';
import { transformSync } from '@swc/core';
import { join } from 'node:path';
import ts from 'typescript';
import { describe, expect, it } from 'vitest';
// BUILD-001 to BUILD-005: `npm run build` compiles with SWC, from the options
// tsc would read in tsconfig.build.json.
const serverRoot = join(__dirname, '..', '..', '..');
const buildConfig = () => readTsconfig(join(serverRoot, 'tsconfig.build.json'));
const base = { module: ts.ModuleKind.CommonJS, esModuleInterop: true, target: ts.ScriptTarget.ES2022 };
describe('build options', () => {
it('BUILD-001: translates tsconfig.build.json the way tsc reads it', () => {
const { options, fileNames } = buildConfig();
expect(swcOptionsFrom(options)).toEqual({
swcrc: false,
configFile: false,
sourceMaps: false,
jsc: {
parser: { syntax: 'typescript', decorators: true },
target: 'es2022',
transform: { legacyDecorator: true, decoratorMetadata: true, useDefineForClassFields: true },
},
module: { type: 'commonjs' },
});
expect(fileNames.some((f) => f.endsWith('/src/index.ts'))).toBe(true);
expect(fileNames.some((f) => /\.(test|spec)\.ts$/.test(f))).toBe(false);
});
it('BUILD-002: emits the constructor metadata Nest injects by', () => {
const source = `
function Injectable(): ClassDecorator { return () => undefined; }
class Repo {}
@Injectable()
export class Service { constructor(readonly repo: Repo) {} }`;
const { code } = transformSync(source, swcOptionsFrom(buildConfig().options));
expect(code).toMatch(/"design:paramtypes",\s*\[\s*typeof Repo === "undefined" \? Object : Repo\s*\]/);
});
it('BUILD-003: defines class fields from ES2022 on, as tsc does, unless the tsconfig says otherwise', () => {
expect(swcOptionsFrom(base).jsc.transform.useDefineForClassFields).toBe(true);
expect(swcOptionsFrom({ ...base, target: ts.ScriptTarget.ES2021 }).jsc.transform.useDefineForClassFields).toBe(
false,
);
expect(swcOptionsFrom({ ...base, useDefineForClassFields: false }).jsc.transform.useDefineForClassFields).toBe(
false,
);
});
it('BUILD-004: refuses a module format or interop it does not translate', () => {
expect(() => swcOptionsFrom({ ...base, module: ts.ModuleKind.ESNext })).toThrow(/only CommonJS/);
expect(() => swcOptionsFrom({ ...base, esModuleInterop: false })).toThrow(/esModuleInterop/);
expect(() => swcOptionsFrom({ ...base, emitDecoratorMetadata: true })).toThrow(/experimentalDecorators/);
});
it('BUILD-005: a tsconfig that cannot be read stops the build', () => {
expect(() => readTsconfig(join(serverRoot, 'does-not-exist.json'))).toThrow();
});
});