/* eslint-disable import/prefer-default-export */ import { readFile } from 'fs-extra'; import yargs = require('yargs'); export const isAutoGeneratedFile = (content: string) => { content = content .replace(/\r\n/g, '\n') .trim(); type Quotes = '"'|'\''; const fileStart = (quotes: Quotes) => `${quotes}use strict${quotes};`; // Check both quote formats: If the file has been processed by eslint, it will use single quotes, // while files generated by tsc usually use double quotes. const matchesStart = content.startsWith(fileStart('"')) || content.startsWith(fileStart('\'')); const hasSourceMap = !!content.match(/\/\/\s?# sourceMappingURL=.+\.map$/); const hasIgnore = content.includes('// ignore: generated check'); return matchesStart && hasSourceMap && !hasIgnore; }; const main = async () => { const argv = await yargs.argv; const filePaths = argv._ as string[]; if (!filePaths || !filePaths.length) return; const generatedFiles = []; for (const filePath of filePaths) { const content = await readFile(filePath, 'utf8'); if (isAutoGeneratedFile(content)) { generatedFiles.push(filePath); } } if (generatedFiles.length) { throw new Error([ 'The following .js file(s) appear to be generated from .ts files:', `\t${generatedFiles.join(', ')}`, 'If any of the above files are not auto-generated, please add a brief comment (e.g. // ignore: generated check)', 'to disable this check.', ].join('\n')); } }; if (require.main === module) { void (async () => { try { await main(); } catch (error) { console.error(error); process.exit(1); } })(); }