Skip to content

Commit

Permalink
syntax validation in build.js
Browse files Browse the repository at this point in the history
  • Loading branch information
olegkron committed Nov 28, 2024
1 parent 03e6c7e commit 6a983c1
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions tasks/CLFScripts/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {task, types} from 'hardhat/config';
import log, {err} from '../../utils/log';
import fs from 'fs';
import path from 'path';

import vm from 'vm';
export const pathToScript = [__dirname, '../', 'CLFScripts'];

function checkFileAccessibility(filePath) {
Expand All @@ -17,6 +17,22 @@ function checkFileAccessibility(filePath) {
}
}

/* Validates the JavaScript syntax of the file content */
function validateSyntax(content, filePath) {
const ignoredErrors = [
'Cannot use import statement outside a module',
'await is only valid in async functions and the top level bodies of modules',
];
try {
new vm.Script(content);
} catch (error) {
if (ignoredErrors.includes(error.message)) return;

err(`Syntax error in file ${filePath}: ${error.message}`, 'validateSyntax');
process.exit(1);
}
}

/* replaces any strings of the form ${VAR_NAME} with the value of the environment variable VAR_NAME */
function replaceEnvironmentVariables(content) {
let missingVariable = false;
Expand Down Expand Up @@ -76,6 +92,8 @@ function build(fileToBuild: string, quiet: boolean): void {

try {
let fileContent = fs.readFileSync(fileToBuild, 'utf8');
validateSyntax(fileContent, fileToBuild);

fileContent = replaceEnvironmentVariables(fileContent);
const cleanedUpFile = cleanupFile(fileContent);
const minifiedFile = minifyFile(cleanedUpFile);
Expand All @@ -85,9 +103,10 @@ function build(fileToBuild: string, quiet: boolean): void {
scriptType = 'infra';
}

// Save the cleaned-up and minified versions
saveProcessedFile(cleanedUpFile, fileToBuild, scriptType, quiet);
saveProcessedFile(minifiedFile, fileToBuild.replace('.js', '.min.js'), scriptType, quiet);
validateSyntax(cleanedUpFile, fileToBuild);
validateSyntax(minifiedFile, fileToBuild);
} catch (error) {
err(`Error processing file ${fileToBuild}: ${error}`, 'buildScript');
process.exit(1);
Expand Down

0 comments on commit 6a983c1

Please sign in to comment.