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(); }); });