Skip to content

Instantly share code, notes, and snippets.

@kevinbuhmann
Last active February 27, 2020 05:57
Show Gist options
  • Save kevinbuhmann/fb368ea8a59721640e54f5a53b02be16 to your computer and use it in GitHub Desktop.
Save kevinbuhmann/fb368ea8a59721640e54f5a53b02be16 to your computer and use it in GitHub Desktop.
export function fileExists(filePath: string) {
return fs.existsSync(filePath);
}
export function readFile(filePath: string) {
return fs.readFileSync(filePath).toString();
}
export function writeFile(filePath: string, contents: string, silent = false) {
filePath = path.normalize(filePath);
ensureDirectoryExists(filePath);
fs.writeFileSync(filePath, contents);
if (!silent) {
console.log(`${filePath} written.`);
}
}
export function ensureDirectoryExists(filePath: string) {
const dirname = path.dirname(filePath);
if (!fs.existsSync(dirname) || !fs.statSync(dirname).isDirectory()) {
ensureDirectoryExists(dirname);
fs.mkdirSync(dirname);
}
}
// Super hacky hack. This is a workaround for https://github.com/angular/angular-cli/issues/8412.
import * as chokidar from 'chokidar';
import * as path from 'path';
import * as Lint from 'tslint';
import * as ts from 'typescript';
import { fileExists, readFile, writeFile } from './lib/helpers';
const invalidTypes = ['Document', 'Event', 'KeyboardEvent', 'MouseEvent'];
const serverBundleFilePath = path.resolve('./dist/server/main.bundle.js');
patchServerBundle();
const watcher = chokidar.watch(path.dirname(serverBundleFilePath), { persistent: true });
watcher.on('add', handleFileChange);
watcher.on('change', handleFileChange);
function handleFileChange(filePath: string) {
if (path.resolve(filePath) === serverBundleFilePath) {
patchServerBundle();
}
}
function patchServerBundle() {
if (fileExists(serverBundleFilePath)) {
const serverBundleOriginalSource = readFile(serverBundleFilePath);
const serverBundleSourceFile = ts.createSourceFile(serverBundleFilePath, serverBundleOriginalSource, ts.ScriptTarget.ES2015, true);
const serverBundlePatchedSource = Lint.Replacement.applyFixes(serverBundleOriginalSource, walk(serverBundleSourceFile));
if (serverBundleOriginalSource !== serverBundlePatchedSource) {
writeFile(serverBundleFilePath, serverBundlePatchedSource);
}
}
}
function walk(sourceFile: ts.SourceFile) {
const replacements: Lint.Replacement[] = [];
ts.forEachChild(sourceFile, function visit(node) {
if (ts.isCallExpression(node) && node.expression.getText() === '__metadata') {
const types = node.arguments[1];
if (ts.isArrayLiteralExpression(types)) {
for (const element of types.elements) {
if (invalidTypes.includes(element.getText())) {
replacements.push(new Lint.Replacement(element.getStart(), element.getWidth(), 'Object'));
}
}
}
}
ts.forEachChild(node, visit);
});
return replacements;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment