From 78f503256a0bf4368bc8cb2e3258f5ad39985c65 Mon Sep 17 00:00:00 2001 From: Angelina Date: Sat, 20 Jul 2024 14:25:43 -0400 Subject: [PATCH 1/4] bug[website-builder]: [issue#1057 correct functions and convert to ts] --- index.js => index.ts | 64 +++++++++++++++++++++++++++++--------------- package-lock.json | 1 + package.json | 4 +-- 3 files changed, 45 insertions(+), 24 deletions(-) rename index.js => index.ts (55%) diff --git a/index.js b/index.ts similarity index 55% rename from index.js rename to index.ts index 17487f8..9b28fcc 100644 --- a/index.js +++ b/index.ts @@ -6,7 +6,8 @@ import dotenv from "dotenv"; dotenv.config(); const app = express(); -const port = process.env.PORT || 3000; +const port = process.env.PORT || '3333'; +const secret = process.env.GITHUB_SECRET || "defaultKey"; let isDocumentationWebsiteUpdated = false; let isMindmapUpdated = false; @@ -20,64 +21,83 @@ app.use(express.json()); app.post("/webhook", async (req, res) => { console.log("req receieved"); - const signature = req.headers["x-hub-signature"]; + const signature = req.headers["x-hub-signature"] as string; + console.log(signature) + console.log("header",req.headers) const payload = JSON.stringify(req.body); - const hmac = crypto.createHmac("sha1", process.env.GITHUB_SECRET); + const hmac = crypto.createHmac("sha1", secret); const calculatedSignature = `sha1=${hmac.update(payload).digest("hex")}`; + console.log("cals", calculatedSignature) if (crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(calculatedSignature))) { - const { result, respMessage } = await getBranchStatus(); + const {result, respMessage } = await getBranchStatus(req.body); console.log("Result: ", result); - res.status(result).send(respMessage); + res.status(200).send({ result, respMessage }); } else { res.status(400).send("Invalid Github signature"); } }); -app.listen(process.env.PORT, () => { +interface BranchStatus { + result: number | string; + respMessage: string ; +} + +app.listen(port, () => { console.log(`Server listening on port ${port}`); }); -const executeCmd = async (cmd) => { +const executeCmd = async (cmd: string) => { try { - const { stdout, stderr } = await exec(cmd); + const {stdout, stderr} = await exec(cmd); return stderr + "\n" + stdout; - } catch (error) { + } catch (error: any) { console.error(`exec error: ${error}`); - throw new Error(stderr + "\n" + stdout); + throw new Error(error.stderr + "\n" + error.stdout); } }; -const getBranchStatus = async (req) => { +async function getBranchStatus(req: any): Promise { console.log("Webhook received successfully"); const branchName = req.body?.ref?.split("/").pop(); + if (!branchName) { - return 400, "Branch name not found in the request."; + return { result: 400, respMessage: "Branch name not found in the request." }; + } + + if (branchName === process.env.BRANCH_NAME) { + const { status, message } = await buildProject(); + return { result: status, respMessage: message }; + } else { + return { result: 200, respMessage: "Build not required." }; } - return branchName === process.env.BRANCH_NAME ? await buildProject() : 202, "Build not required."; }; const isUpdateRequired = () => { const currentTime = Date.now(); - isMindmapUpdated = (currentTime - mindmapBuildTime) / 1000 / 60 > process.env.MINDMAP_UPDATE_TIME_INTERVAL ? true : false; - isDocumentationWebsiteUpdated = (currentTime - documentationWebsiteBuildTime) / 1000 / 60 > process.env.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL ? true : false; + const mindMapUpdateInterval = parseInt("process.env.MINDMAP_UPDATE_TIME_INTERVAL", 10); // converted to number uusing variable + const documentationWebsiteUpdateInterval = parseInt("process.env.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL", 10); // converted to num using variable + + isMindmapUpdated = (currentTime - mindmapBuildTime) / 1000 / 60 > mindMapUpdateInterval ? true : false; + isDocumentationWebsiteUpdated = (currentTime - documentationWebsiteBuildTime) / 1000 / 60 > documentationWebsiteUpdateInterval ? true : false; return isMindmapUpdated || isDocumentationWebsiteUpdated; }; -const buildProject = async () => { +const buildProject = async (): Promise<{ status: number; message: string }> => { const currentTime = Date.now(); + const contributionUpdateTimeInterval = parseInt('process.env.CONTRIBUTORS_UPDATE_TIME_INTERVAL', 10); // adjusted to variable if (!isUpdateRequired()) { - if (contributorsBuildRequired || (currentTime - contributorsBuildTime) / 1000 / 60 > process.env.CONTRIBUTORS_UPDATE_TIME_INTERVAL) { + if (contributorsBuildRequired || (currentTime - contributorsBuildTime) / 1000 / 60 > contributionUpdateTimeInterval) { console.log("No update required, updating the contributors only"); await initiateBuild("npm run contributor-build", process.env.DOCUMENTATION_WEBSITE_PATH, process.env.DOCUMENTATION_WEBSITE_DEST_PATH); contributorsBuildTime = currentTime; contributorsBuildRequired = false; - return 200; + return { status: 200, message: "Contributors build has been created." } } else { contributorsBuildRequired = true; - return 202, "Contributors build will be done after the next build."; + return { status: 202, message: "Contributors build will be done after the next build." } // adjusted return value } } if (isMindmapUpdated) { @@ -95,12 +115,12 @@ const buildProject = async () => { isDocumentationWebsiteUpdated = false; } - return 200, "Build has been created."; + return {status: 200, message: "Contributors build will be done after the next build."}; }; -const initiateBuild = async (command, projectPath, destPath) => { +const initiateBuild = async (command:any, projectPath: any, destPath: any) => { await executeCmd(`cd ${projectPath}/ && git pull`); await executeCmd(`cd ${projectPath}/ && npm ci`); await executeCmd(`cd ${projectPath}/ && ${command}`); await executeCmd(`cp -r ${projectPath}/dist/ ${destPath}/`); -}; +}; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 95e8616..658f76b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1836,6 +1836,7 @@ "version": "4.19.2", "resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz", "integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q==", + "license": "MIT", "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", diff --git a/package.json b/package.json index 1da2456..26440b6 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "version": "1.0.0", "description": "This repository is our website deploy and update tool to minimize github api queries.", "main": "index.js", - "type" : "module", + "type": "module", "scripts": { "start": "node index.js", "lint": "eslint --ext=.ts --debug .", @@ -36,8 +36,8 @@ "express": "^4.19.2" }, "devDependencies": { - "@idrinth-api-bench/eslint-config": "https://github.com/idrinth-api-bench/eslint-config#setup-base-config", "@commitlint/cli": "^19.3.0", + "@idrinth-api-bench/eslint-config": "https://github.com/idrinth-api-bench/eslint-config#setup-base-config", "simple-git-hooks": "^2.11.1" }, "engineStrict": true, From d139c3b7bb8deb2605fc378a24b4946cb248db19 Mon Sep 17 00:00:00 2001 From: Angelina Date: Fri, 26 Jul 2024 10:24:17 -0400 Subject: [PATCH 2/4] bug[website-builder]: [issue#1057 implement sanitize function and correct errors] --- .github/workflows/cron.stale.yml | 3 +- index.js | 193 +++++++++++++++++++++++++++++++ index.ts | 65 ++++++----- tsconfig.json | 110 ++++++++++++++++++ 4 files changed, 344 insertions(+), 27 deletions(-) create mode 100644 index.js create mode 100644 tsconfig.json diff --git a/.github/workflows/cron.stale.yml b/.github/workflows/cron.stale.yml index 8767261..26137ab 100644 --- a/.github/workflows/cron.stale.yml +++ b/.github/workflows/cron.stale.yml @@ -24,4 +24,5 @@ jobs: - name: Unassign contributor after days of inactivity uses: BoundfoxStudios/action-unassign-contributor-after-days-of-inactivity@v1.0.3 with: - last-activity: 14 \ No newline at end of file + last-activity: 14 + \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..996ec7f --- /dev/null +++ b/index.js @@ -0,0 +1,193 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var express_1 = require("express"); +var child_process_1 = require("child_process"); +var crypto_1 = require("crypto"); +var dotenv_1 = require("dotenv"); +dotenv_1.default.config(); +var app = (0, express_1.default)(); +var port = process.env.PORT || '3333'; +var secret = process.env.GITHUB_SECRET; +if (!secret) { + console.error("Error: GITHUB_SECRET environment variable is not set."); + process.exit(1); +} +; +var isDocumentationWebsiteUpdated = false; +var isMindmapUpdated = false; +var contributorsBuildRequired = false; +var documentationWebsiteBuildTime = 0; +var mindmapBuildTime = 0; +var contributorsBuildTime = 0; +app.use(express_1.default.json()); +app.post("/webhook", function (req, res) { return __awaiter(void 0, void 0, void 0, function () { + var signature, payload, hmac, calculatedSignature, _a, result, respMessage; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + console.log("req receieved"); + signature = req.headers["x-hub-signature"]; + payload = JSON.stringify(req.body); + hmac = crypto_1.default.createHmac("sha1", secret); + calculatedSignature = "sha1=".concat(hmac.update(payload).digest("hex")); + console.log("cals", calculatedSignature); + if (!crypto_1.default.timingSafeEqual(Buffer.from(signature), Buffer.from(calculatedSignature))) return [3 /*break*/, 2]; + return [4 /*yield*/, getBranchStatus(req.body)]; + case 1: + _a = _b.sent(), result = _a.result, respMessage = _a.respMessage; + console.log("Result: ", result); + res.status(200).send({ result: result, respMessage: respMessage }); + return [3 /*break*/, 3]; + case 2: + res.status(400).send("Invalid Github signature"); + _b.label = 3; + case 3: return [2 /*return*/]; + } + }); +}); }); +app.listen(port, function () { + console.log("Server listening on port ".concat(port)); +}); +var executeCmd = function (cmd) { return __awaiter(void 0, void 0, void 0, function () { + var _a, stdout, stderr, error_1; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _b.trys.push([0, 2, , 3]); + return [4 /*yield*/, (0, child_process_1.exec)(cmd)]; + case 1: + _a = _b.sent(), stdout = _a.stdout, stderr = _a.stderr; + return [2 /*return*/, stderr + "\n" + stdout]; + case 2: + error_1 = _b.sent(); + console.error("exec error: ".concat(error_1)); + throw new Error(error_1.stderr + "\n" + error_1.stdout); + case 3: return [2 /*return*/]; + } + }); +}); }; +var getBranchStatus = function (req) { return __awaiter(void 0, void 0, void 0, function () { + var branchName, _a, status_1, message; + var _b, _c; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + console.log("Webhook received successfully"); + branchName = (_c = (_b = req.body) === null || _b === void 0 ? void 0 : _b.ref) === null || _c === void 0 ? void 0 : _c.split("/").pop(); + if (!branchName) { + return [2 /*return*/, { result: 400, respMessage: "Branch name not found in the request." }]; + } + if (!(branchName === process.env.BRANCH_NAME)) return [3 /*break*/, 2]; + return [4 /*yield*/, buildProject()]; + case 1: + _a = _d.sent(), status_1 = _a.status, message = _a.message; + return [2 /*return*/, { result: status_1, respMessage: message }]; + case 2: return [2 /*return*/, { result: 200, respMessage: "Build not required." }]; + } + }); +}); }; +var isUpdateRequired = function () { + var currentTime = Date.now(); + var mindMapUpdateInterval = "process.env.MINDMAP_UPDATE_TIME_INTERVAL"; // set to static string + var documentationWebsiteUpdateInterval = parseInt("process.env.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL", 10); // fix + isMindmapUpdated = ((currentTime - mindmapBuildTime) / 1000 / 60).toString() > mindMapUpdateInterval; + isDocumentationWebsiteUpdated = (currentTime - documentationWebsiteBuildTime) / 1000 / 60 > documentationWebsiteUpdateInterval; + return isMindmapUpdated || isDocumentationWebsiteUpdated; +}; +var buildProject = function () { return __awaiter(void 0, void 0, void 0, function () { + var currentTime, contributionUpdateTimeInterval; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + currentTime = Date.now(); + contributionUpdateTimeInterval = parseInt('process.env.CONTRIBUTORS_UPDATE_TIME_INTERVAL', 10); + if (!!isUpdateRequired()) return [3 /*break*/, 3]; + if (!(contributorsBuildRequired || (currentTime - contributorsBuildTime) / 1000 / 60 > contributionUpdateTimeInterval)) return [3 /*break*/, 2]; + console.log("No update required, updating the contributors only"); + return [4 /*yield*/, initiateBuild("npm run contributor-build", process.env.DOCUMENTATION_WEBSITE_PATH, process.env.DOCUMENTATION_WEBSITE_DEST_PATH)]; + case 1: + _a.sent(); + contributorsBuildTime = currentTime; + contributorsBuildRequired = false; + return [2 /*return*/, { status: 200, message: "Contributors build has been created." }]; + case 2: + contributorsBuildRequired = true; + return [2 /*return*/, { status: 202, message: "Contributors build will be done after the next build." }]; // adjusted return value + case 3: + if (!isMindmapUpdated) return [3 /*break*/, 5]; + console.log("Building Mindmap"); + return [4 /*yield*/, initiateBuild("npm run build", process.env.MINDMAP_PATH, process.env.MINDMAP_DEST_PATH)]; + case 4: + _a.sent(); + mindmapBuildTime = currentTime; + isMindmapUpdated = false; + _a.label = 5; + case 5: + if (!isDocumentationWebsiteUpdated) return [3 /*break*/, 7]; + console.log("Building Documentation Website"); + return [4 /*yield*/, initiateBuild("npm run build", process.env.DOCUMENTATION_WEBSITE_PATH, process.env.DOCUMENTATION_WEBSITE_DEST_PATH)]; + case 6: + _a.sent(); + documentationWebsiteBuildTime = currentTime; + contributorsBuildTime = currentTime; + isDocumentationWebsiteUpdated = false; + _a.label = 7; + case 7: return [2 /*return*/, { status: 200, message: "Contributors build will be done after the next build." }]; + } + }); +}); }; +var initiateBuild = function (command, projectPath, destPath) { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, executeCmd("cd ".concat(projectPath, "/ && git pull"))]; + case 1: + _a.sent(); + return [4 /*yield*/, executeCmd("cd ".concat(projectPath, "/ && npm ci"))]; + case 2: + _a.sent(); + return [4 /*yield*/, executeCmd("cd ".concat(projectPath, "/ && ").concat(command))]; + case 3: + _a.sent(); + return [4 /*yield*/, executeCmd("cp -r ".concat(projectPath, "/dist/ ").concat(destPath, "/"))]; + case 4: + _a.sent(); + return [2 /*return*/]; + } + }); +}); }; diff --git a/index.ts b/index.ts index 9b28fcc..7020f9e 100644 --- a/index.ts +++ b/index.ts @@ -7,7 +7,11 @@ dotenv.config(); const app = express(); const port = process.env.PORT || '3333'; -const secret = process.env.GITHUB_SECRET || "defaultKey"; +const secret = process.env.GITHUB_SECRET; +if(!secret) { + console.error("Error: GITHUB_SECRET environment variable is not set."); + process.exit(1); +}; let isDocumentationWebsiteUpdated = false; let isMindmapUpdated = false; @@ -22,16 +26,15 @@ app.use(express.json()); app.post("/webhook", async (req, res) => { console.log("req receieved"); const signature = req.headers["x-hub-signature"] as string; - console.log(signature) - console.log("header",req.headers) - const payload = JSON.stringify(req.body); + const payload = JSON.stringify(req.body); const hmac = crypto.createHmac("sha1", secret); + const calculatedSignature = `sha1=${hmac.update(payload).digest("hex")}`; - console.log("cals", calculatedSignature) + console.log("cals", calculatedSignature) // need this to stay as number seems to change if (crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(calculatedSignature))) { - const {result, respMessage } = await getBranchStatus(req.body); + const {result, respMessage} = await getBranchStatus(req.body); console.log("Result: ", result); res.status(200).send({ result, respMessage }); } else { @@ -42,23 +45,33 @@ app.post("/webhook", async (req, res) => { interface BranchStatus { result: number | string; respMessage: string ; -} +}; app.listen(port, () => { console.log(`Server listening on port ${port}`); }); +const sanitize = (cmd: string) => { + const sanitized = cmd.replace(/[;&|`<>$]/g, ''); + + if(/[\r\n\t]/.test(cmd)) { + throw new Error("Invalid characters in command"); + } + + return sanitized; +}; + const executeCmd = async (cmd: string) => { try { - const {stdout, stderr} = await exec(cmd); + const {stdout, stderr} = await exec(sanitize(cmd)); return stderr + "\n" + stdout; } catch (error: any) { console.error(`exec error: ${error}`); throw new Error(error.stderr + "\n" + error.stdout); - } + }; }; -async function getBranchStatus(req: any): Promise { +const getBranchStatus = async (req): Promise => { console.log("Webhook received successfully"); const branchName = req.body?.ref?.split("/").pop(); @@ -70,34 +83,34 @@ async function getBranchStatus(req: any): Promise { if (branchName === process.env.BRANCH_NAME) { const { status, message } = await buildProject(); return { result: status, respMessage: message }; - } else { - return { result: 200, respMessage: "Build not required." }; } + + return { result: 200, respMessage: "Build not required." }; + }; const isUpdateRequired = () => { const currentTime = Date.now(); - const mindMapUpdateInterval = parseInt("process.env.MINDMAP_UPDATE_TIME_INTERVAL", 10); // converted to number uusing variable - const documentationWebsiteUpdateInterval = parseInt("process.env.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL", 10); // converted to num using variable - - isMindmapUpdated = (currentTime - mindmapBuildTime) / 1000 / 60 > mindMapUpdateInterval ? true : false; - isDocumentationWebsiteUpdated = (currentTime - documentationWebsiteBuildTime) / 1000 / 60 > documentationWebsiteUpdateInterval ? true : false; + const mindMapUpdateInterval = Number.parseInt(process.env.MINDMAP_UPDATE_TIME_INTERVAL ?? "10000"); + const documentationWebsiteUpdateInterval = Number.parseInt(process.env.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL ?? "10000"); + isMindmapUpdated = (currentTime - mindmapBuildTime) / 1000 / 60 > mindMapUpdateInterval; + isDocumentationWebsiteUpdated = (currentTime - documentationWebsiteBuildTime) / 1000 / 60 > documentationWebsiteUpdateInterval; return isMindmapUpdated || isDocumentationWebsiteUpdated; }; const buildProject = async (): Promise<{ status: number; message: string }> => { const currentTime = Date.now(); - const contributionUpdateTimeInterval = parseInt('process.env.CONTRIBUTORS_UPDATE_TIME_INTERVAL', 10); // adjusted to variable + const contributionUpdateTimeInterval = Number.parseInt(process.env.CONTRIBUTORS_UPDATE_TIME_INTERVAL ?? "10000"); if (!isUpdateRequired()) { if (contributorsBuildRequired || (currentTime - contributorsBuildTime) / 1000 / 60 > contributionUpdateTimeInterval) { console.log("No update required, updating the contributors only"); await initiateBuild("npm run contributor-build", process.env.DOCUMENTATION_WEBSITE_PATH, process.env.DOCUMENTATION_WEBSITE_DEST_PATH); contributorsBuildTime = currentTime; contributorsBuildRequired = false; - return { status: 200, message: "Contributors build has been created." } + return { status: 200, message: "Contributors build has been created." }; } else { contributorsBuildRequired = true; - return { status: 202, message: "Contributors build will be done after the next build." } // adjusted return value + return { status: 202, message: "Contributors build will be done after the next build." }; } } if (isMindmapUpdated) { @@ -118,9 +131,9 @@ const buildProject = async (): Promise<{ status: number; message: string }> => { return {status: 200, message: "Contributors build will be done after the next build."}; }; -const initiateBuild = async (command:any, projectPath: any, destPath: any) => { - await executeCmd(`cd ${projectPath}/ && git pull`); - await executeCmd(`cd ${projectPath}/ && npm ci`); - await executeCmd(`cd ${projectPath}/ && ${command}`); - await executeCmd(`cp -r ${projectPath}/dist/ ${destPath}/`); -}; \ No newline at end of file +const initiateBuild = async (command, projectPath, destPath) => { + await executeCmd(`cd ${sanitize(projectPath)}/ && git pull`); + await executeCmd(`cd ${sanitize(projectPath)}/ && npm ci`); + await executeCmd(`cd ${sanitize(projectPath)}/ && ${sanitize(command)}`); + await executeCmd(`cp -r ${sanitize(projectPath)}/dist/ ${sanitize(destPath)}/`); +}; diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..ce81056 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,110 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "include": ["src"], + "exclude": ["node_modules", "**/*.spec.ts"] +} \ No newline at end of file From eb2aa999dce465de54368f182fd4581a2343d21e Mon Sep 17 00:00:00 2001 From: Angelina Date: Sun, 28 Jul 2024 15:37:15 -0400 Subject: [PATCH 3/4] bug[website-builder]: [issue#1057 corrections to ts file] --- .github/workflows/cron.stale.yml | 2 +- index.js | 279 ++++++++++++------------------- index.ts | 29 ++-- package-lock.json | 99 +++++++++++ package.json | 1 + tsconfig.json | 4 +- 6 files changed, 230 insertions(+), 184 deletions(-) diff --git a/.github/workflows/cron.stale.yml b/.github/workflows/cron.stale.yml index 26137ab..02a21e3 100644 --- a/.github/workflows/cron.stale.yml +++ b/.github/workflows/cron.stale.yml @@ -25,4 +25,4 @@ jobs: uses: BoundfoxStudios/action-unassign-contributor-after-days-of-inactivity@v1.0.3 with: last-activity: 14 - \ No newline at end of file + \ No newline at end of file diff --git a/index.js b/index.js index 996ec7f..c2cc42d 100644 --- a/index.js +++ b/index.js @@ -8,186 +8,129 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -var express_1 = require("express"); -var child_process_1 = require("child_process"); -var crypto_1 = require("crypto"); -var dotenv_1 = require("dotenv"); +const express_1 = __importDefault(require("express")); +const child_process_1 = require("child_process"); +const crypto_1 = __importDefault(require("crypto")); +const dotenv_1 = __importDefault(require("dotenv")); dotenv_1.default.config(); -var app = (0, express_1.default)(); -var port = process.env.PORT || '3333'; -var secret = process.env.GITHUB_SECRET; +const app = (0, express_1.default)(); +const port = process.env.PORT || '3333'; +const secret = process.env.GITHUB_SECRET; if (!secret) { console.error("Error: GITHUB_SECRET environment variable is not set."); process.exit(1); } ; -var isDocumentationWebsiteUpdated = false; -var isMindmapUpdated = false; -var contributorsBuildRequired = false; -var documentationWebsiteBuildTime = 0; -var mindmapBuildTime = 0; -var contributorsBuildTime = 0; +let isDocumentationWebsiteUpdated = false; +let isMindmapUpdated = false; +let contributorsBuildRequired = false; +let documentationWebsiteBuildTime = 0; +let mindmapBuildTime = 0; +let contributorsBuildTime = 0; +// fixing TS errors when back app.use(express_1.default.json()); -app.post("/webhook", function (req, res) { return __awaiter(void 0, void 0, void 0, function () { - var signature, payload, hmac, calculatedSignature, _a, result, respMessage; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - console.log("req receieved"); - signature = req.headers["x-hub-signature"]; - payload = JSON.stringify(req.body); - hmac = crypto_1.default.createHmac("sha1", secret); - calculatedSignature = "sha1=".concat(hmac.update(payload).digest("hex")); - console.log("cals", calculatedSignature); - if (!crypto_1.default.timingSafeEqual(Buffer.from(signature), Buffer.from(calculatedSignature))) return [3 /*break*/, 2]; - return [4 /*yield*/, getBranchStatus(req.body)]; - case 1: - _a = _b.sent(), result = _a.result, respMessage = _a.respMessage; - console.log("Result: ", result); - res.status(200).send({ result: result, respMessage: respMessage }); - return [3 /*break*/, 3]; - case 2: - res.status(400).send("Invalid Github signature"); - _b.label = 3; - case 3: return [2 /*return*/]; - } - }); -}); }); -app.listen(port, function () { - console.log("Server listening on port ".concat(port)); +app.post("/webhook", (req, res) => __awaiter(void 0, void 0, void 0, function* () { + console.log("Request received"); + const signature = req.headers["x-hub-signature"]; + const payload = JSON.stringify(req.body); + const hmac = crypto_1.default.createHmac("sha1", secret); + const calculatedSignature = `sha1=${hmac.update(payload).digest("hex")}`; + console.log("Calculated signature received", calculatedSignature); // need this to stay as number seems to change + if (crypto_1.default.timingSafeEqual(Buffer.from(signature), Buffer.from(calculatedSignature))) { + const { result, respMessage } = yield getBranchStatus(req.body); + console.log("Result: ", result); + res.status(200).send({ result, respMessage }); + } + else { + res.status(400).send({ error: "Invalid GitHub signature. Ensure the secret is correctly configured." }); + } +})); +; +app.listen(port, () => { + console.log(`Server listening on port ${port}`); }); -var executeCmd = function (cmd) { return __awaiter(void 0, void 0, void 0, function () { - var _a, stdout, stderr, error_1; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 2, , 3]); - return [4 /*yield*/, (0, child_process_1.exec)(cmd)]; - case 1: - _a = _b.sent(), stdout = _a.stdout, stderr = _a.stderr; - return [2 /*return*/, stderr + "\n" + stdout]; - case 2: - error_1 = _b.sent(); - console.error("exec error: ".concat(error_1)); - throw new Error(error_1.stderr + "\n" + error_1.stdout); - case 3: return [2 /*return*/]; - } - }); -}); }; -var getBranchStatus = function (req) { return __awaiter(void 0, void 0, void 0, function () { - var branchName, _a, status_1, message; - var _b, _c; - return __generator(this, function (_d) { - switch (_d.label) { - case 0: - console.log("Webhook received successfully"); - branchName = (_c = (_b = req.body) === null || _b === void 0 ? void 0 : _b.ref) === null || _c === void 0 ? void 0 : _c.split("/").pop(); - if (!branchName) { - return [2 /*return*/, { result: 400, respMessage: "Branch name not found in the request." }]; - } - if (!(branchName === process.env.BRANCH_NAME)) return [3 /*break*/, 2]; - return [4 /*yield*/, buildProject()]; - case 1: - _a = _d.sent(), status_1 = _a.status, message = _a.message; - return [2 /*return*/, { result: status_1, respMessage: message }]; - case 2: return [2 /*return*/, { result: 200, respMessage: "Build not required." }]; - } - }); -}); }; -var isUpdateRequired = function () { - var currentTime = Date.now(); - var mindMapUpdateInterval = "process.env.MINDMAP_UPDATE_TIME_INTERVAL"; // set to static string - var documentationWebsiteUpdateInterval = parseInt("process.env.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL", 10); // fix - isMindmapUpdated = ((currentTime - mindmapBuildTime) / 1000 / 60).toString() > mindMapUpdateInterval; +const sanitize = (cmd) => { + const sanitized = cmd.replace(/[;&|`<>$(){}[\]]/g, ''); + if (/[\r\n\t]/.test(cmd)) { + throw new Error("Invalid characters in command"); + } + return sanitized; +}; +const executeCmd = (cmd) => __awaiter(void 0, void 0, void 0, function* () { + try { + const { stdout, stderr } = yield (0, child_process_1.exec)(sanitize(cmd)); + return stderr + "\n" + stdout; + } + catch (error) { + console.error(`exec error: ${error}`); + throw new Error("Command execution failed. Check logs for details."); + } + ; +}); +const getBranchStatus = (req) => __awaiter(void 0, void 0, void 0, function* () { + var _a, _b; + console.log("Webhook received successfully"); + const branchName = (_b = (_a = req.body) === null || _a === void 0 ? void 0 : _a.ref) === null || _b === void 0 ? void 0 : _b.split("/").pop(); + if (!branchName) { + return { result: 400, respMessage: "Branch name not found in the request." }; + } + if (branchName === process.env.BRANCH_NAME) { + const { status, message } = yield buildProject(); + return { result: status, respMessage: message }; + } + return { result: 200, respMessage: "Build not required." }; +}); +const isUpdateRequired = () => { + var _a, _b; + const currentTime = Date.now(); + const mindMapUpdateInterval = Number.parseInt((_a = process.env.MINDMAP_UPDATE_TIME_INTERVAL) !== null && _a !== void 0 ? _a : "10000"); + const documentationWebsiteUpdateInterval = Number.parseInt((_b = process.env.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL) !== null && _b !== void 0 ? _b : "10000"); + isMindmapUpdated = (currentTime - mindmapBuildTime) / 1000 / 60 > mindMapUpdateInterval; isDocumentationWebsiteUpdated = (currentTime - documentationWebsiteBuildTime) / 1000 / 60 > documentationWebsiteUpdateInterval; return isMindmapUpdated || isDocumentationWebsiteUpdated; }; -var buildProject = function () { return __awaiter(void 0, void 0, void 0, function () { - var currentTime, contributionUpdateTimeInterval; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - currentTime = Date.now(); - contributionUpdateTimeInterval = parseInt('process.env.CONTRIBUTORS_UPDATE_TIME_INTERVAL', 10); - if (!!isUpdateRequired()) return [3 /*break*/, 3]; - if (!(contributorsBuildRequired || (currentTime - contributorsBuildTime) / 1000 / 60 > contributionUpdateTimeInterval)) return [3 /*break*/, 2]; - console.log("No update required, updating the contributors only"); - return [4 /*yield*/, initiateBuild("npm run contributor-build", process.env.DOCUMENTATION_WEBSITE_PATH, process.env.DOCUMENTATION_WEBSITE_DEST_PATH)]; - case 1: - _a.sent(); - contributorsBuildTime = currentTime; - contributorsBuildRequired = false; - return [2 /*return*/, { status: 200, message: "Contributors build has been created." }]; - case 2: - contributorsBuildRequired = true; - return [2 /*return*/, { status: 202, message: "Contributors build will be done after the next build." }]; // adjusted return value - case 3: - if (!isMindmapUpdated) return [3 /*break*/, 5]; - console.log("Building Mindmap"); - return [4 /*yield*/, initiateBuild("npm run build", process.env.MINDMAP_PATH, process.env.MINDMAP_DEST_PATH)]; - case 4: - _a.sent(); - mindmapBuildTime = currentTime; - isMindmapUpdated = false; - _a.label = 5; - case 5: - if (!isDocumentationWebsiteUpdated) return [3 /*break*/, 7]; - console.log("Building Documentation Website"); - return [4 /*yield*/, initiateBuild("npm run build", process.env.DOCUMENTATION_WEBSITE_PATH, process.env.DOCUMENTATION_WEBSITE_DEST_PATH)]; - case 6: - _a.sent(); - documentationWebsiteBuildTime = currentTime; - contributorsBuildTime = currentTime; - isDocumentationWebsiteUpdated = false; - _a.label = 7; - case 7: return [2 /*return*/, { status: 200, message: "Contributors build will be done after the next build." }]; +const buildProject = () => __awaiter(void 0, void 0, void 0, function* () { + var _a; + const currentTime = Date.now(); + const contributionUpdateTimeInterval = Number.parseInt((_a = process.env.CONTRIBUTORS_UPDATE_TIME_INTERVAL) !== null && _a !== void 0 ? _a : "10000"); + if (!process.env.DOCUMENTATION_WEBSITE_PATH) { + console.log('error'); + } + if (!isUpdateRequired()) { + if (contributorsBuildRequired || (currentTime - contributorsBuildTime) / 1000 / 60 > contributionUpdateTimeInterval) { + console.log("No update required, updating the contributors only"); + yield initiateBuild("npm run contributor-build", process.env.DOCUMENTATION_WEBSITE_PATH, process.env.DOCUMENTATION_WEBSITE_DEST_PATH); + contributorsBuildTime = currentTime; + contributorsBuildRequired = false; + return { status: 200, message: "Contributors build has been created." }; } - }); -}); }; -var initiateBuild = function (command, projectPath, destPath) { return __awaiter(void 0, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, executeCmd("cd ".concat(projectPath, "/ && git pull"))]; - case 1: - _a.sent(); - return [4 /*yield*/, executeCmd("cd ".concat(projectPath, "/ && npm ci"))]; - case 2: - _a.sent(); - return [4 /*yield*/, executeCmd("cd ".concat(projectPath, "/ && ").concat(command))]; - case 3: - _a.sent(); - return [4 /*yield*/, executeCmd("cp -r ".concat(projectPath, "/dist/ ").concat(destPath, "/"))]; - case 4: - _a.sent(); - return [2 /*return*/]; + else { + contributorsBuildRequired = true; + return { status: 202, message: "Contributors build will be done after the next build." }; } - }); -}); }; + } + if (isMindmapUpdated) { + console.log("Building Mindmap"); + yield initiateBuild("npm run build", process.env.MINDMAP_PATH, process.env.MINDMAP_DEST_PATH); + mindmapBuildTime = currentTime; + isMindmapUpdated = false; + } + if (isDocumentationWebsiteUpdated) { + console.log("Building Documentation Website"); + yield initiateBuild("npm run build", process.env.DOCUMENTATION_WEBSITE_PATH, process.env.DOCUMENTATION_WEBSITE_DEST_PATH); + documentationWebsiteBuildTime = currentTime; + contributorsBuildTime = currentTime; + isDocumentationWebsiteUpdated = false; + } + return { status: 200, message: "Contributors build will be done after the next build." }; +}); +const initiateBuild = (command, projectPath, destPath) => __awaiter(void 0, void 0, void 0, function* () { + yield executeCmd(`cd ${sanitize(projectPath)}/ && git pull`); + yield executeCmd(`cd ${sanitize(projectPath)}/ && npm ci`); + yield executeCmd(`cd ${sanitize(projectPath)}/ && ${sanitize(command)}`); + yield executeCmd(`cp -r ${sanitize(projectPath)}/dist/ ${sanitize(destPath)}/`); +}); diff --git a/index.ts b/index.ts index 7020f9e..459ce87 100644 --- a/index.ts +++ b/index.ts @@ -1,4 +1,4 @@ -import express from "express"; +import express, {Request, Response} from "express"; import {exec} from "child_process"; import crypto from "crypto"; import dotenv from "dotenv"; @@ -20,25 +20,25 @@ let contributorsBuildRequired = false; let documentationWebsiteBuildTime = 0; let mindmapBuildTime = 0; let contributorsBuildTime = 0; - +// fixing TS errors when back app.use(express.json()); -app.post("/webhook", async (req, res) => { - console.log("req receieved"); +app.post("/webhook", async (req: Request, res: Response) => { + console.log("Request received"); const signature = req.headers["x-hub-signature"] as string; const payload = JSON.stringify(req.body); const hmac = crypto.createHmac("sha1", secret); const calculatedSignature = `sha1=${hmac.update(payload).digest("hex")}`; - console.log("cals", calculatedSignature) // need this to stay as number seems to change + console.log("Calculated signature received", calculatedSignature) // need this to stay as number seems to change if (crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(calculatedSignature))) { const {result, respMessage} = await getBranchStatus(req.body); console.log("Result: ", result); res.status(200).send({ result, respMessage }); } else { - res.status(400).send("Invalid Github signature"); + res.status(400).send({ error: "Invalid GitHub signature. Ensure the secret is correctly configured." }); } }); @@ -52,7 +52,7 @@ app.listen(port, () => { }); const sanitize = (cmd: string) => { - const sanitized = cmd.replace(/[;&|`<>$]/g, ''); + const sanitized = cmd.replace(/[;&|`<>$(){}[\]]/g, ''); if(/[\r\n\t]/.test(cmd)) { throw new Error("Invalid characters in command"); @@ -67,11 +67,11 @@ const executeCmd = async (cmd: string) => { return stderr + "\n" + stdout; } catch (error: any) { console.error(`exec error: ${error}`); - throw new Error(error.stderr + "\n" + error.stdout); + throw new Error("Command execution failed. Check logs for details."); }; }; -const getBranchStatus = async (req): Promise => { +const getBranchStatus = async (req: Request): Promise => { console.log("Webhook received successfully"); const branchName = req.body?.ref?.split("/").pop(); @@ -101,10 +101,13 @@ const isUpdateRequired = () => { const buildProject = async (): Promise<{ status: number; message: string }> => { const currentTime = Date.now(); const contributionUpdateTimeInterval = Number.parseInt(process.env.CONTRIBUTORS_UPDATE_TIME_INTERVAL ?? "10000"); + if (!process.env.DOCUMENTATION_WEBSITE_PATH) { + console.log('error') + } if (!isUpdateRequired()) { if (contributorsBuildRequired || (currentTime - contributorsBuildTime) / 1000 / 60 > contributionUpdateTimeInterval) { console.log("No update required, updating the contributors only"); - await initiateBuild("npm run contributor-build", process.env.DOCUMENTATION_WEBSITE_PATH, process.env.DOCUMENTATION_WEBSITE_DEST_PATH); + await initiateBuild("npm run contributor-build", process.env.DOCUMENTATION_WEBSITE_PATH!, process.env.DOCUMENTATION_WEBSITE_DEST_PATH!); contributorsBuildTime = currentTime; contributorsBuildRequired = false; return { status: 200, message: "Contributors build has been created." }; @@ -115,14 +118,14 @@ const buildProject = async (): Promise<{ status: number; message: string }> => { } if (isMindmapUpdated) { console.log("Building Mindmap"); - await initiateBuild("npm run build", process.env.MINDMAP_PATH, process.env.MINDMAP_DEST_PATH); + await initiateBuild("npm run build", process.env.MINDMAP_PATH!, process.env.MINDMAP_DEST_PATH!); mindmapBuildTime = currentTime; isMindmapUpdated = false; } if (isDocumentationWebsiteUpdated) { console.log("Building Documentation Website"); - await initiateBuild("npm run build", process.env.DOCUMENTATION_WEBSITE_PATH, process.env.DOCUMENTATION_WEBSITE_DEST_PATH); + await initiateBuild("npm run build", process.env.DOCUMENTATION_WEBSITE_PATH!, process.env.DOCUMENTATION_WEBSITE_DEST_PATH!); documentationWebsiteBuildTime = currentTime; contributorsBuildTime = currentTime; isDocumentationWebsiteUpdated = false; @@ -131,7 +134,7 @@ const buildProject = async (): Promise<{ status: number; message: string }> => { return {status: 200, message: "Contributors build will be done after the next build."}; }; -const initiateBuild = async (command, projectPath, destPath) => { +const initiateBuild = async (command: string, projectPath: string, destPath: string) => { await executeCmd(`cd ${sanitize(projectPath)}/ && git pull`); await executeCmd(`cd ${sanitize(projectPath)}/ && npm ci`); await executeCmd(`cd ${sanitize(projectPath)}/ && ${sanitize(command)}`); diff --git a/package-lock.json b/package-lock.json index 658f76b..66fb3ea 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "devDependencies": { "@commitlint/cli": "^19.3.0", "@idrinth-api-bench/eslint-config": "https://github.com/idrinth-api-bench/eslint-config#setup-base-config", + "@types/express": "^4.17.21", "simple-git-hooks": "^2.11.1" }, "engines": { @@ -588,6 +589,27 @@ "node": ">= 8" } }, + "node_modules/@types/body-parser": { + "version": "1.19.5", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz", + "integrity": "sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/conventional-commits-parser": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/@types/conventional-commits-parser/-/conventional-commits-parser-5.0.0.tgz", @@ -597,12 +619,52 @@ "@types/node": "*" } }, + "node_modules/@types/express": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz", + "integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "*" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.5", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.5.tgz", + "integrity": "sha512-y6W03tvrACO72aijJ5uF02FRq5cgDR9lUxddQ8vyF+GvmjJQqbzDcJngEjURc+ZsG31VI3hODNZJ2URj86pzmg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz", + "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", "dev": true }, + "node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/node": { "version": "20.12.11", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.12.11.tgz", @@ -612,12 +674,49 @@ "undici-types": "~5.26.4" } }, + "node_modules/@types/qs": { + "version": "6.9.15", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.15.tgz", + "integrity": "sha512-uXHQKES6DQKKCLh441Xv/dwxOq1TVS3JPUMlEqoEglvlhR6Mxnlew/Xq/LRVHpLyk7iK3zODe1qYHIMltO7XGg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/semver": { "version": "7.5.8", "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.8.tgz", "integrity": "sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ==", "dev": true }, + "node_modules/@types/send": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz", + "integrity": "sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.7", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.7.tgz", + "integrity": "sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "*" + } + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "7.8.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.8.0.tgz", diff --git a/package.json b/package.json index 26440b6..68d1395 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "devDependencies": { "@commitlint/cli": "^19.3.0", "@idrinth-api-bench/eslint-config": "https://github.com/idrinth-api-bench/eslint-config#setup-base-config", + "@types/express": "^4.17.21", "simple-git-hooks": "^2.11.1" }, "engineStrict": true, diff --git a/tsconfig.json b/tsconfig.json index ce81056..20513f2 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -105,6 +105,6 @@ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ "skipLibCheck": true /* Skip type checking all .d.ts files. */ }, - "include": ["src"], + "include": ["index.ts"], "exclude": ["node_modules", "**/*.spec.ts"] -} \ No newline at end of file +} From 0e7b5d6482b478d32bfc68ffb197b6f39f1866de Mon Sep 17 00:00:00 2001 From: Angelina Date: Tue, 13 Aug 2024 14:15:33 -0400 Subject: [PATCH 4/4] bug[website-builder]: [issue#1057 correct ts file and remove js] --- .github/workflows/cron.stale.yml | 1 - index.js | 136 ------------------------------- index.ts | 47 +++++------ tsconfig.json | 110 ++----------------------- 4 files changed, 25 insertions(+), 269 deletions(-) delete mode 100644 index.js diff --git a/.github/workflows/cron.stale.yml b/.github/workflows/cron.stale.yml index 02a21e3..a816111 100644 --- a/.github/workflows/cron.stale.yml +++ b/.github/workflows/cron.stale.yml @@ -25,4 +25,3 @@ jobs: uses: BoundfoxStudios/action-unassign-contributor-after-days-of-inactivity@v1.0.3 with: last-activity: 14 - \ No newline at end of file diff --git a/index.js b/index.js deleted file mode 100644 index c2cc42d..0000000 --- a/index.js +++ /dev/null @@ -1,136 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const express_1 = __importDefault(require("express")); -const child_process_1 = require("child_process"); -const crypto_1 = __importDefault(require("crypto")); -const dotenv_1 = __importDefault(require("dotenv")); -dotenv_1.default.config(); -const app = (0, express_1.default)(); -const port = process.env.PORT || '3333'; -const secret = process.env.GITHUB_SECRET; -if (!secret) { - console.error("Error: GITHUB_SECRET environment variable is not set."); - process.exit(1); -} -; -let isDocumentationWebsiteUpdated = false; -let isMindmapUpdated = false; -let contributorsBuildRequired = false; -let documentationWebsiteBuildTime = 0; -let mindmapBuildTime = 0; -let contributorsBuildTime = 0; -// fixing TS errors when back -app.use(express_1.default.json()); -app.post("/webhook", (req, res) => __awaiter(void 0, void 0, void 0, function* () { - console.log("Request received"); - const signature = req.headers["x-hub-signature"]; - const payload = JSON.stringify(req.body); - const hmac = crypto_1.default.createHmac("sha1", secret); - const calculatedSignature = `sha1=${hmac.update(payload).digest("hex")}`; - console.log("Calculated signature received", calculatedSignature); // need this to stay as number seems to change - if (crypto_1.default.timingSafeEqual(Buffer.from(signature), Buffer.from(calculatedSignature))) { - const { result, respMessage } = yield getBranchStatus(req.body); - console.log("Result: ", result); - res.status(200).send({ result, respMessage }); - } - else { - res.status(400).send({ error: "Invalid GitHub signature. Ensure the secret is correctly configured." }); - } -})); -; -app.listen(port, () => { - console.log(`Server listening on port ${port}`); -}); -const sanitize = (cmd) => { - const sanitized = cmd.replace(/[;&|`<>$(){}[\]]/g, ''); - if (/[\r\n\t]/.test(cmd)) { - throw new Error("Invalid characters in command"); - } - return sanitized; -}; -const executeCmd = (cmd) => __awaiter(void 0, void 0, void 0, function* () { - try { - const { stdout, stderr } = yield (0, child_process_1.exec)(sanitize(cmd)); - return stderr + "\n" + stdout; - } - catch (error) { - console.error(`exec error: ${error}`); - throw new Error("Command execution failed. Check logs for details."); - } - ; -}); -const getBranchStatus = (req) => __awaiter(void 0, void 0, void 0, function* () { - var _a, _b; - console.log("Webhook received successfully"); - const branchName = (_b = (_a = req.body) === null || _a === void 0 ? void 0 : _a.ref) === null || _b === void 0 ? void 0 : _b.split("/").pop(); - if (!branchName) { - return { result: 400, respMessage: "Branch name not found in the request." }; - } - if (branchName === process.env.BRANCH_NAME) { - const { status, message } = yield buildProject(); - return { result: status, respMessage: message }; - } - return { result: 200, respMessage: "Build not required." }; -}); -const isUpdateRequired = () => { - var _a, _b; - const currentTime = Date.now(); - const mindMapUpdateInterval = Number.parseInt((_a = process.env.MINDMAP_UPDATE_TIME_INTERVAL) !== null && _a !== void 0 ? _a : "10000"); - const documentationWebsiteUpdateInterval = Number.parseInt((_b = process.env.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL) !== null && _b !== void 0 ? _b : "10000"); - isMindmapUpdated = (currentTime - mindmapBuildTime) / 1000 / 60 > mindMapUpdateInterval; - isDocumentationWebsiteUpdated = (currentTime - documentationWebsiteBuildTime) / 1000 / 60 > documentationWebsiteUpdateInterval; - return isMindmapUpdated || isDocumentationWebsiteUpdated; -}; -const buildProject = () => __awaiter(void 0, void 0, void 0, function* () { - var _a; - const currentTime = Date.now(); - const contributionUpdateTimeInterval = Number.parseInt((_a = process.env.CONTRIBUTORS_UPDATE_TIME_INTERVAL) !== null && _a !== void 0 ? _a : "10000"); - if (!process.env.DOCUMENTATION_WEBSITE_PATH) { - console.log('error'); - } - if (!isUpdateRequired()) { - if (contributorsBuildRequired || (currentTime - contributorsBuildTime) / 1000 / 60 > contributionUpdateTimeInterval) { - console.log("No update required, updating the contributors only"); - yield initiateBuild("npm run contributor-build", process.env.DOCUMENTATION_WEBSITE_PATH, process.env.DOCUMENTATION_WEBSITE_DEST_PATH); - contributorsBuildTime = currentTime; - contributorsBuildRequired = false; - return { status: 200, message: "Contributors build has been created." }; - } - else { - contributorsBuildRequired = true; - return { status: 202, message: "Contributors build will be done after the next build." }; - } - } - if (isMindmapUpdated) { - console.log("Building Mindmap"); - yield initiateBuild("npm run build", process.env.MINDMAP_PATH, process.env.MINDMAP_DEST_PATH); - mindmapBuildTime = currentTime; - isMindmapUpdated = false; - } - if (isDocumentationWebsiteUpdated) { - console.log("Building Documentation Website"); - yield initiateBuild("npm run build", process.env.DOCUMENTATION_WEBSITE_PATH, process.env.DOCUMENTATION_WEBSITE_DEST_PATH); - documentationWebsiteBuildTime = currentTime; - contributorsBuildTime = currentTime; - isDocumentationWebsiteUpdated = false; - } - return { status: 200, message: "Contributors build will be done after the next build." }; -}); -const initiateBuild = (command, projectPath, destPath) => __awaiter(void 0, void 0, void 0, function* () { - yield executeCmd(`cd ${sanitize(projectPath)}/ && git pull`); - yield executeCmd(`cd ${sanitize(projectPath)}/ && npm ci`); - yield executeCmd(`cd ${sanitize(projectPath)}/ && ${sanitize(command)}`); - yield executeCmd(`cp -r ${sanitize(projectPath)}/dist/ ${sanitize(destPath)}/`); -}); diff --git a/index.ts b/index.ts index 459ce87..5c1b762 100644 --- a/index.ts +++ b/index.ts @@ -4,9 +4,9 @@ import crypto from "crypto"; import dotenv from "dotenv"; dotenv.config(); - +// waiting for replies const app = express(); -const port = process.env.PORT || '3333'; +const port = process.env.PORT; const secret = process.env.GITHUB_SECRET; if(!secret) { console.error("Error: GITHUB_SECRET environment variable is not set."); @@ -20,18 +20,21 @@ let contributorsBuildRequired = false; let documentationWebsiteBuildTime = 0; let mindmapBuildTime = 0; let contributorsBuildTime = 0; -// fixing TS errors when back + app.use(express.json()); app.post("/webhook", async (req: Request, res: Response) => { console.log("Request received"); const signature = req.headers["x-hub-signature"] as string; + if(!signature) { + throw new Error("Please provide a valid signature") + } + const payload = JSON.stringify(req.body); - const hmac = crypto.createHmac("sha1", secret); + const hmac = crypto.createHmac("sha1", secret) - const calculatedSignature = `sha1=${hmac.update(payload).digest("hex")}`; - console.log("Calculated signature received", calculatedSignature) // need this to stay as number seems to change + const calculatedSignature = `sha1=${hmac.update(payload).digest("hex")}` if (crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(calculatedSignature))) { const {result, respMessage} = await getBranchStatus(req.body); @@ -43,29 +46,19 @@ app.post("/webhook", async (req: Request, res: Response) => { }); interface BranchStatus { - result: number | string; - respMessage: string ; + result: number; + respMessage: string; }; app.listen(port, () => { console.log(`Server listening on port ${port}`); }); -const sanitize = (cmd: string) => { - const sanitized = cmd.replace(/[;&|`<>$(){}[\]]/g, ''); - - if(/[\r\n\t]/.test(cmd)) { - throw new Error("Invalid characters in command"); - } - - return sanitized; -}; - const executeCmd = async (cmd: string) => { try { - const {stdout, stderr} = await exec(sanitize(cmd)); + const {stdout, stderr} = await exec(cmd); return stderr + "\n" + stdout; - } catch (error: any) { + } catch (error: unknown) { console.error(`exec error: ${error}`); throw new Error("Command execution failed. Check logs for details."); }; @@ -90,7 +83,7 @@ const getBranchStatus = async (req: Request): Promise => { }; const isUpdateRequired = () => { - const currentTime = Date.now(); + const currentTime = Date.now() const mindMapUpdateInterval = Number.parseInt(process.env.MINDMAP_UPDATE_TIME_INTERVAL ?? "10000"); const documentationWebsiteUpdateInterval = Number.parseInt(process.env.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL ?? "10000"); isMindmapUpdated = (currentTime - mindmapBuildTime) / 1000 / 60 > mindMapUpdateInterval; @@ -101,9 +94,6 @@ const isUpdateRequired = () => { const buildProject = async (): Promise<{ status: number; message: string }> => { const currentTime = Date.now(); const contributionUpdateTimeInterval = Number.parseInt(process.env.CONTRIBUTORS_UPDATE_TIME_INTERVAL ?? "10000"); - if (!process.env.DOCUMENTATION_WEBSITE_PATH) { - console.log('error') - } if (!isUpdateRequired()) { if (contributorsBuildRequired || (currentTime - contributorsBuildTime) / 1000 / 60 > contributionUpdateTimeInterval) { console.log("No update required, updating the contributors only"); @@ -120,6 +110,7 @@ const buildProject = async (): Promise<{ status: number; message: string }> => { console.log("Building Mindmap"); await initiateBuild("npm run build", process.env.MINDMAP_PATH!, process.env.MINDMAP_DEST_PATH!); mindmapBuildTime = currentTime; + contributorsBuildTime = currentTime; isMindmapUpdated = false; } @@ -135,8 +126,8 @@ const buildProject = async (): Promise<{ status: number; message: string }> => { }; const initiateBuild = async (command: string, projectPath: string, destPath: string) => { - await executeCmd(`cd ${sanitize(projectPath)}/ && git pull`); - await executeCmd(`cd ${sanitize(projectPath)}/ && npm ci`); - await executeCmd(`cd ${sanitize(projectPath)}/ && ${sanitize(command)}`); - await executeCmd(`cp -r ${sanitize(projectPath)}/dist/ ${sanitize(destPath)}/`); + await executeCmd(`cd ${(projectPath)}/ && git pull`); + await executeCmd(`cd ${(projectPath)}/ && npm ci`); + await executeCmd(`cd ${(projectPath)}/ && ${(command)}`); + await executeCmd(`cp -r ${(projectPath)}/dist/ ${(destPath)}/`); }; diff --git a/tsconfig.json b/tsconfig.json index 20513f2..54bdc45 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,109 +1,11 @@ { "compilerOptions": { - /* Visit https://aka.ms/tsconfig to read more about this file */ - - /* Projects */ - // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ - // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - - /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ - // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ - // "jsx": "preserve", /* Specify what JSX code is generated. */ - // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ - // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ - // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ - // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ - // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ - // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ - // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ - // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ - // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ - - /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ - // "rootDir": "./", /* Specify the root folder within your source files. */ - // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ - // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ - // "types": [], /* Specify type package names to be included without being referenced in a source file. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ - // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ - // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ - // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ - // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ - // "resolveJsonModule": true, /* Enable importing .json files. */ - // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ - // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ - - /* JavaScript Support */ - // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ - // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ - // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ - - /* Emit */ - // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ - // "declarationMap": true, /* Create sourcemaps for d.ts files. */ - // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ - // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ - // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ - // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ - // "outDir": "./", /* Specify an output folder for all emitted files. */ - // "removeComments": true, /* Disable emitting comments. */ - // "noEmit": true, /* Disable emitting files from a compilation. */ - // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ - // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ - // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ - // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ - // "newLine": "crlf", /* Set the newline character for emitting files. */ - // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ - // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ - // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ - // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ - // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ - - /* Interop Constraints */ - // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ - // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ - // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ - // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ - // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ - - /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ - // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ - // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ - // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ - // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ - // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ - // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ - // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ - // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ - // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ - // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ - // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ - // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ - // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ - // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ - - /* Completeness */ - // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ + "target": "es2016", + "module": "commonjs", + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "skipLibCheck": true }, "include": ["index.ts"], "exclude": ["node_modules", "**/*.spec.ts"]