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